code
stringlengths
2
1.05M
repo_name
stringlengths
5
114
path
stringlengths
4
991
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * @fileoverview * * It2MeHelpeeChannel relays messages between the Hangouts web page (Hangouts) * and the It2Me Native Messaging Host (It2MeHost) for the helpee (the Hangouts * participant who is receiving remoting assistance). * * It runs in the background page. It contains a chrome.runtime.Port object, * representing a connection to Hangouts, and a remoting.It2MeHostFacade object, * representing a connection to the IT2Me Native Messaging Host. * * Hangouts It2MeHelpeeChannel It2MeHost * |---------runtime.connect()-------->| | * |-----------hello message---------->| | * |<-----helloResponse message------->| | * |----------connect message--------->| | * | |-----showConfirmDialog()----->| * | |----------connect()---------->| * | |<-------hostStateChanged------| * | | (RECEIVED_ACCESS_CODE) | * |<---connect response (access code)-| | * | | | * * Hangouts will send the access code to the web app on the helper side. * The helper will then connect to the It2MeHost using the access code. * * Hangouts It2MeHelpeeChannel It2MeHost * | |<-------hostStateChanged------| * | | (CONNECTED) | * |<-- hostStateChanged(CONNECTED)----| | * |-------disconnect message--------->| | * |<--hostStateChanged(DISCONNECTED)--| | * * * It also handles host downloads and install status queries: * * Hangouts It2MeHelpeeChannel * |------isHostInstalled message----->| * |<-isHostInstalled response(false)--| * | | * |--------downloadHost message------>| * | | * |------isHostInstalled message----->| * |<-isHostInstalled response(false)--| * | | * |------isHostInstalled message----->| * |<-isHostInstalled response(true)---| */ 'use strict'; /** @suppress {duplicate} */ var remoting = remoting || {}; /** * @param {chrome.runtime.Port} hangoutPort * @param {remoting.It2MeHostFacade} host * @param {remoting.HostInstaller} hostInstaller * @param {function()} onDisposedCallback Callback to notify the client when * the connection is torn down. * * @constructor * @implements {base.Disposable} */ remoting.It2MeHelpeeChannel = function(hangoutPort, host, hostInstaller, onDisposedCallback) { /** * @type {chrome.runtime.Port} * @private */ this.hangoutPort_ = hangoutPort; /** * @type {remoting.It2MeHostFacade} * @private */ this.host_ = host; /** * @type {?remoting.HostInstaller} * @private */ this.hostInstaller_ = hostInstaller; /** * @type {remoting.HostSession.State} * @private */ this.hostState_ = remoting.HostSession.State.UNKNOWN; /** * @type {?function()} * @private */ this.onDisposedCallback_ = onDisposedCallback; this.onHangoutMessageRef_ = this.onHangoutMessage_.bind(this); this.onHangoutDisconnectRef_ = this.onHangoutDisconnect_.bind(this); }; /** @enum {string} */ remoting.It2MeHelpeeChannel.HangoutMessageTypes = { CONNECT: 'connect', CONNECT_RESPONSE: 'connectResponse', DISCONNECT: 'disconnect', DOWNLOAD_HOST: 'downloadHost', ERROR: 'error', HELLO: 'hello', HELLO_RESPONSE: 'helloResponse', HOST_STATE_CHANGED: 'hostStateChanged', IS_HOST_INSTALLED: 'isHostInstalled', IS_HOST_INSTALLED_RESPONSE: 'isHostInstalledResponse' }; /** @enum {string} */ remoting.It2MeHelpeeChannel.Features = { REMOTE_ASSISTANCE: 'remoteAssistance' }; remoting.It2MeHelpeeChannel.prototype.init = function() { this.hangoutPort_.onMessage.addListener(this.onHangoutMessageRef_); this.hangoutPort_.onDisconnect.addListener(this.onHangoutDisconnectRef_); }; remoting.It2MeHelpeeChannel.prototype.dispose = function() { if (this.host_ !== null) { this.host_.unhookCallbacks(); this.host_.disconnect(); this.host_ = null; } if (this.hangoutPort_ !== null) { this.hangoutPort_.onMessage.removeListener(this.onHangoutMessageRef_); this.hangoutPort_.onDisconnect.removeListener(this.onHangoutDisconnectRef_); this.hostState_ = remoting.HostSession.State.DISCONNECTED; try { var MessageTypes = remoting.It2MeHelpeeChannel.HangoutMessageTypes; this.hangoutPort_.postMessage({ method: MessageTypes.HOST_STATE_CHANGED, state: this.hostState_ }); } catch (e) { // |postMessage| throws if |this.hangoutPort_| is disconnected // It is safe to ignore the exception. } this.hangoutPort_.disconnect(); this.hangoutPort_ = null; } if (this.onDisposedCallback_ !== null) { this.onDisposedCallback_(); this.onDisposedCallback_ = null; } }; /** * Message Handler for incoming runtime messages from Hangouts. * * @param {{method:string, data:Object.<string,*>}} message * @private */ remoting.It2MeHelpeeChannel.prototype.onHangoutMessage_ = function(message) { try { var MessageTypes = remoting.It2MeHelpeeChannel.HangoutMessageTypes; switch (message.method) { case MessageTypes.HELLO: this.hangoutPort_.postMessage({ method: MessageTypes.HELLO_RESPONSE, supportedFeatures: base.values(remoting.It2MeHelpeeChannel.Features) }); return true; case MessageTypes.IS_HOST_INSTALLED: this.handleIsHostInstalled_(message); return true; case MessageTypes.DOWNLOAD_HOST: this.handleDownloadHost_(message); return true; case MessageTypes.CONNECT: this.handleConnect_(message); return true; case MessageTypes.DISCONNECT: this.dispose(); return true; } throw new Error('Unsupported message method=' + message.method); } catch(e) { var error = /** @type {Error} */ e; this.sendErrorResponse_(message, error.message); } return false; }; /** * Queries the |hostInstaller| for the installation status. * * @param {{method:string, data:Object.<string,*>}} message * @private */ remoting.It2MeHelpeeChannel.prototype.handleIsHostInstalled_ = function(message) { /** @type {remoting.It2MeHelpeeChannel} */ var that = this; /** @param {boolean} installed */ function sendResponse(installed) { var MessageTypes = remoting.It2MeHelpeeChannel.HangoutMessageTypes; that.hangoutPort_.postMessage({ method: MessageTypes.IS_HOST_INSTALLED_RESPONSE, result: installed }); } this.hostInstaller_.isInstalled().then( sendResponse, this.sendErrorResponse_.bind(this, message) ); }; /** * @param {{method:string, data:Object.<string,*>}} message * @private */ remoting.It2MeHelpeeChannel.prototype.handleDownloadHost_ = function(message) { try { this.hostInstaller_.download(); } catch (e) { var error = /** @type {Error} */ e; this.sendErrorResponse_(message, error.message); } }; /** * Disconnect the session if the |hangoutPort| gets disconnected. * @private */ remoting.It2MeHelpeeChannel.prototype.onHangoutDisconnect_ = function() { this.dispose(); }; /** * Connects to the It2Me Native messaging Host and retrieves the access code. * * @param {{method:string, data:Object.<string,*>}} message * @private */ remoting.It2MeHelpeeChannel.prototype.handleConnect_ = function(message) { var email = getStringAttr(message, 'email'); if (!email) { throw new Error('Missing required parameter: email'); } if (this.hostState_ !== remoting.HostSession.State.UNKNOWN) { throw new Error('An existing connection is in progress.'); } this.showConfirmDialog_().then( this.initializeHost_.bind(this) ).then( this.fetchOAuthToken_.bind(this) ).then( this.connectToHost_.bind(this, email), this.sendErrorResponse_.bind(this, message) ); }; /** * Prompts the user before starting the It2Me Native Messaging Host. This * ensures that even if Hangouts is compromised, an attacker cannot start the * host without explicit user confirmation. * * @return {Promise} A promise that resolves to a boolean value, indicating * whether the user accepts the remote assistance or not. * @private */ remoting.It2MeHelpeeChannel.prototype.showConfirmDialog_ = function() { if (base.isAppsV2()) { return this.showConfirmDialogV2_(); } else { return this.showConfirmDialogV1_(); } }; /** * @return {Promise} A promise that resolves to a boolean value, indicating * whether the user accepts the remote assistance or not. * @private */ remoting.It2MeHelpeeChannel.prototype.showConfirmDialogV1_ = function() { var messageHeader = l10n.getTranslationOrError( /*i18n-content*/'HANGOUTS_CONFIRM_DIALOG_MESSAGE_1'); var message1 = l10n.getTranslationOrError( /*i18n-content*/'HANGOUTS_CONFIRM_DIALOG_MESSAGE_2'); var message2 = l10n.getTranslationOrError( /*i18n-content*/'HANGOUTS_CONFIRM_DIALOG_MESSAGE_3'); var message = base.escapeHTML(messageHeader) + '\n' + '- ' + base.escapeHTML(message1) + '\n' + '- ' + base.escapeHTML(message2) + '\n'; if(window.confirm(message)) { return Promise.resolve(); } else { return Promise.reject(new Error(remoting.Error.CANCELLED)); } }; /** * @return {Promise} A promise that resolves to a boolean value, indicating * whether the user accepts the remote assistance or not. * @private */ remoting.It2MeHelpeeChannel.prototype.showConfirmDialogV2_ = function() { var messageHeader = l10n.getTranslationOrError( /*i18n-content*/'HANGOUTS_CONFIRM_DIALOG_MESSAGE_1'); var message1 = l10n.getTranslationOrError( /*i18n-content*/'HANGOUTS_CONFIRM_DIALOG_MESSAGE_2'); var message2 = l10n.getTranslationOrError( /*i18n-content*/'HANGOUTS_CONFIRM_DIALOG_MESSAGE_3'); var message = '<div>' + base.escapeHTML(messageHeader) + '</div>' + '<ul class="insetList">' + '<li>' + base.escapeHTML(message1) + '</li>' + '<li>' + base.escapeHTML(message2) + '</li>' + '</ul>'; /** * @param {function(*=):void} resolve * @param {function(*=):void} reject */ return new Promise(function(resolve, reject) { /** @param {number} result */ function confirmDialogCallback(result) { if (result === 1) { resolve(); } else { reject(new Error(remoting.Error.CANCELLED)); } } remoting.MessageWindow.showConfirmWindow( '', // Empty string to use the package name as the dialog title. message, l10n.getTranslationOrError( /*i18n-content*/'HANGOUTS_CONFIRM_DIALOG_ACCEPT'), l10n.getTranslationOrError( /*i18n-content*/'HANGOUTS_CONFIRM_DIALOG_DECLINE'), confirmDialogCallback ); }); }; /** * @return {Promise} A promise that resolves when the host is initialized. * @private */ remoting.It2MeHelpeeChannel.prototype.initializeHost_ = function() { /** @type {remoting.It2MeHostFacade} */ var host = this.host_; /** * @param {function(*=):void} resolve * @param {function(*=):void} reject */ return new Promise(function(resolve, reject) { if (host.initialized()) { resolve(); } else { host.initialize(resolve, reject); } }); }; /** * @return {Promise} Promise that resolves with the OAuth token as the value. */ remoting.It2MeHelpeeChannel.prototype.fetchOAuthToken_ = function() { if (base.isAppsV2()) { /** * @param {function(*=):void} resolve */ return new Promise(function(resolve){ // TODO(jamiewalch): Make this work with {interactive: true} as well. chrome.identity.getAuthToken({ 'interactive': false }, resolve); }); } else { /** * @param {function(*=):void} resolve */ return new Promise(function(resolve) { /** @type {remoting.OAuth2} */ var oauth2 = new remoting.OAuth2(); var onAuthenticated = function() { oauth2.callWithToken( resolve, function() { throw new Error('Authentication failed.'); }); }; /** @param {remoting.Error} error */ var onError = function(error) { if (error != remoting.Error.NOT_AUTHENTICATED) { throw new Error('Unexpected error fetch auth token: ' + error); } oauth2.doAuthRedirect(onAuthenticated); }; oauth2.callWithToken(resolve, onError); }); } }; /** * Connects to the It2Me Native Messaging Host and retrieves the access code * in the |onHostStateChanged_| callback. * * @param {string} email * @param {string} accessToken * @private */ remoting.It2MeHelpeeChannel.prototype.connectToHost_ = function(email, accessToken) { base.debug.assert(this.host_.initialized()); this.host_.connect( email, 'oauth2:' + accessToken, this.onHostStateChanged_.bind(this), base.doNothing, // Ignore |onNatPolicyChanged|. console.log.bind(console), // Forward logDebugInfo to console.log. remoting.settings.XMPP_SERVER_FOR_IT2ME_HOST, remoting.settings.XMPP_SERVER_USE_TLS, remoting.settings.DIRECTORY_BOT_JID, this.onHostConnectError_); }; /** * @param {remoting.Error} error * @private */ remoting.It2MeHelpeeChannel.prototype.onHostConnectError_ = function(error) { this.sendErrorResponse_(null, error); }; /** * @param {remoting.HostSession.State} state * @private */ remoting.It2MeHelpeeChannel.prototype.onHostStateChanged_ = function(state) { this.hostState_ = state; var MessageTypes = remoting.It2MeHelpeeChannel.HangoutMessageTypes; var HostState = remoting.HostSession.State; switch (state) { case HostState.RECEIVED_ACCESS_CODE: var accessCode = this.host_.getAccessCode(); this.hangoutPort_.postMessage({ method: MessageTypes.CONNECT_RESPONSE, accessCode: accessCode }); break; case HostState.CONNECTED: case HostState.DISCONNECTED: this.hangoutPort_.postMessage({ method: MessageTypes.HOST_STATE_CHANGED, state: state }); break; case HostState.ERROR: this.sendErrorResponse_(null, remoting.Error.UNEXPECTED); break; case HostState.INVALID_DOMAIN_ERROR: this.sendErrorResponse_(null, remoting.Error.INVALID_HOST_DOMAIN); break; default: // It is safe to ignore other state changes. } }; /** * @param {?{method:string, data:Object.<string,*>}} incomingMessage * @param {string|Error} error * @private */ remoting.It2MeHelpeeChannel.prototype.sendErrorResponse_ = function(incomingMessage, error) { if (error instanceof Error) { error = error.message; } console.error('Error responding to message method:' + (incomingMessage ? incomingMessage.method : 'null') + ' error:' + error); this.hangoutPort_.postMessage({ method: remoting.It2MeHelpeeChannel.HangoutMessageTypes.ERROR, message: error, request: incomingMessage }); };
mohamed--abdel-maksoud/chromium.src
remoting/webapp/crd/js/it2me_helpee_channel.js
JavaScript
bsd-3-clause
15,736
KB.onClick('.accordion-toggle', function (e) { var sectionElement = KB.dom(e.target).parent('.accordion-section'); if (sectionElement) { KB.dom(sectionElement).toggleClass('accordion-collapsed'); } });
Shaxine/kanboard
assets/js/components/accordion.js
JavaScript
mit
223
alert("foo!");
beni55/unfiltered
netty-server/src/test/resources/files/foo.js
JavaScript
mit
14
})(); Clazz._coreLoaded = true;
xavierprat/chemEdData
libs/jsmol/jmol-14.8.0/jsmol/js/core/corebottom.js
JavaScript
mit
44
// Don't need this for our purposes module = function(){}; if(typeof equal != 'undefined') { equals = equal; } ok = function(actual, message) { equal(actual, true, message); } raises = function(fn, expected, message) { raisesError(fn, message); }; asyncTest = function(name, delay, fn) { test(name, fn); } start = function() { // Just pass through... } notStrictEqual = function(a, b, message) { equal(a === b, false, message); } var ensureArray = function(obj) { if(obj === null) { return []; } else if(Object.isArray(obj) && (!obj.indexOf || !obj.lastIndexOf)) { return obj.concat(); } else if(!Object.isArray(obj) && typeof obj == 'object') { return Array.prototype.slice.call(obj); } else { return obj; } } var CompatibleMethods = [ { module: Array.prototype, methods: [ { name: 'first', method: function(arr, n, guard){ if(guard) { return arr[0]; } return ensureArray(arr).first(n); } }, { name: 'last', method: function(arr, n, third){ // This is the same check that Underscore makes to hack // _.last to work with _.map if(third) n = 1; return ensureArray(arr).last(n); } }, { name: 'rest', method: function(arr, n, guard){ if(n === undefined) n = 1; if(guard) { return arr.slice(1); } return ensureArray(arr).from(n); } }, { name: 'compact', method: function(arr){ return ensureArray(arr).compact(true); } }, /* Object.extend is no longer compatible as it has conflict resolution now. { name: 'extend', method: function(){ return Object.SugarMethods['merge'].method.apply(this, arguments); } }, */ /* Array#flatten is no longer compatible as it has levels of flattening (not just deep/shallow) { name: 'flatten', method: function(arr){ return ensureArray(arr).flatten(); } }, */ { name: 'uniq', method: function(arr){ return ensureArray(arr).unique(); } }, { name: 'intersection', method: function(arr){ arr = ensureArray(arr); var args = Array.prototype.slice.call(arguments, 1); return Array.prototype.intersect.apply(arr, args); } }, { name: 'union', method: function(arr, a){ arr = ensureArray(arr); var args = Array.prototype.slice.call(arguments, 1); return Array.prototype.union.apply(arr, args); } }, /* { name: 'difference', method: function(arr, a){ arr = ensureArray(arr); var args = Array.prototype.slice.call(arguments, 1); return Array.prototype.subtract.apply(arr, args); } }, */ { name: 'indexOf', method: function(arr, a){ return ensureArray(arr).indexOf(a); } }, { name: 'lastIndexOf', method: function(arr, a){ return ensureArray(arr).lastIndexOf(a); } }, { name: 'range', method: function(start, stop, step){ if(arguments.length == 1){ stop = arguments[0]; start = 0; } var shift = step < 0 ? 1 : -1; return start.upto(stop + shift, null, step); } }, // Collections // _.each -> Array#forEach OR Object.each // _.map -> Array#map // _.reduce -> Array#reduce // _.reduceRight -> Array#reduceRight // _.invoke is doing some strange tapdancing for passing methods directly... // _.sortedIndex ... no direct equivalent // _.toArray ... no direct equivalent for arguments... Array.create? // _.size ... no direct equivalent for objects... obj.keys().length? { name: 'detect', method: function(arr, fn, context){ return Array.SugarMethods['find'].method.call(arr, fn.bind(context)); } }, { name: 'select', method: function(arr, fn, context){ return Array.SugarMethods['findAll'].method.call(arr, fn.bind(context)); } }, { name: 'reject', method: function(arr, fn, context){ return Array.SugarMethods['exclude'].method.call(arr, fn.bind(context)); } }, { name: 'all', method: function(arr, fn, context){ return Array.SugarMethods['all'].method.call(arr, fn.bind(context)); } }, { name: 'any', method: function(arr, fn, context){ if(!fn) fn = function(a){ return a; }; return Array.SugarMethods['some'].method.call(arr, fn.bind(context)); } }, /* { name: 'include', method: function(arr, val){ return Array.SugarMethods['has'].method.call(arr, val); } }, */ { name: 'pluck', method: function(arr, prop){ return Array.SugarMethods['map'].method.call(arr, prop); } }, { name: 'max', method: function(arr, fn, context){ if(!fn) fn = function(a){ return a; }; return Array.SugarMethods['max'].method.call(arr, fn.bind(context))[0]; } }, { name: 'min', method: function(arr, fn, context){ if(!fn) fn = function(a){ return a; }; return Array.SugarMethods['min'].method.call(arr, fn.bind(context))[0]; } }, { name: 'sortBy', method: function(arr, fn, context){ return Array.SugarMethods['sortBy'].method.call(arr, fn.bind(context)); } }, { name: 'groupBy', method: function(arr, fn){ return Array.SugarMethods['groupBy'].method.call(arr, fn); } }, // Objects // _.functions ... no direct equivalent // _.defaults ... no direct equivalent // _.tap ... no direct equivalent // _.isElement ... no direct equivalent // _.isArguments ... no direct equivalent // _.isNaN ... no direct equivalent // _.isNull ... no direct equivalent // _.isUndefined ... no direct equivalent { name: 'keys', method: function(){ return Object.SugarMethods['keys'].method.apply(this, arguments); } }, { name: 'values', method: function(){ return Object.SugarMethods['values'].method.apply(this, arguments); } }, { name: 'clone', method: function(){ return Object.SugarMethods['clone'].method.apply(this, arguments); } }, { name: 'isEqual', method: function(a, b){ if (a && a._chain) a = a._wrapped; if (b && b._chain) b = b._wrapped; if (a && a.isEqual) return a.isEqual(b); if (b && b.isEqual) return b.isEqual(a); return Object.SugarMethods['equal'].method.apply(this, arguments); } }, { name: 'isEmpty', method: function(){ return Object.SugarMethods['isEmpty'].method.apply(this, arguments); } }, { name: 'isArray', method: function(arr){ return Array.isArray(arr); } }, { name: 'isFunction', method: function(){ return Object.SugarMethods['isFunction'].method.apply(this, arguments); } }, { name: 'isString', method: function(){ return Object.SugarMethods['isString'].method.apply(this, arguments); } }, { name: 'isNumber', method: function(){ if(isNaN(arguments[0])) { // Sugar differs here as it's trying to stay aligned with Javascript and is // checking types only. return false; } return Object.SugarMethods['isNumber'].method.apply(this, arguments); } }, { name: 'isBoolean', method: function(){ return Object.SugarMethods['isBoolean'].method.apply(this, arguments); } }, { name: 'isDate', method: function(){ return Object.SugarMethods['isDate'].method.apply(this, arguments); } }, { name: 'isRegExp', method: function(){ return Object.SugarMethods['isRegExp'].method.apply(this, arguments); } }, // Functions // _.bindAll ... no direct equivalent (similar to bindAsEventListener??) // _.memoize ... no direct equivalent // _.debounce ... no direct equivalent // _.once ... no direct equivalent.. is this not similar to memoize? // _.wrap ... no direct equivalent.. // _.compose ... no direct equivalent.. math stuff { name: 'bind', method: function(fn){ var args = Array.prototype.slice.call(arguments, 1); return Function.prototype.bind.apply(fn, args); } }, { name: 'after', method: function(num, fn){ return Function.prototype.after.apply(fn, [num]); } }, { name: 'delay', method: function(fn){ var args = Array.prototype.slice.call(arguments, 1); return Function.prototype.delay.apply(fn, args); } }, { name: 'defer', method: function(fn){ var args = Array.prototype.slice.call(arguments, 1); return Function.prototype.delay.apply(fn, [1].concat(args)); } }, { name: 'throttle', method: function(fn, wait){ return Function.prototype.lazy.apply(fn, [wait]); } }, // Utility // _.noConflict ... no direct equivalent // _.identity ... no direct equivalent // _.mixin ... no direct equivalent // _.uniqueId ... no direct equivalent // _.template ... no direct equivalent // _.chain ... no direct equivalent // _.value ... no direct equivalent { name: 'times', method: function(n, fn){ return n.times(fn); } } ] } ]; var mapMethods = function() { var proto; CompatibleMethods.forEach(function(cm) { cm.methods.forEach(function(m) { _[m.name] = m.method; }); }); } mapMethods();
D1plo1d/Sugar
unit_tests/environments/underscore/adapter.js
JavaScript
mit
10,615
/*@preserve * Tempus Dominus Bootstrap4 v5.0.0-alpha13 (https://tempusdominus.github.io/bootstrap-4/) * Copyright 2016-2017 Jonathan Peterson * Licensed under MIT (https://github.com/tempusdominus/bootstrap-3/blob/master/LICENSE) */ if (typeof jQuery === 'undefined') { throw new Error('Tempus Dominus Bootstrap4\'s requires jQuery. jQuery must be included before Tempus Dominus Bootstrap4\'s JavaScript.'); } +function ($) { var version = $.fn.jquery.split(' ')[0].split('.'); if ((version[0] < 2 && version[1] < 9) || (version[0] === 1 && version[1] === 9 && version[2] < 1) || (version[0] >= 4)) { throw new Error('Tempus Dominus Bootstrap4\'s requires at least jQuery v1.9.1 but less than v4.0.0'); } }(jQuery); if (typeof moment === 'undefined') { throw new Error('Tempus Dominus Bootstrap4\'s requires moment.js. Moment.js must be included before Tempus Dominus Bootstrap4\'s JavaScript.'); } var version = moment.version.split('.') if ((version[0] <= 2 && version[1] < 17) || (version[0] >= 3)) { throw new Error('Tempus Dominus Bootstrap4\'s requires at least moment.js v2.17.0 but less than v3.0.0'); } +function () { var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _createClass = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } // ReSharper disable once InconsistentNaming var DateTimePicker = function ($, moment) { // ReSharper disable InconsistentNaming var NAME = 'datetimepicker', VERSION = '5.0.0-alpha7', DATA_KEY = '' + NAME, EVENT_KEY = '.' + DATA_KEY, EMIT_EVENT_KEY = DATA_KEY + '.', DATA_API_KEY = '.data-api', Selector = { DATA_TOGGLE: '[data-toggle="' + DATA_KEY + '"]' }, ClassName = { INPUT: NAME + '-input' }, Event = { CHANGE: 'change' + EVENT_KEY, BLUR: 'blur' + EVENT_KEY, KEYUP: 'keyup' + EVENT_KEY, KEYDOWN: 'keydown' + EVENT_KEY, FOCUS: 'focus' + EVENT_KEY, CLICK_DATA_API: 'click' + EVENT_KEY + DATA_API_KEY, //emitted UPDATE: EMIT_EVENT_KEY + 'update', ERROR: EMIT_EVENT_KEY + 'error', HIDE: EMIT_EVENT_KEY + 'hide', SHOW: EMIT_EVENT_KEY + 'show' }, Default = { timeZone: '', format: false, dayViewHeaderFormat: 'MMMM YYYY', extraFormats: false, stepping: 1, minDate: false, maxDate: false, useCurrent: true, collapse: true, locale: moment.locale(), defaultDate: false, disabledDates: false, enabledDates: false, icons: { time: 'fa fa-clock-o', date: 'fa fa-calendar', up: 'fa fa-arrow-up', down: 'fa fa-arrow-down', previous: 'fa fa-chevron-left', next: 'fa fa-chevron-right', today: 'fa fa-calendar-check-o', clear: 'fa fa-delete', close: 'fa fa-times' }, tooltips: { today: 'Go to today', clear: 'Clear selection', close: 'Close the picker', selectMonth: 'Select Month', prevMonth: 'Previous Month', nextMonth: 'Next Month', selectYear: 'Select Year', prevYear: 'Previous Year', nextYear: 'Next Year', selectDecade: 'Select Decade', prevDecade: 'Previous Decade', nextDecade: 'Next Decade', prevCentury: 'Previous Century', nextCentury: 'Next Century', pickHour: 'Pick Hour', incrementHour: 'Increment Hour', decrementHour: 'Decrement Hour', pickMinute: 'Pick Minute', incrementMinute: 'Increment Minute', decrementMinute: 'Decrement Minute', pickSecond: 'Pick Second', incrementSecond: 'Increment Second', decrementSecond: 'Decrement Second', togglePeriod: 'Toggle Period', selectTime: 'Select Time', selectDate: 'Select Date' }, useStrict: false, sideBySide: false, daysOfWeekDisabled: false, calendarWeeks: false, viewMode: 'days', toolbarPlacement: 'default', buttons: { showToday: false, showClear: false, showClose: false }, widgetPositioning: { horizontal: 'auto', vertical: 'auto' }, widgetParent: null, ignoreReadonly: false, keepOpen: false, focusOnShow: true, inline: false, keepInvalid: false, keyBinds: { up: function up() { if (!this.widget) { return false; } var d = this._dates[0] || this.getMoment(); if (this.widget.find('.datepicker').is(':visible')) { this.date(d.clone().subtract(7, 'd')); } else { this.date(d.clone().add(this.stepping(), 'm')); } return true; }, down: function down() { if (!this.widget) { this.show(); return false; } var d = this._dates[0] || this.getMoment(); if (this.widget.find('.datepicker').is(':visible')) { this.date(d.clone().add(7, 'd')); } else { this.date(d.clone().subtract(this.stepping(), 'm')); } return true; }, 'control up': function controlUp() { if (!this.widget) { return false; } var d = this._dates[0] || this.getMoment(); if (this.widget.find('.datepicker').is(':visible')) { this.date(d.clone().subtract(1, 'y')); } else { this.date(d.clone().add(1, 'h')); } return true; }, 'control down': function controlDown() { if (!this.widget) { return false; } var d = this._dates[0] || this.getMoment(); if (this.widget.find('.datepicker').is(':visible')) { this.date(d.clone().add(1, 'y')); } else { this.date(d.clone().subtract(1, 'h')); } return true; }, left: function left() { if (!this.widget) { return false; } var d = this._dates[0] || this.getMoment(); if (this.widget.find('.datepicker').is(':visible')) { this.date(d.clone().subtract(1, 'd')); } return true; }, right: function right() { if (!this.widget) { return false; } var d = this._dates[0] || this.getMoment(); if (this.widget.find('.datepicker').is(':visible')) { this.date(d.clone().add(1, 'd')); } return true; }, pageUp: function pageUp() { if (!this.widget) { return false; } var d = this._dates[0] || this.getMoment(); if (this.widget.find('.datepicker').is(':visible')) { this.date(d.clone().subtract(1, 'M')); } return true; }, pageDown: function pageDown() { if (!this.widget) { return false; } var d = this._dates[0] || this.getMoment(); if (this.widget.find('.datepicker').is(':visible')) { this.date(d.clone().add(1, 'M')); } return true; }, enter: function enter() { this.hide(); return true; }, escape: function escape() { if (!this.widget) { return false; } this.hide(); return true; }, 'control space': function controlSpace() { if (!this.widget) { return false; } if (this.widget.find('.timepicker').is(':visible')) { this.widget.find('.btn[data-action="togglePeriod"]').click(); } return true; }, t: function t() { this.date(this.getMoment()); return true; }, 'delete': function _delete() { if (!this.widget) { return false; } this.clear(); return true; } }, debug: false, allowInputToggle: false, disabledTimeIntervals: false, disabledHours: false, enabledHours: false, viewDate: false, allowMultidate: false, multidateSeparator: ',' }, DatePickerModes = [{ CLASS_NAME: 'days', NAV_FUNCTION: 'M', NAV_STEP: 1 }, { CLASS_NAME: 'months', NAV_FUNCTION: 'y', NAV_STEP: 1 }, { CLASS_NAME: 'years', NAV_FUNCTION: 'y', NAV_STEP: 10 }, { CLASS_NAME: 'decades', NAV_FUNCTION: 'y', NAV_STEP: 100 }], KeyMap = { 'up': 38, 38: 'up', 'down': 40, 40: 'down', 'left': 37, 37: 'left', 'right': 39, 39: 'right', 'tab': 9, 9: 'tab', 'escape': 27, 27: 'escape', 'enter': 13, 13: 'enter', 'pageUp': 33, 33: 'pageUp', 'pageDown': 34, 34: 'pageDown', 'shift': 16, 16: 'shift', 'control': 17, 17: 'control', 'space': 32, 32: 'space', 't': 84, 84: 't', 'delete': 46, 46: 'delete' }, ViewModes = ['times', 'days', 'months', 'years', 'decades'], keyState = {}, keyPressHandled = {}; var MinViewModeNumber = 0; // ReSharper restore InconsistentNaming // ReSharper disable once DeclarationHides // ReSharper disable once InconsistentNaming var DateTimePicker = function () { /** @namespace eData.dateOptions */ /** @namespace moment.tz */ function DateTimePicker(element, options) { _classCallCheck(this, DateTimePicker); this._options = this._getOptions(options); this._element = element; this._dates = []; this._datesFormatted = []; this._viewDate = null; this.unset = true; this.component = false; this.widget = false; this.use24Hours = null; this.actualFormat = null; this.parseFormats = null; this.currentViewMode = null; this._int(); } /** * @return {string} */ //private DateTimePicker.prototype._int = function _int() { var targetInput = this._element.data('target-input'); if (this._element.is('input')) { this.input = this._element; } else if (targetInput !== undefined) { if (targetInput === 'nearest') { this.input = this._element.find('input'); } else { this.input = $(targetInput); } } this._dates = []; this._dates[0] = this.getMoment(); this._viewDate = this.getMoment().clone(); $.extend(true, this._options, this._dataToOptions()); this.options(this._options); this._initFormatting(); if (this.input !== undefined && this.input.is('input') && this.input.val().trim().length !== 0) { this._setValue(this._parseInputDate(this.input.val().trim()), 0); } else if (this._options.defaultDate && this.input !== undefined && this.input.attr('placeholder') === undefined) { this._setValue(this._options.defaultDate, 0); } if (this._options.inline) { this.show(); } }; DateTimePicker.prototype._update = function _update() { if (!this.widget) { return; } this._fillDate(); this._fillTime(); }; DateTimePicker.prototype._setValue = function _setValue(targetMoment, index) { var oldDate = this.unset ? null : this._dates[index]; var outpValue = ''; // case of calling setValue(null or false) if (!targetMoment) { if (!this._options.allowMultidate || this._dates.length === 1) { this.unset = true; this._dates = []; this._datesFormatted = []; } else { outpValue = this._element.data('date') + ','; outpValue = outpValue.replace(oldDate.format(this.actualFormat) + ',', '').replace(',,', '').replace(/,\s*$/, ''); this._dates.splice(index, 1); this._datesFormatted.splice(index, 1); } if (this.input !== undefined) { this.input.val(outpValue); this.input.trigger('input'); } this._element.data('date', outpValue); this._notifyEvent({ type: DateTimePicker.Event.CHANGE, date: false, oldDate: oldDate }); this._update(); return; } targetMoment = targetMoment.clone().locale(this._options.locale); if (this._hasTimeZone()) { targetMoment.tz(this._options.timeZone); } if (this._options.stepping !== 1) { targetMoment.minutes(Math.round(targetMoment.minutes() / this._options.stepping) * this._options.stepping).seconds(0); } if (this._isValid(targetMoment)) { this._dates[index] = targetMoment; this._datesFormatted[index] = targetMoment.format('YYYY-MM-DD'); this._viewDate = targetMoment.clone(); if (this._options.allowMultidate && this._dates.length > 1) { for (var i = 0; i < this._dates.length; i++) { outpValue += '' + this._dates[i].format(this.actualFormat) + this._options.multidateSeparator; } outpValue = outpValue.replace(/,\s*$/, ''); } else { outpValue = this._dates[index].format(this.actualFormat); } if (this.input !== undefined) { this.input.val(outpValue); this.input.trigger('input'); } this._element.data('date', outpValue); this.unset = false; this._update(); this._notifyEvent({ type: DateTimePicker.Event.CHANGE, date: this._dates[index].clone(), oldDate: oldDate }); } else { if (!this._options.keepInvalid) { if (this.input !== undefined) { this.input.val('' + (this.unset ? '' : this._dates[index].format(this.actualFormat))); this.input.trigger('input'); } } else { this._notifyEvent({ type: DateTimePicker.Event.CHANGE, date: targetMoment, oldDate: oldDate }); } this._notifyEvent({ type: DateTimePicker.Event.ERROR, date: targetMoment, oldDate: oldDate }); } }; DateTimePicker.prototype._change = function _change(e) { var val = $(e.target).val().trim(), parsedDate = val ? this._parseInputDate(val) : null; this._setValue(parsedDate); e.stopImmediatePropagation(); return false; }; //noinspection JSMethodCanBeStatic DateTimePicker.prototype._getOptions = function _getOptions(options) { options = $.extend(true, {}, Default, options); return options; }; DateTimePicker.prototype._hasTimeZone = function _hasTimeZone() { return moment.tz !== undefined && this._options.timeZone !== undefined && this._options.timeZone !== null && this._options.timeZone !== ''; }; DateTimePicker.prototype._isEnabled = function _isEnabled(granularity) { if (typeof granularity !== 'string' || granularity.length > 1) { throw new TypeError('isEnabled expects a single character string parameter'); } switch (granularity) { case 'y': return this.actualFormat.indexOf('Y') !== -1; case 'M': return this.actualFormat.indexOf('M') !== -1; case 'd': return this.actualFormat.toLowerCase().indexOf('d') !== -1; case 'h': case 'H': return this.actualFormat.toLowerCase().indexOf('h') !== -1; case 'm': return this.actualFormat.indexOf('m') !== -1; case 's': return this.actualFormat.indexOf('s') !== -1; default: return false; } }; DateTimePicker.prototype._hasTime = function _hasTime() { return this._isEnabled('h') || this._isEnabled('m') || this._isEnabled('s'); }; DateTimePicker.prototype._hasDate = function _hasDate() { return this._isEnabled('y') || this._isEnabled('M') || this._isEnabled('d'); }; DateTimePicker.prototype._dataToOptions = function _dataToOptions() { var eData = this._element.data(); var dataOptions = {}; if (eData.dateOptions && eData.dateOptions instanceof Object) { dataOptions = $.extend(true, dataOptions, eData.dateOptions); } $.each(this._options, function (key) { var attributeName = 'date' + key.charAt(0).toUpperCase() + key.slice(1); //todo data api key if (eData[attributeName] !== undefined) { dataOptions[key] = eData[attributeName]; } else { delete dataOptions[key]; } }); return dataOptions; }; DateTimePicker.prototype._notifyEvent = function _notifyEvent(e) { if (e.type === DateTimePicker.Event.CHANGE && e.date && e.date.isSame(e.oldDate) || !e.date && !e.oldDate) { return; } this._element.trigger(e); }; DateTimePicker.prototype._viewUpdate = function _viewUpdate(e) { if (e === 'y') { e = 'YYYY'; } this._notifyEvent({ type: DateTimePicker.Event.UPDATE, change: e, viewDate: this._viewDate.clone() }); }; DateTimePicker.prototype._showMode = function _showMode(dir) { if (!this.widget) { return; } if (dir) { this.currentViewMode = Math.max(MinViewModeNumber, Math.min(3, this.currentViewMode + dir)); } this.widget.find('.datepicker > div').hide().filter('.datepicker-' + DatePickerModes[this.currentViewMode].CLASS_NAME).show(); }; DateTimePicker.prototype._isInDisabledDates = function _isInDisabledDates(testDate) { return this._options.disabledDates[testDate.format('YYYY-MM-DD')] === true; }; DateTimePicker.prototype._isInEnabledDates = function _isInEnabledDates(testDate) { return this._options.enabledDates[testDate.format('YYYY-MM-DD')] === true; }; DateTimePicker.prototype._isInDisabledHours = function _isInDisabledHours(testDate) { return this._options.disabledHours[testDate.format('H')] === true; }; DateTimePicker.prototype._isInEnabledHours = function _isInEnabledHours(testDate) { return this._options.enabledHours[testDate.format('H')] === true; }; DateTimePicker.prototype._isValid = function _isValid(targetMoment, granularity) { if (!targetMoment.isValid()) { return false; } if (this._options.disabledDates && granularity === 'd' && this._isInDisabledDates(targetMoment)) { return false; } if (this._options.enabledDates && granularity === 'd' && !this._isInEnabledDates(targetMoment)) { return false; } if (this._options.minDate && targetMoment.isBefore(this._options.minDate, granularity)) { return false; } if (this._options.maxDate && targetMoment.isAfter(this._options.maxDate, granularity)) { return false; } if (this._options.daysOfWeekDisabled && granularity === 'd' && this._options.daysOfWeekDisabled.indexOf(targetMoment.day()) !== -1) { return false; } if (this._options.disabledHours && (granularity === 'h' || granularity === 'm' || granularity === 's') && this._isInDisabledHours(targetMoment)) { return false; } if (this._options.enabledHours && (granularity === 'h' || granularity === 'm' || granularity === 's') && !this._isInEnabledHours(targetMoment)) { return false; } if (this._options.disabledTimeIntervals && (granularity === 'h' || granularity === 'm' || granularity === 's')) { var found = false; $.each(this._options.disabledTimeIntervals, function () { if (targetMoment.isBetween(this[0], this[1])) { found = true; return false; } }); if (found) { return false; } } return true; }; DateTimePicker.prototype._parseInputDate = function _parseInputDate(inputDate) { if (this._options.parseInputDate === undefined) { if (!moment.isMoment(inputDate)) { inputDate = this.getMoment(inputDate); } } else { inputDate = this._options.parseInputDate(inputDate); } //inputDate.locale(this.options.locale); return inputDate; }; DateTimePicker.prototype._keydown = function _keydown(e) { var handler = null, index = void 0, index2 = void 0, keyBindKeys = void 0, allModifiersPressed = void 0; var pressedKeys = [], pressedModifiers = {}, currentKey = e.which, pressed = 'p'; keyState[currentKey] = pressed; for (index in keyState) { if (keyState.hasOwnProperty(index) && keyState[index] === pressed) { pressedKeys.push(index); if (parseInt(index, 10) !== currentKey) { pressedModifiers[index] = true; } } } for (index in this._options.keyBinds) { if (this._options.keyBinds.hasOwnProperty(index) && typeof this._options.keyBinds[index] === 'function') { keyBindKeys = index.split(' '); if (keyBindKeys.length === pressedKeys.length && KeyMap[currentKey] === keyBindKeys[keyBindKeys.length - 1]) { allModifiersPressed = true; for (index2 = keyBindKeys.length - 2; index2 >= 0; index2--) { if (!(KeyMap[keyBindKeys[index2]] in pressedModifiers)) { allModifiersPressed = false; break; } } if (allModifiersPressed) { handler = this._options.keyBinds[index]; break; } } } } if (handler) { if (handler.call(this.widget)) { e.stopPropagation(); e.preventDefault(); } } }; //noinspection JSMethodCanBeStatic,SpellCheckingInspection DateTimePicker.prototype._keyup = function _keyup(e) { keyState[e.which] = 'r'; if (keyPressHandled[e.which]) { keyPressHandled[e.which] = false; e.stopPropagation(); e.preventDefault(); } }; DateTimePicker.prototype._indexGivenDates = function _indexGivenDates(givenDatesArray) { // Store given enabledDates and disabledDates as keys. // This way we can check their existence in O(1) time instead of looping through whole array. // (for example: options.enabledDates['2014-02-27'] === true) var givenDatesIndexed = {}, self = this; $.each(givenDatesArray, function () { var dDate = self._parseInputDate(this); if (dDate.isValid()) { givenDatesIndexed[dDate.format('YYYY-MM-DD')] = true; } }); return Object.keys(givenDatesIndexed).length ? givenDatesIndexed : false; }; DateTimePicker.prototype._indexGivenHours = function _indexGivenHours(givenHoursArray) { // Store given enabledHours and disabledHours as keys. // This way we can check their existence in O(1) time instead of looping through whole array. // (for example: options.enabledHours['2014-02-27'] === true) var givenHoursIndexed = {}; $.each(givenHoursArray, function () { givenHoursIndexed[this] = true; }); return Object.keys(givenHoursIndexed).length ? givenHoursIndexed : false; }; DateTimePicker.prototype._initFormatting = function _initFormatting() { var format = this._options.format || 'L LT', self = this; this.actualFormat = format.replace(/(\[[^\[]*])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g, function (formatInput) { return self._dates[0].localeData().longDateFormat(formatInput) || formatInput; //todo taking the first date should be ok }); this.parseFormats = this._options.extraFormats ? this._options.extraFormats.slice() : []; if (this.parseFormats.indexOf(format) < 0 && this.parseFormats.indexOf(this.actualFormat) < 0) { this.parseFormats.push(this.actualFormat); } this.use24Hours = this.actualFormat.toLowerCase().indexOf('a') < 1 && this.actualFormat.replace(/\[.*?]/g, '').indexOf('h') < 1; if (this._isEnabled('y')) { MinViewModeNumber = 2; } if (this._isEnabled('M')) { MinViewModeNumber = 1; } if (this._isEnabled('d')) { MinViewModeNumber = 0; } this.currentViewMode = Math.max(MinViewModeNumber, this.currentViewMode); if (!this.unset) { this._setValue(this._dates[0], 0); } }; DateTimePicker.prototype._getLastPickedDate = function _getLastPickedDate() { return this._dates[this._getLastPickedDateIndex()]; }; DateTimePicker.prototype._getLastPickedDateIndex = function _getLastPickedDateIndex() { return this._dates.length - 1; }; //public DateTimePicker.prototype.getMoment = function getMoment(d) { var returnMoment = void 0; if (d === undefined || d === null) { returnMoment = moment(); //TODO should this use format? and locale? } else if (this._hasTimeZone()) { // There is a string to parse and a default time zone // parse with the tz function which takes a default time zone if it is not in the format string returnMoment = moment.tz(d, this.parseFormats, this._options.useStrict, this._options.timeZone); } else { returnMoment = moment(d, this.parseFormats, this._options.useStrict); } if (this._hasTimeZone()) { returnMoment.tz(this._options.timeZone); } return returnMoment; }; DateTimePicker.prototype.toggle = function toggle() { return this.widget ? this.hide() : this.show(); }; DateTimePicker.prototype.ignoreReadonly = function ignoreReadonly(_ignoreReadonly) { if (arguments.length === 0) { return this._options.ignoreReadonly; } if (typeof _ignoreReadonly !== 'boolean') { throw new TypeError('ignoreReadonly () expects a boolean parameter'); } this._options.ignoreReadonly = _ignoreReadonly; }; DateTimePicker.prototype.options = function options(newOptions) { if (arguments.length === 0) { return $.extend(true, {}, this._options); } if (!(newOptions instanceof Object)) { throw new TypeError('options() this.options parameter should be an object'); } $.extend(true, this._options, newOptions); var self = this; $.each(this._options, function (key, value) { if (self[key] !== undefined) { self[key](value); } }); }; DateTimePicker.prototype.date = function date(newDate, index) { index = index || 0; if (arguments.length === 0) { if (this.unset) { return null; } if (this._options.allowMultidate) { return this._dates.join(this._options.multidateSeparator); } else { return this._dates[index].clone(); } } if (newDate !== null && typeof newDate !== 'string' && !moment.isMoment(newDate) && !(newDate instanceof Date)) { throw new TypeError('date() parameter must be one of [null, string, moment or Date]'); } this._setValue(newDate === null ? null : this._parseInputDate(newDate), index); }; DateTimePicker.prototype.format = function format(newFormat) { ///<summary>test su</summary> ///<param name="newFormat">info about para</param> ///<returns type="string|boolean">returns foo</returns> if (arguments.length === 0) { return this._options.format; } if (typeof newFormat !== 'string' && (typeof newFormat !== 'boolean' || newFormat !== false)) { throw new TypeError('format() expects a string or boolean:false parameter ' + newFormat); } this._options.format = newFormat; if (this.actualFormat) { this._initFormatting(); // reinitialize formatting } }; DateTimePicker.prototype.timeZone = function timeZone(newZone) { if (arguments.length === 0) { return this._options.timeZone; } if (typeof newZone !== 'string') { throw new TypeError('newZone() expects a string parameter'); } this._options.timeZone = newZone; }; DateTimePicker.prototype.dayViewHeaderFormat = function dayViewHeaderFormat(newFormat) { if (arguments.length === 0) { return this._options.dayViewHeaderFormat; } if (typeof newFormat !== 'string') { throw new TypeError('dayViewHeaderFormat() expects a string parameter'); } this._options.dayViewHeaderFormat = newFormat; }; DateTimePicker.prototype.extraFormats = function extraFormats(formats) { if (arguments.length === 0) { return this._options.extraFormats; } if (formats !== false && !(formats instanceof Array)) { throw new TypeError('extraFormats() expects an array or false parameter'); } this._options.extraFormats = formats; if (this.parseFormats) { this._initFormatting(); // reinit formatting } }; DateTimePicker.prototype.disabledDates = function disabledDates(dates) { if (arguments.length === 0) { return this._options.disabledDates ? $.extend({}, this._options.disabledDates) : this._options.disabledDates; } if (!dates) { this._options.disabledDates = false; this._update(); return true; } if (!(dates instanceof Array)) { throw new TypeError('disabledDates() expects an array parameter'); } this._options.disabledDates = this._indexGivenDates(dates); this._options.enabledDates = false; this._update(); }; DateTimePicker.prototype.enabledDates = function enabledDates(dates) { if (arguments.length === 0) { return this._options.enabledDates ? $.extend({}, this._options.enabledDates) : this._options.enabledDates; } if (!dates) { this._options.enabledDates = false; this._update(); return true; } if (!(dates instanceof Array)) { throw new TypeError('enabledDates() expects an array parameter'); } this._options.enabledDates = this._indexGivenDates(dates); this._options.disabledDates = false; this._update(); }; DateTimePicker.prototype.daysOfWeekDisabled = function daysOfWeekDisabled(_daysOfWeekDisabled) { if (arguments.length === 0) { return this._options.daysOfWeekDisabled.splice(0); } if (typeof _daysOfWeekDisabled === 'boolean' && !_daysOfWeekDisabled) { this._options.daysOfWeekDisabled = false; this._update(); return true; } if (!(_daysOfWeekDisabled instanceof Array)) { throw new TypeError('daysOfWeekDisabled() expects an array parameter'); } this._options.daysOfWeekDisabled = _daysOfWeekDisabled.reduce(function (previousValue, currentValue) { currentValue = parseInt(currentValue, 10); if (currentValue > 6 || currentValue < 0 || isNaN(currentValue)) { return previousValue; } if (previousValue.indexOf(currentValue) === -1) { previousValue.push(currentValue); } return previousValue; }, []).sort(); if (this._options.useCurrent && !this._options.keepInvalid) { for (var i = 0; i < this._dates.length; i++) { var tries = 0; while (!this._isValid(this._dates[i], 'd')) { this._dates[i].add(1, 'd'); if (tries === 31) { throw 'Tried 31 times to find a valid date'; } tries++; } this._setValue(this._dates[i], i); } } this._update(); }; DateTimePicker.prototype.maxDate = function maxDate(_maxDate) { if (arguments.length === 0) { return this._options.maxDate ? this._options.maxDate.clone() : this._options.maxDate; } if (typeof _maxDate === 'boolean' && _maxDate === false) { this._options.maxDate = false; this._update(); return true; } if (typeof _maxDate === 'string') { if (_maxDate === 'now' || _maxDate === 'moment') { _maxDate = this.getMoment(); } } var parsedDate = this._parseInputDate(_maxDate); if (!parsedDate.isValid()) { throw new TypeError('maxDate() Could not parse date parameter: ' + _maxDate); } if (this._options.minDate && parsedDate.isBefore(this._options.minDate)) { throw new TypeError('maxDate() date parameter is before this.options.minDate: ' + parsedDate.format(this.actualFormat)); } this._options.maxDate = parsedDate; for (var i = 0; i < this._dates.length; i++) { if (this._options.useCurrent && !this._options.keepInvalid && this._dates[i].isAfter(_maxDate)) { this._setValue(this._options.maxDate, i); } } if (this._viewDate.isAfter(parsedDate)) { this._viewDate = parsedDate.clone().subtract(this._options.stepping, 'm'); } this._update(); }; DateTimePicker.prototype.minDate = function minDate(_minDate) { if (arguments.length === 0) { return this._options.minDate ? this._options.minDate.clone() : this._options.minDate; } if (typeof _minDate === 'boolean' && _minDate === false) { this._options.minDate = false; this._update(); return true; } if (typeof _minDate === 'string') { if (_minDate === 'now' || _minDate === 'moment') { _minDate = this.getMoment(); } } var parsedDate = this._parseInputDate(_minDate); if (!parsedDate.isValid()) { throw new TypeError('minDate() Could not parse date parameter: ' + _minDate); } if (this._options.maxDate && parsedDate.isAfter(this._options.maxDate)) { throw new TypeError('minDate() date parameter is after this.options.maxDate: ' + parsedDate.format(this.actualFormat)); } this._options.minDate = parsedDate; for (var i = 0; i < this._dates.length; i++) { if (this._options.useCurrent && !this._options.keepInvalid && this._dates[i].isBefore(_minDate)) { this._setValue(this._options.minDate, i); } } if (this._viewDate.isBefore(parsedDate)) { this._viewDate = parsedDate.clone().add(this._options.stepping, 'm'); } this._update(); }; DateTimePicker.prototype.defaultDate = function defaultDate(_defaultDate) { if (arguments.length === 0) { return this._options.defaultDate ? this._options.defaultDate.clone() : this._options.defaultDate; } if (!_defaultDate) { this._options.defaultDate = false; return true; } if (typeof _defaultDate === 'string') { if (_defaultDate === 'now' || _defaultDate === 'moment') { _defaultDate = this.getMoment(); } else { _defaultDate = this.getMoment(_defaultDate); } } var parsedDate = this._parseInputDate(_defaultDate); if (!parsedDate.isValid()) { throw new TypeError('defaultDate() Could not parse date parameter: ' + _defaultDate); } if (!this._isValid(parsedDate)) { throw new TypeError('defaultDate() date passed is invalid according to component setup validations'); } this._options.defaultDate = parsedDate; if (this._options.defaultDate && this._options.inline || this.input !== undefined && this.input.val().trim() === '') { this._setValue(this._options.defaultDate, 0); } }; DateTimePicker.prototype.locale = function locale(_locale) { if (arguments.length === 0) { return this._options.locale; } if (!moment.localeData(_locale)) { throw new TypeError('locale() locale ' + _locale + ' is not loaded from moment locales!'); } for (var i = 0; i < this._dates.length; i++) { this._dates[i].locale(this._options.locale); } this._viewDate.locale(this._options.locale); if (this.actualFormat) { this._initFormatting(); // reinitialize formatting } if (this.widget) { this.hide(); this.show(); } }; DateTimePicker.prototype.stepping = function stepping(_stepping) { if (arguments.length === 0) { return this._options.stepping; } _stepping = parseInt(_stepping, 10); if (isNaN(_stepping) || _stepping < 1) { _stepping = 1; } this._options.stepping = _stepping; }; DateTimePicker.prototype.useCurrent = function useCurrent(_useCurrent) { var useCurrentOptions = ['year', 'month', 'day', 'hour', 'minute']; if (arguments.length === 0) { return this._options.useCurrent; } if (typeof _useCurrent !== 'boolean' && typeof _useCurrent !== 'string') { throw new TypeError('useCurrent() expects a boolean or string parameter'); } if (typeof _useCurrent === 'string' && useCurrentOptions.indexOf(_useCurrent.toLowerCase()) === -1) { throw new TypeError('useCurrent() expects a string parameter of ' + useCurrentOptions.join(', ')); } this._options.useCurrent = _useCurrent; }; DateTimePicker.prototype.collapse = function collapse(_collapse) { if (arguments.length === 0) { return this._options.collapse; } if (typeof _collapse !== 'boolean') { throw new TypeError('collapse() expects a boolean parameter'); } if (this._options.collapse === _collapse) { return true; } this._options.collapse = _collapse; if (this.widget) { this.hide(); this.show(); } }; DateTimePicker.prototype.icons = function icons(_icons) { if (arguments.length === 0) { return $.extend({}, this._options.icons); } if (!(_icons instanceof Object)) { throw new TypeError('icons() expects parameter to be an Object'); } $.extend(this._options.icons, _icons); if (this.widget) { this.hide(); this.show(); } }; DateTimePicker.prototype.tooltips = function tooltips(_tooltips) { if (arguments.length === 0) { return $.extend({}, this._options.tooltips); } if (!(_tooltips instanceof Object)) { throw new TypeError('tooltips() expects parameter to be an Object'); } $.extend(this._options.tooltips, _tooltips); if (this.widget) { this.hide(); this.show(); } }; DateTimePicker.prototype.useStrict = function useStrict(_useStrict) { if (arguments.length === 0) { return this._options.useStrict; } if (typeof _useStrict !== 'boolean') { throw new TypeError('useStrict() expects a boolean parameter'); } this._options.useStrict = _useStrict; }; DateTimePicker.prototype.sideBySide = function sideBySide(_sideBySide) { if (arguments.length === 0) { return this._options.sideBySide; } if (typeof _sideBySide !== 'boolean') { throw new TypeError('sideBySide() expects a boolean parameter'); } this._options.sideBySide = _sideBySide; if (this.widget) { this.hide(); this.show(); } }; DateTimePicker.prototype.viewMode = function viewMode(_viewMode) { if (arguments.length === 0) { return this._options.viewMode; } if (typeof _viewMode !== 'string') { throw new TypeError('viewMode() expects a string parameter'); } if (DateTimePicker.ViewModes.indexOf(_viewMode) === -1) { throw new TypeError('viewMode() parameter must be one of (' + DateTimePicker.ViewModes.join(', ') + ') value'); } this._options.viewMode = _viewMode; this.currentViewMode = Math.max(DateTimePicker.ViewModes.indexOf(_viewMode) - 1, DateTimePicker.MinViewModeNumber); this._showMode(); }; DateTimePicker.prototype.calendarWeeks = function calendarWeeks(_calendarWeeks) { if (arguments.length === 0) { return this._options.calendarWeeks; } if (typeof _calendarWeeks !== 'boolean') { throw new TypeError('calendarWeeks() expects parameter to be a boolean value'); } this._options.calendarWeeks = _calendarWeeks; this._update(); }; DateTimePicker.prototype.buttons = function buttons(_buttons) { if (arguments.length === 0) { return $.extend({}, this._options.buttons); } if (!(_buttons instanceof Object)) { throw new TypeError('buttons() expects parameter to be an Object'); } $.extend(this._options.buttons, _buttons); if (typeof this._options.buttons.showToday !== 'boolean') { throw new TypeError('buttons.showToday expects a boolean parameter'); } if (typeof this._options.buttons.showClear !== 'boolean') { throw new TypeError('buttons.showClear expects a boolean parameter'); } if (typeof this._options.buttons.showClose !== 'boolean') { throw new TypeError('buttons.showClose expects a boolean parameter'); } if (this.widget) { this.hide(); this.show(); } }; DateTimePicker.prototype.keepOpen = function keepOpen(_keepOpen) { if (arguments.length === 0) { return this._options.keepOpen; } if (typeof _keepOpen !== 'boolean') { throw new TypeError('keepOpen() expects a boolean parameter'); } this._options.keepOpen = _keepOpen; }; DateTimePicker.prototype.focusOnShow = function focusOnShow(_focusOnShow) { if (arguments.length === 0) { return this._options.focusOnShow; } if (typeof _focusOnShow !== 'boolean') { throw new TypeError('focusOnShow() expects a boolean parameter'); } this._options.focusOnShow = _focusOnShow; }; DateTimePicker.prototype.inline = function inline(_inline) { if (arguments.length === 0) { return this._options.inline; } if (typeof _inline !== 'boolean') { throw new TypeError('inline() expects a boolean parameter'); } this._options.inline = _inline; }; DateTimePicker.prototype.clear = function clear() { this._setValue(null); //todo }; DateTimePicker.prototype.keyBinds = function keyBinds(_keyBinds) { if (arguments.length === 0) { return this._options.keyBinds; } this._options.keyBinds = _keyBinds; }; DateTimePicker.prototype.debug = function debug(_debug) { if (typeof _debug !== 'boolean') { throw new TypeError('debug() expects a boolean parameter'); } this._options.debug = _debug; }; DateTimePicker.prototype.allowInputToggle = function allowInputToggle(_allowInputToggle) { if (arguments.length === 0) { return this._options.allowInputToggle; } if (typeof _allowInputToggle !== 'boolean') { throw new TypeError('allowInputToggle() expects a boolean parameter'); } this._options.allowInputToggle = _allowInputToggle; }; DateTimePicker.prototype.keepInvalid = function keepInvalid(_keepInvalid) { if (arguments.length === 0) { return this._options.keepInvalid; } if (typeof _keepInvalid !== 'boolean') { throw new TypeError('keepInvalid() expects a boolean parameter'); } this._options.keepInvalid = _keepInvalid; }; DateTimePicker.prototype.datepickerInput = function datepickerInput(_datepickerInput) { if (arguments.length === 0) { return this._options.datepickerInput; } if (typeof _datepickerInput !== 'string') { throw new TypeError('datepickerInput() expects a string parameter'); } this._options.datepickerInput = _datepickerInput; }; DateTimePicker.prototype.parseInputDate = function parseInputDate(_parseInputDate2) { if (arguments.length === 0) { return this._options.parseInputDate; } if (typeof _parseInputDate2 !== 'function') { throw new TypeError('parseInputDate() should be as function'); } this._options.parseInputDate = _parseInputDate2; }; DateTimePicker.prototype.disabledTimeIntervals = function disabledTimeIntervals(_disabledTimeIntervals) { if (arguments.length === 0) { return this._options.disabledTimeIntervals ? $.extend({}, this._options.disabledTimeIntervals) : this._options.disabledTimeIntervals; } if (!_disabledTimeIntervals) { this._options.disabledTimeIntervals = false; this._update(); return true; } if (!(_disabledTimeIntervals instanceof Array)) { throw new TypeError('disabledTimeIntervals() expects an array parameter'); } this._options.disabledTimeIntervals = _disabledTimeIntervals; this._update(); }; DateTimePicker.prototype.disabledHours = function disabledHours(hours) { if (arguments.length === 0) { return this._options.disabledHours ? $.extend({}, this._options.disabledHours) : this._options.disabledHours; } if (!hours) { this._options.disabledHours = false; this._update(); return true; } if (!(hours instanceof Array)) { throw new TypeError('disabledHours() expects an array parameter'); } this._options.disabledHours = this._indexGivenHours(hours); this._options.enabledHours = false; if (this._options.useCurrent && !this._options.keepInvalid) { for (var i = 0; i < this._dates.length; i++) { var tries = 0; while (!this._isValid(this._dates[i], 'h')) { this._dates[i].add(1, 'h'); if (tries === 24) { throw 'Tried 24 times to find a valid date'; } tries++; } this._setValue(this._dates[i], i); } } this._update(); }; DateTimePicker.prototype.enabledHours = function enabledHours(hours) { if (arguments.length === 0) { return this._options.enabledHours ? $.extend({}, this._options.enabledHours) : this._options.enabledHours; } if (!hours) { this._options.enabledHours = false; this._update(); return true; } if (!(hours instanceof Array)) { throw new TypeError('enabledHours() expects an array parameter'); } this._options.enabledHours = this._indexGivenHours(hours); this._options.disabledHours = false; if (this._options.useCurrent && !this._options.keepInvalid) { for (var i = 0; i < this._dates.length; i++) { var tries = 0; while (!this._isValid(this._dates[i], 'h')) { this._dates[i].add(1, 'h'); if (tries === 24) { throw 'Tried 24 times to find a valid date'; } tries++; } this._setValue(this._dates[i], i); } } this._update(); }; DateTimePicker.prototype.viewDate = function viewDate(newDate) { if (arguments.length === 0) { return this._viewDate.clone(); } if (!newDate) { this._viewDate = (this._dates[0] || this.getMoment()).clone(); return true; } if (typeof newDate !== 'string' && !moment.isMoment(newDate) && !(newDate instanceof Date)) { throw new TypeError('viewDate() parameter must be one of [string, moment or Date]'); } this._viewDate = this._parseInputDate(newDate); this._viewUpdate(); }; DateTimePicker.prototype.allowMultidate = function allowMultidate(_allowMultidate) { if (typeof _allowMultidate !== 'boolean') { throw new TypeError('allowMultidate() expects a boolean parameter'); } this._options.allowMultidate = _allowMultidate; }; DateTimePicker.prototype.multidateSeparator = function multidateSeparator(_multidateSeparator) { if (arguments.length === 0) { return this._options.multidateSeparator; } if (typeof _multidateSeparator !== 'string' || _multidateSeparator.length > 1) { throw new TypeError('multidateSeparator expects a single character string parameter'); } this._options.multidateSeparator = _multidateSeparator; }; _createClass(DateTimePicker, null, [{ key: 'NAME', get: function get() { return NAME; } /** * @return {string} */ }, { key: 'VERSION', get: function get() { return VERSION; } /** * @return {string} */ }, { key: 'DATA_KEY', get: function get() { return DATA_KEY; } /** * @return {string} */ }, { key: 'EVENT_KEY', get: function get() { return EVENT_KEY; } /** * @return {string} */ }, { key: 'DATA_API_KEY', get: function get() { return DATA_API_KEY; } }, { key: 'DatePickerModes', get: function get() { return DatePickerModes; } }, { key: 'ViewModes', get: function get() { return ViewModes; } /** * @return {number} */ }, { key: 'MinViewModeNumber', get: function get() { return MinViewModeNumber; } }, { key: 'Event', get: function get() { return Event; } }, { key: 'Selector', get: function get() { return Selector; } }, { key: 'Default', get: function get() { return Default; } }, { key: 'ClassName', get: function get() { return ClassName; } }]); return DateTimePicker; }(); return DateTimePicker; }(jQuery, moment); //noinspection JSUnusedGlobalSymbols /* global DateTimePicker */ var TempusDominusBootstrap4 = function ($) { // eslint-disable-line no-unused-vars // ReSharper disable once InconsistentNaming var JQUERY_NO_CONFLICT = $.fn[DateTimePicker.NAME], verticalModes = ['top', 'bottom', 'auto'], horizontalModes = ['left', 'right', 'auto'], toolbarPlacements = ['default', 'top', 'bottom'], getSelectorFromElement = function getSelectorFromElement($element) { var selector = $element.data('target'), $selector = void 0; if (!selector) { selector = $element.attr('href') || ''; selector = /^#[a-z]/i.test(selector) ? selector : null; } $selector = $(selector); if ($selector.length === 0) { return $selector; } if (!$selector.data(DateTimePicker.DATA_KEY)) { $.extend({}, $selector.data(), $(this).data()); } return $selector; }; // ReSharper disable once InconsistentNaming var TempusDominusBootstrap4 = function (_DateTimePicker) { _inherits(TempusDominusBootstrap4, _DateTimePicker); function TempusDominusBootstrap4(element, options) { _classCallCheck(this, TempusDominusBootstrap4); var _this = _possibleConstructorReturn(this, _DateTimePicker.call(this, element, options)); _this._init(); return _this; } TempusDominusBootstrap4.prototype._init = function _init() { if (this._element.hasClass('input-group')) { // in case there is more then one 'input-group-addon' Issue #48 var datepickerButton = this._element.find('.datepickerbutton'); if (datepickerButton.length === 0) { this.component = this._element.find('.input-group-addon'); } else { this.component = datepickerButton; } } }; TempusDominusBootstrap4.prototype._getDatePickerTemplate = function _getDatePickerTemplate() { var headTemplate = $('<thead>').append($('<tr>').append($('<th>').addClass('prev').attr('data-action', 'previous').append($('<span>').addClass(this._options.icons.previous))).append($('<th>').addClass('picker-switch').attr('data-action', 'pickerSwitch').attr('colspan', '' + (this._options.calendarWeeks ? '6' : '5'))).append($('<th>').addClass('next').attr('data-action', 'next').append($('<span>').addClass(this._options.icons.next)))), contTemplate = $('<tbody>').append($('<tr>').append($('<td>').attr('colspan', '' + (this._options.calendarWeeks ? '8' : '7')))); return [$('<div>').addClass('datepicker-days').append($('<table>').addClass('table table-sm').append(headTemplate).append($('<tbody>'))), $('<div>').addClass('datepicker-months').append($('<table>').addClass('table-condensed').append(headTemplate.clone()).append(contTemplate.clone())), $('<div>').addClass('datepicker-years').append($('<table>').addClass('table-condensed').append(headTemplate.clone()).append(contTemplate.clone())), $('<div>').addClass('datepicker-decades').append($('<table>').addClass('table-condensed').append(headTemplate.clone()).append(contTemplate.clone()))]; }; TempusDominusBootstrap4.prototype._getTimePickerMainTemplate = function _getTimePickerMainTemplate() { var topRow = $('<tr>'), middleRow = $('<tr>'), bottomRow = $('<tr>'); if (this._isEnabled('h')) { topRow.append($('<td>').append($('<a>').attr({ href: '#', tabindex: '-1', 'title': this._options.tooltips.incrementHour }).addClass('btn').attr('data-action', 'incrementHours').append($('<span>').addClass(this._options.icons.up)))); middleRow.append($('<td>').append($('<span>').addClass('timepicker-hour').attr({ 'data-time-component': 'hours', 'title': this._options.tooltips.pickHour }).attr('data-action', 'showHours'))); bottomRow.append($('<td>').append($('<a>').attr({ href: '#', tabindex: '-1', 'title': this._options.tooltips.decrementHour }).addClass('btn').attr('data-action', 'decrementHours').append($('<span>').addClass(this._options.icons.down)))); } if (this._isEnabled('m')) { if (this._isEnabled('h')) { topRow.append($('<td>').addClass('separator')); middleRow.append($('<td>').addClass('separator').html(':')); bottomRow.append($('<td>').addClass('separator')); } topRow.append($('<td>').append($('<a>').attr({ href: '#', tabindex: '-1', 'title': this._options.tooltips.incrementMinute }).addClass('btn').attr('data-action', 'incrementMinutes').append($('<span>').addClass(this._options.icons.up)))); middleRow.append($('<td>').append($('<span>').addClass('timepicker-minute').attr({ 'data-time-component': 'minutes', 'title': this._options.tooltips.pickMinute }).attr('data-action', 'showMinutes'))); bottomRow.append($('<td>').append($('<a>').attr({ href: '#', tabindex: '-1', 'title': this._options.tooltips.decrementMinute }).addClass('btn').attr('data-action', 'decrementMinutes').append($('<span>').addClass(this._options.icons.down)))); } if (this._isEnabled('s')) { if (this._isEnabled('m')) { topRow.append($('<td>').addClass('separator')); middleRow.append($('<td>').addClass('separator').html(':')); bottomRow.append($('<td>').addClass('separator')); } topRow.append($('<td>').append($('<a>').attr({ href: '#', tabindex: '-1', 'title': this._options.tooltips.incrementSecond }).addClass('btn').attr('data-action', 'incrementSeconds').append($('<span>').addClass(this._options.icons.up)))); middleRow.append($('<td>').append($('<span>').addClass('timepicker-second').attr({ 'data-time-component': 'seconds', 'title': this._options.tooltips.pickSecond }).attr('data-action', 'showSeconds'))); bottomRow.append($('<td>').append($('<a>').attr({ href: '#', tabindex: '-1', 'title': this._options.tooltips.decrementSecond }).addClass('btn').attr('data-action', 'decrementSeconds').append($('<span>').addClass(this._options.icons.down)))); } if (!this.use24Hours) { topRow.append($('<td>').addClass('separator')); middleRow.append($('<td>').append($('<button>').addClass('btn btn-primary').attr({ 'data-action': 'togglePeriod', tabindex: '-1', 'title': this._options.tooltips.togglePeriod }))); bottomRow.append($('<td>').addClass('separator')); } return $('<div>').addClass('timepicker-picker').append($('<table>').addClass('table-condensed').append([topRow, middleRow, bottomRow])); }; TempusDominusBootstrap4.prototype._getTimePickerTemplate = function _getTimePickerTemplate() { var hoursView = $('<div>').addClass('timepicker-hours').append($('<table>').addClass('table-condensed')), minutesView = $('<div>').addClass('timepicker-minutes').append($('<table>').addClass('table-condensed')), secondsView = $('<div>').addClass('timepicker-seconds').append($('<table>').addClass('table-condensed')), ret = [this._getTimePickerMainTemplate()]; if (this._isEnabled('h')) { ret.push(hoursView); } if (this._isEnabled('m')) { ret.push(minutesView); } if (this._isEnabled('s')) { ret.push(secondsView); } return ret; }; TempusDominusBootstrap4.prototype._getToolbar = function _getToolbar() { var row = []; if (this._options.buttons.showToday) { row.push($('<td>').append($('<a>').attr({ 'data-action': 'today', 'title': this._options.tooltips.today }).append($('<span>').addClass(this._options.icons.today)))); } if (!this._options.sideBySide && this._hasDate() && this._hasTime()) { row.push($('<td>').append($('<a>').attr({ 'data-action': 'togglePicker', 'title': this._options.tooltips.selectTime }).append($('<span>').addClass(this._options.icons.time)))); } if (this._options.buttons.showClear) { row.push($('<td>').append($('<a>').attr({ 'data-action': 'clear', 'title': this._options.tooltips.clear }).append($('<span>').addClass(this._options.icons.clear)))); } if (this._options.buttons.showClose) { row.push($('<td>').append($('<a>').attr({ 'data-action': 'close', 'title': this._options.tooltips.close }).append($('<span>').addClass(this._options.icons.close)))); } return row.length === 0 ? '' : $('<table>').addClass('table-condensed').append($('<tbody>').append($('<tr>').append(row))); }; TempusDominusBootstrap4.prototype._getTemplate = function _getTemplate() { var template = $('<div>').addClass('bootstrap-datetimepicker-widget dropdown-menu'), dateView = $('<div>').addClass('datepicker').append(this._getDatePickerTemplate()), timeView = $('<div>').addClass('timepicker').append(this._getTimePickerTemplate()), content = $('<ul>').addClass('list-unstyled'), toolbar = $('<li>').addClass('picker-switch' + (this._options.collapse ? ' accordion-toggle' : '')).append(this._getToolbar()); if (this._options.inline) { template.removeClass('dropdown-menu'); } if (this.use24Hours) { template.addClass('usetwentyfour'); } if (this._isEnabled('s') && !this.use24Hours) { template.addClass('wider'); } if (this._options.sideBySide && this._hasDate() && this._hasTime()) { template.addClass('timepicker-sbs'); if (this._options.toolbarPlacement === 'top') { template.append(toolbar); } template.append($('<div>').addClass('row').append(dateView.addClass('col-md-6')).append(timeView.addClass('col-md-6'))); if (this._options.toolbarPlacement === 'bottom' || this._options.toolbarPlacement === 'default') { template.append(toolbar); } return template; } if (this._options.toolbarPlacement === 'top') { content.append(toolbar); } if (this._hasDate()) { content.append($('<li>').addClass(this._options.collapse && this._hasTime() ? 'collapse' : '').addClass(this._options.collapse && this._hasTime() && this._options.viewMode === 'time' ? '' : 'show').append(dateView)); } if (this._options.toolbarPlacement === 'default') { content.append(toolbar); } if (this._hasTime()) { content.append($('<li>').addClass(this._options.collapse && this._hasDate() ? 'collapse' : '').addClass(this._options.collapse && this._hasDate() && this._options.viewMode === 'time' ? 'show' : '').append(timeView)); } if (this._options.toolbarPlacement === 'bottom') { content.append(toolbar); } return template.append(content); }; TempusDominusBootstrap4.prototype._place = function _place(e) { var self = e && e.data && e.data.picker || this, vertical = self._options.widgetPositioning.vertical, horizontal = self._options.widgetPositioning.horizontal, parent = void 0; var position = (self.component || self._element).position(), offset = (self.component || self._element).offset(); if (self._options.widgetParent) { parent = self._options.widgetParent.append(self.widget); } else if (self._element.is('input')) { parent = self._element.after(self.widget).parent(); } else if (self._options.inline) { parent = self._element.append(self.widget); return; } else { parent = self._element; self._element.children().first().after(self.widget); } // Top and bottom logic if (vertical === 'auto') { //noinspection JSValidateTypes if (offset.top + self.widget.height() * 1.5 >= $(window).height() + $(window).scrollTop() && self.widget.height() + self._element.outerHeight() < offset.top) { vertical = 'top'; } else { vertical = 'bottom'; } } // Left and right logic if (horizontal === 'auto') { if (parent.width() < offset.left + self.widget.outerWidth() / 2 && offset.left + self.widget.outerWidth() > $(window).width()) { horizontal = 'right'; } else { horizontal = 'left'; } } if (vertical === 'top') { self.widget.addClass('top').removeClass('bottom'); } else { self.widget.addClass('bottom').removeClass('top'); } if (horizontal === 'right') { self.widget.addClass('float-right'); } else { self.widget.removeClass('float-right'); } // find the first parent element that has a relative css positioning if (parent.css('position') !== 'relative') { parent = parent.parents().filter(function () { return $(this).css('position') === 'relative'; }).first(); } if (parent.length === 0) { throw new Error('datetimepicker component should be placed within a relative positioned container'); } self.widget.css({ top: vertical === 'top' ? 'auto' : position.top + self._element.outerHeight() + 'px', bottom: vertical === 'top' ? parent.outerHeight() - (parent === self._element ? 0 : position.top) + 'px' : 'auto', left: horizontal === 'left' ? (parent === self._element ? 0 : position.left) + 'px' : 'auto', right: horizontal === 'left' ? 'auto' : parent.outerWidth() - self._element.outerWidth() - (parent === self._element ? 0 : position.left) + 'px' }); }; TempusDominusBootstrap4.prototype._fillDow = function _fillDow() { var row = $('<tr>'), currentDate = this._viewDate.clone().startOf('w').startOf('d'); if (this._options.calendarWeeks === true) { row.append($('<th>').addClass('cw').text('#')); } while (currentDate.isBefore(this._viewDate.clone().endOf('w'))) { row.append($('<th>').addClass('dow').text(currentDate.format('dd'))); currentDate.add(1, 'd'); } this.widget.find('.datepicker-days thead').append(row); }; TempusDominusBootstrap4.prototype._fillMonths = function _fillMonths() { var spans = [], monthsShort = this._viewDate.clone().startOf('y').startOf('d'); while (monthsShort.isSame(this._viewDate, 'y')) { spans.push($('<span>').attr('data-action', 'selectMonth').addClass('month').text(monthsShort.format('MMM'))); monthsShort.add(1, 'M'); } this.widget.find('.datepicker-months td').empty().append(spans); }; TempusDominusBootstrap4.prototype._updateMonths = function _updateMonths() { var monthsView = this.widget.find('.datepicker-months'), monthsViewHeader = monthsView.find('th'), months = monthsView.find('tbody').find('span'), self = this; monthsViewHeader.eq(0).find('span').attr('title', this._options.tooltips.prevYear); monthsViewHeader.eq(1).attr('title', this._options.tooltips.selectYear); monthsViewHeader.eq(2).find('span').attr('title', this._options.tooltips.nextYear); monthsView.find('.disabled').removeClass('disabled'); if (!this._isValid(this._viewDate.clone().subtract(1, 'y'), 'y')) { monthsViewHeader.eq(0).addClass('disabled'); } monthsViewHeader.eq(1).text(this._viewDate.year()); if (!this._isValid(this._viewDate.clone().add(1, 'y'), 'y')) { monthsViewHeader.eq(2).addClass('disabled'); } months.removeClass('active'); if (this._getLastPickedDate().isSame(this._viewDate, 'y') && !this.unset) { months.eq(this._getLastPickedDate().month()).addClass('active'); } months.each(function (index) { if (!self._isValid(self._viewDate.clone().month(index), 'M')) { $(this).addClass('disabled'); } }); }; TempusDominusBootstrap4.prototype._getStartEndYear = function _getStartEndYear(factor, year) { var step = factor / 10, startYear = Math.floor(year / factor) * factor, endYear = startYear + step * 9, focusValue = Math.floor(year / step) * step; return [startYear, endYear, focusValue]; }; TempusDominusBootstrap4.prototype._updateYears = function _updateYears() { var yearsView = this.widget.find('.datepicker-years'), yearsViewHeader = yearsView.find('th'), yearCaps = this._getStartEndYear(10, this._viewDate.year()), startYear = this._viewDate.clone().year(yearCaps[0]), endYear = this._viewDate.clone().year(yearCaps[1]); var html = ''; yearsViewHeader.eq(0).find('span').attr('title', this._options.tooltips.prevDecade); yearsViewHeader.eq(1).attr('title', this._options.tooltips.selectDecade); yearsViewHeader.eq(2).find('span').attr('title', this._options.tooltips.nextDecade); yearsView.find('.disabled').removeClass('disabled'); if (this._options.minDate && this._options.minDate.isAfter(startYear, 'y')) { yearsViewHeader.eq(0).addClass('disabled'); } yearsViewHeader.eq(1).text(startYear.year() + '-' + endYear.year()); if (this._options.maxDate && this._options.maxDate.isBefore(endYear, 'y')) { yearsViewHeader.eq(2).addClass('disabled'); } html += '<span data-action="selectYear" class="year old">' + (startYear.year() - 1) + '</span>'; while (!startYear.isAfter(endYear, 'y')) { html += '<span data-action="selectYear" class="year' + (startYear.isSame(this._getLastPickedDate(), 'y') && !this.unset ? ' active' : '') + (!this._isValid(startYear, 'y') ? ' disabled' : '') + '">' + startYear.year() + '</span>'; startYear.add(1, 'y'); } html += '<span data-action="selectYear" class="year old">' + startYear.year() + '</span>'; yearsView.find('td').html(html); }; TempusDominusBootstrap4.prototype._updateDecades = function _updateDecades() { var decadesView = this.widget.find('.datepicker-decades'), decadesViewHeader = decadesView.find('th'), yearCaps = this._getStartEndYear(100, this._viewDate.year()), startDecade = this._viewDate.clone().year(yearCaps[0]), endDecade = this._viewDate.clone().year(yearCaps[1]); var minDateDecade = false, maxDateDecade = false, endDecadeYear = void 0, html = ''; decadesViewHeader.eq(0).find('span').attr('title', this._options.tooltips.prevCentury); decadesViewHeader.eq(2).find('span').attr('title', this._options.tooltips.nextCentury); decadesView.find('.disabled').removeClass('disabled'); if (startDecade.year() === 0 || this._options.minDate && this._options.minDate.isAfter(startDecade, 'y')) { decadesViewHeader.eq(0).addClass('disabled'); } decadesViewHeader.eq(1).text(startDecade.year() + '-' + endDecade.year()); if (this._options.maxDate && this._options.maxDate.isBefore(endDecade, 'y')) { decadesViewHeader.eq(2).addClass('disabled'); } if (startDecade.year() - 10 < 0) { html += '<span>&nbsp;</span>'; } else { html += '<span data-action="selectDecade" class="decade old" data-selection="' + (startDecade.year() + 6) + '">' + (startDecade.year() - 10) + '</span>'; } while (!startDecade.isAfter(endDecade, 'y')) { endDecadeYear = startDecade.year() + 11; minDateDecade = this._options.minDate && this._options.minDate.isAfter(startDecade, 'y') && this._options.minDate.year() <= endDecadeYear; maxDateDecade = this._options.maxDate && this._options.maxDate.isAfter(startDecade, 'y') && this._options.maxDate.year() <= endDecadeYear; html += '<span data-action="selectDecade" class="decade' + (this._getLastPickedDate().isAfter(startDecade) && this._getLastPickedDate().year() <= endDecadeYear ? ' active' : '') + (!this._isValid(startDecade, 'y') && !minDateDecade && !maxDateDecade ? ' disabled' : '') + '" data-selection="' + (startDecade.year() + 6) + '">' + startDecade.year() + '</span>'; startDecade.add(10, 'y'); } html += '<span data-action="selectDecade" class="decade old" data-selection="' + (startDecade.year() + 6) + '">' + startDecade.year() + '</span>'; decadesView.find('td').html(html); }; TempusDominusBootstrap4.prototype._fillDate = function _fillDate() { var daysView = this.widget.find('.datepicker-days'), daysViewHeader = daysView.find('th'), html = []; var currentDate = void 0, row = void 0, clsName = void 0, i = void 0; if (!this._hasDate()) { return; } daysViewHeader.eq(0).find('span').attr('title', this._options.tooltips.prevMonth); daysViewHeader.eq(1).attr('title', this._options.tooltips.selectMonth); daysViewHeader.eq(2).find('span').attr('title', this._options.tooltips.nextMonth); daysView.find('.disabled').removeClass('disabled'); daysViewHeader.eq(1).text(this._viewDate.format(this._options.dayViewHeaderFormat)); if (!this._isValid(this._viewDate.clone().subtract(1, 'M'), 'M')) { daysViewHeader.eq(0).addClass('disabled'); } if (!this._isValid(this._viewDate.clone().add(1, 'M'), 'M')) { daysViewHeader.eq(2).addClass('disabled'); } currentDate = this._viewDate.clone().startOf('M').startOf('w').startOf('d'); for (i = 0; i < 42; i++) { //always display 42 days (should show 6 weeks) if (currentDate.weekday() === 0) { row = $('<tr>'); if (this._options.calendarWeeks) { row.append('<td class="cw">' + currentDate.week() + '</td>'); } html.push(row); } clsName = ''; if (currentDate.isBefore(this._viewDate, 'M')) { clsName += ' old'; } if (currentDate.isAfter(this._viewDate, 'M')) { clsName += ' new'; } if (this._options.allowMultidate) { var index = this._datesFormatted.indexOf(currentDate.format('YYYY-MM-DD')); if (index !== -1) { if (currentDate.isSame(this._datesFormatted[index], 'd') && !this.unset) { clsName += ' active'; } } } else { if (currentDate.isSame(this._getLastPickedDate(), 'd') && !this.unset) { clsName += ' active'; } } if (!this._isValid(currentDate, 'd')) { clsName += ' disabled'; } if (currentDate.isSame(this.getMoment(), 'd')) { clsName += ' today'; } if (currentDate.day() === 0 || currentDate.day() === 6) { clsName += ' weekend'; } row.append('<td data-action="selectDay" data-day="' + currentDate.format('L') + '" class="day' + clsName + '">' + currentDate.date() + '</td>'); currentDate.add(1, 'd'); } daysView.find('tbody').empty().append(html); this._updateMonths(); this._updateYears(); this._updateDecades(); }; TempusDominusBootstrap4.prototype._fillHours = function _fillHours() { var table = this.widget.find('.timepicker-hours table'), currentHour = this._viewDate.clone().startOf('d'), html = []; var row = $('<tr>'); if (this._viewDate.hour() > 11 && !this.use24Hours) { currentHour.hour(12); } while (currentHour.isSame(this._viewDate, 'd') && (this.use24Hours || this._viewDate.hour() < 12 && currentHour.hour() < 12 || this._viewDate.hour() > 11)) { if (currentHour.hour() % 4 === 0) { row = $('<tr>'); html.push(row); } row.append('<td data-action="selectHour" class="hour' + (!this._isValid(currentHour, 'h') ? ' disabled' : '') + '">' + currentHour.format(this.use24Hours ? 'HH' : 'hh') + '</td>'); currentHour.add(1, 'h'); } table.empty().append(html); }; TempusDominusBootstrap4.prototype._fillMinutes = function _fillMinutes() { var table = this.widget.find('.timepicker-minutes table'), currentMinute = this._viewDate.clone().startOf('h'), html = [], step = this._options.stepping === 1 ? 5 : this._options.stepping; var row = $('<tr>'); while (this._viewDate.isSame(currentMinute, 'h')) { if (currentMinute.minute() % (step * 4) === 0) { row = $('<tr>'); html.push(row); } row.append('<td data-action="selectMinute" class="minute' + (!this._isValid(currentMinute, 'm') ? ' disabled' : '') + '">' + currentMinute.format('mm') + '</td>'); currentMinute.add(step, 'm'); } table.empty().append(html); }; TempusDominusBootstrap4.prototype._fillSeconds = function _fillSeconds() { var table = this.widget.find('.timepicker-seconds table'), currentSecond = this._viewDate.clone().startOf('m'), html = []; var row = $('<tr>'); while (this._viewDate.isSame(currentSecond, 'm')) { if (currentSecond.second() % 20 === 0) { row = $('<tr>'); html.push(row); } row.append('<td data-action="selectSecond" class="second' + (!this._isValid(currentSecond, 's') ? ' disabled' : '') + '">' + currentSecond.format('ss') + '</td>'); currentSecond.add(5, 's'); } table.empty().append(html); }; TempusDominusBootstrap4.prototype._fillTime = function _fillTime() { var toggle = void 0, newDate = void 0; var timeComponents = this.widget.find('.timepicker span[data-time-component]'); if (!this.use24Hours) { toggle = this.widget.find('.timepicker [data-action=togglePeriod]'); newDate = this._getLastPickedDate().clone().add(this._getLastPickedDate().hours() >= 12 ? -12 : 12, 'h'); toggle.text(this._getLastPickedDate().format('A')); if (this._isValid(newDate, 'h')) { toggle.removeClass('disabled'); } else { toggle.addClass('disabled'); } } timeComponents.filter('[data-time-component=hours]').text(this._getLastPickedDate().format('' + (this.use24Hours ? 'HH' : 'hh'))); timeComponents.filter('[data-time-component=minutes]').text(this._getLastPickedDate().format('mm')); timeComponents.filter('[data-time-component=seconds]').text(this._getLastPickedDate().format('ss')); this._fillHours(); this._fillMinutes(); this._fillSeconds(); }; TempusDominusBootstrap4.prototype._doAction = function _doAction(e, action) { var lastPicked = this._getLastPickedDate(); if ($(e.currentTarget).is('.disabled')) { return false; } action = action || $(e.currentTarget).data('action'); switch (action) { case 'next': { var navFnc = DateTimePicker.DatePickerModes[this.currentViewMode].NAV_FUNCTION; this._viewDate.add(DateTimePicker.DatePickerModes[this.currentViewMode].NAV_STEP, navFnc); this._fillDate(); this._viewUpdate(navFnc); break; } case 'previous': { var _navFnc = DateTimePicker.DatePickerModes[this.currentViewMode].NAV_FUNCTION; this._viewDate.subtract(DateTimePicker.DatePickerModes[this.currentViewMode].NAV_STEP, _navFnc); this._fillDate(); this._viewUpdate(_navFnc); break; } case 'pickerSwitch': this._showMode(1); break; case 'selectMonth': { var month = $(e.target).closest('tbody').find('span').index($(e.target)); this._viewDate.month(month); if (this.currentViewMode === DateTimePicker.MinViewModeNumber) { this._setValue(lastPicked.clone().year(this._viewDate.year()).month(this._viewDate.month()), this._getLastPickedDateIndex()); if (!this._options.inline) { this.hide(); } } else { this._showMode(-1); this._fillDate(); } this._viewUpdate('M'); break; } case 'selectYear': { var year = parseInt($(e.target).text(), 10) || 0; this._viewDate.year(year); if (this.currentViewMode === DateTimePicker.MinViewModeNumber) { this._setValue(lastPicked.clone().year(this._viewDate.year()), this._getLastPickedDateIndex()); if (!this._options.inline) { this.hide(); } } else { this._showMode(-1); this._fillDate(); } this._viewUpdate('YYYY'); break; } case 'selectDecade': { var _year = parseInt($(e.target).data('selection'), 10) || 0; this._viewDate.year(_year); if (this.currentViewMode === DateTimePicker.MinViewModeNumber) { this._setValue(lastPicked.clone().year(this._viewDate.year()), this._getLastPickedDateIndex()); if (!this._options.inline) { this.hide(); } } else { this._showMode(-1); this._fillDate(); } this._viewUpdate('YYYY'); break; } case 'selectDay': { var day = this._viewDate.clone(); if ($(e.target).is('.old')) { day.subtract(1, 'M'); } if ($(e.target).is('.new')) { day.add(1, 'M'); } this._setValue(day.date(parseInt($(e.target).text(), 10)), this._getLastPickedDateIndex()); if (!this._hasTime() && !this._options.keepOpen && !this._options.inline) { this.hide(); } break; } case 'incrementHours': { var newDate = lastPicked.clone().add(1, 'h'); if (this._isValid(newDate, 'h')) { this._setValue(newDate, this._getLastPickedDateIndex()); } break; } case 'incrementMinutes': { var _newDate = lastPicked.clone().add(this._options.stepping, 'm'); if (this._isValid(_newDate, 'm')) { this._setValue(_newDate, this._getLastPickedDateIndex()); } break; } case 'incrementSeconds': { var _newDate2 = lastPicked.clone().add(1, 's'); if (this._isValid(_newDate2, 's')) { this._setValue(_newDate2, this._getLastPickedDateIndex()); } break; } case 'decrementHours': { var _newDate3 = lastPicked.clone().subtract(1, 'h'); if (this._isValid(_newDate3, 'h')) { this._setValue(_newDate3, this._getLastPickedDateIndex()); } break; } case 'decrementMinutes': { var _newDate4 = lastPicked.clone().subtract(this._options.stepping, 'm'); if (this._isValid(_newDate4, 'm')) { this._setValue(_newDate4, this._getLastPickedDateIndex()); } break; } case 'decrementSeconds': { var _newDate5 = lastPicked.clone().subtract(1, 's'); if (this._isValid(_newDate5, 's')) { this._setValue(_newDate5, this._getLastPickedDateIndex()); } break; } case 'togglePeriod': { this._setValue(lastPicked.clone().add(lastPicked.hours() >= 12 ? -12 : 12, 'h'), this._getLastPickedDateIndex()); break; } case 'togglePicker': { var $this = $(e.target), $link = $this.closest('a'), $parent = $this.closest('ul'), expanded = $parent.find('.show'), closed = $parent.find('.collapse:not(.show)'), $span = $this.is('span') ? $this : $this.find('span'); var collapseData = void 0; if (expanded && expanded.length) { collapseData = expanded.data('collapse'); if (collapseData && collapseData.transitioning) { return true; } if (expanded.collapse) { // if collapse plugin is available through bootstrap.js then use it expanded.collapse('hide'); closed.collapse('show'); } else { // otherwise just toggle in class on the two views expanded.removeClass('show'); closed.addClass('show'); } $span.toggleClass(this._options.icons.time + ' ' + this._options.icons.date); if ($span.hasClass(this._options.icons.date)) { $link.attr('title', this._options.tooltips.selectDate); } else { $link.attr('title', this._options.tooltips.selectTime); } } } break; case 'showPicker': this.widget.find('.timepicker > div:not(.timepicker-picker)').hide(); this.widget.find('.timepicker .timepicker-picker').show(); break; case 'showHours': this.widget.find('.timepicker .timepicker-picker').hide(); this.widget.find('.timepicker .timepicker-hours').show(); break; case 'showMinutes': this.widget.find('.timepicker .timepicker-picker').hide(); this.widget.find('.timepicker .timepicker-minutes').show(); break; case 'showSeconds': this.widget.find('.timepicker .timepicker-picker').hide(); this.widget.find('.timepicker .timepicker-seconds').show(); break; case 'selectHour': { var hour = parseInt($(e.target).text(), 10); if (!this.use24Hours) { if (lastPicked.hours() >= 12) { if (hour !== 12) { hour += 12; } } else { if (hour === 12) { hour = 0; } } } this._setValue(lastPicked.clone().hours(hour), this._getLastPickedDateIndex()); this._doAction(e, 'showPicker'); break; } case 'selectMinute': this._setValue(lastPicked.clone().minutes(parseInt($(e.target).text(), 10)), this._getLastPickedDateIndex()); this._doAction(e, 'showPicker'); break; case 'selectSecond': this._setValue(lastPicked.clone().seconds(parseInt($(e.target).text(), 10)), this._getLastPickedDateIndex()); this._doAction(e, 'showPicker'); break; case 'clear': this.clear(); break; case 'today': { var todaysDate = this.getMoment(); if (this._isValid(todaysDate, 'd')) { this._setValue(todaysDate, this._getLastPickedDateIndex()); } break; } } return false; }; //public TempusDominusBootstrap4.prototype.hide = function hide() { var transitioning = false; if (!this.widget) { return; } // Ignore event if in the middle of a picker transition this.widget.find('.collapse').each(function () { var collapseData = $(this).data('collapse'); if (collapseData && collapseData.transitioning) { transitioning = true; return false; } return true; }); if (transitioning) { return; } if (this.component && this.component.hasClass('btn')) { this.component.toggleClass('active'); } this.widget.hide(); $(window).off('resize', this._place()); this.widget.off('click', '[data-action]'); this.widget.off('mousedown', false); this.widget.remove(); this.widget = false; this._notifyEvent({ type: DateTimePicker.Event.HIDE, date: this._getLastPickedDate().clone() }); if (this.input !== undefined) { this.input.blur(); } this._viewDate = this._getLastPickedDate().clone(); }; TempusDominusBootstrap4.prototype.show = function show() { var currentMoment = void 0; var useCurrentGranularity = { 'year': function year(m) { return m.month(0).date(1).hours(0).seconds(0).minutes(0); }, 'month': function month(m) { return m.date(1).hours(0).seconds(0).minutes(0); }, 'day': function day(m) { return m.hours(0).seconds(0).minutes(0); }, 'hour': function hour(m) { return m.seconds(0).minutes(0); }, 'minute': function minute(m) { return m.seconds(0); } }; if (this.input !== undefined) { if (this.input.prop('disabled') || !this._options.ignoreReadonly && this.input.prop('readonly') || this.widget) { return; } if (this.input.val() !== undefined && this.input.val().trim().length !== 0) { this._setValue(this._parseInputDate(this.input.val().trim()), 0); } else if (this.unset && this._options.useCurrent) { currentMoment = this.getMoment(); if (typeof this._options.useCurrent === 'string') { currentMoment = useCurrentGranularity[this._options.useCurrent](currentMoment); } this._setValue(currentMoment, 0); } } else if (this.unset && this._options.useCurrent) { currentMoment = this.getMoment(); if (typeof this._options.useCurrent === 'string') { currentMoment = useCurrentGranularity[this._options.useCurrent](currentMoment); } this._setValue(currentMoment, 0); } this.widget = this._getTemplate(); this._fillDow(); this._fillMonths(); this.widget.find('.timepicker-hours').hide(); this.widget.find('.timepicker-minutes').hide(); this.widget.find('.timepicker-seconds').hide(); this._update(); this._showMode(); $(window).on('resize', { picker: this }, this._place); this.widget.on('click', '[data-action]', $.proxy(this._doAction, this)); // this handles clicks on the widget this.widget.on('mousedown', false); if (this.component && this.component.hasClass('btn')) { this.component.toggleClass('active'); } this._place(); this.widget.show(); if (this.input !== undefined && this._options.focusOnShow && !this.input.is(':focus')) { this.input.focus(); } this._notifyEvent({ type: DateTimePicker.Event.SHOW }); }; TempusDominusBootstrap4.prototype.destroy = function destroy() { this.hide(); //todo doc off? this._element.removeData(DateTimePicker.DATA_KEY); this._element.removeData('date'); }; TempusDominusBootstrap4.prototype.disable = function disable() { this.hide(); if (this.component && this.component.hasClass('btn')) { this.component.addClass('disabled'); } if (this.input !== undefined) { this.input.prop('disabled', true); //todo disable this/comp if input is null } }; TempusDominusBootstrap4.prototype.enable = function enable() { if (this.component && this.component.hasClass('btn')) { this.component.removeClass('disabled'); } if (this.input !== undefined) { this.input.prop('disabled', false); //todo enable comp/this if input is null } }; TempusDominusBootstrap4.prototype.toolbarPlacement = function toolbarPlacement(_toolbarPlacement) { if (arguments.length === 0) { return this._options.toolbarPlacement; } if (typeof _toolbarPlacement !== 'string') { throw new TypeError('toolbarPlacement() expects a string parameter'); } if (toolbarPlacements.indexOf(_toolbarPlacement) === -1) { throw new TypeError('toolbarPlacement() parameter must be one of (' + toolbarPlacements.join(', ') + ') value'); } this._options.toolbarPlacement = _toolbarPlacement; if (this.widget) { this.hide(); this.show(); } }; TempusDominusBootstrap4.prototype.widgetPositioning = function widgetPositioning(_widgetPositioning) { if (arguments.length === 0) { return $.extend({}, this._options.widgetPositioning); } if ({}.toString.call(_widgetPositioning) !== '[object Object]') { throw new TypeError('widgetPositioning() expects an object variable'); } if (_widgetPositioning.horizontal) { if (typeof _widgetPositioning.horizontal !== 'string') { throw new TypeError('widgetPositioning() horizontal variable must be a string'); } _widgetPositioning.horizontal = _widgetPositioning.horizontal.toLowerCase(); if (horizontalModes.indexOf(_widgetPositioning.horizontal) === -1) { throw new TypeError('widgetPositioning() expects horizontal parameter to be one of (' + horizontalModes.join(', ') + ')'); } this._options.widgetPositioning.horizontal = _widgetPositioning.horizontal; } if (_widgetPositioning.vertical) { if (typeof _widgetPositioning.vertical !== 'string') { throw new TypeError('widgetPositioning() vertical variable must be a string'); } _widgetPositioning.vertical = _widgetPositioning.vertical.toLowerCase(); if (verticalModes.indexOf(_widgetPositioning.vertical) === -1) { throw new TypeError('widgetPositioning() expects vertical parameter to be one of (' + verticalModes.join(', ') + ')'); } this._options.widgetPositioning.vertical = _widgetPositioning.vertical; } this._update(); }; TempusDominusBootstrap4.prototype.widgetParent = function widgetParent(_widgetParent) { if (arguments.length === 0) { return this._options.widgetParent; } if (typeof _widgetParent === 'string') { _widgetParent = $(_widgetParent); } if (_widgetParent !== null && typeof _widgetParent !== 'string' && !(_widgetParent instanceof $)) { throw new TypeError('widgetParent() expects a string or a jQuery object parameter'); } this._options.widgetParent = _widgetParent; if (this.widget) { this.hide(); this.show(); } }; //static TempusDominusBootstrap4._jQueryHandleThis = function _jQueryHandleThis(me, option, argument) { var data = $(me).data(DateTimePicker.DATA_KEY); if ((typeof option === 'undefined' ? 'undefined' : _typeof(option)) === 'object') { $.extend({}, DateTimePicker.Default, option); } if (!data) { data = new TempusDominusBootstrap4($(me), option); $(me).data(DateTimePicker.DATA_KEY, data); } if (typeof option === 'string') { if (data[option] === undefined) { throw new Error('No method named "' + option + '"'); } if (argument === undefined) { return data[option](); } else { return data[option](argument); } } }; TempusDominusBootstrap4._jQueryInterface = function _jQueryInterface(option, argument) { if (this.length === 1) { return TempusDominusBootstrap4._jQueryHandleThis(this[0], option, argument); } return this.each(function () { TempusDominusBootstrap4._jQueryHandleThis(this, option, argument); }); }; return TempusDominusBootstrap4; }(DateTimePicker); /** * ------------------------------------------------------------------------ * jQuery * ------------------------------------------------------------------------ */ $(document).on(DateTimePicker.Event.CLICK_DATA_API, DateTimePicker.Selector.DATA_TOGGLE, function () { var $target = getSelectorFromElement($(this)); if ($target.length === 0) { return; } TempusDominusBootstrap4._jQueryInterface.call($target, 'toggle'); }).on(DateTimePicker.Event.CHANGE, '.' + DateTimePicker.ClassName.INPUT, function (event) { var $target = getSelectorFromElement($(this)); if ($target.length === 0) { return; } TempusDominusBootstrap4._jQueryInterface.call($target, '_change', event); }).on(DateTimePicker.Event.BLUR, '.' + DateTimePicker.ClassName.INPUT, function (event) { var $target = getSelectorFromElement($(this)), config = $target.data(DateTimePicker.DATA_KEY); if ($target.length === 0) { return; } if (config._options.debug || window.debug) { return; } TempusDominusBootstrap4._jQueryInterface.call($target, 'hide', event); }).on(DateTimePicker.Event.KEYDOWN, '.' + DateTimePicker.ClassName.INPUT, function (event) { var $target = getSelectorFromElement($(this)); if ($target.length === 0) { return; } TempusDominusBootstrap4._jQueryInterface.call($target, '_keydown', event); }).on(DateTimePicker.Event.KEYUP, '.' + DateTimePicker.ClassName.INPUT, function (event) { var $target = getSelectorFromElement($(this)); if ($target.length === 0) { return; } TempusDominusBootstrap4._jQueryInterface.call($target, '_keyup', event); }).on(DateTimePicker.Event.FOCUS, '.' + DateTimePicker.ClassName.INPUT, function (event) { var $target = getSelectorFromElement($(this)), config = $target.data(DateTimePicker.DATA_KEY); if ($target.length === 0) { return; } if (!config._options.allowInputToggle) { return; } TempusDominusBootstrap4._jQueryInterface.call($target, config, event); }); $.fn[DateTimePicker.NAME] = TempusDominusBootstrap4._jQueryInterface; $.fn[DateTimePicker.NAME].Constructor = TempusDominusBootstrap4; $.fn[DateTimePicker.NAME].noConflict = function () { $.fn[DateTimePicker.NAME] = JQUERY_NO_CONFLICT; return TempusDominusBootstrap4._jQueryInterface; }; return TempusDominusBootstrap4; }(jQuery); }();
sashberd/cdnjs
ajax/libs/tempusdominus-bootstrap-4/5.0.0-alpha13/js/tempusdominus-bootstrap-4.js
JavaScript
mit
114,603
/* Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'elementspath', 'si', { eleLabel: 'මුලද්‍රව්‍ය මාර්ගය', eleTitle: '%1 මුල' } );
gmuro/dolibarr
htdocs/includes/ckeditor/ckeditor/_source/plugins/elementspath/lang/si.js
JavaScript
gpl-3.0
291
/* * * (c) 2010-2019 Torstein Honsi * * License: www.highcharts.com/license */ 'use strict'; import H from './Globals.js'; import './Utilities.js'; import './Options.js'; import './Series.js'; var pick = H.pick, seriesType = H.seriesType; /** * Spline series type. * * @private * @class * @name Highcharts.seriesTypes.spline * * @augments Highcarts.Series */ seriesType( 'spline', 'line', /** * A spline series is a special type of line series, where the segments * between the data points are smoothed. * * @sample {highcharts} highcharts/demo/spline-irregular-time/ * Spline chart * @sample {highstock} stock/demo/spline/ * Spline chart * * @extends plotOptions.series * @excluding step * @product highcharts highstock * @optionparent plotOptions.spline */ { }, /** @lends seriesTypes.spline.prototype */ { /** * Get the spline segment from a given point's previous neighbour to the * given point. * * @private * @function Highcharts.seriesTypes.spline#getPointSpline * * @param {Array<Highcharts.Point>} * * @param {Highcharts.Point} point * * @param {number} i * * @return {Highcharts.SVGPathArray} */ getPointSpline: function (points, point, i) { var // 1 means control points midway between points, 2 means 1/3 // from the point, 3 is 1/4 etc smoothing = 1.5, denom = smoothing + 1, plotX = point.plotX, plotY = point.plotY, lastPoint = points[i - 1], nextPoint = points[i + 1], leftContX, leftContY, rightContX, rightContY, ret; function doCurve(otherPoint) { return otherPoint && !otherPoint.isNull && otherPoint.doCurve !== false && !point.isCliff; // #6387, area splines next to null } // Find control points if (doCurve(lastPoint) && doCurve(nextPoint)) { var lastX = lastPoint.plotX, lastY = lastPoint.plotY, nextX = nextPoint.plotX, nextY = nextPoint.plotY, correction = 0; leftContX = (smoothing * plotX + lastX) / denom; leftContY = (smoothing * plotY + lastY) / denom; rightContX = (smoothing * plotX + nextX) / denom; rightContY = (smoothing * plotY + nextY) / denom; // Have the two control points make a straight line through main // point if (rightContX !== leftContX) { // #5016, division by zero correction = ( ((rightContY - leftContY) * (rightContX - plotX)) / (rightContX - leftContX) + plotY - rightContY ); } leftContY += correction; rightContY += correction; // to prevent false extremes, check that control points are // between neighbouring points' y values if (leftContY > lastY && leftContY > plotY) { leftContY = Math.max(lastY, plotY); // mirror of left control point rightContY = 2 * plotY - leftContY; } else if (leftContY < lastY && leftContY < plotY) { leftContY = Math.min(lastY, plotY); rightContY = 2 * plotY - leftContY; } if (rightContY > nextY && rightContY > plotY) { rightContY = Math.max(nextY, plotY); leftContY = 2 * plotY - rightContY; } else if (rightContY < nextY && rightContY < plotY) { rightContY = Math.min(nextY, plotY); leftContY = 2 * plotY - rightContY; } // record for drawing in next point point.rightContX = rightContX; point.rightContY = rightContY; } // Visualize control points for debugging /* if (leftContX) { this.chart.renderer.circle( leftContX + this.chart.plotLeft, leftContY + this.chart.plotTop, 2 ) .attr({ stroke: 'red', 'stroke-width': 2, fill: 'none', zIndex: 9 }) .add(); this.chart.renderer.path(['M', leftContX + this.chart.plotLeft, leftContY + this.chart.plotTop, 'L', plotX + this.chart.plotLeft, plotY + this.chart.plotTop]) .attr({ stroke: 'red', 'stroke-width': 2, zIndex: 9 }) .add(); } if (rightContX) { this.chart.renderer.circle( rightContX + this.chart.plotLeft, rightContY + this.chart.plotTop, 2 ) .attr({ stroke: 'green', 'stroke-width': 2, fill: 'none', zIndex: 9 }) .add(); this.chart.renderer.path(['M', rightContX + this.chart.plotLeft, rightContY + this.chart.plotTop, 'L', plotX + this.chart.plotLeft, plotY + this.chart.plotTop]) .attr({ stroke: 'green', 'stroke-width': 2, zIndex: 9 }) .add(); } // */ ret = [ 'C', pick(lastPoint.rightContX, lastPoint.plotX), pick(lastPoint.rightContY, lastPoint.plotY), pick(leftContX, plotX), pick(leftContY, plotY), plotX, plotY ]; // reset for updating series later lastPoint.rightContX = lastPoint.rightContY = null; return ret; } } ); /** * A `spline` series. If the [type](#series.spline.type) option is * not specified, it is inherited from [chart.type](#chart.type). * * @extends series,plotOptions.spline * @excluding dataParser, dataURL, step * @product highcharts highstock * @apioption series.spline */ /** * An array of data points for the series. For the `spline` series type, * points can be given in the following ways: * * 1. An array of numerical values. In this case, the numerical values will be * interpreted as `y` options. The `x` values will be automatically * calculated, either starting at 0 and incremented by 1, or from * `pointStart` and `pointInterval` given in the series options. If the axis * has categories, these will be used. Example: * ```js * data: [0, 5, 3, 5] * ``` * * 2. An array of arrays with 2 values. In this case, the values correspond to * `x,y`. If the first value is a string, it is applied as the name of the * point, and the `x` value is inferred. * ```js * data: [ * [0, 9], * [1, 2], * [2, 8] * ] * ``` * * 3. An array of objects with named values. The following snippet shows only a * few settings, see the complete options set below. If the total number of * data points exceeds the series' * [turboThreshold](#series.spline.turboThreshold), this option is not * available. * ```js * data: [{ * x: 1, * y: 9, * name: "Point2", * color: "#00FF00" * }, { * x: 1, * y: 0, * name: "Point1", * color: "#FF00FF" * }] * ``` * * @sample {highcharts} highcharts/chart/reflow-true/ * Numerical values * @sample {highcharts} highcharts/series/data-array-of-arrays/ * Arrays of numeric x and y * @sample {highcharts} highcharts/series/data-array-of-arrays-datetime/ * Arrays of datetime x and y * @sample {highcharts} highcharts/series/data-array-of-name-value/ * Arrays of point.name and y * @sample {highcharts} highcharts/series/data-array-of-objects/ * Config objects * * @type {Array<number|Array<(number|string),number>|*>} * @extends series.line.data * @product highcharts highstock * @apioption series.spline.data */
blue-eyed-devil/testCMS
externals/highcharts/es-modules/parts/SplineSeries.js
JavaScript
gpl-3.0
8,806
/** * Copyright (c) 2006-2015, JGraph Ltd * Copyright (c) 2006-2015, Gaudenz Alder */ /** * Class: mxHandle * * Implements a single custom handle for vertices. * * Constructor: mxHandle * * Constructs a new handle for the given state. * * Parameters: * * state - <mxCellState> of the cell to be handled. */ function mxHandle(state, cursor, image) { this.graph = state.view.graph; this.state = state; this.cursor = (cursor != null) ? cursor : this.cursor; this.image = (image != null) ? image : this.image; this.init(); }; /** * Variable: cursor * * Specifies the cursor to be used for this handle. Default is 'default'. */ mxHandle.prototype.cursor = 'default'; /** * Variable: image * * Specifies the <mxImage> to be used to render the handle. Default is null. */ mxHandle.prototype.image = null; /** * Variable: image * * Specifies the <mxImage> to be used to render the handle. Default is null. */ mxHandle.prototype.ignoreGrid = false; /** * Function: getPosition * * Hook for subclassers to return the current position of the handle. */ mxHandle.prototype.getPosition = function(bounds) { }; /** * Function: setPosition * * Hooks for subclassers to update the style in the <state>. */ mxHandle.prototype.setPosition = function(bounds, pt, me) { }; /** * Function: execute * * Hook for subclassers to execute the handle. */ mxHandle.prototype.execute = function() { }; /** * Function: copyStyle * * Sets the cell style with the given name to the corresponding value in <state>. */ mxHandle.prototype.copyStyle = function(key) { this.graph.setCellStyles(key, this.state.style[key], [this.state.cell]); }; /** * Function: processEvent * * Processes the given <mxMouseEvent> and invokes <setPosition>. */ mxHandle.prototype.processEvent = function(me) { var scale = this.graph.view.scale; var tr = this.graph.view.translate; var pt = new mxPoint(me.getGraphX() / scale - tr.x, me.getGraphY() / scale - tr.y); // Center shape on mouse cursor if (this.shape != null && this.shape.bounds != null) { pt.x -= this.shape.bounds.width / scale / 4; pt.y -= this.shape.bounds.height / scale / 4; } // Snaps to grid for the rotated position then applies the rotation for the direction after that var alpha1 = -mxUtils.toRadians(this.getRotation()); var alpha2 = -mxUtils.toRadians(this.getTotalRotation()) - alpha1; pt = this.flipPoint(this.rotatePoint(this.snapPoint(this.rotatePoint(pt, alpha1), this.ignoreGrid || !this.graph.isGridEnabledEvent(me.getEvent())), alpha2)); this.setPosition(this.state.getPaintBounds(), pt, me); this.positionChanged(); this.redraw(); }; /** * Function: positionChanged * * Called after <setPosition> has been called in <processEvent>. This repaints * the state using <mxCellRenderer>. */ mxHandle.prototype.positionChanged = function() { if (this.state.text != null) { this.state.text.apply(this.state); } if (this.state.shape != null) { this.state.shape.apply(this.state); } this.graph.cellRenderer.redraw(this.state, true); }; /** * Function: getRotation * * Returns the rotation defined in the style of the cell. */ mxHandle.prototype.getRotation = function() { if (this.state.shape != null) { return this.state.shape.getRotation(); } return 0; }; /** * Function: getTotalRotation * * Returns the rotation from the style and the rotation from the direction of * the cell. */ mxHandle.prototype.getTotalRotation = function() { if (this.state.shape != null) { return this.state.shape.getShapeRotation(); } return 0; }; /** * Function: init * * Creates and initializes the shapes required for this handle. */ mxHandle.prototype.init = function() { var html = this.isHtmlRequired(); if (this.image != null) { this.shape = new mxImageShape(new mxRectangle(0, 0, this.image.width, this.image.height), this.image.src); this.shape.preserveImageAspect = false; } else { this.shape = this.createShape(html); } this.initShape(html); }; /** * Function: createShape * * Creates and returns the shape for this handle. */ mxHandle.prototype.createShape = function(html) { var bounds = new mxRectangle(0, 0, mxConstants.HANDLE_SIZE, mxConstants.HANDLE_SIZE); return new mxRectangleShape(bounds, mxConstants.HANDLE_FILLCOLOR, mxConstants.HANDLE_STROKECOLOR); }; /** * Function: initShape * * Initializes <shape> and sets its cursor. */ mxHandle.prototype.initShape = function(html) { if (html && this.shape.isHtmlAllowed()) { this.shape.dialect = mxConstants.DIALECT_STRICTHTML; this.shape.init(this.graph.container); } else { this.shape.dialect = (this.graph.dialect != mxConstants.DIALECT_SVG) ? mxConstants.DIALECT_MIXEDHTML : mxConstants.DIALECT_SVG; if (this.cursor != null) { this.shape.init(this.graph.getView().getOverlayPane()); } } mxEvent.redirectMouseEvents(this.shape.node, this.graph, this.state); this.shape.node.style.cursor = this.cursor; }; /** * Function: redraw * * Renders the shape for this handle. */ mxHandle.prototype.redraw = function() { if (this.shape != null && this.state.shape != null) { var pt = this.getPosition(this.state.getPaintBounds()); if (pt != null) { var alpha = mxUtils.toRadians(this.getTotalRotation()); pt = this.rotatePoint(this.flipPoint(pt), alpha); var scale = this.graph.view.scale; var tr = this.graph.view.translate; this.shape.bounds.x = Math.floor((pt.x + tr.x) * scale - this.shape.bounds.width / 2); this.shape.bounds.y = Math.floor((pt.y + tr.y) * scale - this.shape.bounds.height / 2); // Needed to force update of text bounds this.state.unscaledWidth = null; this.shape.redraw(); } } }; /** * Function: isHtmlRequired * * Returns true if this handle should be rendered in HTML. This returns true if * the text node is in the graph container. */ mxHandle.prototype.isHtmlRequired = function() { return this.state.text != null && this.state.text.node.parentNode == this.graph.container; }; /** * Function: rotatePoint * * Rotates the point by the given angle. */ mxHandle.prototype.rotatePoint = function(pt, alpha) { var bounds = this.state.getCellBounds(); var cx = new mxPoint(bounds.getCenterX(), bounds.getCenterY()); var cos = Math.cos(alpha); var sin = Math.sin(alpha); return mxUtils.getRotatedPoint(pt, cos, sin, cx); }; /** * Function: flipPoint * * Flips the given point vertically and/or horizontally. */ mxHandle.prototype.flipPoint = function(pt) { if (this.state.shape != null) { var bounds = this.state.getCellBounds(); if (this.state.shape.flipH) { pt.x = 2 * bounds.x + bounds.width - pt.x; } if (this.state.shape.flipV) { pt.y = 2 * bounds.y + bounds.height - pt.y; } } return pt; }; /** * Function: snapPoint * * Snaps the given point to the grid if ignore is false. This modifies * the given point in-place and also returns it. */ mxHandle.prototype.snapPoint = function(pt, ignore) { if (!ignore) { pt.x = this.graph.snap(pt.x); pt.y = this.graph.snap(pt.y); } return pt; }; /** * Function: setVisible * * Shows or hides this handle. */ mxHandle.prototype.setVisible = function(visible) { if (this.shape != null && this.shape.node != null) { this.shape.node.style.display = (visible) ? '' : 'none'; } }; /** * Function: reset * * Resets the state of this handle by setting its visibility to true. */ mxHandle.prototype.reset = function() { this.setVisible(true); this.state.style = this.graph.getCellStyle(this.state.cell); this.positionChanged(); }; /** * Function: destroy * * Destroys this handle. */ mxHandle.prototype.destroy = function() { if (this.shape != null) { this.shape.destroy(); this.shape = null; } };
kyro46/assMxGraphQuestion
templates/mxgraph/js/handler/mxHandle.js
JavaScript
gpl-3.0
7,788
/* YUI 3.8.0 (build 5744) Copyright 2012 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add('anim-scroll', function (Y, NAME) { /** * Adds support for the <code>scroll</code> property in <code>to</code> * and <code>from</code> attributes. * @module anim * @submodule anim-scroll */ var NUM = Number; //TODO: deprecate for scrollTop/Left properties? Y.Anim.behaviors.scroll = { set: function(anim, att, from, to, elapsed, duration, fn) { var node = anim._node, val = ([ fn(elapsed, NUM(from[0]), NUM(to[0]) - NUM(from[0]), duration), fn(elapsed, NUM(from[1]), NUM(to[1]) - NUM(from[1]), duration) ]); if (val[0]) { node.set('scrollLeft', val[0]); } if (val[1]) { node.set('scrollTop', val[1]); } }, get: function(anim) { var node = anim._node; return [node.get('scrollLeft'), node.get('scrollTop')]; } }; }, '3.8.0', {"requires": ["anim-base"]});
relipse/cworklog
public_html/js/yui/3.8.0/build/anim-scroll/anim-scroll.js
JavaScript
gpl-3.0
1,067
/** * * Spacebrew Library for Javascript * -------------------------------- * * This library was designed to work on front-end (browser) envrionments, and back-end (server) * environments. Please refer to the readme file, the documentation and examples to learn how to * use this library. * * Spacebrew is an open, dynamically re-routable software toolkit for choreographing interactive * spaces. Or, in other words, a simple way to connect interactive things to one another. Learn * more about Spacebrew here: http://docs.spacebrew.cc/ * * To import into your web apps, we recommend using the minimized version of this library. * * Latest Updates: * - added blank "options" attribute to config message - for future use * - caps number of messages sent to 60 per second * - reconnect to spacebrew if connection lost * - enable client apps to extend libs with admin functionality. * - added close method to close Spacebrew connection. * * @author Brett Renfer and Julio Terra from LAB @ Rockwell Group * @filename sb-1.3.0.js * @version 1.3.0 * @date May 7, 2013 * */ /** * Check if Bind method exists in current enviroment. If not, it creates an implementation of * this useful method. */ if (!Function.prototype.bind) { Function.prototype.bind = function (oThis) { if (typeof this !== "function") { // closest thing possible to the ECMAScript 5 internal IsCallable function throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable"); } var aArgs = Array.prototype.slice.call(arguments, 1), fToBind = this, fNOP = function () {}, fBound = function () { return fToBind.apply(this instanceof fNOP ? this : oThis || window, aArgs.concat(Array.prototype.slice.call(arguments))); }; fNOP.prototype = this.prototype; fBound.prototype = new fNOP(); return fBound; }; } /** * @namespace for Spacebrew library */ var Spacebrew = Spacebrew || {}; /** * create placeholder var for WebSocket object, if it does not already exist */ var WebSocket = WebSocket || {}; /** * Check if Running in Browser or Server (Node) Environment * */ // check if window object already exists to determine if running browswer var window = window || undefined; // check if module object already exists to determine if this is a node application var module = module || undefined; // if app is running in a browser, then define the getQueryString method if (window) { if (!window['getQueryString']){ /** * Get parameters from a query string * @param {String} name Name of query string to parse (w/o '?' or '&') * @return {String} value of parameter (or empty string if not found) */ window.getQueryString = function( name ) { if (!window.location) return; name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]"); var regexS = "[\\?&]"+name+"=([^&#]*)"; var regex = new RegExp( regexS ); var results = regex.exec( window.location.href ); if( results == null ) return ""; else return results[1]; } } } // if app is running in a node server environment then package Spacebrew library as a module. // WebSocket module (ws) needs to be saved in a node_modules so that it can be imported. if (!window && module) { WebSocket = require("ws"); module.exports = { Spacebrew: Spacebrew } } /** * Define the Spacebrew Library * */ /** * Spacebrew client! * @constructor * @param {String} server (Optional) Base address of Spacebrew server. This server address is overwritten if server defined in query string; defaults to localhost. * @param {String} name (Optional) Base name of app. Base name is overwritten if "name" is defined in query string; defaults to window.location.href. * @param {String} description (Optional) Base description of app. Description name is overwritten if "description" is defined in query string; * @param {Object} options (Optional) An object that holds the optional parameters described below * port (Optional) Port number for the Spacebrew server * admin (Optional) Flag that identifies when app should register for admin privileges with server * debug (Optional) Debug flag that turns on info and debug messaging (limited use) */ Spacebrew.Client = function( server, name, description, options ){ var options = options || {}; // check if the server variable is an object that holds all config values if (server != undefined) { if (toString.call(server) !== '[object String]') { options.port = server.port || undefined; options.debug = server.debug || false; options.reconnect = server.reconnect || false; description = server.description || undefined; name = server.name || undefined; server = server.server || undefined; } } this.debug = (window.getQueryString('debug') === "true" ? true : (options.debug || false)); this.reconnect = options.reconnect || true; this.reconnect_timer = undefined; this.send_interval = 16; this.send_blocked = false; this.msg = {}; /** * Name of app * @type {String} */ this._name = name || "javascript client #"; if (window) { this._name = (window.getQueryString('name') !== "" ? unescape(window.getQueryString('name')) : this._name); } /** * Description of your app * @type {String} */ this._description = description || "spacebrew javascript client"; if (window) { this._description = (window.getQueryString('description') !== "" ? unescape(window.getQueryString('description')) : this._description); } /** * Spacebrew server to which the app will connect * @type {String} */ this.server = server || "sandbox.spacebrew.cc"; if (window) { this.server = (window.getQueryString('server') !== "" ? unescape(window.getQueryString('server')) : this.server); } /** * Port number on which Spacebrew server is running * @type {Integer} */ this.port = options.port || 9000; if (window) { port = window.getQueryString('port'); if (port !== "" && !isNaN(port)) { this.port = port; } } /** * Reference to WebSocket * @type {WebSocket} */ this.socket = null; /** * Configuration file for Spacebrew * @type {Object} */ this.client_config = { name: this._name, description: this._description, publish:{ messages:[] }, subscribe:{ messages:[] }, options:{} }; this.admin = {} /** * Are we connected to a Spacebrew server? * @type {Boolean} */ this._isConnected = false; } /** * Connect to Spacebrew * @memberOf Spacebrew.Client */ Spacebrew.Client.prototype.connect = function(){ try { this.socket = new WebSocket("ws://" + this.server + ":" + this.port); this.socket.onopen = this._onOpen.bind(this); this.socket.onmessage = this._onMessage.bind(this); this.socket.onclose = this._onClose.bind(this); } catch(e){ this._isConnected = false; console.log("[connect:Spacebrew] connection attempt failed") } } /** * Close Spacebrew connection * @memberOf Spacebrew.Client */ Spacebrew.Client.prototype.close = function(){ try { if (this._isConnected) { this.socket.close(); this._isConnected = false; console.log("[close:Spacebrew] closing websocket connection") } } catch (e) { this._isConnected = false; } } /** * Override in your app to receive on open event for connection * @memberOf Spacebrew.Client * @public */ Spacebrew.Client.prototype.onOpen = function( name, value ){} /** * Override in your app to receive on close event for connection * @memberOf Spacebrew.Client * @public */ Spacebrew.Client.prototype.onClose = function( name, value ){} /** * Override in your app to receive "range" messages, e.g. sb.onRangeMessage = yourRangeFunction * @param {String} name Name of incoming route * @param {String} value [description] * @memberOf Spacebrew.Client * @public */ Spacebrew.Client.prototype.onRangeMessage = function( name, value ){} /** * Override in your app to receive "boolean" messages, e.g. sb.onBooleanMessage = yourBoolFunction * @param {String} name Name of incoming route * @param {String} value [description] * @memberOf Spacebrew.Client * @public */ Spacebrew.Client.prototype.onBooleanMessage = function( name, value ){} /** * Override in your app to receive "string" messages, e.g. sb.onStringMessage = yourStringFunction * @param {String} name Name of incoming route * @param {String} value [description] * @memberOf Spacebrew.Client * @public */ Spacebrew.Client.prototype.onStringMessage = function( name, value ){} /** * Override in your app to receive "custom" messages, e.g. sb.onCustomMessage = yourStringFunction * @param {String} name Name of incoming route * @param {String} value [description] * @memberOf Spacebrew.Client * @public */ Spacebrew.Client.prototype.onCustomMessage = function( name, value, type ){} /** * Add a route you are publishing on * @param {String} name Name of incoming route * @param {String} type "boolean", "range", or "string" * @param {String} def default value * @memberOf Spacebrew.Client * @public */ Spacebrew.Client.prototype.addPublish = function( name, type, def ){ this.client_config.publish.messages.push({"name":name, "type":type, "default":def}); this.updatePubSub(); } /** * [addSubscriber description] * @param {String} name Name of outgoing route * @param {String} type "boolean", "range", or "string" * @memberOf Spacebrew.Client * @public */ Spacebrew.Client.prototype.addSubscribe = function( name, type ){ this.client_config.subscribe.messages.push({"name":name, "type":type }); this.updatePubSub(); } /** * Update publishers and subscribers * @memberOf Spacebrew.Client * @private */ Spacebrew.Client.prototype.updatePubSub = function(){ if (this._isConnected) { this.socket.send(JSON.stringify({"config": this.client_config})); } } /** * Send a route to Spacebrew * @param {String} name Name of outgoing route (must match something in addPublish) * @param {String} type "boolean", "range", or "string" * @param {String} value Value to send * @memberOf Spacebrew.Client * @public */ Spacebrew.Client.prototype.send = function( name, type, value ){ var self = this; this.msg = { "message": { "clientName":this._name, "name": name, "type": type, "value": value } } // if send block is not active then send message if (!this.send_blocked) { this.socket.send(JSON.stringify(this.msg)); this.send_blocked = true; this.msg = undefined; // set the timer to unblock message sending setTimeout(function() { self.send_blocked = false; // remove send block if (self.msg != undefined) { // if message exists then sent it self.send(self.msg.message.name, self.msg.message.type, self.msg.message.value); } }, self.send_interval); } } /** * Called on WebSocket open * @private * @memberOf Spacebrew.Client */ Spacebrew.Client.prototype._onOpen = function() { console.log("[_onOpen:Spacebrew] Spacebrew connection opened, client name is: " + this._name); this._isConnected = true; if (this.admin.active) this.connectAdmin(); // if reconnect functionality is activated then clear interval timer when connection succeeds if (this.reconnect_timer) { console.log("[_onOpen:Spacebrew] tearing down reconnect timer") this.reconnect_timer = clearInterval(this.reconnect_timer); this.reconnect_timer = undefined; } // send my config this.updatePubSub(); this.onOpen(); } /** * Called on WebSocket message * @private * @param {Object} e * @memberOf Spacebrew.Client */ Spacebrew.Client.prototype._onMessage = function( e ){ var data = JSON.parse(e.data) , name , type , value ; // handle client messages if (data["message"]) { // check to make sure that this is not an admin message if (!data.message["clientName"]) { name = data.message.name; type = data.message.type; value = data.message.value; switch( type ){ case "boolean": this.onBooleanMessage( name, value == "true" ); break; case "string": this.onStringMessage( name, value ); break; case "range": this.onRangeMessage( name, Number(value) ); break; default: this.onCustomMessage( name, value, type ); } } } // handle admin messages else { if (this.admin.active) { this._handleAdminMessages( data ); } } } /** * Called on WebSocket close * @private * @memberOf Spacebrew.Client */ Spacebrew.Client.prototype._onClose = function() { var self = this; console.log("[_onClose:Spacebrew] Spacebrew connection closed"); this._isConnected = false; if (this.admin.active) this.admin.remoteAddress = undefined; // if reconnect functionality is activated set interval timer if connection dies if (this.reconnect && !this.reconnect_timer) { console.log("[_onClose:Spacebrew] setting up reconnect timer"); this.reconnect_timer = setInterval(function () { if (self.isConnected != false) { self.connect(); console.log("[reconnect:Spacebrew] attempting to reconnect to spacebrew"); } }, 5000); } this.onClose(); }; /** * name Method that sets or gets the spacebrew app name. If parameter is provided then it sets the name, otherwise * it just returns the current app name. * @param {String} newName New name of the spacebrew app * @return {String} Returns the name of the spacebrew app if called as a getter function. If called as a * setter function it will return false if the method is called after connecting to spacebrew, * because the name must be configured before connection is made. */ Spacebrew.Client.prototype.name = function (newName){ if (newName) { // if a name has been passed in then update it if (this._isConnected) return false; // if already connected we can't update name this._name = newName; if (window) { this._name = (window.getQueryString('name') !== "" ? unescape(window.getQueryString('name')) : this._name); } this.client_config.name = this._name; // update spacebrew config file } return this._name; }; /** * name Method that sets or gets the spacebrew app description. If parameter is provided then it sets the description, * otherwise it just returns the current app description. * @param {String} newDesc New description of the spacebrew app * @return {String} Returns the description of the spacebrew app if called as a getter function. If called as a * setter function it will return false if the method is called after connecting to spacebrew, * because the description must be configured before connection is made. */ Spacebrew.Client.prototype.description = function (newDesc){ if (newDesc) { // if a description has been passed in then update it if (this._isConnected) return false; // if already connected we can't update description this._description = newDesc || "spacebrew javascript client"; if (window) { this._description = (window.getQueryString('description') !== "" ? unescape(window.getQueryString('description')) : this._description); } this.client_config.description = this._description; // update spacebrew config file } return this._description; }; /** * isConnected Method that returns current connection state of the spacebrew client. * @return {Boolean} Returns true if currently connected to Spacebrew */ Spacebrew.Client.prototype.isConnected = function (){ return this._isConnected; }; Spacebrew.Client.prototype.extend = function ( mixin ) { for (var prop in mixin) { if (mixin.hasOwnProperty(prop)) { this[prop] = mixin[prop]; } } };
RyanteckLTD/RTK-000-001-Controller
touchClient/js/sb-1.3.0.js
JavaScript
gpl-3.0
15,832
import { expect } from 'chai'; import parse from 'url-parse'; import { buildDfpVideoUrl, buildAdpodVideoUrl } from 'modules/dfpAdServerVideo.js'; import adUnit from 'test/fixtures/video/adUnit.json'; import * as utils from 'src/utils.js'; import { config } from 'src/config.js'; import { targeting } from 'src/targeting.js'; import { auctionManager } from 'src/auctionManager.js'; import { gdprDataHandler, uspDataHandler } from 'src/adapterManager.js'; import * as adpod from 'modules/adpod.js'; import { server } from 'test/mocks/xhr.js'; const bid = { videoCacheKey: 'abc', adserverTargeting: { hb_uuid: 'abc', hb_cache_id: 'abc', }, }; describe('The DFP video support module', function () { it('should make a legal request URL when given the required params', function () { const url = parse(buildDfpVideoUrl({ adUnit: adUnit, bid: bid, params: { 'iu': 'my/adUnit', 'description_url': 'someUrl.com', } })); expect(url.protocol).to.equal('https:'); expect(url.host).to.equal('securepubads.g.doubleclick.net'); const queryParams = utils.parseQS(url.query); expect(queryParams).to.have.property('correlator'); expect(queryParams).to.have.property('description_url', 'someUrl.com'); expect(queryParams).to.have.property('env', 'vp'); expect(queryParams).to.have.property('gdfp_req', '1'); expect(queryParams).to.have.property('iu', 'my/adUnit'); expect(queryParams).to.have.property('output', 'vast'); expect(queryParams).to.have.property('sz', '640x480'); expect(queryParams).to.have.property('unviewed_position_start', '1'); expect(queryParams).to.have.property('url'); }); it('can take an adserver url as a parameter', function () { const bidCopy = utils.deepClone(bid); bidCopy.vastUrl = 'vastUrl.example'; const url = parse(buildDfpVideoUrl({ adUnit: adUnit, bid: bidCopy, url: 'https://video.adserver.example/', })); expect(url.host).to.equal('video.adserver.example'); const queryObject = utils.parseQS(url.query); expect(queryObject.description_url).to.equal('vastUrl.example'); }); it('requires a params object or url', function () { const url = buildDfpVideoUrl({ adUnit: adUnit, bid: bid, }); expect(url).to.be.undefined; }); it('overwrites url params when both url and params object are given', function () { const url = parse(buildDfpVideoUrl({ adUnit: adUnit, bid: bid, url: 'https://video.adserver.example/ads?sz=640x480&iu=/123/aduniturl&impl=s', params: { iu: 'my/adUnit' } })); const queryObject = utils.parseQS(url.query); expect(queryObject.iu).to.equal('my/adUnit'); }); it('should override param defaults with user-provided ones', function () { const url = parse(buildDfpVideoUrl({ adUnit: adUnit, bid: bid, params: { 'iu': 'my/adUnit', 'output': 'vast', } })); expect(utils.parseQS(url.query)).to.have.property('output', 'vast'); }); it('should include the cache key and adserver targeting in cust_params', function () { const bidCopy = utils.deepClone(bid); bidCopy.adserverTargeting = Object.assign(bidCopy.adserverTargeting, { hb_adid: 'ad_id', }); const url = parse(buildDfpVideoUrl({ adUnit: adUnit, bid: bidCopy, params: { 'iu': 'my/adUnit' } })); const queryObject = utils.parseQS(url.query); const customParams = utils.parseQS('?' + decodeURIComponent(queryObject.cust_params)); expect(customParams).to.have.property('hb_adid', 'ad_id'); expect(customParams).to.have.property('hb_uuid', bid.videoCacheKey); expect(customParams).to.have.property('hb_cache_id', bid.videoCacheKey); }); it('should include the us_privacy key when USP Consent is available', function () { let uspDataHandlerStub = sinon.stub(uspDataHandler, 'getConsentData'); uspDataHandlerStub.returns('1YYY'); const bidCopy = utils.deepClone(bid); bidCopy.adserverTargeting = Object.assign(bidCopy.adserverTargeting, { hb_adid: 'ad_id', }); const url = parse(buildDfpVideoUrl({ adUnit: adUnit, bid: bidCopy, params: { 'iu': 'my/adUnit' } })); const queryObject = utils.parseQS(url.query); expect(queryObject.us_privacy).to.equal('1YYY'); uspDataHandlerStub.restore(); }); it('should not include the us_privacy key when USP Consent is not available', function () { const bidCopy = utils.deepClone(bid); bidCopy.adserverTargeting = Object.assign(bidCopy.adserverTargeting, { hb_adid: 'ad_id', }); const url = parse(buildDfpVideoUrl({ adUnit: adUnit, bid: bidCopy, params: { 'iu': 'my/adUnit' } })); const queryObject = utils.parseQS(url.query); expect(queryObject.us_privacy).to.equal(undefined); }); it('should include the GDPR keys when GDPR Consent is available', function () { let gdprDataHandlerStub = sinon.stub(gdprDataHandler, 'getConsentData'); gdprDataHandlerStub.returns({ gdprApplies: true, consentString: 'consent', addtlConsent: 'moreConsent' }); const bidCopy = utils.deepClone(bid); bidCopy.adserverTargeting = Object.assign(bidCopy.adserverTargeting, { hb_adid: 'ad_id', }); const url = parse(buildDfpVideoUrl({ adUnit: adUnit, bid: bidCopy, params: { 'iu': 'my/adUnit' } })); const queryObject = utils.parseQS(url.query); expect(queryObject.gdpr).to.equal('1'); expect(queryObject.gdpr_consent).to.equal('consent'); expect(queryObject.addtl_consent).to.equal('moreConsent'); gdprDataHandlerStub.restore(); }); it('should not include the GDPR keys when GDPR Consent is not available', function () { const bidCopy = utils.deepClone(bid); bidCopy.adserverTargeting = Object.assign(bidCopy.adserverTargeting, { hb_adid: 'ad_id', }); const url = parse(buildDfpVideoUrl({ adUnit: adUnit, bid: bidCopy, params: { 'iu': 'my/adUnit' } })); const queryObject = utils.parseQS(url.query); expect(queryObject.gdpr).to.equal(undefined); expect(queryObject.gdpr_consent).to.equal(undefined); expect(queryObject.addtl_consent).to.equal(undefined); }); it('should only include the GDPR keys for GDPR Consent fields with values', function () { let gdprDataHandlerStub = sinon.stub(gdprDataHandler, 'getConsentData'); gdprDataHandlerStub.returns({ gdprApplies: true, consentString: 'consent', }); const bidCopy = utils.deepClone(bid); bidCopy.adserverTargeting = Object.assign(bidCopy.adserverTargeting, { hb_adid: 'ad_id', }); const url = parse(buildDfpVideoUrl({ adUnit: adUnit, bid: bidCopy, params: { 'iu': 'my/adUnit' } })); const queryObject = utils.parseQS(url.query); expect(queryObject.gdpr).to.equal('1'); expect(queryObject.gdpr_consent).to.equal('consent'); expect(queryObject.addtl_consent).to.equal(undefined); gdprDataHandlerStub.restore(); }); describe('special targeting unit test', function () { const allTargetingData = { 'hb_format': 'video', 'hb_source': 'client', 'hb_size': '640x480', 'hb_pb': '5.00', 'hb_adid': '2c4f6cc3ba128a', 'hb_bidder': 'testBidder2', 'hb_format_testBidder2': 'video', 'hb_source_testBidder2': 'client', 'hb_size_testBidder2': '640x480', 'hb_pb_testBidder2': '5.00', 'hb_adid_testBidder2': '2c4f6cc3ba128a', 'hb_bidder_testBidder2': 'testBidder2', 'hb_format_appnexus': 'video', 'hb_source_appnexus': 'client', 'hb_size_appnexus': '640x480', 'hb_pb_appnexus': '5.00', 'hb_adid_appnexus': '44e0b5f2e5cace', 'hb_bidder_appnexus': 'appnexus' }; let targetingStub; before(function () { targetingStub = sinon.stub(targeting, 'getAllTargeting'); targetingStub.returns({'video1': allTargetingData}); config.setConfig({ enableSendAllBids: true }); }); after(function () { config.resetConfig(); targetingStub.restore(); }); it('should include all adserver targeting in cust_params if pbjs.enableSendAllBids is true', function () { const adUnitsCopy = utils.deepClone(adUnit); adUnitsCopy.bids.push({ 'bidder': 'testBidder2', 'params': { 'placementId': '9333431', 'video': { 'skipppable': false, 'playback_methods': ['auto_play_sound_off'] } } }); const bidCopy = utils.deepClone(bid); bidCopy.adserverTargeting = Object.assign(bidCopy.adserverTargeting, { hb_adid: 'ad_id', }); const url = parse(buildDfpVideoUrl({ adUnit: adUnitsCopy, bid: bidCopy, params: { 'iu': 'my/adUnit' } })); const queryObject = utils.parseQS(url.query); const customParams = utils.parseQS('?' + decodeURIComponent(queryObject.cust_params)); expect(customParams).to.have.property('hb_adid', 'ad_id'); expect(customParams).to.have.property('hb_uuid', bid.videoCacheKey); expect(customParams).to.have.property('hb_cache_id', bid.videoCacheKey); expect(customParams).to.have.property('hb_bidder_appnexus', 'appnexus'); expect(customParams).to.have.property('hb_bidder_testBidder2', 'testBidder2'); }); }); it('should merge the user-provided cust_params with the default ones', function () { const bidCopy = utils.deepClone(bid); bidCopy.adserverTargeting = Object.assign(bidCopy.adserverTargeting, { hb_adid: 'ad_id', }); const url = parse(buildDfpVideoUrl({ adUnit: adUnit, bid: bidCopy, params: { 'iu': 'my/adUnit', cust_params: { 'my_targeting': 'foo', }, }, })); const queryObject = utils.parseQS(url.query); const customParams = utils.parseQS('?' + decodeURIComponent(queryObject.cust_params)); expect(customParams).to.have.property('hb_adid', 'ad_id'); expect(customParams).to.have.property('my_targeting', 'foo'); }); it('should merge the user-provided cust-params with the default ones when using url object', function () { const bidCopy = utils.deepClone(bid); bidCopy.adserverTargeting = Object.assign(bidCopy.adserverTargeting, { hb_adid: 'ad_id', }); const url = parse(buildDfpVideoUrl({ adUnit: adUnit, bid: bidCopy, url: 'https://video.adserver.example/ads?sz=640x480&iu=/123/aduniturl&impl=s&cust_params=section%3dblog%26mykey%3dmyvalue' })); const queryObject = utils.parseQS(url.query); const customParams = utils.parseQS('?' + decodeURIComponent(queryObject.cust_params)); expect(customParams).to.have.property('hb_adid', 'ad_id'); expect(customParams).to.have.property('section', 'blog'); expect(customParams).to.have.property('mykey', 'myvalue'); expect(customParams).to.have.property('hb_uuid', 'abc'); expect(customParams).to.have.property('hb_cache_id', 'abc'); }); it('should not overwrite an existing description_url for object input and cache disabled', function () { const bidCopy = utils.deepClone(bid); bidCopy.vastUrl = 'vastUrl.example'; const url = parse(buildDfpVideoUrl({ adUnit: adUnit, bid: bidCopy, params: { iu: 'my/adUnit', description_url: 'descriptionurl.example' } })); const queryObject = utils.parseQS(url.query); expect(queryObject.description_url).to.equal('descriptionurl.example'); }); it('should work with nobid responses', function () { const url = buildDfpVideoUrl({ adUnit: adUnit, params: { 'iu': 'my/adUnit' } }); expect(url).to.be.a('string'); }); it('should include hb_uuid and hb_cache_id in cust_params when both keys are exluded from overwritten bidderSettings', function () { const bidCopy = utils.deepClone(bid); delete bidCopy.adserverTargeting.hb_uuid; delete bidCopy.adserverTargeting.hb_cache_id; const url = parse(buildDfpVideoUrl({ adUnit: adUnit, bid: bidCopy, params: { 'iu': 'my/adUnit' } })); const queryObject = utils.parseQS(url.query); const customParams = utils.parseQS('?' + decodeURIComponent(queryObject.cust_params)); expect(customParams).to.have.property('hb_uuid', bid.videoCacheKey); expect(customParams).to.have.property('hb_cache_id', bid.videoCacheKey); }); it('should include hb_uuid and hb_cache_id in cust params from overwritten standard bidderSettings', function () { const bidCopy = utils.deepClone(bid); bidCopy.adserverTargeting = Object.assign(bidCopy.adserverTargeting, { hb_uuid: 'def', hb_cache_id: 'def' }); const url = parse(buildDfpVideoUrl({ adUnit: adUnit, bid: bidCopy, params: { 'iu': 'my/adUnit' } })); const queryObject = utils.parseQS(url.query); const customParams = utils.parseQS('?' + decodeURIComponent(queryObject.cust_params)); expect(customParams).to.have.property('hb_uuid', 'def'); expect(customParams).to.have.property('hb_cache_id', 'def'); }); describe('adpod unit tests', function () { let amStub; let amGetAdUnitsStub; before(function () { let adUnits = [{ code: 'adUnitCode-1', mediaTypes: { video: { context: 'adpod', playerSize: [640, 480], adPodDurationSec: 60, durationRangeSec: [15, 30], requireExactDuration: true } }, bids: [ { bidder: 'appnexus', params: { placementId: 14542875, } } ] }]; amGetAdUnitsStub = sinon.stub(auctionManager, 'getAdUnits'); amGetAdUnitsStub.returns(adUnits); amStub = sinon.stub(auctionManager, 'getBidsReceived'); }); beforeEach(function () { config.setConfig({ adpod: { brandCategoryExclusion: true, deferCaching: false } }); }) afterEach(function() { config.resetConfig(); }); after(function () { amGetAdUnitsStub.restore(); amStub.restore(); }); it('should return masterTag url', function() { amStub.returns(getBidsReceived()); let uspDataHandlerStub = sinon.stub(uspDataHandler, 'getConsentData'); uspDataHandlerStub.returns('1YYY'); let gdprDataHandlerStub = sinon.stub(gdprDataHandler, 'getConsentData'); gdprDataHandlerStub.returns({ gdprApplies: true, consentString: 'consent', addtlConsent: 'moreConsent' }); let url; parse(buildAdpodVideoUrl({ code: 'adUnitCode-1', callback: handleResponse, params: { 'iu': 'my/adUnit', 'description_url': 'someUrl.com', } })); function handleResponse(err, masterTag) { if (err) { return; } url = parse(masterTag); expect(url.protocol).to.equal('https:'); expect(url.host).to.equal('securepubads.g.doubleclick.net'); const queryParams = utils.parseQS(url.query); expect(queryParams).to.have.property('correlator'); expect(queryParams).to.have.property('description_url', 'someUrl.com'); expect(queryParams).to.have.property('env', 'vp'); expect(queryParams).to.have.property('gdfp_req', '1'); expect(queryParams).to.have.property('iu', 'my/adUnit'); expect(queryParams).to.have.property('output', 'vast'); expect(queryParams).to.have.property('sz', '640x480'); expect(queryParams).to.have.property('unviewed_position_start', '1'); expect(queryParams).to.have.property('url'); expect(queryParams).to.have.property('cust_params'); expect(queryParams).to.have.property('us_privacy', '1YYY'); expect(queryParams).to.have.property('gdpr', '1'); expect(queryParams).to.have.property('gdpr_consent', 'consent'); expect(queryParams).to.have.property('addtl_consent', 'moreConsent'); const custParams = utils.parseQS(decodeURIComponent(queryParams.cust_params)); expect(custParams).to.have.property('hb_cache_id', '123'); expect(custParams).to.have.property('hb_pb_cat_dur', '15.00_395_15s,15.00_406_30s,10.00_395_15s'); uspDataHandlerStub.restore(); gdprDataHandlerStub.restore(); } }); it('should return masterTag url with correct custom params when brandCategoryExclusion is false', function() { config.setConfig({ adpod: { brandCategoryExclusion: false, } }); function getBids() { let bids = [ createBid(10, 'adUnitCode-1', 15, '10.00_15s', '123', '395', '10.00'), createBid(15, 'adUnitCode-1', 15, '15.00_15s', '123', '395', '15.00'), createBid(25, 'adUnitCode-1', 30, '15.00_30s', '123', '406', '25.00'), ]; bids.forEach((bid) => { delete bid.meta; }); return bids; } amStub.returns(getBids()); let url; parse(buildAdpodVideoUrl({ code: 'adUnitCode-1', callback: handleResponse, params: { 'iu': 'my/adUnit', 'description_url': 'someUrl.com', } })); function handleResponse(err, masterTag) { if (err) { return; } url = parse(masterTag); expect(url.protocol).to.equal('https:'); expect(url.host).to.equal('securepubads.g.doubleclick.net'); const queryParams = utils.parseQS(url.query); expect(queryParams).to.have.property('correlator'); expect(queryParams).to.have.property('description_url', 'someUrl.com'); expect(queryParams).to.have.property('env', 'vp'); expect(queryParams).to.have.property('gdfp_req', '1'); expect(queryParams).to.have.property('iu', 'my/adUnit'); expect(queryParams).to.have.property('output', 'xml_vast3'); expect(queryParams).to.have.property('sz', '640x480'); expect(queryParams).to.have.property('unviewed_position_start', '1'); expect(queryParams).to.have.property('url'); expect(queryParams).to.have.property('cust_params'); const custParams = utils.parseQS(decodeURIComponent(queryParams.cust_params)); expect(custParams).to.have.property('hb_cache_id', '123'); expect(custParams).to.have.property('hb_pb_cat_dur', '10.00_15s,15.00_15s,15.00_30s'); } }); it('should handle error when cache fails', function() { config.setConfig({ adpod: { brandCategoryExclusion: true, deferCaching: true } }); amStub.returns(getBidsReceived()); parse(buildAdpodVideoUrl({ code: 'adUnitCode-1', callback: handleResponse, params: { 'iu': 'my/adUnit', 'description_url': 'someUrl.com', } })); server.requests[0].respond(503, { 'Content-Type': 'plain/text', }, 'The server could not save anything at the moment.'); function handleResponse(err, masterTag) { expect(masterTag).to.be.null; expect(err).to.be.an('error'); } }); }) }); function getBidsReceived() { return [ createBid(10, 'adUnitCode-1', 15, '10.00_395_15s', '123', '395', '10.00'), createBid(15, 'adUnitCode-1', 15, '15.00_395_15s', '123', '395', '15.00'), createBid(25, 'adUnitCode-1', 30, '15.00_406_30s', '123', '406', '25.00'), ] } function createBid(cpm, adUnitCode, durationBucket, priceIndustryDuration, uuid, label, hbpb) { return { 'bidderCode': 'appnexus', 'width': 640, 'height': 360, 'statusMessage': 'Bid available', 'adId': '28f24ced14586c', 'mediaType': 'video', 'source': 'client', 'requestId': '28f24ced14586c', 'cpm': cpm, 'creativeId': 97517771, 'currency': 'USD', 'netRevenue': true, 'ttl': 3600, 'adUnitCode': adUnitCode, 'video': { 'context': 'adpod', 'durationBucket': durationBucket }, 'appnexus': { 'buyerMemberId': 9325 }, 'vastUrl': 'http://some-vast-url.com', 'vastImpUrl': 'http://some-vast-imp-url.com', 'auctionId': 'ec266b31-d652-49c5-8295-e83fafe5532b', 'responseTimestamp': 1548442460888, 'requestTimestamp': 1548442460827, 'bidder': 'appnexus', 'timeToRespond': 61, 'pbLg': '5.00', 'pbMg': '5.00', 'pbHg': '5.00', 'pbAg': '5.00', 'pbDg': '5.00', 'pbCg': '', 'size': '640x360', 'adserverTargeting': { 'hb_bidder': 'appnexus', 'hb_adid': '28f24ced14586c', 'hb_pb': hbpb, 'hb_size': '640x360', 'hb_source': 'client', 'hb_format': 'video', 'hb_pb_cat_dur': priceIndustryDuration, 'hb_cache_id': uuid }, 'customCacheKey': `${priceIndustryDuration}_${uuid}`, 'meta': { 'primaryCatId': 'iab-1', 'adServerCatId': label }, 'videoCacheKey': '4cf395af-8fee-4960-af0e-88d44e399f14' } }
prebid/Prebid.js
test/spec/modules/dfpAdServerVideo_spec.js
JavaScript
apache-2.0
21,329
// Copyright 2007 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview DOM pattern to match a sequence of other patterns. */ goog.provide('goog.dom.pattern.Sequence'); goog.require('goog.dom.NodeType'); goog.require('goog.dom.pattern'); goog.require('goog.dom.pattern.AbstractPattern'); goog.require('goog.dom.pattern.MatchType'); /** * Pattern object that matches a sequence of other patterns. * * @param {Array<goog.dom.pattern.AbstractPattern>} patterns Ordered array of * patterns to match. * @param {boolean=} opt_ignoreWhitespace Optional flag to ignore text nodes * consisting entirely of whitespace. The default is to not ignore them. * @constructor * @extends {goog.dom.pattern.AbstractPattern} * @final */ goog.dom.pattern.Sequence = function(patterns, opt_ignoreWhitespace) { /** * Ordered array of patterns to match. * * @type {Array<goog.dom.pattern.AbstractPattern>} */ this.patterns = patterns; /** * Whether or not to ignore whitespace only Text nodes. * * @private {boolean} */ this.ignoreWhitespace_ = !!opt_ignoreWhitespace; /** * Position in the patterns array we have reached by successful matches. * * @private {number} */ this.currentPosition_ = 0; }; goog.inherits(goog.dom.pattern.Sequence, goog.dom.pattern.AbstractPattern); /** * Regular expression for breaking text nodes. * @private {!RegExp} */ goog.dom.pattern.Sequence.BREAKING_TEXTNODE_RE_ = /^\s*$/; /** * Test whether the given token starts, continues, or finishes the sequence * of patterns given in the constructor. * * @param {Node} token Token to match against. * @param {goog.dom.TagWalkType} type The type of token. * @return {goog.dom.pattern.MatchType} <code>MATCH</code> if the pattern * matches, <code>MATCHING</code> if the pattern starts a match, and * <code>NO_MATCH</code> if the pattern does not match. * @override */ goog.dom.pattern.Sequence.prototype.matchToken = function(token, type) { // If the option is set, ignore any whitespace only text nodes if (this.ignoreWhitespace_ && token.nodeType == goog.dom.NodeType.TEXT && goog.dom.pattern.Sequence.BREAKING_TEXTNODE_RE_.test(token.nodeValue)) { return goog.dom.pattern.MatchType.MATCHING; } switch (this.patterns[this.currentPosition_].matchToken(token, type)) { case goog.dom.pattern.MatchType.MATCH: // Record the first token we match. if (this.currentPosition_ == 0) { this.matchedNode = token; } // Move forward one position. this.currentPosition_++; // Check if this is the last position. if (this.currentPosition_ == this.patterns.length) { this.reset(); return goog.dom.pattern.MatchType.MATCH; } else { return goog.dom.pattern.MatchType.MATCHING; } case goog.dom.pattern.MatchType.MATCHING: // This can happen when our child pattern is a sequence or a repetition. return goog.dom.pattern.MatchType.MATCHING; case goog.dom.pattern.MatchType.BACKTRACK_MATCH: // This means a repetitive match succeeded 1 token ago. // TODO(robbyw): Backtrack further if necessary. this.currentPosition_++; if (this.currentPosition_ == this.patterns.length) { this.reset(); return goog.dom.pattern.MatchType.BACKTRACK_MATCH; } else { // Retry the same token on the next pattern. return this.matchToken(token, type); } default: this.reset(); return goog.dom.pattern.MatchType.NO_MATCH; } }; /** * Reset any internal state this pattern keeps. * @override */ goog.dom.pattern.Sequence.prototype.reset = function() { if (this.patterns[this.currentPosition_]) { this.patterns[this.currentPosition_].reset(); } this.currentPosition_ = 0; };
scheib/chromium
third_party/google-closure-library/closure/goog/dom/pattern/sequence.js
JavaScript
bsd-3-clause
4,393
angular.module('ordercloud-address', []) .directive('ordercloudAddressForm', AddressFormDirective) .directive('ordercloudAddressInfo', AddressInfoDirective) .filter('address', AddressFilter) ; function AddressFormDirective(OCGeography) { return { restrict: 'E', scope: { address: '=', isbilling: '=' }, templateUrl: 'common/address/templates/address.form.tpl.html', link: function(scope) { scope.countries = OCGeography.Countries; scope.states = OCGeography.States; } }; } function AddressInfoDirective() { return { restrict: 'E', scope: { addressid: '@' }, templateUrl: 'common/address/templates/address.info.tpl.html', controller: 'AddressInfoCtrl', controllerAs: 'addressInfo' }; } function AddressFilter() { return function(address, option) { if (!address) return null; if (option === 'full') { var result = []; if (address.AddressName) { result.push(address.AddressName); } result.push((address.FirstName ? address.FirstName + ' ' : '') + address.LastName); result.push(address.Street1); if (address.Street2) { result.push(address.Street2); } result.push(address.City + ', ' + address.State + ' ' + address.Zip); return result.join('\n'); } else { return address.Street1 + (address.Street2 ? ', ' + address.Street2 : ''); } } }
Four51/OrderCloud-Seed-AngularJS
src/app/common/address/address.js
JavaScript
mit
1,620
// Approach: // // 1. Get the minimatch set // 2. For each pattern in the set, PROCESS(pattern, false) // 3. Store matches per-set, then uniq them // // PROCESS(pattern, inGlobStar) // Get the first [n] items from pattern that are all strings // Join these together. This is PREFIX. // If there is no more remaining, then stat(PREFIX) and // add to matches if it succeeds. END. // // If inGlobStar and PREFIX is symlink and points to dir // set ENTRIES = [] // else readdir(PREFIX) as ENTRIES // If fail, END // // with ENTRIES // If pattern[n] is GLOBSTAR // // handle the case where the globstar match is empty // // by pruning it out, and testing the resulting pattern // PROCESS(pattern[0..n] + pattern[n+1 .. $], false) // // handle other cases. // for ENTRY in ENTRIES (not dotfiles) // // attach globstar + tail onto the entry // // Mark that this entry is a globstar match // PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true) // // else // not globstar // for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot) // Test ENTRY against pattern[n] // If fails, continue // If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $]) // // Caveat: // Cache all stats and readdirs results to minimize syscall. Since all // we ever care about is existence and directory-ness, we can just keep // `true` for files, and [children,...] for directories, or `false` for // things that don't exist. module.exports = glob var rp = require('fs.realpath') var minimatch = require('minimatch') var Minimatch = minimatch.Minimatch var inherits = require('inherits') var EE = require('events').EventEmitter var path = require('path') var assert = require('assert') var isAbsolute = require('path-is-absolute') var globSync = require('./sync.js') var common = require('./common.js') var setopts = common.setopts var ownProp = common.ownProp var inflight = require('inflight') var util = require('util') var childrenIgnored = common.childrenIgnored var isIgnored = common.isIgnored var once = require('once') function glob (pattern, options, cb) { if (typeof options === 'function') cb = options, options = {} if (!options) options = {} if (options.sync) { if (cb) throw new TypeError('callback provided to sync glob') return globSync(pattern, options) } return new Glob(pattern, options, cb) } glob.sync = globSync var GlobSync = glob.GlobSync = globSync.GlobSync // old api surface glob.glob = glob function extend (origin, add) { if (add === null || typeof add !== 'object') { return origin } var keys = Object.keys(add) var i = keys.length while (i--) { origin[keys[i]] = add[keys[i]] } return origin } glob.hasMagic = function (pattern, options_) { var options = extend({}, options_) options.noprocess = true var g = new Glob(pattern, options) var set = g.minimatch.set if (!pattern) return false if (set.length > 1) return true for (var j = 0; j < set[0].length; j++) { if (typeof set[0][j] !== 'string') return true } return false } glob.Glob = Glob inherits(Glob, EE) function Glob (pattern, options, cb) { if (typeof options === 'function') { cb = options options = null } if (options && options.sync) { if (cb) throw new TypeError('callback provided to sync glob') return new GlobSync(pattern, options) } if (!(this instanceof Glob)) return new Glob(pattern, options, cb) setopts(this, pattern, options) this._didRealPath = false // process each pattern in the minimatch set var n = this.minimatch.set.length // The matches are stored as {<filename>: true,...} so that // duplicates are automagically pruned. // Later, we do an Object.keys() on these. // Keep them as a list so we can fill in when nonull is set. this.matches = new Array(n) if (typeof cb === 'function') { cb = once(cb) this.on('error', cb) this.on('end', function (matches) { cb(null, matches) }) } var self = this this._processing = 0 this._emitQueue = [] this._processQueue = [] this.paused = false if (this.noprocess) return this if (n === 0) return done() var sync = true for (var i = 0; i < n; i ++) { this._process(this.minimatch.set[i], i, false, done) } sync = false function done () { --self._processing if (self._processing <= 0) { if (sync) { process.nextTick(function () { self._finish() }) } else { self._finish() } } } } Glob.prototype._finish = function () { assert(this instanceof Glob) if (this.aborted) return if (this.realpath && !this._didRealpath) return this._realpath() common.finish(this) this.emit('end', this.found) } Glob.prototype._realpath = function () { if (this._didRealpath) return this._didRealpath = true var n = this.matches.length if (n === 0) return this._finish() var self = this for (var i = 0; i < this.matches.length; i++) this._realpathSet(i, next) function next () { if (--n === 0) self._finish() } } Glob.prototype._realpathSet = function (index, cb) { var matchset = this.matches[index] if (!matchset) return cb() var found = Object.keys(matchset) var self = this var n = found.length if (n === 0) return cb() var set = this.matches[index] = Object.create(null) found.forEach(function (p, i) { // If there's a problem with the stat, then it means that // one or more of the links in the realpath couldn't be // resolved. just return the abs value in that case. p = self._makeAbs(p) rp.realpath(p, self.realpathCache, function (er, real) { if (!er) set[real] = true else if (er.syscall === 'stat') set[p] = true else self.emit('error', er) // srsly wtf right here if (--n === 0) { self.matches[index] = set cb() } }) }) } Glob.prototype._mark = function (p) { return common.mark(this, p) } Glob.prototype._makeAbs = function (f) { return common.makeAbs(this, f) } Glob.prototype.abort = function () { this.aborted = true this.emit('abort') } Glob.prototype.pause = function () { if (!this.paused) { this.paused = true this.emit('pause') } } Glob.prototype.resume = function () { if (this.paused) { this.emit('resume') this.paused = false if (this._emitQueue.length) { var eq = this._emitQueue.slice(0) this._emitQueue.length = 0 for (var i = 0; i < eq.length; i ++) { var e = eq[i] this._emitMatch(e[0], e[1]) } } if (this._processQueue.length) { var pq = this._processQueue.slice(0) this._processQueue.length = 0 for (var i = 0; i < pq.length; i ++) { var p = pq[i] this._processing-- this._process(p[0], p[1], p[2], p[3]) } } } } Glob.prototype._process = function (pattern, index, inGlobStar, cb) { assert(this instanceof Glob) assert(typeof cb === 'function') if (this.aborted) return this._processing++ if (this.paused) { this._processQueue.push([pattern, index, inGlobStar, cb]) return } //console.error('PROCESS %d', this._processing, pattern) // Get the first [n] parts of pattern that are all strings. var n = 0 while (typeof pattern[n] === 'string') { n ++ } // now n is the index of the first one that is *not* a string. // see if there's anything else var prefix switch (n) { // if not, then this is rather simple case pattern.length: this._processSimple(pattern.join('/'), index, cb) return case 0: // pattern *starts* with some non-trivial item. // going to readdir(cwd), but not include the prefix in matches. prefix = null break default: // pattern has some string bits in the front. // whatever it starts with, whether that's 'absolute' like /foo/bar, // or 'relative' like '../baz' prefix = pattern.slice(0, n).join('/') break } var remain = pattern.slice(n) // get the list of entries. var read if (prefix === null) read = '.' else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) { if (!prefix || !isAbsolute(prefix)) prefix = '/' + prefix read = prefix } else read = prefix var abs = this._makeAbs(read) //if ignored, skip _processing if (childrenIgnored(this, read)) return cb() var isGlobStar = remain[0] === minimatch.GLOBSTAR if (isGlobStar) this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb) else this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb) } Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) { var self = this this._readdir(abs, inGlobStar, function (er, entries) { return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb) }) } Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { // if the abs isn't a dir, then nothing can match! if (!entries) return cb() // It will only match dot entries if it starts with a dot, or if // dot is set. Stuff like @(.foo|.bar) isn't allowed. var pn = remain[0] var negate = !!this.minimatch.negate var rawGlob = pn._glob var dotOk = this.dot || rawGlob.charAt(0) === '.' var matchedEntries = [] for (var i = 0; i < entries.length; i++) { var e = entries[i] if (e.charAt(0) !== '.' || dotOk) { var m if (negate && !prefix) { m = !e.match(pn) } else { m = e.match(pn) } if (m) matchedEntries.push(e) } } //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries) var len = matchedEntries.length // If there are no matched entries, then nothing matches. if (len === 0) return cb() // if this is the last remaining pattern bit, then no need for // an additional stat *unless* the user has specified mark or // stat explicitly. We know they exist, since readdir returned // them. if (remain.length === 1 && !this.mark && !this.stat) { if (!this.matches[index]) this.matches[index] = Object.create(null) for (var i = 0; i < len; i ++) { var e = matchedEntries[i] if (prefix) { if (prefix !== '/') e = prefix + '/' + e else e = prefix + e } if (e.charAt(0) === '/' && !this.nomount) { e = path.join(this.root, e) } this._emitMatch(index, e) } // This was the last one, and no stats were needed return cb() } // now test all matched entries as stand-ins for that part // of the pattern. remain.shift() for (var i = 0; i < len; i ++) { var e = matchedEntries[i] var newPattern if (prefix) { if (prefix !== '/') e = prefix + '/' + e else e = prefix + e } this._process([e].concat(remain), index, inGlobStar, cb) } cb() } Glob.prototype._emitMatch = function (index, e) { if (this.aborted) return if (isIgnored(this, e)) return if (this.paused) { this._emitQueue.push([index, e]) return } var abs = isAbsolute(e) ? e : this._makeAbs(e) if (this.mark) e = this._mark(e) if (this.absolute) e = abs if (this.matches[index][e]) return if (this.nodir) { var c = this.cache[abs] if (c === 'DIR' || Array.isArray(c)) return } this.matches[index][e] = true var st = this.statCache[abs] if (st) this.emit('stat', e, st) this.emit('match', e) } Glob.prototype._readdirInGlobStar = function (abs, cb) { if (this.aborted) return // follow all symlinked directories forever // just proceed as if this is a non-globstar situation if (this.follow) return this._readdir(abs, false, cb) var lstatkey = 'lstat\0' + abs var self = this var lstatcb = inflight(lstatkey, lstatcb_) if (lstatcb) self.fs.lstat(abs, lstatcb) function lstatcb_ (er, lstat) { if (er && er.code === 'ENOENT') return cb() var isSym = lstat && lstat.isSymbolicLink() self.symlinks[abs] = isSym // If it's not a symlink or a dir, then it's definitely a regular file. // don't bother doing a readdir in that case. if (!isSym && lstat && !lstat.isDirectory()) { self.cache[abs] = 'FILE' cb() } else self._readdir(abs, false, cb) } } Glob.prototype._readdir = function (abs, inGlobStar, cb) { if (this.aborted) return cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb) if (!cb) return //console.error('RD %j %j', +inGlobStar, abs) if (inGlobStar && !ownProp(this.symlinks, abs)) return this._readdirInGlobStar(abs, cb) if (ownProp(this.cache, abs)) { var c = this.cache[abs] if (!c || c === 'FILE') return cb() if (Array.isArray(c)) return cb(null, c) } var self = this self.fs.readdir(abs, readdirCb(this, abs, cb)) } function readdirCb (self, abs, cb) { return function (er, entries) { if (er) self._readdirError(abs, er, cb) else self._readdirEntries(abs, entries, cb) } } Glob.prototype._readdirEntries = function (abs, entries, cb) { if (this.aborted) return // if we haven't asked to stat everything, then just // assume that everything in there exists, so we can avoid // having to stat it a second time. if (!this.mark && !this.stat) { for (var i = 0; i < entries.length; i ++) { var e = entries[i] if (abs === '/') e = abs + e else e = abs + '/' + e this.cache[e] = true } } this.cache[abs] = entries return cb(null, entries) } Glob.prototype._readdirError = function (f, er, cb) { if (this.aborted) return // handle errors, and cache the information switch (er.code) { case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 case 'ENOTDIR': // totally normal. means it *does* exist. var abs = this._makeAbs(f) this.cache[abs] = 'FILE' if (abs === this.cwdAbs) { var error = new Error(er.code + ' invalid cwd ' + this.cwd) error.path = this.cwd error.code = er.code this.emit('error', error) this.abort() } break case 'ENOENT': // not terribly unusual case 'ELOOP': case 'ENAMETOOLONG': case 'UNKNOWN': this.cache[this._makeAbs(f)] = false break default: // some unusual error. Treat as failure. this.cache[this._makeAbs(f)] = false if (this.strict) { this.emit('error', er) // If the error is handled, then we abort // if not, we threw out of here this.abort() } if (!this.silent) console.error('glob error', er) break } return cb() } Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) { var self = this this._readdir(abs, inGlobStar, function (er, entries) { self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb) }) } Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { //console.error('pgs2', prefix, remain[0], entries) // no entries means not a dir, so it can never have matches // foo.txt/** doesn't match foo.txt if (!entries) return cb() // test without the globstar, and with every child both below // and replacing the globstar. var remainWithoutGlobStar = remain.slice(1) var gspref = prefix ? [ prefix ] : [] var noGlobStar = gspref.concat(remainWithoutGlobStar) // the noGlobStar pattern exits the inGlobStar state this._process(noGlobStar, index, false, cb) var isSym = this.symlinks[abs] var len = entries.length // If it's a symlink, and we're in a globstar, then stop if (isSym && inGlobStar) return cb() for (var i = 0; i < len; i++) { var e = entries[i] if (e.charAt(0) === '.' && !this.dot) continue // these two cases enter the inGlobStar state var instead = gspref.concat(entries[i], remainWithoutGlobStar) this._process(instead, index, true, cb) var below = gspref.concat(entries[i], remain) this._process(below, index, true, cb) } cb() } Glob.prototype._processSimple = function (prefix, index, cb) { // XXX review this. Shouldn't it be doing the mounting etc // before doing stat? kinda weird? var self = this this._stat(prefix, function (er, exists) { self._processSimple2(prefix, index, er, exists, cb) }) } Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) { //console.error('ps2', prefix, exists) if (!this.matches[index]) this.matches[index] = Object.create(null) // If it doesn't exist, then just mark the lack of results if (!exists) return cb() if (prefix && isAbsolute(prefix) && !this.nomount) { var trail = /[\/\\]$/.test(prefix) if (prefix.charAt(0) === '/') { prefix = path.join(this.root, prefix) } else { prefix = path.resolve(this.root, prefix) if (trail) prefix += '/' } } if (process.platform === 'win32') prefix = prefix.replace(/\\/g, '/') // Mark this as a match this._emitMatch(index, prefix) cb() } // Returns either 'DIR', 'FILE', or false Glob.prototype._stat = function (f, cb) { var abs = this._makeAbs(f) var needDir = f.slice(-1) === '/' if (f.length > this.maxLength) return cb() if (!this.stat && ownProp(this.cache, abs)) { var c = this.cache[abs] if (Array.isArray(c)) c = 'DIR' // It exists, but maybe not how we need it if (!needDir || c === 'DIR') return cb(null, c) if (needDir && c === 'FILE') return cb() // otherwise we have to stat, because maybe c=true // if we know it exists, but not what it is. } var exists var stat = this.statCache[abs] if (stat !== undefined) { if (stat === false) return cb(null, stat) else { var type = stat.isDirectory() ? 'DIR' : 'FILE' if (needDir && type === 'FILE') return cb() else return cb(null, type, stat) } } var self = this var statcb = inflight('stat\0' + abs, lstatcb_) if (statcb) self.fs.lstat(abs, statcb) function lstatcb_ (er, lstat) { if (lstat && lstat.isSymbolicLink()) { // If it's a symlink, then treat it as the target, unless // the target does not exist, then treat it as a file. return self.fs.stat(abs, function (er, stat) { if (er) self._stat2(f, abs, null, lstat, cb) else self._stat2(f, abs, er, stat, cb) }) } else { self._stat2(f, abs, er, lstat, cb) } } } Glob.prototype._stat2 = function (f, abs, er, stat, cb) { if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { this.statCache[abs] = false return cb() } var needDir = f.slice(-1) === '/' this.statCache[abs] = stat if (abs.slice(-1) === '/' && stat && !stat.isDirectory()) return cb(null, false, stat) var c = true if (stat) c = stat.isDirectory() ? 'DIR' : 'FILE' this.cache[abs] = this.cache[abs] || c if (needDir && c === 'FILE') return cb() return cb(null, c, stat) }
ealbertos/dotfiles
vscode.symlink/extensions/ms-mssql.mssql-1.11.1/node_modules/glob/glob.js
JavaScript
mit
19,362
/* ======================================================================== * Bootstrap: iconset-typicon-2.0.6.js by @recktoner * https://victor-valencia.github.com/bootstrap-iconpicker * * Iconset: Typicons 2.0.6 * https://github.com/stephenhutchings/typicons.font * ======================================================================== * Copyright 2013-2014 Victor Valencia Rico. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ======================================================================== */ ;(function($){ $.iconset_typicon = { iconClass: 'typcn', iconClassFix: 'typcn-', icons: [ 'adjust-brightness', 'adjust-contrast', 'anchor-outline', 'anchor', 'archive', 'arrow-back-outline', 'arrow-back', 'arrow-down-outline', 'arrow-down-thick', 'arrow-down', 'arrow-forward-outline', 'arrow-forward', 'arrow-left-outline', 'arrow-left-thick', 'arrow-left', 'arrow-loop-outline', 'arrow-loop', 'arrow-maximise-outline', 'arrow-maximise', 'arrow-minimise-outline', 'arrow-minimise', 'arrow-move-outline', 'arrow-move', 'arrow-repeat-outline', 'arrow-repeat', 'arrow-right-outline', 'arrow-right-thick', 'arrow-right', 'arrow-shuffle', 'arrow-sorted-down', 'arrow-sorted-up', 'arrow-sync-outline', 'arrow-sync', 'arrow-unsorted', 'arrow-up-outline', 'arrow-up-thick', 'arrow-up', 'at', 'attachment-outline', 'attachment', 'backspace-outline', 'backspace', 'battery-charge', 'battery-full', 'battery-high', 'battery-low', 'battery-mid', 'beaker', 'beer', 'bell', 'book', 'bookmark', 'briefcase', 'brush', 'business-card', 'calculator', 'calendar-outline', 'calendar', 'camera-outline', 'camera', 'cancel-outline', 'cancel', 'chart-area-outline', 'chart-area', 'chart-bar-outline', 'chart-bar', 'chart-line-outline', 'chart-line', 'chart-pie-outline', 'chart-pie', 'chevron-left-outline', 'chevron-left', 'chevron-right-outline', 'chevron-right', 'clipboard', 'cloud-storage', 'cloud-storage-outline', 'code-outline', 'code', 'coffee', 'cog-outline', 'cog', 'compass', 'contacts', 'credit-card', 'css3', 'database', 'delete-outline', 'delete', 'device-desktop', 'device-laptop', 'device-phone', 'device-tablet', 'directions', 'divide-outline', 'divide', 'document-add', 'document-delete', 'document-text', 'document', 'download-outline', 'download', 'dropbox', 'edit', 'eject-outline', 'eject', 'equals-outline', 'equals', 'export-outline', 'export', 'eye-outline', 'eye', 'feather', 'film', 'filter', 'flag-outline', 'flag', 'flash-outline', 'flash', 'flow-children', 'flow-merge', 'flow-parallel', 'flow-switch', 'folder-add', 'folder-delete', 'folder-open', 'folder', 'gift', 'globe-outline', 'globe', 'group-outline', 'group', 'headphones', 'heart-full-outline', 'heart-half-outline', 'heart-outline', 'heart', 'home-outline', 'home', 'html5', 'image-outline', 'image', 'infinity-outline', 'infinity', 'info-large-outline', 'info-large', 'info-outline', 'info', 'input-checked-outline', 'input-checked', 'key-outline', 'key', 'keyboard', 'leaf', 'lightbulb', 'link-outline', 'link', 'location-arrow-outline', 'location-arrow', 'location-outline', 'location', 'lock-closed-outline', 'lock-closed', 'lock-open-outline', 'lock-open', 'mail', 'map', 'media-eject-outline', 'media-eject', 'media-fast-forward-outline', 'media-fast-forward', 'media-pause-outline', 'media-pause', 'media-play-outline', 'media-play-reverse-outline', 'media-play-reverse', 'media-play', 'media-record-outline', 'media-record', 'media-rewind-outline', 'media-rewind', 'media-stop-outline', 'media-stop', 'message-typing', 'message', 'messages', 'microphone-outline', 'microphone', 'minus-outline', 'minus', 'mortar-board', 'news', 'notes-outline', 'notes', 'pen', 'pencil', 'phone-outline', 'phone', 'pi-outline', 'pi', 'pin-outline', 'pin', 'pipette', 'plane-outline', 'plane', 'plug', 'plus-outline', 'plus', 'point-of-interest-outline', 'point-of-interest', 'power-outline', 'power', 'printer', 'puzzle-outline', 'puzzle', 'radar-outline', 'radar', 'refresh-outline', 'refresh', 'rss-outline', 'rss', 'scissors-outline', 'scissors', 'shopping-bag', 'shopping-cart', 'social-at-circular', 'social-dribbble-circular', 'social-dribbble', 'social-facebook-circular', 'social-facebook', 'social-flickr-circular', 'social-flickr', 'social-github-circular', 'social-github', 'social-google-plus-circular', 'social-google-plus', 'social-instagram-circular', 'social-instagram', 'social-last-fm-circular', 'social-last-fm', 'social-linkedin-circular', 'social-linkedin', 'social-pinterest-circular', 'social-pinterest', 'social-skype-outline', 'social-skype', 'social-tumbler-circular', 'social-tumbler', 'social-twitter-circular', 'social-twitter', 'social-vimeo-circular', 'social-vimeo', 'social-youtube-circular', 'social-youtube', 'sort-alphabetically-outline', 'sort-alphabetically', 'sort-numerically-outline', 'sort-numerically', 'spanner-outline', 'spanner', 'spiral', 'star-full-outline', 'star-half-outline', 'star-half', 'star-outline', 'star', 'starburst-outline', 'starburst', 'stopwatch', 'support', 'tabs-outline', 'tag', 'tags', 'th-large-outline', 'th-large', 'th-list-outline', 'th-list', 'th-menu-outline', 'th-menu', 'th-small-outline', 'th-small', 'thermometer', 'thumbs-down', 'thumbs-ok', 'thumbs-up', 'tick-outline', 'tick', 'ticket', 'time', 'times-outline', 'times', 'trash', 'tree', 'upload-outline', 'upload', 'user-add-outline', 'user-add', 'user-delete-outline', 'user-delete', 'user-outline', 'user', 'vendor-android', 'vendor-apple', 'vendor-microsoft', 'video-outline', 'video', 'volume-down', 'volume-mute', 'volume-up', 'volume', 'warning-outline', 'warning', 'watch', 'waves-outline', 'waves', 'weather-cloudy', 'weather-downpour', 'weather-night', 'weather-partly-sunny', 'weather-shower', 'weather-snow', 'weather-stormy', 'weather-sunny', 'weather-windy-cloudy', 'weather-windy', 'wi-fi-outline', 'wi-fi', 'wine', 'world-outline', 'world', 'zoom-in-outline', 'zoom-in', 'zoom-out-outline', 'zoom-out', 'zoom-outline', 'zoom' ]}; })(jQuery);
ahsina/StudExpo
wp-content/plugins/tiny-bootstrap-elements-light/assets/js/iconset/iconset-typicon-2.0.6.js
JavaScript
gpl-2.0
10,551
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* * Date: 2001-07-12 * * SUMMARY: Regression test for bug 89443 * See http://bugzilla.mozilla.org/show_bug.cgi?id=89443 * * Just seeing if this script will compile without stack overflow. */ //----------------------------------------------------------------------------- var gTestfile = 'regress-89443.js'; var BUGNUMBER = 89443; var summary = 'Testing this script will compile without stack overflow'; printBugNumber(BUGNUMBER); printStatus (summary); // I don't know what these functions are supposed to be; use dummies - function isPlainHostName() { } function dnsDomainIs() { } // Here's the big function - function FindProxyForURL(url, host) { if (isPlainHostName(host) || dnsDomainIs(host, ".hennepin.lib.mn.us") || dnsDomainIs(host, ".hclib.org") ) return "DIRECT"; else if (isPlainHostName(host) // subscription database access || dnsDomainIs(host, ".asahi.com") || dnsDomainIs(host, ".2facts.com") || dnsDomainIs(host, ".oclc.org") || dnsDomainIs(host, ".collegesource.com") || dnsDomainIs(host, ".cq.com") || dnsDomainIs(host, ".grolier.com") || dnsDomainIs(host, ".groveart.com") || dnsDomainIs(host, ".groveopera.com") || dnsDomainIs(host, ".fsonline.com") || dnsDomainIs(host, ".carl.org") || dnsDomainIs(host, ".newslibrary.com") || dnsDomainIs(host, ".pioneerplanet.com") || dnsDomainIs(host, ".startribune.com") || dnsDomainIs(host, ".poemfinder.com") || dnsDomainIs(host, ".umi.com") || dnsDomainIs(host, ".referenceusa.com") || dnsDomainIs(host, ".sirs.com") || dnsDomainIs(host, ".krmediastream.com") || dnsDomainIs(host, ".gale.com") || dnsDomainIs(host, ".galenet.com") || dnsDomainIs(host, ".galegroup.com") || dnsDomainIs(host, ".facts.com") || dnsDomainIs(host, ".eb.com") || dnsDomainIs(host, ".worldbookonline.com") || dnsDomainIs(host, ".galegroup.com") || dnsDomainIs(host, ".accessscience.com") || dnsDomainIs(host, ".booksinprint.com") || dnsDomainIs(host, ".infolearning.com") || dnsDomainIs(host, ".standardpoor.com") // image servers || dnsDomainIs(host, ".akamaitech.net") || dnsDomainIs(host, ".akamai.net") || dnsDomainIs(host, ".yimg.com") || dnsDomainIs(host, ".imgis.com") || dnsDomainIs(host, ".ibsys.com") // KidsClick-linked kids search engines || dnsDomainIs(host, ".edview.com") || dnsDomainIs(host, ".searchopolis.com") || dnsDomainIs(host, ".onekey.com") || dnsDomainIs(host, ".askjeeves.com") // Non-subscription Reference Tools URLs from the RecWebSites DBData table || dnsDomainIs(host, "www.cnn.com") || dnsDomainIs(host, "www.emulateme.com") || dnsDomainIs(host, "terraserver.microsoft.com") || dnsDomainIs(host, "www.theodora.com") || dnsDomainIs(host, "www.3datlas.com") || dnsDomainIs(host, "www.infoplease.com") || dnsDomainIs(host, "www.switchboard.com") || dnsDomainIs(host, "www.bartleby.com") || dnsDomainIs(host, "www.mn-politics.com") || dnsDomainIs(host, "www.thesaurus.com") || dnsDomainIs(host, "www.usnews.com") || dnsDomainIs(host, "www.petersons.com") || dnsDomainIs(host, "www.collegenet.com") || dnsDomainIs(host, "www.m-w.com") || dnsDomainIs(host, "clever.net") || dnsDomainIs(host, "maps.expedia.com") || dnsDomainIs(host, "www.CollegeEdge.com") || dnsDomainIs(host, "www.homeworkcentral.com") || dnsDomainIs(host, "www.studyweb.com") || dnsDomainIs(host, "www.mnpro.com") // custom URLs for local and other access || dnsDomainIs(host, ".dsdukes.com") || dnsDomainIs(host, ".spsaints.com") || dnsDomainIs(host, ".mnzoo.com") || dnsDomainIs(host, ".realaudio.com") || dnsDomainIs(host, ".co.hennepin.mn.us") || dnsDomainIs(host, ".gov") || dnsDomainIs(host, ".org") || dnsDomainIs(host, ".edu") || dnsDomainIs(host, ".fox29.com") || dnsDomainIs(host, ".wcco.com") || dnsDomainIs(host, ".kstp.com") || dnsDomainIs(host, ".kmsp.com") || dnsDomainIs(host, ".kare11.com") || dnsDomainIs(host, ".macromedia.com") || dnsDomainIs(host, ".shockwave.com") || dnsDomainIs(host, ".wwf.com") || dnsDomainIs(host, ".wwfsuperstars.com") || dnsDomainIs(host, ".summerslam.com") || dnsDomainIs(host, ".yahooligans.com") || dnsDomainIs(host, ".mhoob.com") || dnsDomainIs(host, "www.hmonginternet.com") || dnsDomainIs(host, "www.hmongonline.com") || dnsDomainIs(host, ".yahoo.com") || dnsDomainIs(host, ".pokemon.com") || dnsDomainIs(host, ".bet.com") || dnsDomainIs(host, ".smallworld.com") || dnsDomainIs(host, ".cartoonnetwork.com") || dnsDomainIs(host, ".carmensandiego.com") || dnsDomainIs(host, ".disney.com") || dnsDomainIs(host, ".powerpuffgirls.com") || dnsDomainIs(host, ".aol.com") // Smithsonian || dnsDomainIs(host, "160.111.100.190") // Hotmail || dnsDomainIs(host, ".passport.com") || dnsDomainIs(host, ".hotmail.com") || dnsDomainIs(host, "216.33.236.24") || dnsDomainIs(host, "216.32.182.251") || dnsDomainIs(host, ".hotmail.msn.com") // K12 schools || dnsDomainIs(host, ".k12.al.us") || dnsDomainIs(host, ".k12.ak.us") || dnsDomainIs(host, ".k12.ar.us") || dnsDomainIs(host, ".k12.az.us") || dnsDomainIs(host, ".k12.ca.us") || dnsDomainIs(host, ".k12.co.us") || dnsDomainIs(host, ".k12.ct.us") || dnsDomainIs(host, ".k12.dc.us") || dnsDomainIs(host, ".k12.de.us") || dnsDomainIs(host, ".k12.fl.us") || dnsDomainIs(host, ".k12.ga.us") || dnsDomainIs(host, ".k12.hi.us") || dnsDomainIs(host, ".k12.id.us") || dnsDomainIs(host, ".k12.il.us") || dnsDomainIs(host, ".k12.in.us") || dnsDomainIs(host, ".k12.ia.us") || dnsDomainIs(host, ".k12.ks.us") || dnsDomainIs(host, ".k12.ky.us") || dnsDomainIs(host, ".k12.la.us") || dnsDomainIs(host, ".k12.me.us") || dnsDomainIs(host, ".k12.md.us") || dnsDomainIs(host, ".k12.ma.us") || dnsDomainIs(host, ".k12.mi.us") || dnsDomainIs(host, ".k12.mn.us") || dnsDomainIs(host, ".k12.ms.us") || dnsDomainIs(host, ".k12.mo.us") || dnsDomainIs(host, ".k12.mt.us") || dnsDomainIs(host, ".k12.ne.us") || dnsDomainIs(host, ".k12.nv.us") || dnsDomainIs(host, ".k12.nh.us") || dnsDomainIs(host, ".k12.nj.us") || dnsDomainIs(host, ".k12.nm.us") || dnsDomainIs(host, ".k12.ny.us") || dnsDomainIs(host, ".k12.nc.us") || dnsDomainIs(host, ".k12.nd.us") || dnsDomainIs(host, ".k12.oh.us") || dnsDomainIs(host, ".k12.ok.us") || dnsDomainIs(host, ".k12.or.us") || dnsDomainIs(host, ".k12.pa.us") || dnsDomainIs(host, ".k12.ri.us") || dnsDomainIs(host, ".k12.sc.us") || dnsDomainIs(host, ".k12.sd.us") || dnsDomainIs(host, ".k12.tn.us") || dnsDomainIs(host, ".k12.tx.us") || dnsDomainIs(host, ".k12.ut.us") || dnsDomainIs(host, ".k12.vt.us") || dnsDomainIs(host, ".k12.va.us") || dnsDomainIs(host, ".k12.wa.us") || dnsDomainIs(host, ".k12.wv.us") || dnsDomainIs(host, ".k12.wi.us") || dnsDomainIs(host, ".k12.wy.us") // U.S. Libraries || dnsDomainIs(host, ".lib.al.us") || dnsDomainIs(host, ".lib.ak.us") || dnsDomainIs(host, ".lib.ar.us") || dnsDomainIs(host, ".lib.az.us") || dnsDomainIs(host, ".lib.ca.us") || dnsDomainIs(host, ".lib.co.us") || dnsDomainIs(host, ".lib.ct.us") || dnsDomainIs(host, ".lib.dc.us") || dnsDomainIs(host, ".lib.de.us") || dnsDomainIs(host, ".lib.fl.us") || dnsDomainIs(host, ".lib.ga.us") || dnsDomainIs(host, ".lib.hi.us") || dnsDomainIs(host, ".lib.id.us") || dnsDomainIs(host, ".lib.il.us") || dnsDomainIs(host, ".lib.in.us") || dnsDomainIs(host, ".lib.ia.us") || dnsDomainIs(host, ".lib.ks.us") || dnsDomainIs(host, ".lib.ky.us") || dnsDomainIs(host, ".lib.la.us") || dnsDomainIs(host, ".lib.me.us") || dnsDomainIs(host, ".lib.md.us") || dnsDomainIs(host, ".lib.ma.us") || dnsDomainIs(host, ".lib.mi.us") || dnsDomainIs(host, ".lib.mn.us") || dnsDomainIs(host, ".lib.ms.us") || dnsDomainIs(host, ".lib.mo.us") || dnsDomainIs(host, ".lib.mt.us") || dnsDomainIs(host, ".lib.ne.us") || dnsDomainIs(host, ".lib.nv.us") || dnsDomainIs(host, ".lib.nh.us") || dnsDomainIs(host, ".lib.nj.us") || dnsDomainIs(host, ".lib.nm.us") || dnsDomainIs(host, ".lib.ny.us") || dnsDomainIs(host, ".lib.nc.us") || dnsDomainIs(host, ".lib.nd.us") || dnsDomainIs(host, ".lib.oh.us") || dnsDomainIs(host, ".lib.ok.us") || dnsDomainIs(host, ".lib.or.us") || dnsDomainIs(host, ".lib.pa.us") || dnsDomainIs(host, ".lib.ri.us") || dnsDomainIs(host, ".lib.sc.us") || dnsDomainIs(host, ".lib.sd.us") || dnsDomainIs(host, ".lib.tn.us") || dnsDomainIs(host, ".lib.tx.us") || dnsDomainIs(host, ".lib.ut.us") || dnsDomainIs(host, ".lib.vt.us") || dnsDomainIs(host, ".lib.va.us") || dnsDomainIs(host, ".lib.wa.us") || dnsDomainIs(host, ".lib.wv.us") || dnsDomainIs(host, ".lib.wi.us") || dnsDomainIs(host, ".lib.wy.us") // U.S. Cities || dnsDomainIs(host, ".ci.al.us") || dnsDomainIs(host, ".ci.ak.us") || dnsDomainIs(host, ".ci.ar.us") || dnsDomainIs(host, ".ci.az.us") || dnsDomainIs(host, ".ci.ca.us") || dnsDomainIs(host, ".ci.co.us") || dnsDomainIs(host, ".ci.ct.us") || dnsDomainIs(host, ".ci.dc.us") || dnsDomainIs(host, ".ci.de.us") || dnsDomainIs(host, ".ci.fl.us") || dnsDomainIs(host, ".ci.ga.us") || dnsDomainIs(host, ".ci.hi.us") || dnsDomainIs(host, ".ci.id.us") || dnsDomainIs(host, ".ci.il.us") || dnsDomainIs(host, ".ci.in.us") || dnsDomainIs(host, ".ci.ia.us") || dnsDomainIs(host, ".ci.ks.us") || dnsDomainIs(host, ".ci.ky.us") || dnsDomainIs(host, ".ci.la.us") || dnsDomainIs(host, ".ci.me.us") || dnsDomainIs(host, ".ci.md.us") || dnsDomainIs(host, ".ci.ma.us") || dnsDomainIs(host, ".ci.mi.us") || dnsDomainIs(host, ".ci.mn.us") || dnsDomainIs(host, ".ci.ms.us") || dnsDomainIs(host, ".ci.mo.us") || dnsDomainIs(host, ".ci.mt.us") || dnsDomainIs(host, ".ci.ne.us") || dnsDomainIs(host, ".ci.nv.us") || dnsDomainIs(host, ".ci.nh.us") || dnsDomainIs(host, ".ci.nj.us") || dnsDomainIs(host, ".ci.nm.us") || dnsDomainIs(host, ".ci.ny.us") || dnsDomainIs(host, ".ci.nc.us") || dnsDomainIs(host, ".ci.nd.us") || dnsDomainIs(host, ".ci.oh.us") || dnsDomainIs(host, ".ci.ok.us") || dnsDomainIs(host, ".ci.or.us") || dnsDomainIs(host, ".ci.pa.us") || dnsDomainIs(host, ".ci.ri.us") || dnsDomainIs(host, ".ci.sc.us") || dnsDomainIs(host, ".ci.sd.us") || dnsDomainIs(host, ".ci.tn.us") || dnsDomainIs(host, ".ci.tx.us") || dnsDomainIs(host, ".ci.ut.us") || dnsDomainIs(host, ".ci.vt.us") || dnsDomainIs(host, ".ci.va.us") || dnsDomainIs(host, ".ci.wa.us") || dnsDomainIs(host, ".ci.wv.us") || dnsDomainIs(host, ".ci.wi.us") || dnsDomainIs(host, ".ci.wy.us") // U.S. Counties || dnsDomainIs(host, ".co.al.us") || dnsDomainIs(host, ".co.ak.us") || dnsDomainIs(host, ".co.ar.us") || dnsDomainIs(host, ".co.az.us") || dnsDomainIs(host, ".co.ca.us") || dnsDomainIs(host, ".co.co.us") || dnsDomainIs(host, ".co.ct.us") || dnsDomainIs(host, ".co.dc.us") || dnsDomainIs(host, ".co.de.us") || dnsDomainIs(host, ".co.fl.us") || dnsDomainIs(host, ".co.ga.us") || dnsDomainIs(host, ".co.hi.us") || dnsDomainIs(host, ".co.id.us") || dnsDomainIs(host, ".co.il.us") || dnsDomainIs(host, ".co.in.us") || dnsDomainIs(host, ".co.ia.us") || dnsDomainIs(host, ".co.ks.us") || dnsDomainIs(host, ".co.ky.us") || dnsDomainIs(host, ".co.la.us") || dnsDomainIs(host, ".co.me.us") || dnsDomainIs(host, ".co.md.us") || dnsDomainIs(host, ".co.ma.us") || dnsDomainIs(host, ".co.mi.us") || dnsDomainIs(host, ".co.mn.us") || dnsDomainIs(host, ".co.ms.us") || dnsDomainIs(host, ".co.mo.us") || dnsDomainIs(host, ".co.mt.us") || dnsDomainIs(host, ".co.ne.us") || dnsDomainIs(host, ".co.nv.us") || dnsDomainIs(host, ".co.nh.us") || dnsDomainIs(host, ".co.nj.us") || dnsDomainIs(host, ".co.nm.us") || dnsDomainIs(host, ".co.ny.us") || dnsDomainIs(host, ".co.nc.us") || dnsDomainIs(host, ".co.nd.us") || dnsDomainIs(host, ".co.oh.us") || dnsDomainIs(host, ".co.ok.us") || dnsDomainIs(host, ".co.or.us") || dnsDomainIs(host, ".co.pa.us") || dnsDomainIs(host, ".co.ri.us") || dnsDomainIs(host, ".co.sc.us") || dnsDomainIs(host, ".co.sd.us") || dnsDomainIs(host, ".co.tn.us") || dnsDomainIs(host, ".co.tx.us") || dnsDomainIs(host, ".co.ut.us") || dnsDomainIs(host, ".co.vt.us") || dnsDomainIs(host, ".co.va.us") || dnsDomainIs(host, ".co.wa.us") || dnsDomainIs(host, ".co.wv.us") || dnsDomainIs(host, ".co.wi.us") || dnsDomainIs(host, ".co.wy.us") // U.S. States || dnsDomainIs(host, ".state.al.us") || dnsDomainIs(host, ".state.ak.us") || dnsDomainIs(host, ".state.ar.us") || dnsDomainIs(host, ".state.az.us") || dnsDomainIs(host, ".state.ca.us") || dnsDomainIs(host, ".state.co.us") || dnsDomainIs(host, ".state.ct.us") || dnsDomainIs(host, ".state.dc.us") || dnsDomainIs(host, ".state.de.us") || dnsDomainIs(host, ".state.fl.us") || dnsDomainIs(host, ".state.ga.us") || dnsDomainIs(host, ".state.hi.us") || dnsDomainIs(host, ".state.id.us") || dnsDomainIs(host, ".state.il.us") || dnsDomainIs(host, ".state.in.us") || dnsDomainIs(host, ".state.ia.us") || dnsDomainIs(host, ".state.ks.us") || dnsDomainIs(host, ".state.ky.us") || dnsDomainIs(host, ".state.la.us") || dnsDomainIs(host, ".state.me.us") || dnsDomainIs(host, ".state.md.us") || dnsDomainIs(host, ".state.ma.us") || dnsDomainIs(host, ".state.mi.us") || dnsDomainIs(host, ".state.mn.us") || dnsDomainIs(host, ".state.ms.us") || dnsDomainIs(host, ".state.mo.us") || dnsDomainIs(host, ".state.mt.us") || dnsDomainIs(host, ".state.ne.us") || dnsDomainIs(host, ".state.nv.us") || dnsDomainIs(host, ".state.nh.us") || dnsDomainIs(host, ".state.nj.us") || dnsDomainIs(host, ".state.nm.us") || dnsDomainIs(host, ".state.ny.us") || dnsDomainIs(host, ".state.nc.us") || dnsDomainIs(host, ".state.nd.us") || dnsDomainIs(host, ".state.oh.us") || dnsDomainIs(host, ".state.ok.us") || dnsDomainIs(host, ".state.or.us") || dnsDomainIs(host, ".state.pa.us") || dnsDomainIs(host, ".state.ri.us") || dnsDomainIs(host, ".state.sc.us") || dnsDomainIs(host, ".state.sd.us") || dnsDomainIs(host, ".state.tn.us") || dnsDomainIs(host, ".state.tx.us") || dnsDomainIs(host, ".state.ut.us") || dnsDomainIs(host, ".state.vt.us") || dnsDomainIs(host, ".state.va.us") || dnsDomainIs(host, ".state.wa.us") || dnsDomainIs(host, ".state.wv.us") || dnsDomainIs(host, ".state.wi.us") || dnsDomainIs(host, ".state.wy.us") // KidsClick URLs || dnsDomainIs(host, "12.16.163.163") || dnsDomainIs(host, "128.59.173.136") || dnsDomainIs(host, "165.112.78.61") || dnsDomainIs(host, "216.55.23.140") || dnsDomainIs(host, "63.111.53.150") || dnsDomainIs(host, "64.94.206.8") || dnsDomainIs(host, "abc.go.com") || dnsDomainIs(host, "acmepet.petsmart.com") || dnsDomainIs(host, "adver-net.com") || dnsDomainIs(host, "aint-it-cool-news.com") || dnsDomainIs(host, "akidsheart.com") || dnsDomainIs(host, "alabanza.com") || dnsDomainIs(host, "allerdays.com") || dnsDomainIs(host, "allgame.com") || dnsDomainIs(host, "allowancenet.com") || dnsDomainIs(host, "amish-heartland.com") || dnsDomainIs(host, "ancienthistory.about.com") || dnsDomainIs(host, "animals.about.com") || dnsDomainIs(host, "antenna.nl") || dnsDomainIs(host, "arcweb.sos.state.or.us") || dnsDomainIs(host, "artistmummer.homestead.com") || dnsDomainIs(host, "artists.vh1.com") || dnsDomainIs(host, "arts.lausd.k12.ca.us") || dnsDomainIs(host, "asiatravel.com") || dnsDomainIs(host, "asterius.com") || dnsDomainIs(host, "atlas.gc.ca") || dnsDomainIs(host, "atschool.eduweb.co.uk") || dnsDomainIs(host, "ayya.pd.net") || dnsDomainIs(host, "babelfish.altavista.com") || dnsDomainIs(host, "babylon5.warnerbros.com") || dnsDomainIs(host, "banzai.neosoft.com") || dnsDomainIs(host, "barneyonline.com") || dnsDomainIs(host, "baroque-music.com") || dnsDomainIs(host, "barsoom.msss.com") || dnsDomainIs(host, "baseball-almanac.com") || dnsDomainIs(host, "bcadventure.com") || dnsDomainIs(host, "beadiecritters.hosting4less.com") || dnsDomainIs(host, "beverlyscrafts.com") || dnsDomainIs(host, "biology.about.com") || dnsDomainIs(host, "birding.about.com") || dnsDomainIs(host, "boatsafe.com") || dnsDomainIs(host, "bombpop.com") || dnsDomainIs(host, "boulter.com") || dnsDomainIs(host, "bright-ideas-software.com") || dnsDomainIs(host, "buckman.pps.k12.or.us") || dnsDomainIs(host, "buffalobills.com") || dnsDomainIs(host, "bvsd.k12.co.us") || dnsDomainIs(host, "cagle.slate.msn.com") || dnsDomainIs(host, "calc.entisoft.com") || dnsDomainIs(host, "canada.gc.ca") || dnsDomainIs(host, "candleandsoap.about.com") || dnsDomainIs(host, "caselaw.lp.findlaw.com") || dnsDomainIs(host, "catalog.com") || dnsDomainIs(host, "catalog.socialstudies.com") || dnsDomainIs(host, "cavern.com") || dnsDomainIs(host, "cbs.sportsline.com") || dnsDomainIs(host, "cc.matsuyama-u.ac.jp") || dnsDomainIs(host, "celt.net") || dnsDomainIs(host, "cgfa.kelloggcreek.com") || dnsDomainIs(host, "channel4000.com") || dnsDomainIs(host, "chess.delorie.com") || dnsDomainIs(host, "chess.liveonthenet.com") || dnsDomainIs(host, "childfun.com") || dnsDomainIs(host, "christmas.com") || dnsDomainIs(host, "citystar.com") || dnsDomainIs(host, "claim.goldrush.com") || dnsDomainIs(host, "clairerosemaryjane.com") || dnsDomainIs(host, "clevermedia.com") || dnsDomainIs(host, "cobblestonepub.com") || dnsDomainIs(host, "codebrkr.infopages.net") || dnsDomainIs(host, "colitz.com") || dnsDomainIs(host, "collections.ic.gc.ca") || dnsDomainIs(host, "coloquio.com") || dnsDomainIs(host, "come.to") || dnsDomainIs(host, "coombs.anu.edu.au") || dnsDomainIs(host, "crafterscommunity.com") || dnsDomainIs(host, "craftsforkids.about.com") || dnsDomainIs(host, "creativity.net") || dnsDomainIs(host, "cslewis.drzeus.net") || dnsDomainIs(host, "cust.idl.com.au") || dnsDomainIs(host, "cvs.anu.edu.au") || dnsDomainIs(host, "cybersleuth-kids.com") || dnsDomainIs(host, "cybertown.com") || dnsDomainIs(host, "darkfish.com") || dnsDomainIs(host, "datadragon.com") || dnsDomainIs(host, "davesite.com") || dnsDomainIs(host, "dbertens.www.cistron.nl") || dnsDomainIs(host, "detnews.com") || dnsDomainIs(host, "dhr.dos.state.fl.us") || dnsDomainIs(host, "dialspace.dial.pipex.com") || dnsDomainIs(host, "dictionaries.travlang.com") || dnsDomainIs(host, "disney.go.com") || dnsDomainIs(host, "disneyland.disney.go.com") || dnsDomainIs(host, "district.gresham.k12.or.us") || dnsDomainIs(host, "dmarie.com") || dnsDomainIs(host, "dreamwater.com") || dnsDomainIs(host, "duke.fuse.net") || dnsDomainIs(host, "earlyamerica.com") || dnsDomainIs(host, "earthsky.com") || dnsDomainIs(host, "easyweb.easynet.co.uk") || dnsDomainIs(host, "ecards1.bansheeweb.com") || dnsDomainIs(host, "edugreen.teri.res.in") || dnsDomainIs(host, "edwardlear.tripod.com") || dnsDomainIs(host, "eelink.net") || dnsDomainIs(host, "elizabethsings.com") || dnsDomainIs(host, "enature.com") || dnsDomainIs(host, "encarta.msn.com") || dnsDomainIs(host, "endangeredspecie.com") || dnsDomainIs(host, "enterprise.america.com") || dnsDomainIs(host, "ericae.net") || dnsDomainIs(host, "esl.about.com") || dnsDomainIs(host, "eveander.com") || dnsDomainIs(host, "exn.ca") || dnsDomainIs(host, "fallscam.niagara.com") || dnsDomainIs(host, "family.go.com") || dnsDomainIs(host, "family2.go.com") || dnsDomainIs(host, "familyeducation.com") || dnsDomainIs(host, "finditquick.com") || dnsDomainIs(host, "fln-bma.yazigi.com.br") || dnsDomainIs(host, "fln-con.yazigi.com.br") || dnsDomainIs(host, "food.epicurious.com") || dnsDomainIs(host, "forums.sympatico.ca") || dnsDomainIs(host, "fotw.vexillum.com") || dnsDomainIs(host, "fox.nstn.ca") || dnsDomainIs(host, "framingham.com") || dnsDomainIs(host, "freevote.com") || dnsDomainIs(host, "freeweb.pdq.net") || dnsDomainIs(host, "games.yahoo.com") || dnsDomainIs(host, "gardening.sierrahome.com") || dnsDomainIs(host, "gardenofpraise.com") || dnsDomainIs(host, "gcclearn.gcc.cc.va.us") || dnsDomainIs(host, "genealogytoday.com") || dnsDomainIs(host, "genesis.ne.mediaone.net") || dnsDomainIs(host, "geniefind.com") || dnsDomainIs(host, "geography.about.com") || dnsDomainIs(host, "gf.state.wy.us") || dnsDomainIs(host, "gi.grolier.com") || dnsDomainIs(host, "golf.com") || dnsDomainIs(host, "greatseal.com") || dnsDomainIs(host, "guardians.net") || dnsDomainIs(host, "hamlet.hypermart.net") || dnsDomainIs(host, "happypuppy.com") || dnsDomainIs(host, "harcourt.fsc.follett.com") || dnsDomainIs(host, "haringkids.com") || dnsDomainIs(host, "harrietmaysavitz.com") || dnsDomainIs(host, "harrypotter.warnerbros.com") || dnsDomainIs(host, "hca.gilead.org.il") || dnsDomainIs(host, "header.future.easyspace.com") || dnsDomainIs(host, "historymedren.about.com") || dnsDomainIs(host, "home.att.net") || dnsDomainIs(host, "home.austin.rr.com") || dnsDomainIs(host, "home.capu.net") || dnsDomainIs(host, "home.cfl.rr.com") || dnsDomainIs(host, "home.clara.net") || dnsDomainIs(host, "home.clear.net.nz") || dnsDomainIs(host, "home.earthlink.net") || dnsDomainIs(host, "home.eznet.net") || dnsDomainIs(host, "home.flash.net") || dnsDomainIs(host, "home.hiwaay.net") || dnsDomainIs(host, "home.hkstar.com") || dnsDomainIs(host, "home.ici.net") || dnsDomainIs(host, "home.inreach.com") || dnsDomainIs(host, "home.interlynx.net") || dnsDomainIs(host, "home.istar.ca") || dnsDomainIs(host, "home.mira.net") || dnsDomainIs(host, "home.nycap.rr.com") || dnsDomainIs(host, "home.online.no") || dnsDomainIs(host, "home.pb.net") || dnsDomainIs(host, "home2.pacific.net.sg") || dnsDomainIs(host, "homearts.com") || dnsDomainIs(host, "homepage.mac.com") || dnsDomainIs(host, "hometown.aol.com") || dnsDomainIs(host, "homiliesbyemail.com") || dnsDomainIs(host, "hotei.fix.co.jp") || dnsDomainIs(host, "hotwired.lycos.com") || dnsDomainIs(host, "hp.vector.co.jp") || dnsDomainIs(host, "hum.amu.edu.pl") || dnsDomainIs(host, "i-cias.com") || dnsDomainIs(host, "icatapults.freeservers.com") || dnsDomainIs(host, "ind.cioe.com") || dnsDomainIs(host, "info.ex.ac.uk") || dnsDomainIs(host, "infocan.gc.ca") || dnsDomainIs(host, "infoservice.gc.ca") || dnsDomainIs(host, "interoz.com") || dnsDomainIs(host, "ireland.iol.ie") || dnsDomainIs(host, "is.dal.ca") || dnsDomainIs(host, "itss.raytheon.com") || dnsDomainIs(host, "iul.com") || dnsDomainIs(host, "jameswhitcombriley.com") || dnsDomainIs(host, "jellieszone.com") || dnsDomainIs(host, "jordan.sportsline.com") || dnsDomainIs(host, "judyanddavid.com") || dnsDomainIs(host, "jurai.murdoch.edu.au") || dnsDomainIs(host, "just.about.com") || dnsDomainIs(host, "kayleigh.tierranet.com") || dnsDomainIs(host, "kcwingwalker.tripod.com") || dnsDomainIs(host, "kidexchange.about.com") || dnsDomainIs(host, "kids-world.colgatepalmolive.com") || dnsDomainIs(host, "kids.mysterynet.com") || dnsDomainIs(host, "kids.ot.com") || dnsDomainIs(host, "kidsartscrafts.about.com") || dnsDomainIs(host, "kidsastronomy.about.com") || dnsDomainIs(host, "kidscience.about.com") || dnsDomainIs(host, "kidscience.miningco.com") || dnsDomainIs(host, "kidscollecting.about.com") || dnsDomainIs(host, "kidsfun.co.uk") || dnsDomainIs(host, "kidsinternet.about.com") || dnsDomainIs(host, "kidslangarts.about.com") || dnsDomainIs(host, "kidspenpals.about.com") || dnsDomainIs(host, "kitecast.com") || dnsDomainIs(host, "knight.city.ba.k12.md.us") || dnsDomainIs(host, "kodak.com") || dnsDomainIs(host, "kwanzaa4kids.homestead.com") || dnsDomainIs(host, "lagos.africaonline.com") || dnsDomainIs(host, "lancearmstrong.com") || dnsDomainIs(host, "landru.i-link-2.net") || dnsDomainIs(host, "lang.nagoya-u.ac.jp") || dnsDomainIs(host, "lascala.milano.it") || dnsDomainIs(host, "latinoculture.about.com") || dnsDomainIs(host, "litcal.yasuda-u.ac.jp") || dnsDomainIs(host, "littlebit.com") || dnsDomainIs(host, "live.edventures.com") || dnsDomainIs(host, "look.net") || dnsDomainIs(host, "lycoskids.infoplease.com") || dnsDomainIs(host, "lynx.uio.no") || dnsDomainIs(host, "macdict.dict.mq.edu.au") || dnsDomainIs(host, "maori.culture.co.nz") || dnsDomainIs(host, "marktwain.about.com") || dnsDomainIs(host, "marktwain.miningco.com") || dnsDomainIs(host, "mars2030.net") || dnsDomainIs(host, "martin.parasitology.mcgill.ca") || dnsDomainIs(host, "martinlutherking.8m.com") || dnsDomainIs(host, "mastercollector.com") || dnsDomainIs(host, "mathcentral.uregina.ca") || dnsDomainIs(host, "members.aol.com") || dnsDomainIs(host, "members.carol.net") || dnsDomainIs(host, "members.cland.net") || dnsDomainIs(host, "members.cruzio.com") || dnsDomainIs(host, "members.easyspace.com") || dnsDomainIs(host, "members.eisa.net.au") || dnsDomainIs(host, "members.home.net") || dnsDomainIs(host, "members.iinet.net.au") || dnsDomainIs(host, "members.nbci.com") || dnsDomainIs(host, "members.ozemail.com.au") || dnsDomainIs(host, "members.surfsouth.com") || dnsDomainIs(host, "members.theglobe.com") || dnsDomainIs(host, "members.tripod.com") || dnsDomainIs(host, "mexplaza.udg.mx") || dnsDomainIs(host, "mgfx.com") || dnsDomainIs(host, "microimg.com") || dnsDomainIs(host, "midusa.net") || dnsDomainIs(host, "mildan.com") || dnsDomainIs(host, "millennianet.com") || dnsDomainIs(host, "mindbreakers.e-fun.nu") || dnsDomainIs(host, "missjanet.xs4all.nl") || dnsDomainIs(host, "mistral.culture.fr") || dnsDomainIs(host, "mobileation.com") || dnsDomainIs(host, "mrshowbiz.go.com") || dnsDomainIs(host, "ms.simplenet.com") || dnsDomainIs(host, "museum.gov.ns.ca") || dnsDomainIs(host, "music.excite.com") || dnsDomainIs(host, "musicfinder.yahoo.com") || dnsDomainIs(host, "my.freeway.net") || dnsDomainIs(host, "mytrains.com") || dnsDomainIs(host, "nativeauthors.com") || dnsDomainIs(host, "nba.com") || dnsDomainIs(host, "nch.ari.net") || dnsDomainIs(host, "neonpeach.tripod.com") || dnsDomainIs(host, "net.indra.com") || dnsDomainIs(host, "ngeorgia.com") || dnsDomainIs(host, "ngp.ngpc.state.ne.us") || dnsDomainIs(host, "nhd.heinle.com") || dnsDomainIs(host, "nick.com") || dnsDomainIs(host, "normandy.eb.com") || dnsDomainIs(host, "northshore.shore.net") || dnsDomainIs(host, "now2000.com") || dnsDomainIs(host, "npc.nunavut.ca") || dnsDomainIs(host, "ns2.carib-link.net") || dnsDomainIs(host, "ntl.sympatico.ca") || dnsDomainIs(host, "oceanographer.navy.mil") || dnsDomainIs(host, "oddens.geog.uu.nl") || dnsDomainIs(host, "officialcitysites.com") || dnsDomainIs(host, "oneida-nation.net") || dnsDomainIs(host, "onlinegeorgia.com") || dnsDomainIs(host, "originator_2.tripod.com") || dnsDomainIs(host, "ortech-engr.com") || dnsDomainIs(host, "osage.voorhees.k12.nj.us") || dnsDomainIs(host, "osiris.sund.ac.uk") || dnsDomainIs(host, "ourworld.compuserve.com") || dnsDomainIs(host, "outdoorphoto.com") || dnsDomainIs(host, "pages.map.com") || dnsDomainIs(host, "pages.prodigy.com") || dnsDomainIs(host, "pages.prodigy.net") || dnsDomainIs(host, "pages.tca.net") || dnsDomainIs(host, "parcsafari.qc.ca") || dnsDomainIs(host, "parenthoodweb.com") || dnsDomainIs(host, "pathfinder.com") || dnsDomainIs(host, "people.clarityconnect.com") || dnsDomainIs(host, "people.enternet.com.au") || dnsDomainIs(host, "people.ne.mediaone.net") || dnsDomainIs(host, "phonics.jazzles.com") || dnsDomainIs(host, "pibburns.com") || dnsDomainIs(host, "pilgrims.net") || dnsDomainIs(host, "pinenet.com") || dnsDomainIs(host, "place.scholastic.com") || dnsDomainIs(host, "playground.kodak.com") || dnsDomainIs(host, "politicalgraveyard.com") || dnsDomainIs(host, "polk.ga.net") || dnsDomainIs(host, "pompstory.home.mindspring.com") || dnsDomainIs(host, "popularmechanics.com") || dnsDomainIs(host, "projects.edtech.sandi.net") || dnsDomainIs(host, "psyche.usno.navy.mil") || dnsDomainIs(host, "pubweb.parc.xerox.com") || dnsDomainIs(host, "puzzlemaker.school.discovery.com") || dnsDomainIs(host, "quest.classroom.com") || dnsDomainIs(host, "quilting.about.com") || dnsDomainIs(host, "rabbitmoon.home.mindspring.com") || dnsDomainIs(host, "radio.cbc.ca") || dnsDomainIs(host, "rats2u.com") || dnsDomainIs(host, "rbcm1.rbcm.gov.bc.ca") || dnsDomainIs(host, "readplay.com") || dnsDomainIs(host, "recipes4children.homestead.com") || dnsDomainIs(host, "redsox.com") || dnsDomainIs(host, "renaissance.district96.k12.il.us") || dnsDomainIs(host, "rhyme.lycos.com") || dnsDomainIs(host, "rhythmweb.com") || dnsDomainIs(host, "riverresource.com") || dnsDomainIs(host, "rockhoundingar.com") || dnsDomainIs(host, "rockies.mlb.com") || dnsDomainIs(host, "rosecity.net") || dnsDomainIs(host, "rr-vs.informatik.uni-ulm.de") || dnsDomainIs(host, "rubens.anu.edu.au") || dnsDomainIs(host, "rummelplatz.uni-mannheim.de") || dnsDomainIs(host, "sandbox.xerox.com") || dnsDomainIs(host, "sarah.fredart.com") || dnsDomainIs(host, "schmidel.com") || dnsDomainIs(host, "scholastic.com") || dnsDomainIs(host, "school.discovery.com") || dnsDomainIs(host, "schoolcentral.com") || dnsDomainIs(host, "seattletimes.nwsource.com") || dnsDomainIs(host, "sericulum.com") || dnsDomainIs(host, "sf.airforce.com") || dnsDomainIs(host, "shop.usps.com") || dnsDomainIs(host, "showcase.netins.net") || dnsDomainIs(host, "sikids.com") || dnsDomainIs(host, "sites.huji.ac.il") || dnsDomainIs(host, "sjliving.com") || dnsDomainIs(host, "skullduggery.com") || dnsDomainIs(host, "skyways.lib.ks.us") || dnsDomainIs(host, "snowdaymovie.nick.com") || dnsDomainIs(host, "sosa21.hypermart.net") || dnsDomainIs(host, "soundamerica.com") || dnsDomainIs(host, "spaceboy.nasda.go.jp") || dnsDomainIs(host, "sports.nfl.com") || dnsDomainIs(host, "sportsillustrated.cnn.com") || dnsDomainIs(host, "starwars.hasbro.com") || dnsDomainIs(host, "statelibrary.dcr.state.nc.us") || dnsDomainIs(host, "streetplay.com") || dnsDomainIs(host, "sts.gsc.nrcan.gc.ca") || dnsDomainIs(host, "sunniebunniezz.com") || dnsDomainIs(host, "sunsite.nus.edu.sg") || dnsDomainIs(host, "sunsite.sut.ac.jp") || dnsDomainIs(host, "superm.bart.nl") || dnsDomainIs(host, "surf.to") || dnsDomainIs(host, "svinet2.fs.fed.us") || dnsDomainIs(host, "swiminfo.com") || dnsDomainIs(host, "tabletennis.about.com") || dnsDomainIs(host, "teacher.scholastic.com") || dnsDomainIs(host, "theforce.net") || dnsDomainIs(host, "thejessicas.homestead.com") || dnsDomainIs(host, "themes.editthispage.com") || dnsDomainIs(host, "theory.uwinnipeg.ca") || dnsDomainIs(host, "theshadowlands.net") || dnsDomainIs(host, "thinks.com") || dnsDomainIs(host, "thryomanes.tripod.com") || dnsDomainIs(host, "time_zone.tripod.com") || dnsDomainIs(host, "titania.cobuild.collins.co.uk") || dnsDomainIs(host, "torre.duomo.pisa.it") || dnsDomainIs(host, "touregypt.net") || dnsDomainIs(host, "toycollecting.about.com") || dnsDomainIs(host, "trace.ntu.ac.uk") || dnsDomainIs(host, "travelwithkids.about.com") || dnsDomainIs(host, "tukids.tucows.com") || dnsDomainIs(host, "tv.yahoo.com") || dnsDomainIs(host, "tycho.usno.navy.mil") || dnsDomainIs(host, "ubl.artistdirect.com") || dnsDomainIs(host, "uk-pages.net") || dnsDomainIs(host, "ukraine.uazone.net") || dnsDomainIs(host, "unmuseum.mus.pa.us") || dnsDomainIs(host, "us.imdb.com") || dnsDomainIs(host, "userpage.chemie.fu-berlin.de") || dnsDomainIs(host, "userpage.fu-berlin.de") || dnsDomainIs(host, "userpages.aug.com") || dnsDomainIs(host, "users.aol.com") || dnsDomainIs(host, "users.bigpond.net.au") || dnsDomainIs(host, "users.breathemail.net") || dnsDomainIs(host, "users.erols.com") || dnsDomainIs(host, "users.imag.net") || dnsDomainIs(host, "users.inetw.net") || dnsDomainIs(host, "users.massed.net") || dnsDomainIs(host, "users.skynet.be") || dnsDomainIs(host, "users.uniserve.com") || dnsDomainIs(host, "venus.spaceports.com") || dnsDomainIs(host, "vgstrategies.about.com") || dnsDomainIs(host, "victorian.fortunecity.com") || dnsDomainIs(host, "vilenski.com") || dnsDomainIs(host, "village.infoweb.ne.jp") || dnsDomainIs(host, "virtual.finland.fi") || dnsDomainIs(host, "vrml.fornax.hu") || dnsDomainIs(host, "vvv.com") || dnsDomainIs(host, "w1.xrefer.com") || dnsDomainIs(host, "w3.one.net") || dnsDomainIs(host, "w3.rz-berlin.mpg.de") || dnsDomainIs(host, "w3.trib.com") || dnsDomainIs(host, "wallofsound.go.com") || dnsDomainIs(host, "web.aimnet.com") || dnsDomainIs(host, "web.ccsd.k12.wy.us") || dnsDomainIs(host, "web.cs.ualberta.ca") || dnsDomainIs(host, "web.idirect.com") || dnsDomainIs(host, "web.kyoto-inet.or.jp") || dnsDomainIs(host, "web.macam98.ac.il") || dnsDomainIs(host, "web.massvacation.com") || dnsDomainIs(host, "web.one.net.au") || dnsDomainIs(host, "web.qx.net") || dnsDomainIs(host, "web.uvic.ca") || dnsDomainIs(host, "web2.airmail.net") || dnsDomainIs(host, "webcoast.com") || dnsDomainIs(host, "webgames.kalisto.com") || dnsDomainIs(host, "webhome.idirect.com") || dnsDomainIs(host, "webpages.homestead.com") || dnsDomainIs(host, "webrum.uni-mannheim.de") || dnsDomainIs(host, "webusers.anet-stl.com") || dnsDomainIs(host, "welcome.to") || dnsDomainIs(host, "wgntv.com") || dnsDomainIs(host, "whales.magna.com.au") || dnsDomainIs(host, "wildheart.com") || dnsDomainIs(host, "wilstar.net") || dnsDomainIs(host, "winter-wonderland.com") || dnsDomainIs(host, "women.com") || dnsDomainIs(host, "woodrow.mpls.frb.fed.us") || dnsDomainIs(host, "wordzap.com") || dnsDomainIs(host, "worldkids.net") || dnsDomainIs(host, "worldwideguide.net") || dnsDomainIs(host, "ww3.bay.k12.fl.us") || dnsDomainIs(host, "ww3.sportsline.com") || dnsDomainIs(host, "www-groups.dcs.st-and.ac.uk") || dnsDomainIs(host, "www-public.rz.uni-duesseldorf.de") || dnsDomainIs(host, "www.1stkids.com") || dnsDomainIs(host, "www.2020tech.com") || dnsDomainIs(host, "www.21stcenturytoys.com") || dnsDomainIs(host, "www.4adventure.com") || dnsDomainIs(host, "www.50states.com") || dnsDomainIs(host, "www.800padutch.com") || dnsDomainIs(host, "www.88.com") || dnsDomainIs(host, "www.a-better.com") || dnsDomainIs(host, "www.aaa.com.au") || dnsDomainIs(host, "www.aacca.com") || dnsDomainIs(host, "www.aalbc.com") || dnsDomainIs(host, "www.aardman.com") || dnsDomainIs(host, "www.aardvarkelectric.com") || dnsDomainIs(host, "www.aawc.com") || dnsDomainIs(host, "www.ababmx.com") || dnsDomainIs(host, "www.abbeville.com") || dnsDomainIs(host, "www.abc.net.au") || dnsDomainIs(host, "www.abcb.com") || dnsDomainIs(host, "www.abctooncenter.com") || dnsDomainIs(host, "www.about.ch") || dnsDomainIs(host, "www.accessart.org.uk") || dnsDomainIs(host, "www.accu.or.jp") || dnsDomainIs(host, "www.accuweather.com") || dnsDomainIs(host, "www.achuka.co.uk") || dnsDomainIs(host, "www.acmecity.com") || dnsDomainIs(host, "www.acorn-group.com") || dnsDomainIs(host, "www.acs.ucalgary.ca") || dnsDomainIs(host, "www.actden.com") || dnsDomainIs(host, "www.actionplanet.com") || dnsDomainIs(host, "www.activityvillage.co.uk") || dnsDomainIs(host, "www.actwin.com") || dnsDomainIs(host, "www.adequate.com") || dnsDomainIs(host, "www.adidas.com") || dnsDomainIs(host, "www.advent-calendars.com") || dnsDomainIs(host, "www.aegis.com") || dnsDomainIs(host, "www.af.mil") || dnsDomainIs(host, "www.africaindex.africainfo.no") || dnsDomainIs(host, "www.africam.com") || dnsDomainIs(host, "www.africancrafts.com") || dnsDomainIs(host, "www.aggressive.com") || dnsDomainIs(host, "www.aghines.com") || dnsDomainIs(host, "www.agirlsworld.com") || dnsDomainIs(host, "www.agora.stm.it") || dnsDomainIs(host, "www.agriculture.com") || dnsDomainIs(host, "www.aikidofaq.com") || dnsDomainIs(host, "www.ajkids.com") || dnsDomainIs(host, "www.akfkoala.gil.com.au") || dnsDomainIs(host, "www.akhlah.com") || dnsDomainIs(host, "www.alabamainfo.com") || dnsDomainIs(host, "www.aland.fi") || dnsDomainIs(host, "www.albion.com") || dnsDomainIs(host, "www.alcoholismhelp.com") || dnsDomainIs(host, "www.alcottweb.com") || dnsDomainIs(host, "www.alfanet.it") || dnsDomainIs(host, "www.alfy.com") || dnsDomainIs(host, "www.algebra-online.com") || dnsDomainIs(host, "www.alienexplorer.com") || dnsDomainIs(host, "www.aliensatschool.com") || dnsDomainIs(host, "www.all-links.com") || dnsDomainIs(host, "www.alldetroit.com") || dnsDomainIs(host, "www.allexperts.com") || dnsDomainIs(host, "www.allmixedup.com") || dnsDomainIs(host, "www.allmusic.com") || dnsDomainIs(host, "www.almanac.com") || dnsDomainIs(host, "www.almaz.com") || dnsDomainIs(host, "www.almondseed.com") || dnsDomainIs(host, "www.aloha.com") || dnsDomainIs(host, "www.aloha.net") || dnsDomainIs(host, "www.altonweb.com") || dnsDomainIs(host, "www.alyeska-pipe.com") || dnsDomainIs(host, "www.am-wood.com") || dnsDomainIs(host, "www.amazingadventure.com") || dnsDomainIs(host, "www.amazon.com") || dnsDomainIs(host, "www.americancheerleader.com") || dnsDomainIs(host, "www.americancowboy.com") || dnsDomainIs(host, "www.americangirl.com") || dnsDomainIs(host, "www.americanparknetwork.com") || dnsDomainIs(host, "www.americansouthwest.net") || dnsDomainIs(host, "www.americanwest.com") || dnsDomainIs(host, "www.ameritech.net") || dnsDomainIs(host, "www.amtexpo.com") || dnsDomainIs(host, "www.anbg.gov.au") || dnsDomainIs(host, "www.anc.org.za") || dnsDomainIs(host, "www.ancientegypt.co.uk") || dnsDomainIs(host, "www.angelfire.com") || dnsDomainIs(host, "www.angelsbaseball.com") || dnsDomainIs(host, "www.anholt.co.uk") || dnsDomainIs(host, "www.animabets.com") || dnsDomainIs(host, "www.animalnetwork.com") || dnsDomainIs(host, "www.animalpicturesarchive.com") || dnsDomainIs(host, "www.anime-genesis.com") || dnsDomainIs(host, "www.annefrank.com") || dnsDomainIs(host, "www.annefrank.nl") || dnsDomainIs(host, "www.annie75.com") || dnsDomainIs(host, "www.antbee.com") || dnsDomainIs(host, "www.antiquetools.com") || dnsDomainIs(host, "www.antiquetoy.com") || dnsDomainIs(host, "www.anzsbeg.org.au") || dnsDomainIs(host, "www.aol.com") || dnsDomainIs(host, "www.aone.com") || dnsDomainIs(host, "www.aphids.com") || dnsDomainIs(host, "www.apl.com") || dnsDomainIs(host, "www.aplusmath.com") || dnsDomainIs(host, "www.applebookshop.co.uk") || dnsDomainIs(host, "www.appropriatesoftware.com") || dnsDomainIs(host, "www.appukids.com") || dnsDomainIs(host, "www.april-joy.com") || dnsDomainIs(host, "www.arab.net") || dnsDomainIs(host, "www.aracnet.com") || dnsDomainIs(host, "www.arborday.com") || dnsDomainIs(host, "www.arcadevillage.com") || dnsDomainIs(host, "www.archiecomics.com") || dnsDomainIs(host, "www.archives.state.al.us") || dnsDomainIs(host, "www.arctic.ca") || dnsDomainIs(host, "www.ardenjohnson.com") || dnsDomainIs(host, "www.aristotle.net") || dnsDomainIs(host, "www.arizhwys.com") || dnsDomainIs(host, "www.arizonaguide.com") || dnsDomainIs(host, "www.arlingtoncemetery.com") || dnsDomainIs(host, "www.armory.com") || dnsDomainIs(host, "www.armwrestling.com") || dnsDomainIs(host, "www.arnprior.com") || dnsDomainIs(host, "www.artabunga.com") || dnsDomainIs(host, "www.artcarte.com") || dnsDomainIs(host, "www.artchive.com") || dnsDomainIs(host, "www.artcontest.com") || dnsDomainIs(host, "www.artcyclopedia.com") || dnsDomainIs(host, "www.artisandevelopers.com") || dnsDomainIs(host, "www.artlex.com") || dnsDomainIs(host, "www.artsandkids.com") || dnsDomainIs(host, "www.artyastro.com") || dnsDomainIs(host, "www.arwhead.com") || dnsDomainIs(host, "www.asahi-net.or.jp") || dnsDomainIs(host, "www.asap.unimelb.edu.au") || dnsDomainIs(host, "www.ascpl.lib.oh.us") || dnsDomainIs(host, "www.asia-art.net") || dnsDomainIs(host, "www.asiabigtime.com") || dnsDomainIs(host, "www.asianart.com") || dnsDomainIs(host, "www.asiatour.com") || dnsDomainIs(host, "www.asiaweek.com") || dnsDomainIs(host, "www.askanexpert.com") || dnsDomainIs(host, "www.askbasil.com") || dnsDomainIs(host, "www.assa.org.au") || dnsDomainIs(host, "www.ast.cam.ac.uk") || dnsDomainIs(host, "www.astronomy.com") || dnsDomainIs(host, "www.astros.com") || dnsDomainIs(host, "www.atek.com") || dnsDomainIs(host, "www.athlete.com") || dnsDomainIs(host, "www.athropolis.com") || dnsDomainIs(host, "www.atkielski.com") || dnsDomainIs(host, "www.atlantabraves.com") || dnsDomainIs(host, "www.atlantafalcons.com") || dnsDomainIs(host, "www.atlantathrashers.com") || dnsDomainIs(host, "www.atlanticus.com") || dnsDomainIs(host, "www.atm.ch.cam.ac.uk") || dnsDomainIs(host, "www.atom.co.jp") || dnsDomainIs(host, "www.atomicarchive.com") || dnsDomainIs(host, "www.att.com") || dnsDomainIs(host, "www.audreywood.com") || dnsDomainIs(host, "www.auntannie.com") || dnsDomainIs(host, "www.auntie.com") || dnsDomainIs(host, "www.avi-writer.com") || dnsDomainIs(host, "www.awesomeclipartforkids.com") || dnsDomainIs(host, "www.awhitehorse.com") || dnsDomainIs(host, "www.axess.com") || dnsDomainIs(host, "www.ayles.com") || dnsDomainIs(host, "www.ayn.ca") || dnsDomainIs(host, "www.azcardinals.com") || dnsDomainIs(host, "www.azdiamondbacks.com") || dnsDomainIs(host, "www.azsolarcenter.com") || dnsDomainIs(host, "www.azstarnet.com") || dnsDomainIs(host, "www.aztecafoods.com") || dnsDomainIs(host, "www.b-witched.com") || dnsDomainIs(host, "www.baberuthmuseum.com") || dnsDomainIs(host, "www.backstreetboys.com") || dnsDomainIs(host, "www.bagheera.com") || dnsDomainIs(host, "www.bahamas.com") || dnsDomainIs(host, "www.baileykids.com") || dnsDomainIs(host, "www.baldeagleinfo.com") || dnsDomainIs(host, "www.balloonhq.com") || dnsDomainIs(host, "www.balloonzone.com") || dnsDomainIs(host, "www.ballparks.com") || dnsDomainIs(host, "www.balmoralsoftware.com") || dnsDomainIs(host, "www.banja.com") || dnsDomainIs(host, "www.banph.com") || dnsDomainIs(host, "www.barbie.com") || dnsDomainIs(host, "www.barkingbuddies.com") || dnsDomainIs(host, "www.barnsdle.demon.co.uk") || dnsDomainIs(host, "www.barrysclipart.com") || dnsDomainIs(host, "www.bartleby.com") || dnsDomainIs(host, "www.baseplate.com") || dnsDomainIs(host, "www.batman-superman.com") || dnsDomainIs(host, "www.batmanbeyond.com") || dnsDomainIs(host, "www.bbc.co.uk") || dnsDomainIs(host, "www.bbhighway.com") || dnsDomainIs(host, "www.bboy.com") || dnsDomainIs(host, "www.bcit.tec.nj.us") || dnsDomainIs(host, "www.bconnex.net") || dnsDomainIs(host, "www.bcpl.net") || dnsDomainIs(host, "www.beach-net.com") || dnsDomainIs(host, "www.beachboys.com") || dnsDomainIs(host, "www.beakman.com") || dnsDomainIs(host, "www.beano.co.uk") || dnsDomainIs(host, "www.beans.demon.co.uk") || dnsDomainIs(host, "www.beartime.com") || dnsDomainIs(host, "www.bearyspecial.co.uk") || dnsDomainIs(host, "www.bedtime.com") || dnsDomainIs(host, "www.beingme.com") || dnsDomainIs(host, "www.belizeexplorer.com") || dnsDomainIs(host, "www.bell-labs.com") || dnsDomainIs(host, "www.bemorecreative.com") || dnsDomainIs(host, "www.bengals.com") || dnsDomainIs(host, "www.benjerry.com") || dnsDomainIs(host, "www.bennygoodsport.com") || dnsDomainIs(host, "www.berenstainbears.com") || dnsDomainIs(host, "www.beringia.com") || dnsDomainIs(host, "www.beritsbest.com") || dnsDomainIs(host, "www.berksweb.com") || dnsDomainIs(host, "www.best.com") || dnsDomainIs(host, "www.betsybyars.com") || dnsDomainIs(host, "www.bfro.net") || dnsDomainIs(host, "www.bgmm.com") || dnsDomainIs(host, "www.bibliography.com") || dnsDomainIs(host, "www.bigblue.com.au") || dnsDomainIs(host, "www.bigchalk.com") || dnsDomainIs(host, "www.bigidea.com") || dnsDomainIs(host, "www.bigtop.com") || dnsDomainIs(host, "www.bikecrawler.com") || dnsDomainIs(host, "www.billboard.com") || dnsDomainIs(host, "www.billybear4kids.com") || dnsDomainIs(host, "www.biography.com") || dnsDomainIs(host, "www.birdnature.com") || dnsDomainIs(host, "www.birdsnways.com") || dnsDomainIs(host, "www.birdtimes.com") || dnsDomainIs(host, "www.birminghamzoo.com") || dnsDomainIs(host, "www.birthdaypartyideas.com") || dnsDomainIs(host, "www.bis.arachsys.com") || dnsDomainIs(host, "www.bkgm.com") || dnsDomainIs(host, "www.blackbaseball.com") || dnsDomainIs(host, "www.blackbeardthepirate.com") || dnsDomainIs(host, "www.blackbeltmag.com") || dnsDomainIs(host, "www.blackfacts.com") || dnsDomainIs(host, "www.blackfeetnation.com") || dnsDomainIs(host, "www.blackhills-info.com") || dnsDomainIs(host, "www.blackholegang.com") || dnsDomainIs(host, "www.blaque.net") || dnsDomainIs(host, "www.blarg.net") || dnsDomainIs(host, "www.blasternaut.com") || dnsDomainIs(host, "www.blizzard.com") || dnsDomainIs(host, "www.blocksite.com") || dnsDomainIs(host, "www.bluejackets.com") || dnsDomainIs(host, "www.bluejays.ca") || dnsDomainIs(host, "www.bluemountain.com") || dnsDomainIs(host, "www.blupete.com") || dnsDomainIs(host, "www.blyton.co.uk") || dnsDomainIs(host, "www.boatnerd.com") || dnsDomainIs(host, "www.boatsafe.com") || dnsDomainIs(host, "www.bonus.com") || dnsDomainIs(host, "www.boowakwala.com") || dnsDomainIs(host, "www.bostonbruins.com") || dnsDomainIs(host, "www.braceface.com") || dnsDomainIs(host, "www.bracesinfo.com") || dnsDomainIs(host, "www.bradkent.com") || dnsDomainIs(host, "www.brainium.com") || dnsDomainIs(host, "www.brainmania.com") || dnsDomainIs(host, "www.brainpop.com") || dnsDomainIs(host, "www.bridalcave.com") || dnsDomainIs(host, "www.brightmoments.com") || dnsDomainIs(host, "www.britannia.com") || dnsDomainIs(host, "www.britannica.com") || dnsDomainIs(host, "www.british-museum.ac.uk") || dnsDomainIs(host, "www.brookes.ac.uk") || dnsDomainIs(host, "www.brookfieldreader.com") || dnsDomainIs(host, "www.btinternet.com") || dnsDomainIs(host, "www.bubbledome.co.nz") || dnsDomainIs(host, "www.buccaneers.com") || dnsDomainIs(host, "www.buffy.com") || dnsDomainIs(host, "www.bullying.co.uk") || dnsDomainIs(host, "www.bumply.com") || dnsDomainIs(host, "www.bungi.com") || dnsDomainIs(host, "www.burlco.lib.nj.us") || dnsDomainIs(host, "www.burlingamepezmuseum.com") || dnsDomainIs(host, "www.bus.ualberta.ca") || dnsDomainIs(host, "www.busprod.com") || dnsDomainIs(host, "www.butlerart.com") || dnsDomainIs(host, "www.butterflies.com") || dnsDomainIs(host, "www.butterflyfarm.co.cr") || dnsDomainIs(host, "www.bway.net") || dnsDomainIs(host, "www.bydonovan.com") || dnsDomainIs(host, "www.ca-mall.com") || dnsDomainIs(host, "www.cabinessence.com") || dnsDomainIs(host, "www.cablecarmuseum.com") || dnsDomainIs(host, "www.cadbury.co.uk") || dnsDomainIs(host, "www.calendarzone.com") || dnsDomainIs(host, "www.calgaryflames.com") || dnsDomainIs(host, "www.californiamissions.com") || dnsDomainIs(host, "www.camalott.com") || dnsDomainIs(host, "www.camelotintl.com") || dnsDomainIs(host, "www.campbellsoup.com") || dnsDomainIs(host, "www.camvista.com") || dnsDomainIs(host, "www.canadiens.com") || dnsDomainIs(host, "www.canals.state.ny.us") || dnsDomainIs(host, "www.candlelightstories.com") || dnsDomainIs(host, "www.candles-museum.com") || dnsDomainIs(host, "www.candystand.com") || dnsDomainIs(host, "www.caneshockey.com") || dnsDomainIs(host, "www.canismajor.com") || dnsDomainIs(host, "www.canucks.com") || dnsDomainIs(host, "www.capecod.net") || dnsDomainIs(host, "www.capital.net") || dnsDomainIs(host, "www.capstonestudio.com") || dnsDomainIs(host, "www.cardblvd.com") || dnsDomainIs(host, "www.caro.net") || dnsDomainIs(host, "www.carolhurst.com") || dnsDomainIs(host, "www.carr.lib.md.us") || dnsDomainIs(host, "www.cartooncorner.com") || dnsDomainIs(host, "www.cartooncritters.com") || dnsDomainIs(host, "www.cartoonnetwork.com") || dnsDomainIs(host, "www.carvingpatterns.com") || dnsDomainIs(host, "www.cashuniversity.com") || dnsDomainIs(host, "www.castles-of-britain.com") || dnsDomainIs(host, "www.castlewales.com") || dnsDomainIs(host, "www.catholic-forum.com") || dnsDomainIs(host, "www.catholic.net") || dnsDomainIs(host, "www.cattle.guelph.on.ca") || dnsDomainIs(host, "www.cavedive.com") || dnsDomainIs(host, "www.caveofthewinds.com") || dnsDomainIs(host, "www.cbc4kids.ca") || dnsDomainIs(host, "www.ccer.ggl.ruu.nl") || dnsDomainIs(host, "www.ccnet.com") || dnsDomainIs(host, "www.celineonline.com") || dnsDomainIs(host, "www.cellsalive.com") || dnsDomainIs(host, "www.centuryinshoes.com") || dnsDomainIs(host, "www.cfl.ca") || dnsDomainIs(host, "www.channel4.com") || dnsDomainIs(host, "www.channel8.net") || dnsDomainIs(host, "www.chanukah99.com") || dnsDomainIs(host, "www.charged.com") || dnsDomainIs(host, "www.chargers.com") || dnsDomainIs(host, "www.charlotte.com") || dnsDomainIs(host, "www.chaseday.com") || dnsDomainIs(host, "www.chateauversailles.fr") || dnsDomainIs(host, "www.cheatcc.com") || dnsDomainIs(host, "www.cheerleading.net") || dnsDomainIs(host, "www.cheese.com") || dnsDomainIs(host, "www.chem4kids.com") || dnsDomainIs(host, "www.chemicool.com") || dnsDomainIs(host, "www.cherbearsden.com") || dnsDomainIs(host, "www.chesskids.com") || dnsDomainIs(host, "www.chessvariants.com") || dnsDomainIs(host, "www.cheungswingchun.com") || dnsDomainIs(host, "www.chevroncars.com") || dnsDomainIs(host, "www.chibi.simplenet.com") || dnsDomainIs(host, "www.chicagobears.com") || dnsDomainIs(host, "www.chicagoblackhawks.com") || dnsDomainIs(host, "www.chickasaw.net") || dnsDomainIs(host, "www.childrensmusic.co.uk") || dnsDomainIs(host, "www.childrenssoftware.com") || dnsDomainIs(host, "www.childrenstory.com") || dnsDomainIs(host, "www.childrenwithdiabetes.com") || dnsDomainIs(host, "www.chinapage.com") || dnsDomainIs(host, "www.chinatoday.com") || dnsDomainIs(host, "www.chinavista.com") || dnsDomainIs(host, "www.chinnet.net") || dnsDomainIs(host, "www.chiquita.com") || dnsDomainIs(host, "www.chisox.com") || dnsDomainIs(host, "www.chivalry.com") || dnsDomainIs(host, "www.christiananswers.net") || dnsDomainIs(host, "www.christianity.com") || dnsDomainIs(host, "www.christmas.com") || dnsDomainIs(host, "www.christmas98.com") || dnsDomainIs(host, "www.chron.com") || dnsDomainIs(host, "www.chronique.com") || dnsDomainIs(host, "www.chuckecheese.com") || dnsDomainIs(host, "www.chucklebait.com") || dnsDomainIs(host, "www.chunkymonkey.com") || dnsDomainIs(host, "www.ci.chi.il.us") || dnsDomainIs(host, "www.ci.nyc.ny.us") || dnsDomainIs(host, "www.ci.phoenix.az.us") || dnsDomainIs(host, "www.ci.san-diego.ca.us") || dnsDomainIs(host, "www.cibc.com") || dnsDomainIs(host, "www.ciderpresspottery.com") || dnsDomainIs(host, "www.cincinnatireds.com") || dnsDomainIs(host, "www.circusparade.com") || dnsDomainIs(host, "www.circusweb.com") || dnsDomainIs(host, "www.cirquedusoleil.com") || dnsDomainIs(host, "www.cit.state.vt.us") || dnsDomainIs(host, "www.citycastles.com") || dnsDomainIs(host, "www.cityu.edu.hk") || dnsDomainIs(host, "www.civicmind.com") || dnsDomainIs(host, "www.civil-war.net") || dnsDomainIs(host, "www.civilization.ca") || dnsDomainIs(host, "www.cl.cam.ac.uk") || dnsDomainIs(host, "www.clantongang.com") || dnsDomainIs(host, "www.clark.net") || dnsDomainIs(host, "www.classicgaming.com") || dnsDomainIs(host, "www.claus.com") || dnsDomainIs(host, "www.clayz.com") || dnsDomainIs(host, "www.clearcf.uvic.ca") || dnsDomainIs(host, "www.clearlight.com") || dnsDomainIs(host, "www.clemusart.com") || dnsDomainIs(host, "www.clevelandbrowns.com") || dnsDomainIs(host, "www.clipartcastle.com") || dnsDomainIs(host, "www.clubi.ie") || dnsDomainIs(host, "www.cnn.com") || dnsDomainIs(host, "www.co.henrico.va.us") || dnsDomainIs(host, "www.coax.net") || dnsDomainIs(host, "www.cocacola.com") || dnsDomainIs(host, "www.cocori.com") || dnsDomainIs(host, "www.codesmiths.com") || dnsDomainIs(host, "www.codetalk.fed.us") || dnsDomainIs(host, "www.coin-gallery.com") || dnsDomainIs(host, "www.colinthompson.com") || dnsDomainIs(host, "www.collectoronline.com") || dnsDomainIs(host, "www.colonialhall.com") || dnsDomainIs(host, "www.coloradoavalanche.com") || dnsDomainIs(host, "www.coloradorockies.com") || dnsDomainIs(host, "www.colormathpink.com") || dnsDomainIs(host, "www.colts.com") || dnsDomainIs(host, "www.comet.net") || dnsDomainIs(host, "www.cometsystems.com") || dnsDomainIs(host, "www.comicbookresources.com") || dnsDomainIs(host, "www.comicspage.com") || dnsDomainIs(host, "www.compassnet.com") || dnsDomainIs(host, "www.compleatbellairs.com") || dnsDomainIs(host, "www.comptons.com") || dnsDomainIs(host, "www.concentric.net") || dnsDomainIs(host, "www.congogorillaforest.com") || dnsDomainIs(host, "www.conjuror.com") || dnsDomainIs(host, "www.conk.com") || dnsDomainIs(host, "www.conservation.state.mo.us") || dnsDomainIs(host, "www.contracostatimes.com") || dnsDomainIs(host, "www.control.chalmers.se") || dnsDomainIs(host, "www.cookierecipe.com") || dnsDomainIs(host, "www.cooljapanesetoys.com") || dnsDomainIs(host, "www.cooper.com") || dnsDomainIs(host, "www.corpcomm.net") || dnsDomainIs(host, "www.corrietenboom.com") || dnsDomainIs(host, "www.corynet.com") || dnsDomainIs(host, "www.corypaints.com") || dnsDomainIs(host, "www.cosmosmith.com") || dnsDomainIs(host, "www.countdown2000.com") || dnsDomainIs(host, "www.cowboy.net") || dnsDomainIs(host, "www.cowboypal.com") || dnsDomainIs(host, "www.cowcreek.com") || dnsDomainIs(host, "www.cowgirl.net") || dnsDomainIs(host, "www.cowgirls.com") || dnsDomainIs(host, "www.cp.duluth.mn.us") || dnsDomainIs(host, "www.cpsweb.com") || dnsDomainIs(host, "www.craftideas.com") || dnsDomainIs(host, "www.craniamania.com") || dnsDomainIs(host, "www.crater.lake.national-park.com") || dnsDomainIs(host, "www.crayoncrawler.com") || dnsDomainIs(host, "www.crazybone.com") || dnsDomainIs(host, "www.crazybones.com") || dnsDomainIs(host, "www.crd.ge.com") || dnsDomainIs(host, "www.create4kids.com") || dnsDomainIs(host, "www.creativemusic.com") || dnsDomainIs(host, "www.crocodilian.com") || dnsDomainIs(host, "www.crop.cri.nz") || dnsDomainIs(host, "www.cruzio.com") || dnsDomainIs(host, "www.crwflags.com") || dnsDomainIs(host, "www.cryptograph.com") || dnsDomainIs(host, "www.cryst.bbk.ac.uk") || dnsDomainIs(host, "www.cs.bilkent.edu.tr") || dnsDomainIs(host, "www.cs.man.ac.uk") || dnsDomainIs(host, "www.cs.sfu.ca") || dnsDomainIs(host, "www.cs.ubc.ca") || dnsDomainIs(host, "www.csd.uu.se") || dnsDomainIs(host, "www.csmonitor.com") || dnsDomainIs(host, "www.csse.monash.edu.au") || dnsDomainIs(host, "www.cstone.net") || dnsDomainIs(host, "www.csu.edu.au") || dnsDomainIs(host, "www.cubs.com") || dnsDomainIs(host, "www.culture.fr") || dnsDomainIs(host, "www.cultures.com") || dnsDomainIs(host, "www.curtis-collection.com") || dnsDomainIs(host, "www.cut-the-knot.com") || dnsDomainIs(host, "www.cws-scf.ec.gc.ca") || dnsDomainIs(host, "www.cyber-dyne.com") || dnsDomainIs(host, "www.cyberbee.com") || dnsDomainIs(host, "www.cyberbee.net") || dnsDomainIs(host, "www.cybercom.net") || dnsDomainIs(host, "www.cybercomm.net") || dnsDomainIs(host, "www.cybercomm.nl") || dnsDomainIs(host, "www.cybercorp.co.nz") || dnsDomainIs(host, "www.cybercs.com") || dnsDomainIs(host, "www.cybergoal.com") || dnsDomainIs(host, "www.cyberkids.com") || dnsDomainIs(host, "www.cyberspaceag.com") || dnsDomainIs(host, "www.cyberteens.com") || dnsDomainIs(host, "www.cybertours.com") || dnsDomainIs(host, "www.cybiko.com") || dnsDomainIs(host, "www.czweb.com") || dnsDomainIs(host, "www.d91.k12.id.us") || dnsDomainIs(host, "www.dailygrammar.com") || dnsDomainIs(host, "www.dakidz.com") || dnsDomainIs(host, "www.dalejarrettonline.com") || dnsDomainIs(host, "www.dallascowboys.com") || dnsDomainIs(host, "www.dallasdogndisc.com") || dnsDomainIs(host, "www.dallasstars.com") || dnsDomainIs(host, "www.damnyankees.com") || dnsDomainIs(host, "www.danceart.com") || dnsDomainIs(host, "www.daniellesplace.com") || dnsDomainIs(host, "www.dare-america.com") || dnsDomainIs(host, "www.darkfish.com") || dnsDomainIs(host, "www.darsbydesign.com") || dnsDomainIs(host, "www.datadragon.com") || dnsDomainIs(host, "www.davidreilly.com") || dnsDomainIs(host, "www.dccomics.com") || dnsDomainIs(host, "www.dcn.davis.ca.us") || dnsDomainIs(host, "www.deepseaworld.com") || dnsDomainIs(host, "www.delawaretribeofindians.nsn.us") || dnsDomainIs(host, "www.demon.co.uk") || dnsDomainIs(host, "www.denverbroncos.com") || dnsDomainIs(host, "www.denverpost.com") || dnsDomainIs(host, "www.dep.state.pa.us") || dnsDomainIs(host, "www.desert-fairy.com") || dnsDomainIs(host, "www.desert-storm.com") || dnsDomainIs(host, "www.desertusa.com") || dnsDomainIs(host, "www.designltd.com") || dnsDomainIs(host, "www.designsbykat.com") || dnsDomainIs(host, "www.detnews.com") || dnsDomainIs(host, "www.detroitlions.com") || dnsDomainIs(host, "www.detroitredwings.com") || dnsDomainIs(host, "www.detroittigers.com") || dnsDomainIs(host, "www.deutsches-museum.de") || dnsDomainIs(host, "www.devilray.com") || dnsDomainIs(host, "www.dhorse.com") || dnsDomainIs(host, "www.diana-ross.co.uk") || dnsDomainIs(host, "www.dianarossandthesupremes.net") || dnsDomainIs(host, "www.diaryproject.com") || dnsDomainIs(host, "www.dickbutkus.com") || dnsDomainIs(host, "www.dickshovel.com") || dnsDomainIs(host, "www.dictionary.com") || dnsDomainIs(host, "www.didyouknow.com") || dnsDomainIs(host, "www.diegorivera.com") || dnsDomainIs(host, "www.digitalcentury.com") || dnsDomainIs(host, "www.digitaldog.com") || dnsDomainIs(host, "www.digiweb.com") || dnsDomainIs(host, "www.dimdima.com") || dnsDomainIs(host, "www.dinodon.com") || dnsDomainIs(host, "www.dinosauria.com") || dnsDomainIs(host, "www.discovereso.com") || dnsDomainIs(host, "www.discovergalapagos.com") || dnsDomainIs(host, "www.discovergames.com") || dnsDomainIs(host, "www.discoveringarchaeology.com") || dnsDomainIs(host, "www.discoveringmontana.com") || dnsDomainIs(host, "www.discoverlearning.com") || dnsDomainIs(host, "www.discovery.com") || dnsDomainIs(host, "www.disknet.com") || dnsDomainIs(host, "www.disney.go.com") || dnsDomainIs(host, "www.distinguishedwomen.com") || dnsDomainIs(host, "www.dkonline.com") || dnsDomainIs(host, "www.dltk-kids.com") || dnsDomainIs(host, "www.dmgi.com") || dnsDomainIs(host, "www.dnr.state.md.us") || dnsDomainIs(host, "www.dnr.state.mi.us") || dnsDomainIs(host, "www.dnr.state.wi.us") || dnsDomainIs(host, "www.dodgers.com") || dnsDomainIs(host, "www.dodoland.com") || dnsDomainIs(host, "www.dog-play.com") || dnsDomainIs(host, "www.dogbreedinfo.com") || dnsDomainIs(host, "www.doginfomat.com") || dnsDomainIs(host, "www.dole5aday.com") || dnsDomainIs(host, "www.dollart.com") || dnsDomainIs(host, "www.dolliedish.com") || dnsDomainIs(host, "www.dome2000.co.uk") || dnsDomainIs(host, "www.domtar.com") || dnsDomainIs(host, "www.donegal.k12.pa.us") || dnsDomainIs(host, "www.dorneypark.com") || dnsDomainIs(host, "www.dorothyhinshawpatent.com") || dnsDomainIs(host, "www.dougweb.com") || dnsDomainIs(host, "www.dps.state.ak.us") || dnsDomainIs(host, "www.draw3d.com") || dnsDomainIs(host, "www.dreamgate.com") || dnsDomainIs(host, "www.dreamkitty.com") || dnsDomainIs(host, "www.dreamscape.com") || dnsDomainIs(host, "www.dreamtime.net.au") || dnsDomainIs(host, "www.drpeppermuseum.com") || dnsDomainIs(host, "www.drscience.com") || dnsDomainIs(host, "www.drseward.com") || dnsDomainIs(host, "www.drtoy.com") || dnsDomainIs(host, "www.dse.nl") || dnsDomainIs(host, "www.dtic.mil") || dnsDomainIs(host, "www.duracell.com") || dnsDomainIs(host, "www.dustbunny.com") || dnsDomainIs(host, "www.dynanet.com") || dnsDomainIs(host, "www.eagerreaders.com") || dnsDomainIs(host, "www.eaglekids.com") || dnsDomainIs(host, "www.earthcalendar.net") || dnsDomainIs(host, "www.earthday.net") || dnsDomainIs(host, "www.earthdog.com") || dnsDomainIs(host, "www.earthwatch.com") || dnsDomainIs(host, "www.ease.com") || dnsDomainIs(host, "www.eastasia.ws") || dnsDomainIs(host, "www.easytype.com") || dnsDomainIs(host, "www.eblewis.com") || dnsDomainIs(host, "www.ebs.hw.ac.uk") || dnsDomainIs(host, "www.eclipse.net") || dnsDomainIs(host, "www.eco-pros.com") || dnsDomainIs(host, "www.edbydesign.com") || dnsDomainIs(host, "www.eddytheeco-dog.com") || dnsDomainIs(host, "www.edgate.com") || dnsDomainIs(host, "www.edmontonoilers.com") || dnsDomainIs(host, "www.edu-source.com") || dnsDomainIs(host, "www.edu.gov.on.ca") || dnsDomainIs(host, "www.edu4kids.com") || dnsDomainIs(host, "www.educ.uvic.ca") || dnsDomainIs(host, "www.educate.org.uk") || dnsDomainIs(host, "www.education-world.com") || dnsDomainIs(host, "www.edunet.com") || dnsDomainIs(host, "www.eduplace.com") || dnsDomainIs(host, "www.edupuppy.com") || dnsDomainIs(host, "www.eduweb.com") || dnsDomainIs(host, "www.ee.ryerson.ca") || dnsDomainIs(host, "www.ee.surrey.ac.uk") || dnsDomainIs(host, "www.eeggs.com") || dnsDomainIs(host, "www.efes.com") || dnsDomainIs(host, "www.egalvao.com") || dnsDomainIs(host, "www.egypt.com") || dnsDomainIs(host, "www.egyptology.com") || dnsDomainIs(host, "www.ehobbies.com") || dnsDomainIs(host, "www.ehow.com") || dnsDomainIs(host, "www.eia.brad.ac.uk") || dnsDomainIs(host, "www.elbalero.gob.mx") || dnsDomainIs(host, "www.eliki.com") || dnsDomainIs(host, "www.elnino.com") || dnsDomainIs(host, "www.elok.com") || dnsDomainIs(host, "www.emf.net") || dnsDomainIs(host, "www.emsphone.com") || dnsDomainIs(host, "www.emulateme.com") || dnsDomainIs(host, "www.en.com") || dnsDomainIs(host, "www.enature.com") || dnsDomainIs(host, "www.enchantedlearning.com") || dnsDomainIs(host, "www.encyclopedia.com") || dnsDomainIs(host, "www.endex.com") || dnsDomainIs(host, "www.enjoyillinois.com") || dnsDomainIs(host, "www.enn.com") || dnsDomainIs(host, "www.enriqueig.com") || dnsDomainIs(host, "www.enteract.com") || dnsDomainIs(host, "www.epals.com") || dnsDomainIs(host, "www.equine-world.co.uk") || dnsDomainIs(host, "www.eric-carle.com") || dnsDomainIs(host, "www.ericlindros.net") || dnsDomainIs(host, "www.escape.com") || dnsDomainIs(host, "www.eskimo.com") || dnsDomainIs(host, "www.essentialsofmusic.com") || dnsDomainIs(host, "www.etch-a-sketch.com") || dnsDomainIs(host, "www.ethanallen.together.com") || dnsDomainIs(host, "www.etoys.com") || dnsDomainIs(host, "www.eurekascience.com") || dnsDomainIs(host, "www.euronet.nl") || dnsDomainIs(host, "www.everyrule.com") || dnsDomainIs(host, "www.ex.ac.uk") || dnsDomainIs(host, "www.excite.com") || dnsDomainIs(host, "www.execpc.com") || dnsDomainIs(host, "www.execulink.com") || dnsDomainIs(host, "www.exn.net") || dnsDomainIs(host, "www.expa.hvu.nl") || dnsDomainIs(host, "www.expage.com") || dnsDomainIs(host, "www.explode.to") || dnsDomainIs(host, "www.explorescience.com") || dnsDomainIs(host, "www.explorezone.com") || dnsDomainIs(host, "www.extremescience.com") || dnsDomainIs(host, "www.eyelid.co.uk") || dnsDomainIs(host, "www.eyeneer.com") || dnsDomainIs(host, "www.eyesofachild.com") || dnsDomainIs(host, "www.eyesofglory.com") || dnsDomainIs(host, "www.ezschool.com") || dnsDomainIs(host, "www.f1-live.com") || dnsDomainIs(host, "www.fables.co.uk") || dnsDomainIs(host, "www.factmonster.com") || dnsDomainIs(host, "www.fairygodmother.com") || dnsDomainIs(host, "www.familybuzz.com") || dnsDomainIs(host, "www.familygames.com") || dnsDomainIs(host, "www.familygardening.com") || dnsDomainIs(host, "www.familyinternet.com") || dnsDomainIs(host, "www.familymoney.com") || dnsDomainIs(host, "www.familyplay.com") || dnsDomainIs(host, "www.famousbirthdays.com") || dnsDomainIs(host, "www.fandom.com") || dnsDomainIs(host, "www.fansites.com") || dnsDomainIs(host, "www.faoschwarz.com") || dnsDomainIs(host, "www.fbe.unsw.edu.au") || dnsDomainIs(host, "www.fcps.k12.va.us") || dnsDomainIs(host, "www.fellersartsfactory.com") || dnsDomainIs(host, "www.ferrari.it") || dnsDomainIs(host, "www.fertnel.com") || dnsDomainIs(host, "www.fh-konstanz.de") || dnsDomainIs(host, "www.fhw.gr") || dnsDomainIs(host, "www.fibblesnork.com") || dnsDomainIs(host, "www.fidnet.com") || dnsDomainIs(host, "www.fieldhockey.com") || dnsDomainIs(host, "www.fieldhockeytraining.com") || dnsDomainIs(host, "www.fieler.com") || dnsDomainIs(host, "www.finalfour.net") || dnsDomainIs(host, "www.finifter.com") || dnsDomainIs(host, "www.fireworks-safety.com") || dnsDomainIs(host, "www.firstcut.com") || dnsDomainIs(host, "www.firstnations.com") || dnsDomainIs(host, "www.fishbc.com") || dnsDomainIs(host, "www.fisher-price.com") || dnsDomainIs(host, "www.fisheyeview.com") || dnsDomainIs(host, "www.fishgeeks.com") || dnsDomainIs(host, "www.fishindex.com") || dnsDomainIs(host, "www.fitzgeraldstudio.com") || dnsDomainIs(host, "www.flags.net") || dnsDomainIs(host, "www.flail.com") || dnsDomainIs(host, "www.flamarlins.com") || dnsDomainIs(host, "www.flausa.com") || dnsDomainIs(host, "www.floodlight-findings.com") || dnsDomainIs(host, "www.floridahistory.com") || dnsDomainIs(host, "www.floridapanthers.com") || dnsDomainIs(host, "www.fng.fi") || dnsDomainIs(host, "www.foodsci.uoguelph.ca") || dnsDomainIs(host, "www.foremost.com") || dnsDomainIs(host, "www.fortress.am") || dnsDomainIs(host, "www.fortunecity.com") || dnsDomainIs(host, "www.fosterclub.com") || dnsDomainIs(host, "www.foundus.com") || dnsDomainIs(host, "www.fourmilab.ch") || dnsDomainIs(host, "www.fox.com") || dnsDomainIs(host, "www.foxfamilychannel.com") || dnsDomainIs(host, "www.foxhome.com") || dnsDomainIs(host, "www.foxkids.com") || dnsDomainIs(host, "www.franceway.com") || dnsDomainIs(host, "www.fred.net") || dnsDomainIs(host, "www.fredpenner.com") || dnsDomainIs(host, "www.freedomknot.com") || dnsDomainIs(host, "www.freejigsawpuzzles.com") || dnsDomainIs(host, "www.freenet.edmonton.ab.ca") || dnsDomainIs(host, "www.frii.com") || dnsDomainIs(host, "www.frisbee.com") || dnsDomainIs(host, "www.fritolay.com") || dnsDomainIs(host, "www.frogsonice.com") || dnsDomainIs(host, "www.frontiernet.net") || dnsDomainIs(host, "www.fs.fed.us") || dnsDomainIs(host, "www.funattic.com") || dnsDomainIs(host, ".funbrain.com") || dnsDomainIs(host, "www.fundango.com") || dnsDomainIs(host, "www.funisland.com") || dnsDomainIs(host, "www.funkandwagnalls.com") || dnsDomainIs(host, "www.funorama.com") || dnsDomainIs(host, "www.funschool.com") || dnsDomainIs(host, "www.funster.com") || dnsDomainIs(host, "www.furby.com") || dnsDomainIs(host, "www.fusion.org.uk") || dnsDomainIs(host, "www.futcher.com") || dnsDomainIs(host, "www.futurescan.com") || dnsDomainIs(host, "www.fyi.net") || dnsDomainIs(host, "www.gailgibbons.com") || dnsDomainIs(host, "www.galegroup.com") || dnsDomainIs(host, "www.gambia.com") || dnsDomainIs(host, "www.gamecabinet.com") || dnsDomainIs(host, "www.gamecenter.com") || dnsDomainIs(host, "www.gamefaqs.com") || dnsDomainIs(host, "www.garfield.com") || dnsDomainIs(host, "www.garyharbo.com") || dnsDomainIs(host, "www.gatefish.com") || dnsDomainIs(host, "www.gateway-va.com") || dnsDomainIs(host, "www.gazillionaire.com") || dnsDomainIs(host, "www.gearhead.com") || dnsDomainIs(host, "www.genesplicing.com") || dnsDomainIs(host, "www.genhomepage.com") || dnsDomainIs(host, "www.geobop.com") || dnsDomainIs(host, "www.geocities.com") || dnsDomainIs(host, "www.geographia.com") || dnsDomainIs(host, "www.georgeworld.com") || dnsDomainIs(host, "www.georgian.net") || dnsDomainIs(host, "www.german-way.com") || dnsDomainIs(host, "www.germanfortravellers.com") || dnsDomainIs(host, "www.germantown.k12.il.us") || dnsDomainIs(host, "www.germany-tourism.de") || dnsDomainIs(host, "www.getmusic.com") || dnsDomainIs(host, "www.gettysburg.com") || dnsDomainIs(host, "www.ghirardellisq.com") || dnsDomainIs(host, "www.ghosttowngallery.com") || dnsDomainIs(host, "www.ghosttownsusa.com") || dnsDomainIs(host, "www.giants.com") || dnsDomainIs(host, "www.gibraltar.gi") || dnsDomainIs(host, "www.gigglepoetry.com") || dnsDomainIs(host, "www.gilchriststudios.com") || dnsDomainIs(host, "www.gillslap.freeserve.co.uk") || dnsDomainIs(host, "www.gilmer.net") || dnsDomainIs(host, "www.gio.gov.tw") || dnsDomainIs(host, "www.girltech.com") || dnsDomainIs(host, "www.girlzone.com") || dnsDomainIs(host, "www.globalgang.org.uk") || dnsDomainIs(host, "www.globalindex.com") || dnsDomainIs(host, "www.globalinfo.com") || dnsDomainIs(host, "www.gloriafan.com") || dnsDomainIs(host, "www.gms.ocps.k12.fl.us") || dnsDomainIs(host, "www.go-go-diggity.com") || dnsDomainIs(host, "www.goals.com") || dnsDomainIs(host, "www.godiva.com") || dnsDomainIs(host, "www.golden-retriever.com") || dnsDomainIs(host, "www.goldenbooks.com") || dnsDomainIs(host, "www.goldeneggs.com.au") || dnsDomainIs(host, "www.golfonline.com") || dnsDomainIs(host, "www.goobo.com") || dnsDomainIs(host, "www.goodearthgraphics.com") || dnsDomainIs(host, "www.goodyear.com") || dnsDomainIs(host, "www.gopbi.com") || dnsDomainIs(host, "www.gorge.net") || dnsDomainIs(host, "www.gorp.com") || dnsDomainIs(host, "www.got-milk.com") || dnsDomainIs(host, "www.gov.ab.ca") || dnsDomainIs(host, "www.gov.nb.ca") || dnsDomainIs(host, "www.grammarbook.com") || dnsDomainIs(host, "www.grammarlady.com") || dnsDomainIs(host, "www.grandparents-day.com") || dnsDomainIs(host, "www.granthill.com") || dnsDomainIs(host, "www.grayweb.com") || dnsDomainIs(host, "www.greatbuildings.com") || dnsDomainIs(host, "www.greatkids.com") || dnsDomainIs(host, "www.greatscience.com") || dnsDomainIs(host, "www.greeceny.com") || dnsDomainIs(host, "www.greenkeepers.com") || dnsDomainIs(host, "www.greylabyrinth.com") || dnsDomainIs(host, "www.grimmy.com") || dnsDomainIs(host, "www.gsrg.nmh.ac.uk") || dnsDomainIs(host, "www.gti.net") || dnsDomainIs(host, "www.guinnessworldrecords.com") || dnsDomainIs(host, "www.guitar.net") || dnsDomainIs(host, "www.guitarplaying.com") || dnsDomainIs(host, "www.gumbyworld.com") || dnsDomainIs(host, "www.gurlwurld.com") || dnsDomainIs(host, "www.gwi.net") || dnsDomainIs(host, "www.gymn-forum.com") || dnsDomainIs(host, "www.gzkidzone.com") || dnsDomainIs(host, "www.haemibalgassi.com") || dnsDomainIs(host, "www.hairstylist.com") || dnsDomainIs(host, "www.halcyon.com") || dnsDomainIs(host, "www.halifax.cbc.ca") || dnsDomainIs(host, "www.halloween-online.com") || dnsDomainIs(host, "www.halloweenkids.com") || dnsDomainIs(host, "www.halloweenmagazine.com") || dnsDomainIs(host, "www.hamill.co.uk") || dnsDomainIs(host, "www.hamsterdance2.com") || dnsDomainIs(host, "www.hamsters.co.uk") || dnsDomainIs(host, "www.hamstertours.com") || dnsDomainIs(host, "www.handsonmath.com") || dnsDomainIs(host, "www.handspeak.com") || dnsDomainIs(host, "www.hansonline.com") || dnsDomainIs(host, "www.happychild.org.uk") || dnsDomainIs(host, "www.happyfamilies.com") || dnsDomainIs(host, "www.happytoy.com") || dnsDomainIs(host, "www.harley-davidson.com") || dnsDomainIs(host, "www.harmonicalessons.com") || dnsDomainIs(host, "www.harperchildrens.com") || dnsDomainIs(host, "www.harvey.com") || dnsDomainIs(host, "www.hasbro-interactive.com") || dnsDomainIs(host, "www.haynet.net") || dnsDomainIs(host, "www.hbc.com") || dnsDomainIs(host, "www.hblewis.com") || dnsDomainIs(host, "www.hbook.com") || dnsDomainIs(host, "www.he.net") || dnsDomainIs(host, "www.headbone.com") || dnsDomainIs(host, "www.healthatoz.com") || dnsDomainIs(host, "www.healthypet.com") || dnsDomainIs(host, "www.heartfoundation.com.au") || dnsDomainIs(host, "www.heatersworld.com") || dnsDomainIs(host, "www.her-online.com") || dnsDomainIs(host, "www.heroesofhistory.com") || dnsDomainIs(host, "www.hersheypa.com") || dnsDomainIs(host, "www.hersheys.com") || dnsDomainIs(host, "www.hevanet.com") || dnsDomainIs(host, "www.heynetwork.com") || dnsDomainIs(host, "www.hgo.com") || dnsDomainIs(host, "www.hhof.com") || dnsDomainIs(host, "www.hideandseekpuppies.com") || dnsDomainIs(host, "www.hifusion.com") || dnsDomainIs(host, "www.highbridgepress.com") || dnsDomainIs(host, "www.his.com") || dnsDomainIs(host, "www.history.navy.mil") || dnsDomainIs(host, "www.historychannel.com") || dnsDomainIs(host, "www.historyhouse.com") || dnsDomainIs(host, "www.historyplace.com") || dnsDomainIs(host, "www.hisurf.com") || dnsDomainIs(host, "www.hiyah.com") || dnsDomainIs(host, "www.hmnet.com") || dnsDomainIs(host, "www.hoboes.com") || dnsDomainIs(host, "www.hockeydb.com") || dnsDomainIs(host, "www.hohnerusa.com") || dnsDomainIs(host, "www.holidaychannel.com") || dnsDomainIs(host, "www.holidayfestival.com") || dnsDomainIs(host, "www.holidays.net") || dnsDomainIs(host, "www.hollywood.com") || dnsDomainIs(host, "www.holoworld.com") || dnsDomainIs(host, "www.homepagers.com") || dnsDomainIs(host, "www.homeschoolzone.com") || dnsDomainIs(host, "www.homestead.com") || dnsDomainIs(host, "www.homeworkspot.com") || dnsDomainIs(host, "www.hompro.com") || dnsDomainIs(host, "www.honey.com") || dnsDomainIs(host, "www.hooked.net") || dnsDomainIs(host, "www.hoophall.com") || dnsDomainIs(host, "www.hooverdam.com") || dnsDomainIs(host, "www.hopepaul.com") || dnsDomainIs(host, "www.horse-country.com") || dnsDomainIs(host, "www.horsechat.com") || dnsDomainIs(host, "www.horsefun.com") || dnsDomainIs(host, "www.horus.ics.org.eg") || dnsDomainIs(host, "www.hotbraille.com") || dnsDomainIs(host, "www.hotwheels.com") || dnsDomainIs(host, "www.howstuffworks.com") || dnsDomainIs(host, "www.hpdigitalbookclub.com") || dnsDomainIs(host, "www.hpj.com") || dnsDomainIs(host, "www.hpl.hp.com") || dnsDomainIs(host, "www.hpl.lib.tx.us") || dnsDomainIs(host, "www.hpnetwork.f2s.com") || dnsDomainIs(host, "www.hsswp.com") || dnsDomainIs(host, "www.hsx.com") || dnsDomainIs(host, "www.humboldt1.com") || dnsDomainIs(host, "www.humongous.com") || dnsDomainIs(host, "www.humph3.freeserve.co.uk") || dnsDomainIs(host, "www.humphreybear.com ") || dnsDomainIs(host, "www.hurricanehunters.com") || dnsDomainIs(host, "www.hyperhistory.com") || dnsDomainIs(host, "www.i2k.com") || dnsDomainIs(host, "www.ibhof.com") || dnsDomainIs(host, "www.ibiscom.com") || dnsDomainIs(host, "www.ibm.com") || dnsDomainIs(host, "www.icangarden.com") || dnsDomainIs(host, "www.icecreamusa.com") || dnsDomainIs(host, "www.icn.co.uk") || dnsDomainIs(host, "www.icomm.ca") || dnsDomainIs(host, "www.idfishnhunt.com") || dnsDomainIs(host, "www.iditarod.com") || dnsDomainIs(host, "www.iei.net") || dnsDomainIs(host, "www.iemily.com") || dnsDomainIs(host, "www.iir.com") || dnsDomainIs(host, "www.ika.com") || dnsDomainIs(host, "www.ikoala.com") || dnsDomainIs(host, "www.iln.net") || dnsDomainIs(host, "www.imagine5.com") || dnsDomainIs(host, "www.imes.boj.or.jp") || dnsDomainIs(host, "www.inch.com") || dnsDomainIs(host, "www.incwell.com") || dnsDomainIs(host, "www.indian-river.fl.us") || dnsDomainIs(host, "www.indians.com") || dnsDomainIs(host, "www.indo.com") || dnsDomainIs(host, "www.indyracingleague.com") || dnsDomainIs(host, "www.indyzoo.com") || dnsDomainIs(host, "www.info-canada.com") || dnsDomainIs(host, "www.infomagic.net") || dnsDomainIs(host, "www.infoplease.com") || dnsDomainIs(host, "www.infoporium.com") || dnsDomainIs(host, "www.infostuff.com") || dnsDomainIs(host, "www.inhandmuseum.com") || dnsDomainIs(host, "www.inil.com") || dnsDomainIs(host, "www.inkspot.com") || dnsDomainIs(host, "www.inkyfingers.com") || dnsDomainIs(host, "www.innerauto.com") || dnsDomainIs(host, "www.innerbody.com") || dnsDomainIs(host, "www.inqpub.com") || dnsDomainIs(host, "www.insecta-inspecta.com") || dnsDomainIs(host, "www.insectclopedia.com") || dnsDomainIs(host, "www.inside-mexico.com") || dnsDomainIs(host, "www.insiders.com") || dnsDomainIs(host, "www.insteam.com") || dnsDomainIs(host, "www.intel.com") || dnsDomainIs(host, "www.intellicast.com") || dnsDomainIs(host, "www.interads.co.uk") || dnsDomainIs(host, "www.intercot.com") || dnsDomainIs(host, "www.intergraffix.com") || dnsDomainIs(host, "www.interknowledge.com") || dnsDomainIs(host, "www.interlog.com") || dnsDomainIs(host, "www.internet4kids.com") || dnsDomainIs(host, "www.intersurf.com") || dnsDomainIs(host, "www.inthe80s.com") || dnsDomainIs(host, "www.inventorsmuseum.com") || dnsDomainIs(host, "www.inwap.com") || dnsDomainIs(host, "www.ioa.com") || dnsDomainIs(host, "www.ionet.net") || dnsDomainIs(host, "www.iowacity.com") || dnsDomainIs(host, "www.ireland-now.com") || dnsDomainIs(host, "www.ireland.com") || dnsDomainIs(host, "www.irelandseye.com") || dnsDomainIs(host, "www.irlgov.ie") || dnsDomainIs(host, "www.isd.net") || dnsDomainIs(host, "www.islandnet.com") || dnsDomainIs(host, "www.isomedia.com") || dnsDomainIs(host, "www.itftennis.com") || dnsDomainIs(host, "www.itpi.dpi.state.nc.us") || dnsDomainIs(host, "www.itskwanzaatime.com") || dnsDomainIs(host, "www.itss.raytheon.com") || dnsDomainIs(host, "www.iuma.com") || dnsDomainIs(host, "www.iwaynet.net") || dnsDomainIs(host, "www.iwc.com") || dnsDomainIs(host, "www.iwight.gov.uk") || dnsDomainIs(host, "www.ixpres.com") || dnsDomainIs(host, "www.j.b.allen.btinternet.co.uk") || dnsDomainIs(host, "www.jabuti.com") || dnsDomainIs(host, "www.jackinthebox.com") || dnsDomainIs(host, "www.jaffebros.com") || dnsDomainIs(host, "www.jaguars.com") || dnsDomainIs(host, "www.jamaica-gleaner.com") || dnsDomainIs(host, "www.jamm.com") || dnsDomainIs(host, "www.janbrett.com") || dnsDomainIs(host, "www.janetstevens.com") || dnsDomainIs(host, "www.japan-guide.com") || dnsDomainIs(host, "www.jargon.net") || dnsDomainIs(host, "www.javelinamx.com") || dnsDomainIs(host, "www.jayjay.com") || dnsDomainIs(host, "www.jazclass.aust.com") || dnsDomainIs(host, "www.jedinet.com") || dnsDomainIs(host, "www.jenniferlopez.com") || dnsDomainIs(host, "www.jlpanagopoulos.com") || dnsDomainIs(host, "www.jmarshall.com") || dnsDomainIs(host, "www.jmccall.demon.co.uk") || dnsDomainIs(host, "www.jmts.com") || dnsDomainIs(host, "www.joesherlock.com") || dnsDomainIs(host, "www.jorvik-viking-centre.co.uk") || dnsDomainIs(host, "www.joycecarolthomas.com") || dnsDomainIs(host, "www.joycone.com") || dnsDomainIs(host, "www.joyrides.com") || dnsDomainIs(host, "www.jps.net") || dnsDomainIs(host, "www.jspub.com") || dnsDomainIs(host, "www.judaica.com") || dnsDomainIs(host, "www.judyblume.com") || dnsDomainIs(host, "www.julen.net") || dnsDomainIs(host, "www.june29.com") || dnsDomainIs(host, "www.juneteenth.com") || dnsDomainIs(host, "www.justuskidz.com") || dnsDomainIs(host, "www.justwomen.com") || dnsDomainIs(host, "www.jwindow.net") || dnsDomainIs(host, "www.k9web.com") || dnsDomainIs(host, "www.kaercher.de") || dnsDomainIs(host, "www.kaleidoscapes.com") || dnsDomainIs(host, "www.kapili.com") || dnsDomainIs(host, "www.kcchiefs.com") || dnsDomainIs(host, "www.kcpl.lib.mo.us") || dnsDomainIs(host, "www.kcroyals.com") || dnsDomainIs(host, "www.kcsd.k12.pa.us") || dnsDomainIs(host, "www.kdu.com") || dnsDomainIs(host, "www.kelloggs.com") || dnsDomainIs(host, "www.kentuckyfriedchicken.com") || dnsDomainIs(host, "www.kenyaweb.com") || dnsDomainIs(host, "www.keypals.com") || dnsDomainIs(host, "www.kfn.com") || dnsDomainIs(host, "www.kid-at-art.com") || dnsDomainIs(host, "www.kid-channel.com") || dnsDomainIs(host, "www.kidallergy.com") || dnsDomainIs(host, "www.kidbibs.com") || dnsDomainIs(host, "www.kidcomics.com") || dnsDomainIs(host, "www.kiddesafety.com") || dnsDomainIs(host, "www.kiddiecampus.com") || dnsDomainIs(host, "www.kididdles.com") || dnsDomainIs(host, "www.kidnews.com") || dnsDomainIs(host, "www.kidocracy.com") || dnsDomainIs(host, "www.kidport.com") || dnsDomainIs(host, "www.kids-channel.co.uk") || dnsDomainIs(host, "www.kids-drawings.com") || dnsDomainIs(host, "www.kids-in-mind.com") || dnsDomainIs(host, "www.kids4peace.com") || dnsDomainIs(host, "www.kidsandcomputers.com") || dnsDomainIs(host, "www.kidsart.co.uk") || dnsDomainIs(host, "www.kidsastronomy.com") || dnsDomainIs(host, "www.kidsbank.com") || dnsDomainIs(host, "www.kidsbookshelf.com") || dnsDomainIs(host, "www.kidsclick.com") || dnsDomainIs(host, "www.kidscom.com") || dnsDomainIs(host, "www.kidscook.com") || dnsDomainIs(host, "www.kidsdoctor.com") || dnsDomainIs(host, "www.kidsdomain.com") || dnsDomainIs(host, "www.kidsfarm.com") || dnsDomainIs(host, "www.kidsfreeware.com") || dnsDomainIs(host, "www.kidsfun.tv") || dnsDomainIs(host, "www.kidsgolf.com") || dnsDomainIs(host, "www.kidsgowild.com") || dnsDomainIs(host, "www.kidsjokes.com") || dnsDomainIs(host, "www.kidsloveamystery.com") || dnsDomainIs(host, "www.kidsmoneycents.com") || dnsDomainIs(host, "www.kidsnewsroom.com") || dnsDomainIs(host, "www.kidsource.com") || dnsDomainIs(host, "www.kidsparties.com") || dnsDomainIs(host, "www.kidsplaytown.com") || dnsDomainIs(host, "www.kidsreads.com") || dnsDomainIs(host, "www.kidsreport.com") || dnsDomainIs(host, "www.kidsrunning.com") || dnsDomainIs(host, "www.kidstamps.com") || dnsDomainIs(host, "www.kidsvideogames.com") || dnsDomainIs(host, "www.kidsway.com") || dnsDomainIs(host, "www.kidswithcancer.com") || dnsDomainIs(host, "www.kidszone.ourfamily.com") || dnsDomainIs(host, "www.kidzup.com") || dnsDomainIs(host, "www.kinderart.com") || dnsDomainIs(host, "www.kineticcity.com") || dnsDomainIs(host, "www.kings.k12.ca.us") || dnsDomainIs(host, "www.kiplinger.com") || dnsDomainIs(host, "www.kiwirecovery.org.nz") || dnsDomainIs(host, "www.klipsan.com") || dnsDomainIs(host, "www.klutz.com") || dnsDomainIs(host, "www.kn.pacbell.com") || dnsDomainIs(host, "www.knex.com") || dnsDomainIs(host, "www.knowledgeadventure.com") || dnsDomainIs(host, "www.knto.or.kr") || dnsDomainIs(host, "www.kodak.com") || dnsDomainIs(host, "www.konica.co.jp") || dnsDomainIs(host, "www.kraftfoods.com") || dnsDomainIs(host, "www.kudzukids.com") || dnsDomainIs(host, "www.kulichki.com") || dnsDomainIs(host, "www.kuttu.com") || dnsDomainIs(host, "www.kv5.com") || dnsDomainIs(host, "www.kyes-world.com") || dnsDomainIs(host, "www.kyohaku.go.jp") || dnsDomainIs(host, "www.kyrene.k12.az.us") || dnsDomainIs(host, "www.kz") || dnsDomainIs(host, "www.la-hq.org.uk") || dnsDomainIs(host, "www.labs.net") || dnsDomainIs(host, "www.labyrinth.net.au") || dnsDomainIs(host, "www.laffinthedark.com") || dnsDomainIs(host, "www.lakhota.com") || dnsDomainIs(host, "www.lakings.com") || dnsDomainIs(host, "www.lam.mus.ca.us") || dnsDomainIs(host, "www.lampstras.k12.pa.us") || dnsDomainIs(host, "www.lams.losalamos.k12.nm.us") || dnsDomainIs(host, "www.landofcadbury.ca") || dnsDomainIs(host, "www.larry-boy.com") || dnsDomainIs(host, "www.lasersite.com") || dnsDomainIs(host, "www.last-word.com") || dnsDomainIs(host, "www.latimes.com") || dnsDomainIs(host, "www.laughon.com") || dnsDomainIs(host, "www.laurasmidiheaven.com") || dnsDomainIs(host, "www.lausd.k12.ca.us") || dnsDomainIs(host, "www.learn2.com") || dnsDomainIs(host, "www.learn2type.com") || dnsDomainIs(host, "www.learnfree-hobbies.com") || dnsDomainIs(host, "www.learningkingdom.com") || dnsDomainIs(host, "www.learningplanet.com") || dnsDomainIs(host, "www.leftjustified.com") || dnsDomainIs(host, "www.legalpadjr.com") || dnsDomainIs(host, "www.legendarysurfers.com") || dnsDomainIs(host, "www.legends.dm.net") || dnsDomainIs(host, "www.legis.state.wi.us") || dnsDomainIs(host, "www.legis.state.wv.us") || dnsDomainIs(host, "www.lego.com") || dnsDomainIs(host, "www.leje.com") || dnsDomainIs(host, "www.leonardodicaprio.com") || dnsDomainIs(host, "www.lessonplanspage.com") || dnsDomainIs(host, "www.letour.fr") || dnsDomainIs(host, "www.levins.com") || dnsDomainIs(host, "www.levistrauss.com") || dnsDomainIs(host, "www.libertystatepark.com") || dnsDomainIs(host, "www.libraryspot.com") || dnsDomainIs(host, "www.lifelong.com") || dnsDomainIs(host, "www.lighthouse.cc") || dnsDomainIs(host, "www.lightlink.com") || dnsDomainIs(host, "www.lightspan.com") || dnsDomainIs(host, "www.lil-fingers.com") || dnsDomainIs(host, "www.linc.or.jp") || dnsDomainIs(host, "www.lindsaysbackyard.com") || dnsDomainIs(host, "www.lindtchocolate.com") || dnsDomainIs(host, "www.lineone.net") || dnsDomainIs(host, "www.lionel.com") || dnsDomainIs(host, "www.lisafrank.com") || dnsDomainIs(host, "www.lissaexplains.com") || dnsDomainIs(host, "www.literacycenter.net") || dnsDomainIs(host, "www.littleartist.com") || dnsDomainIs(host, "www.littlechiles.com") || dnsDomainIs(host, "www.littlecritter.com") || dnsDomainIs(host, "www.littlecrowtoys.com") || dnsDomainIs(host, "www.littlehousebooks.com") || dnsDomainIs(host, "www.littlejason.com") || dnsDomainIs(host, "www.littleplanettimes.com") || dnsDomainIs(host, "www.liveandlearn.com") || dnsDomainIs(host, "www.loadstar.prometeus.net") || dnsDomainIs(host, "www.localaccess.com") || dnsDomainIs(host, "www.lochness.co.uk") || dnsDomainIs(host, "www.lochness.scotland.net") || dnsDomainIs(host, "www.logos.it") || dnsDomainIs(host, "www.lonelyplanet.com") || dnsDomainIs(host, "www.looklearnanddo.com") || dnsDomainIs(host, "www.loosejocks.com") || dnsDomainIs(host, "www.lost-worlds.com") || dnsDomainIs(host, "www.love-story.com") || dnsDomainIs(host, "www.lpga.com") || dnsDomainIs(host, "www.lsjunction.com") || dnsDomainIs(host, "www.lucasarts.com") || dnsDomainIs(host, "www.lucent.com") || dnsDomainIs(host, "www.lucie.com") || dnsDomainIs(host, "www.lunaland.co.za") || dnsDomainIs(host, "www.luth.se") || dnsDomainIs(host, "www.lyricalworks.com") || dnsDomainIs(host, "www.infoporium.com") || dnsDomainIs(host, "www.infostuff.com") || dnsDomainIs(host, "www.inhandmuseum.com") || dnsDomainIs(host, "www.inil.com") || dnsDomainIs(host, "www.inkspot.com") || dnsDomainIs(host, "www.inkyfingers.com") || dnsDomainIs(host, "www.innerauto.com") || dnsDomainIs(host, "www.innerbody.com") || dnsDomainIs(host, "www.inqpub.com") || dnsDomainIs(host, "www.insecta-inspecta.com") || dnsDomainIs(host, "www.insectclopedia.com") || dnsDomainIs(host, "www.inside-mexico.com") || dnsDomainIs(host, "www.insiders.com") || dnsDomainIs(host, "www.insteam.com") || dnsDomainIs(host, "www.intel.com") || dnsDomainIs(host, "www.intellicast.com") || dnsDomainIs(host, "www.interads.co.uk") || dnsDomainIs(host, "www.intercot.com") || dnsDomainIs(host, "www.intergraffix.com") || dnsDomainIs(host, "www.interknowledge.com") || dnsDomainIs(host, "www.interlog.com") || dnsDomainIs(host, "www.internet4kids.com") || dnsDomainIs(host, "www.intersurf.com") || dnsDomainIs(host, "www.inthe80s.com") || dnsDomainIs(host, "www.inventorsmuseum.com") || dnsDomainIs(host, "www.inwap.com") || dnsDomainIs(host, "www.ioa.com") || dnsDomainIs(host, "www.ionet.net") || dnsDomainIs(host, "www.iowacity.com") || dnsDomainIs(host, "www.ireland-now.com") || dnsDomainIs(host, "www.ireland.com") || dnsDomainIs(host, "www.irelandseye.com") || dnsDomainIs(host, "www.irlgov.ie") || dnsDomainIs(host, "www.isd.net") || dnsDomainIs(host, "www.islandnet.com") || dnsDomainIs(host, "www.isomedia.com") || dnsDomainIs(host, "www.itftennis.com") || dnsDomainIs(host, "www.itpi.dpi.state.nc.us") || dnsDomainIs(host, "www.itskwanzaatime.com") || dnsDomainIs(host, "www.itss.raytheon.com") || dnsDomainIs(host, "www.iuma.com") || dnsDomainIs(host, "www.iwaynet.net") || dnsDomainIs(host, "www.iwc.com") || dnsDomainIs(host, "www.iwight.gov.uk") || dnsDomainIs(host, "www.ixpres.com") || dnsDomainIs(host, "www.j.b.allen.btinternet.co.uk") || dnsDomainIs(host, "www.jabuti.com") || dnsDomainIs(host, "www.jackinthebox.com") || dnsDomainIs(host, "www.jaffebros.com") || dnsDomainIs(host, "www.jaguars.com") || dnsDomainIs(host, "www.jamaica-gleaner.com") || dnsDomainIs(host, "www.jamm.com") || dnsDomainIs(host, "www.janbrett.com") || dnsDomainIs(host, "www.janetstevens.com") || dnsDomainIs(host, "www.japan-guide.com") || dnsDomainIs(host, "www.jargon.net") || dnsDomainIs(host, "www.javelinamx.com") || dnsDomainIs(host, "www.jayjay.com") || dnsDomainIs(host, "www.jazclass.aust.com") ) return "PROXY proxy.hclib.org:80"; else return "PROXY 172.16.100.20:8080"; } reportCompare('No Crash', 'No Crash', '');
sam/htmlunit-rhino-fork
testsrc/tests/js1_5/Regress/regress-89443.js
JavaScript
mpl-2.0
94,445
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ (function() { 'use strict'; var ALERT_FETCH_LIMIT = 1000 * 60 * 60 * 12; var ALERT_REFRESH_INTERVAL = 1000 * 10; var ALERT_TEMPLATE = '#/site/${siteId}/alert/detail/${alertId}?timestamp=${timestamp}'; var serviceModule = angular.module('eagle.service'); serviceModule.service('Alert', function ($notification, Time, CompatibleEntity) { var Alert = { list: null, }; $notification.getPromise().then(function () { function queryAlerts() { var endTime = new Time(); var list = CompatibleEntity.query("LIST", { query: "AlertService", startTime: endTime.clone().subtract(ALERT_FETCH_LIMIT, 'ms'), endTime: endTime }); list._then(function () { if (!Alert.list) { Alert.list = list; return; } var subList = common.array.minus(list, Alert.list, ['encodedRowkey'], ['encodedRowkey']); Alert.list = list; $.each(subList, function (i, alert) { $notification(alert.alertSubject, common.template(ALERT_TEMPLATE, { siteId: alert.tags.siteId, alertId: alert.tags.alertId, timestamp: alert.timestamp, })); }); }); } queryAlerts(); setInterval(queryAlerts, ALERT_REFRESH_INTERVAL); }); return Alert; }); })();
qingwen220/eagle
eagle-server/src/main/webapp/app/dev/public/js/services/alertSrv.js
JavaScript
apache-2.0
2,048
HandlebarsIntl.__addLocaleData({"locale":"guz","pluralRuleFunction":function (n,ord){if(ord)return"other";return"other"},"fields":{"year":{"displayName":"Omwaka","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}},"month":{"displayName":"Omotienyi","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"day":{"displayName":"Rituko","relative":{"0":"Rero","1":"Mambia","-1":"Igoro"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"hour":{"displayName":"Ensa","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"minute":{"displayName":"Edakika","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"second":{"displayName":"Esekendi","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}}}}); HandlebarsIntl.__addLocaleData({"locale":"guz-KE","parentLocale":"guz"});
yoanngern/iahm_2016
wp-content/themes/iahm_2016/js/vendor/handlebars-intl/locale-data/guz.js
JavaScript
apache-2.0
1,039
/*jshint globalstrict:false, strict:false, unused : false */ /*global assertEqual, assertFalse, assertTrue */ //////////////////////////////////////////////////////////////////////////////// /// @brief tests for dump/reload /// /// @file /// /// DISCLAIMER /// /// Copyright 2010-2012 triagens GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is triAGENS GmbH, Cologne, Germany /// /// @author Jan Steemann /// @author Copyright 2012, triAGENS GmbH, Cologne, Germany //////////////////////////////////////////////////////////////////////////////// var db = require("org/arangodb").db; var internal = require("internal"); var jsunity = require("jsunity"); function runSetup () { 'use strict'; internal.debugClearFailAt(); db._drop("UnitTestsRecovery1"); var c = db._create("UnitTestsRecovery1"), i; c.ensureSkiplist("value"); for (i = 0; i < 1000; ++i) { c.save({ value: i }); } db._drop("UnitTestsRecovery2"); c = db._create("UnitTestsRecovery2"); c.ensureUniqueSkiplist("a.value"); for (i = 0; i < 1000; ++i) { c.save({ a: { value: i } }); } db._drop("UnitTestsRecovery3"); c = db._create("UnitTestsRecovery3"); c.ensureSkiplist("a", "b"); for (i = 0; i < 500; ++i) { c.save({ a: (i % 2) + 1, b: 1 }); c.save({ a: (i % 2) + 1, b: 2 }); } db._drop("test"); c = db._create("test"); c.save({ _key: "crashme" }, true); internal.debugSegfault("crashing server"); } //////////////////////////////////////////////////////////////////////////////// /// @brief test suite //////////////////////////////////////////////////////////////////////////////// function recoverySuite () { 'use strict'; jsunity.jsUnity.attachAssertions(); return { setUp: function () { }, tearDown: function () { }, //////////////////////////////////////////////////////////////////////////////// /// @brief test whether we can restore the trx data //////////////////////////////////////////////////////////////////////////////// testIndexesSkiplist : function () { var c = db._collection("UnitTestsRecovery1"), idx, i; idx = c.getIndexes()[1]; assertFalse(idx.unique); assertFalse(idx.sparse); assertEqual([ "value" ], idx.fields); for (i = 0; i < 1000; ++i) { assertEqual(1, c.byExampleSkiplist(idx.id, { value: i }).toArray().length); } c = db._collection("UnitTestsRecovery2"); idx = c.getIndexes()[1]; assertTrue(idx.unique); assertFalse(idx.sparse); assertEqual([ "a.value" ], idx.fields); for (i = 0; i < 1000; ++i) { assertEqual(1, c.byExampleSkiplist(idx.id, { "a.value" : i }).toArray().length); } c = db._collection("UnitTestsRecovery3"); idx = c.getIndexes()[1]; assertFalse(idx.unique); assertFalse(idx.sparse); assertEqual([ "a", "b" ], idx.fields); assertEqual(250, c.byExampleSkiplist(idx.id, { a: 1, b: 1 }).toArray().length); assertEqual(250, c.byExampleSkiplist(idx.id, { a: 1, b: 2 }).toArray().length); assertEqual(250, c.byExampleSkiplist(idx.id, { a: 2, b: 1 }).toArray().length); assertEqual(250, c.byExampleSkiplist(idx.id, { a: 2, b: 2 }).toArray().length); } }; } //////////////////////////////////////////////////////////////////////////////// /// @brief executes the test suite //////////////////////////////////////////////////////////////////////////////// function main (argv) { 'use strict'; if (argv[1] === "setup") { runSetup(); return 0; } else { jsunity.run(recoverySuite); return jsunity.done().status ? 0 : 1; } }
CoDEmanX/ArangoDB
js/server/tests/recovery/indexes-skiplist.js
JavaScript
apache-2.0
4,197
/** * @license * Copyright (c) 2014 The Polymer Project Authors. All rights reserved. * This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt * The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt * The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt * Code distributed by Google as part of the polymer project is also * subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt */ /** * Implements custom element observation and attached/detached callbacks * @module observe */ window.CustomElements.addModule(function(scope){ // imports var flags = scope.flags; var forSubtree = scope.forSubtree; var forDocumentTree = scope.forDocumentTree; /* Manage nodes attached to document trees */ // manage lifecycle on added node and it's subtree; upgrade the node and // entire subtree if necessary and process attached for the node and entire // subtree function addedNode(node, isAttached) { return added(node, isAttached) || addedSubtree(node, isAttached); } // manage lifecycle on added node; upgrade if necessary and process attached function added(node, isAttached) { if (scope.upgrade(node, isAttached)) { // Return true to indicate return true; } if (isAttached) { attached(node); } } // manage lifecycle on added node's subtree only; allows the entire subtree // to upgrade if necessary and process attached function addedSubtree(node, isAttached) { forSubtree(node, function(e) { if (added(e, isAttached)) { return true; } }); } // On platforms without MutationObserver, mutations may not be // reliable and therefore attached/detached are not reliable. // To make these callbacks less likely to fail, we defer all inserts and removes // to give a chance for elements to be attached into dom. // This ensures attachedCallback fires for elements that are created and // immediately added to dom. var hasPolyfillMutations = (!window.MutationObserver || (window.MutationObserver === window.JsMutationObserver)); scope.hasPolyfillMutations = hasPolyfillMutations; var isPendingMutations = false; var pendingMutations = []; function deferMutation(fn) { pendingMutations.push(fn); if (!isPendingMutations) { isPendingMutations = true; setTimeout(takeMutations); } } function takeMutations() { isPendingMutations = false; var $p = pendingMutations; for (var i=0, l=$p.length, p; (i<l) && (p=$p[i]); i++) { p(); } pendingMutations = []; } function attached(element) { if (hasPolyfillMutations) { deferMutation(function() { _attached(element); }); } else { _attached(element); } } // NOTE: due to how MO works (see comments below), an element may be attached // multiple times so we protect against extra processing here. function _attached(element) { // track element for insertion if it's upgraded and cares about insertion // bail if the element is already marked as attached if (element.__upgraded__ && !element.__attached) { element.__attached = true; if (element.attachedCallback) { element.attachedCallback(); } } } /* Manage nodes detached from document trees */ // manage lifecycle on detached node and it's subtree; process detached // for the node and entire subtree function detachedNode(node) { detached(node); forSubtree(node, function(e) { detached(e); }); } function detached(element) { if (hasPolyfillMutations) { deferMutation(function() { _detached(element); }); } else { _detached(element); } } // NOTE: due to how MO works (see comments below), an element may be detached // multiple times so we protect against extra processing here. function _detached(element) { // track element for removal if it's upgraded and cares about removal // bail if the element is already marked as not attached if (element.__upgraded__ && element.__attached) { element.__attached = false; if (element.detachedCallback) { element.detachedCallback(); } } } // recurse up the tree to check if an element is actually in the main document. function inDocument(element) { var p = element; var doc = window.wrap(document); while (p) { if (p == doc) { return true; } p = p.parentNode || ((p.nodeType === Node.DOCUMENT_FRAGMENT_NODE) && p.host); } } // Install an element observer on all shadowRoots owned by node. function watchShadow(node) { if (node.shadowRoot && !node.shadowRoot.__watched) { flags.dom && console.log('watching shadow-root for: ', node.localName); // watch all unwatched roots... var root = node.shadowRoot; while (root) { observe(root); root = root.olderShadowRoot; } } } /* NOTE: In order to process all mutations, it's necessary to recurse into any added nodes. However, it's not possible to determine a priori if a node will get its own mutation record. This means *nodes can be seen multiple times*. Here's an example: (1) In this case, recursion is required to see `child`: node.innerHTML = '<div><child></child></div>' (2) In this case, child will get its own mutation record: node.appendChild(div).appendChild(child); We cannot know ahead of time if we need to walk into the node in (1) so we do and see child; however, if it was added via case (2) then it will have its own record and therefore be seen 2x. */ function handler(root, mutations) { // for logging only if (flags.dom) { var mx = mutations[0]; if (mx && mx.type === 'childList' && mx.addedNodes) { if (mx.addedNodes) { var d = mx.addedNodes[0]; while (d && d !== document && !d.host) { d = d.parentNode; } var u = d && (d.URL || d._URL || (d.host && d.host.localName)) || ''; u = u.split('/?').shift().split('/').pop(); } } console.group('mutations (%d) [%s]', mutations.length, u || ''); } // handle mutations // NOTE: do an `inDocument` check dynamically here. It's possible that `root` // is a document in which case the answer here can never change; however // `root` may be an element like a shadowRoot that can be added/removed // from the main document. var isAttached = inDocument(root); mutations.forEach(function(mx) { if (mx.type === 'childList') { forEach(mx.addedNodes, function(n) { if (!n.localName) { return; } addedNode(n, isAttached); }); forEach(mx.removedNodes, function(n) { if (!n.localName) { return; } detachedNode(n); }); } }); flags.dom && console.groupEnd(); }; /* When elements are added to the dom, upgrade and attached/detached may be asynchronous. `CustomElements.takeRecords` can be called to process any pending upgrades and attached/detached callbacks synchronously. */ function takeRecords(node) { node = window.wrap(node); // If the optional node is not supplied, assume we mean the whole document. if (!node) { node = window.wrap(document); } // Find the root of the tree, which will be an Document or ShadowRoot. while (node.parentNode) { node = node.parentNode; } var observer = node.__observer; if (observer) { handler(node, observer.takeRecords()); takeMutations(); } } var forEach = Array.prototype.forEach.call.bind(Array.prototype.forEach); // observe a node tree; bail if it's already being observed. function observe(inRoot) { if (inRoot.__observer) { return; } // For each ShadowRoot, we create a new MutationObserver, so the root can be // garbage collected once all references to the `inRoot` node are gone. // Give the handler access to the root so that an 'in document' check can // be done. var observer = new MutationObserver(handler.bind(this, inRoot)); observer.observe(inRoot, {childList: true, subtree: true}); inRoot.__observer = observer; } // upgrade an entire document and observe it for elements changes. function upgradeDocument(doc) { doc = window.wrap(doc); flags.dom && console.group('upgradeDocument: ', (doc.baseURI).split('/').pop()); var isMainDocument = (doc === window.wrap(document)); addedNode(doc, isMainDocument); observe(doc); flags.dom && console.groupEnd(); } /* This method is intended to be called when the document tree (including imports) has pending custom elements to upgrade. It can be called multiple times and should do nothing if no elements are in need of upgrade. */ function upgradeDocumentTree(doc) { forDocumentTree(doc, upgradeDocument); } // Patch `createShadowRoot()` if Shadow DOM is available, otherwise leave // undefined to aid feature detection of Shadow DOM. var originalCreateShadowRoot = Element.prototype.createShadowRoot; if (originalCreateShadowRoot) { Element.prototype.createShadowRoot = function() { var root = originalCreateShadowRoot.call(this); window.CustomElements.watchShadow(this); return root; }; } // exports scope.watchShadow = watchShadow; scope.upgradeDocumentTree = upgradeDocumentTree; scope.upgradeDocument = upgradeDocument; scope.upgradeSubtree = addedSubtree; scope.upgradeAll = addedNode; scope.attached = attached; scope.takeRecords = takeRecords; });
tachyon1337/webcomponentsjs
src/CustomElements/observe.js
JavaScript
bsd-3-clause
9,347
// Any copyright is dedicated to the Public Domain. // http://creativecommons.org/licenses/publicdomain/ //----------------------------------------------------------------------------- var BUGNUMBER = 565604; var summary = "Typed-array properties don't work when accessed from an object whose " + "prototype (or further-descended prototype) is a typed array"; print(BUGNUMBER + ": " + summary); /************** * BEGIN TEST * **************/ var o = Object.create(new Uint8Array(1)); assertEq(o.length, 1); var o2 = Object.create(o); assertEq(o2.length, 1); var VARIABLE_OBJECT = {}; var props = [ { property: "length", value: 1 }, { property: "byteLength", value: 1 }, { property: "byteOffset", value: 0 }, { property: "buffer", value: VARIABLE_OBJECT }, ]; for (var i = 0, sz = props.length; i < sz; i++) { var p = props[i]; var o = Object.create(new Uint8Array(1)); var v = o[p.property]; if (p.value !== VARIABLE_OBJECT) assertEq(o[p.property], p.value, "bad " + p.property + " (proto)"); var o2 = Object.create(o); if (p.value !== VARIABLE_OBJECT) assertEq(o2[p.property], p.value, "bad " + p.property + " (grand-proto)"); assertEq(o2[p.property], v, p.property + " mismatch"); } reportCompare(true, true);
darkrsw/safe
tests/browser_extensions/js1_8_5/extensions/typedarray-prototype.js
JavaScript
bsd-3-clause
1,266
import AuthenticatedRoute from 'ghost/routes/authenticated'; import CurrentUserSettings from 'ghost/mixins/current-user-settings'; import styleBody from 'ghost/mixins/style-body'; var AppsRoute = AuthenticatedRoute.extend(styleBody, CurrentUserSettings, { titleToken: 'Apps', classNames: ['settings-view-apps'], beforeModel: function () { if (!this.get('config.apps')) { return this.transitionTo('settings.general'); } return this.get('session.user') .then(this.transitionAuthor()) .then(this.transitionEditor()); }, model: function () { return this.store.find('app'); } }); export default AppsRoute;
PepijnSenders/whatsontheotherside
core/client/app/routes/settings/apps.js
JavaScript
mit
699
import Ember from 'ember-metal'; // Ember as namespace import { A as emberA, typeOf, String as StringUtils, Namespace, Object as EmberObject } from 'ember-runtime'; /** @module ember @submodule ember-extension-support */ /** The `ContainerDebugAdapter` helps the container and resolver interface with tools that debug Ember such as the [Ember Extension](https://github.com/tildeio/ember-extension) for Chrome and Firefox. This class can be extended by a custom resolver implementer to override some of the methods with library-specific code. The methods likely to be overridden are: * `canCatalogEntriesByType` * `catalogEntriesByType` The adapter will need to be registered in the application's container as `container-debug-adapter:main`. Example: ```javascript Application.initializer({ name: "containerDebugAdapter", initialize(application) { application.register('container-debug-adapter:main', require('app/container-debug-adapter')); } }); ``` @class ContainerDebugAdapter @namespace Ember @extends Ember.Object @since 1.5.0 @public */ export default EmberObject.extend({ /** The resolver instance of the application being debugged. This property will be injected on creation. @property resolver @default null @public */ resolver: null, /** Returns true if it is possible to catalog a list of available classes in the resolver for a given type. @method canCatalogEntriesByType @param {String} type The type. e.g. "model", "controller", "route". @return {boolean} whether a list is available for this type. @public */ canCatalogEntriesByType(type) { if (type === 'model' || type === 'template') { return false; } return true; }, /** Returns the available classes a given type. @method catalogEntriesByType @param {String} type The type. e.g. "model", "controller", "route". @return {Array} An array of strings. @public */ catalogEntriesByType(type) { let namespaces = emberA(Namespace.NAMESPACES); let types = emberA(); let typeSuffixRegex = new RegExp(`${StringUtils.classify(type)}$`); namespaces.forEach(namespace => { if (namespace !== Ember) { for (let key in namespace) { if (!namespace.hasOwnProperty(key)) { continue; } if (typeSuffixRegex.test(key)) { let klass = namespace[key]; if (typeOf(klass) === 'class') { types.push(StringUtils.dasherize(key.replace(typeSuffixRegex, ''))); } } } } }); return types; } });
duggiefresh/ember.js
packages/ember-extension-support/lib/container_debug_adapter.js
JavaScript
mit
2,656
(function ($) { 'use strict'; $.extend(true, $.trumbowyg, { langs: { // jshint camelcase:false en: { fontFamily: 'Font' }, es: { fontFamily: 'Fuente' }, da: { fontFamily: 'Skrifttype' }, fr: { fontFamily: 'Police' }, de: { fontFamily: 'Schriftart' }, nl: { fontFamily: 'Lettertype' }, tr: { fontFamily: 'Yazı Tipi' }, zh_tw: { fontFamily: '字體', }, pt_br: { fontFamily: 'Fonte', } } }); // jshint camelcase:true var defaultOptions = { fontList: [ {name: 'Arial', family: 'Arial, Helvetica, sans-serif'}, {name: 'Arial Black', family: '\'Arial Black\', Gadget, sans-serif'}, {name: 'Comic Sans', family: '\'Comic Sans MS\', Textile, cursive, sans-serif'}, {name: 'Courier New', family: '\'Courier New\', Courier, monospace'}, {name: 'Georgia', family: 'Georgia, serif'}, {name: 'Impact', family: 'Impact, Charcoal, sans-serif'}, {name: 'Lucida Console', family: '\'Lucida Console\', Monaco, monospace'}, {name: 'Lucida Sans', family: '\'Lucida Sans Uncide\', \'Lucida Grande\', sans-serif'}, {name: 'Palatino', family: '\'Palatino Linotype\', \'Book Antiqua\', Palatino, serif'}, {name: 'Tahoma', family: 'Tahoma, Geneva, sans-serif'}, {name: 'Times New Roman', family: '\'Times New Roman\', Times, serif'}, {name: 'Trebuchet', family: '\'Trebuchet MS\', Helvetica, sans-serif'}, {name: 'Verdana', family: 'Verdana, Geneva, sans-serif'} ] }; // Add dropdown with web safe fonts $.extend(true, $.trumbowyg, { plugins: { fontfamily: { init: function (trumbowyg) { trumbowyg.o.plugins.fontfamily = $.extend(true, {}, defaultOptions, trumbowyg.o.plugins.fontfamily || {} ); trumbowyg.addBtnDef('fontfamily', { dropdown: buildDropdown(trumbowyg), hasIcon: false, text: trumbowyg.lang.fontFamily }); } } } }); function buildDropdown(trumbowyg) { var dropdown = []; $.each(trumbowyg.o.plugins.fontfamily.fontList, function (index, font) { trumbowyg.addBtnDef('fontfamily_' + index, { title: '<span style="font-family: ' + font.family + ';">' + font.name + '</span>', hasIcon: false, fn: function () { trumbowyg.execCmd('fontName', font.family, true); } }); dropdown.push('fontfamily_' + index); }); return dropdown; } })(jQuery);
extend1994/cdnjs
ajax/libs/Trumbowyg/2.16.2/plugins/fontfamily/trumbowyg.fontfamily.js
JavaScript
mit
3,157
CKEDITOR.plugins.setLang("uicolor","ro",{title:"Interfața cu utilizatorul a Selectorului de culoare",options:"Opțiuni culoare",highlight:"Evidențiere",selected:"Culoare selectată",predefined:"Seturi de culoare predefinite",config:"Copiază această expresie în fișierul tău config.js"});
cdnjs/cdnjs
ajax/libs/ckeditor/4.17.2/plugins/uicolor/lang/ro.min.js
JavaScript
mit
294
(function(){tinymce.PluginManager.requireLangPack('codemagic');tinymce.create('tinymce.plugins.CodeMagic',{init:function(ed,url){ed.addCommand('mceCodeMagic',function(){ed.windowManager.open({file:url+'/codemagic.php',width:1200,height:600,inline:1,maximizable:true},{plugin_url:url})});ed.addButton('codemagic',{title:'codemagic.editor_button',cmd:'mceCodeMagic',image:url+'/img/code.png'});ed.onNodeChange.add(function(ed,cm,n,co){cm.setDisabled('link',co&&n.nodeName!='A');cm.setActive('link',n.nodeName=='A'&&!n.name)})},getInfo:function(){return{longname:'CodeMagic - syntax coloring and intendation',author:'Sutulustus',authorurl:'http://www.triad.sk/#/en',version:'0.9.5'}}});tinymce.PluginManager.add('codemagic',tinymce.plugins.CodeMagic)})();
tgrimault/manorhouseporto.wp
wp-content/plugins/ultimate-tinymce/addons/codemagic/editor_plugin.js
JavaScript
gpl-2.0
752
Clazz.declarePackage ("JSV.common"); Clazz.load (["java.lang.Enum", "JSV.source.JDXDataObject", "JU.Lst"], "JSV.common.Spectrum", ["java.lang.Boolean", "$.Double", "java.util.Hashtable", "JU.PT", "JSV.common.Coordinate", "$.Parameters", "$.PeakInfo", "JSV.source.JDXSourceStreamTokenizer", "JU.Logger"], function () { c$ = Clazz.decorateAsClass (function () { this.subSpectra = null; this.peakList = null; this.piUnitsX = null; this.piUnitsY = null; this.selectedPeak = null; this.highlightedPeak = null; this.specShift = 0; this.currentSubSpectrumIndex = 0; this.$isForcedSubset = false; this.id = ""; this.convertedSpectrum = null; this.userYFactor = 1; this.exportXAxisLeftToRight = false; this.fillColor = null; Clazz.instantialize (this, arguments); }, JSV.common, "Spectrum", JSV.source.JDXDataObject); Clazz.prepareFields (c$, function () { this.peakList = new JU.Lst (); }); Clazz.overrideMethod (c$, "finalize", function () { System.out.println ("JDXSpectrum " + this + " finalized " + this.title); }); Clazz.defineMethod (c$, "dispose", function () { }); Clazz.defineMethod (c$, "isForcedSubset", function () { return this.$isForcedSubset; }); Clazz.defineMethod (c$, "setId", function (id) { this.id = id; }, "~S"); Clazz.makeConstructor (c$, function () { Clazz.superConstructor (this, JSV.common.Spectrum, []); this.headerTable = new JU.Lst (); this.xyCoords = new Array (0); this.parent = this; }); Clazz.defineMethod (c$, "copy", function () { var newSpectrum = new JSV.common.Spectrum (); this.copyTo (newSpectrum); newSpectrum.setPeakList (this.peakList, this.piUnitsX, null); newSpectrum.fillColor = this.fillColor; return newSpectrum; }); Clazz.defineMethod (c$, "getXYCoords", function () { return this.getCurrentSubSpectrum ().xyCoords; }); Clazz.defineMethod (c$, "getPeakList", function () { return this.peakList; }); Clazz.defineMethod (c$, "setPeakList", function (list, piUnitsX, piUnitsY) { this.peakList = list; this.piUnitsX = piUnitsX; this.piUnitsY = piUnitsY; for (var i = list.size (); --i >= 0; ) this.peakList.get (i).spectrum = this; if (JU.Logger.debugging) JU.Logger.info ("Spectrum " + this.getTitle () + " peaks: " + list.size ()); return list.size (); }, "JU.Lst,~S,~S"); Clazz.defineMethod (c$, "selectPeakByFileIndex", function (filePath, index, atomKey) { if (this.peakList != null && this.peakList.size () > 0 && (atomKey == null || this.sourceID.equals (index))) for (var i = 0; i < this.peakList.size (); i++) if (this.peakList.get (i).checkFileIndex (filePath, index, atomKey)) { System.out.println ("selecting peak by FileIndex " + this + " " + this.peakList.get (i)); return (this.selectedPeak = this.peakList.get (i)); } return null; }, "~S,~S,~S"); Clazz.defineMethod (c$, "selectPeakByFilePathTypeModel", function (filePath, type, model) { if (this.peakList != null && this.peakList.size () > 0) for (var i = 0; i < this.peakList.size (); i++) if (this.peakList.get (i).checkFileTypeModel (filePath, type, model)) { System.out.println ("selecting peak byFilePathTypeModel " + this + " " + this.peakList.get (i)); return (this.selectedPeak = this.peakList.get (i)); } return null; }, "~S,~S,~S"); Clazz.defineMethod (c$, "matchesPeakTypeModel", function (type, model) { if (type.equals ("ID")) return (this.sourceID.equalsIgnoreCase (model)); if (this.peakList != null && this.peakList.size () > 0) for (var i = 0; i < this.peakList.size (); i++) if (this.peakList.get (i).checkTypeModel (type, model)) return true; return false; }, "~S,~S"); Clazz.defineMethod (c$, "setSelectedPeak", function (peak) { this.selectedPeak = peak; }, "JSV.common.PeakInfo"); Clazz.defineMethod (c$, "setHighlightedPeak", function (peak) { this.highlightedPeak = peak; }, "JSV.common.PeakInfo"); Clazz.defineMethod (c$, "getSelectedPeak", function () { return this.selectedPeak; }); Clazz.defineMethod (c$, "getModelPeakInfoForAutoSelectOnLoad", function () { if (this.peakList != null) for (var i = 0; i < this.peakList.size (); i++) if (this.peakList.get (i).autoSelectOnLoad ()) return this.peakList.get (i); return null; }); Clazz.defineMethod (c$, "getAssociatedPeakInfo", function (xPixel, coord) { this.selectedPeak = this.findPeakByCoord (xPixel, coord); return (this.selectedPeak == null ? this.getBasePeakInfo () : this.selectedPeak); }, "~N,JSV.common.Coordinate"); Clazz.defineMethod (c$, "findPeakByCoord", function (xPixel, coord) { if (coord != null && this.peakList != null && this.peakList.size () > 0) { var xVal = coord.getXVal (); var iBest = -1; var dBest = 1e100; for (var i = 0; i < this.peakList.size (); i++) { var d = this.peakList.get (i).checkRange (xPixel, xVal); if (d < dBest) { dBest = d; iBest = i; }} if (iBest >= 0) return this.peakList.get (iBest); }return null; }, "~N,JSV.common.Coordinate"); Clazz.defineMethod (c$, "getPeakTitle", function () { return (this.selectedPeak != null ? this.selectedPeak.getTitle () : this.highlightedPeak != null ? this.highlightedPeak.getTitle () : this.getTitleLabel ()); }); Clazz.defineMethod (c$, "getTitleLabel", function () { var type = (this.peakList == null || this.peakList.size () == 0 ? this.getQualifiedDataType () : this.peakList.get (0).getType ()); if (type != null && type.startsWith ("NMR")) { if (this.nucleusY != null && !this.nucleusY.equals ("?")) { type = "2D" + type; } else { type = this.nucleusX + type; }}return (type != null && type.length > 0 ? type + " " : "") + this.getTitle (); }); Clazz.defineMethod (c$, "setNextPeak", function (coord, istep) { if (this.peakList == null || this.peakList.size () == 0) return -1; var x0 = coord.getXVal () + istep * 0.000001; var ipt1 = -1; var ipt2 = -1; var dmin1 = 1.7976931348623157E308 * istep; var dmin2 = 0; for (var i = this.peakList.size (); --i >= 0; ) { var x = this.peakList.get (i).getX (); if (istep > 0) { if (x > x0 && x < dmin1) { ipt1 = i; dmin1 = x; } else if (x < x0 && x - x0 < dmin2) { ipt2 = i; dmin2 = x - x0; }} else { if (x < x0 && x > dmin1) { ipt1 = i; dmin1 = x; } else if (x > x0 && x - x0 > dmin2) { ipt2 = i; dmin2 = x - x0; }}} if (ipt1 < 0) { if (ipt2 < 0) return -1; ipt1 = ipt2; }return ipt1; }, "JSV.common.Coordinate,~N"); Clazz.defineMethod (c$, "getPercentYValueAt", function (x) { if (!this.isContinuous ()) return NaN; return this.getYValueAt (x); }, "~N"); Clazz.defineMethod (c$, "getYValueAt", function (x) { return JSV.common.Coordinate.getYValueAt (this.xyCoords, x); }, "~N"); Clazz.defineMethod (c$, "setUserYFactor", function (userYFactor) { this.userYFactor = userYFactor; }, "~N"); Clazz.defineMethod (c$, "getUserYFactor", function () { return this.userYFactor; }); Clazz.defineMethod (c$, "getConvertedSpectrum", function () { return this.convertedSpectrum; }); Clazz.defineMethod (c$, "setConvertedSpectrum", function (spectrum) { this.convertedSpectrum = spectrum; }, "JSV.common.Spectrum"); c$.taConvert = Clazz.defineMethod (c$, "taConvert", function (spectrum, mode) { if (!spectrum.isContinuous ()) return spectrum; switch (mode) { case JSV.common.Spectrum.IRMode.NO_CONVERT: return spectrum; case JSV.common.Spectrum.IRMode.TO_ABS: if (!spectrum.isTransmittance ()) return spectrum; break; case JSV.common.Spectrum.IRMode.TO_TRANS: if (!spectrum.isAbsorbance ()) return spectrum; break; case JSV.common.Spectrum.IRMode.TOGGLE: break; } var spec = spectrum.getConvertedSpectrum (); return (spec != null ? spec : spectrum.isAbsorbance () ? JSV.common.Spectrum.toT (spectrum) : JSV.common.Spectrum.toA (spectrum)); }, "JSV.common.Spectrum,JSV.common.Spectrum.IRMode"); c$.toT = Clazz.defineMethod (c$, "toT", function (spectrum) { if (!spectrum.isAbsorbance ()) return null; var xyCoords = spectrum.getXYCoords (); var newXYCoords = new Array (xyCoords.length); if (!JSV.common.Coordinate.isYInRange (xyCoords, 0, 4.0)) xyCoords = JSV.common.Coordinate.normalise (xyCoords, 0, 4.0); for (var i = 0; i < xyCoords.length; i++) newXYCoords[i] = new JSV.common.Coordinate ().set (xyCoords[i].getXVal (), JSV.common.Spectrum.toTransmittance (xyCoords[i].getYVal ())); return JSV.common.Spectrum.newSpectrum (spectrum, newXYCoords, "TRANSMITTANCE"); }, "JSV.common.Spectrum"); c$.toA = Clazz.defineMethod (c$, "toA", function (spectrum) { if (!spectrum.isTransmittance ()) return null; var xyCoords = spectrum.getXYCoords (); var newXYCoords = new Array (xyCoords.length); var isPercent = JSV.common.Coordinate.isYInRange (xyCoords, -2, 2); for (var i = 0; i < xyCoords.length; i++) newXYCoords[i] = new JSV.common.Coordinate ().set (xyCoords[i].getXVal (), JSV.common.Spectrum.toAbsorbance (xyCoords[i].getYVal (), isPercent)); return JSV.common.Spectrum.newSpectrum (spectrum, newXYCoords, "ABSORBANCE"); }, "JSV.common.Spectrum"); c$.newSpectrum = Clazz.defineMethod (c$, "newSpectrum", function (spectrum, newXYCoords, units) { var specNew = spectrum.copy (); specNew.setOrigin ("JSpecView Converted"); specNew.setOwner ("JSpecView Generated"); specNew.setXYCoords (newXYCoords); specNew.setYUnits (units); spectrum.setConvertedSpectrum (specNew); specNew.setConvertedSpectrum (spectrum); return specNew; }, "JSV.common.Spectrum,~A,~S"); c$.toAbsorbance = Clazz.defineMethod (c$, "toAbsorbance", function (x, isPercent) { return (Math.min (4.0, isPercent ? 2 - JSV.common.Spectrum.log10 (x) : -JSV.common.Spectrum.log10 (x))); }, "~N,~B"); c$.toTransmittance = Clazz.defineMethod (c$, "toTransmittance", function (x) { return (x <= 0 ? 1 : Math.pow (10, -x)); }, "~N"); c$.log10 = Clazz.defineMethod (c$, "log10", function (value) { return Math.log (value) / Math.log (10); }, "~N"); c$.process = Clazz.defineMethod (c$, "process", function (specs, irMode) { if (irMode === JSV.common.Spectrum.IRMode.TO_ABS || irMode === JSV.common.Spectrum.IRMode.TO_TRANS) for (var i = 0; i < specs.size (); i++) specs.set (i, JSV.common.Spectrum.taConvert (specs.get (i), irMode)); return true; }, "JU.Lst,JSV.common.Spectrum.IRMode"); Clazz.defineMethod (c$, "getSubSpectra", function () { return this.subSpectra; }); Clazz.defineMethod (c$, "getCurrentSubSpectrum", function () { return (this.subSpectra == null ? this : this.subSpectra.get (this.currentSubSpectrumIndex)); }); Clazz.defineMethod (c$, "advanceSubSpectrum", function (dir) { return this.setCurrentSubSpectrum (this.currentSubSpectrumIndex + dir); }, "~N"); Clazz.defineMethod (c$, "setCurrentSubSpectrum", function (n) { return (this.currentSubSpectrumIndex = JSV.common.Coordinate.intoRange (n, 0, this.subSpectra.size () - 1)); }, "~N"); Clazz.defineMethod (c$, "addSubSpectrum", function (spectrum, forceSub) { if (!forceSub && (this.numDim < 2 || this.blockID != spectrum.blockID) || !JSV.common.Spectrum.allowSubSpec (this, spectrum)) return false; this.$isForcedSubset = forceSub; if (this.subSpectra == null) { this.subSpectra = new JU.Lst (); this.addSubSpectrum (this, true); }this.subSpectra.addLast (spectrum); spectrum.parent = this; return true; }, "JSV.common.Spectrum,~B"); Clazz.defineMethod (c$, "getSubIndex", function () { return (this.subSpectra == null ? -1 : this.currentSubSpectrumIndex); }); Clazz.defineMethod (c$, "setExportXAxisDirection", function (leftToRight) { this.exportXAxisLeftToRight = leftToRight; }, "~B"); Clazz.defineMethod (c$, "isExportXAxisLeftToRight", function () { return this.exportXAxisLeftToRight; }); Clazz.defineMethod (c$, "getInfo", function (key) { var info = new java.util.Hashtable (); if ("id".equalsIgnoreCase (key)) { info.put (key, this.id); return info; }info.put ("id", this.id); JSV.common.Parameters.putInfo (key, info, "specShift", Double.$valueOf (this.specShift)); var justHeader = ("header".equals (key)); if (!justHeader && key != null) { for (var i = this.headerTable.size (); --i >= 0; ) { var entry = this.headerTable.get (i); if (entry[0].equalsIgnoreCase (key) || entry[2].equalsIgnoreCase (key)) { info.put (key, entry[1]); return info; }} }var head = new java.util.Hashtable (); var list = this.getHeaderRowDataAsArray (); for (var i = 0; i < list.length; i++) { var label = JSV.source.JDXSourceStreamTokenizer.cleanLabel (list[i][0]); if (key != null && !justHeader && !label.equals (key)) continue; var val = JSV.common.Spectrum.fixInfoValue (list[i][1]); if (key == null) { var data = new java.util.Hashtable (); data.put ("value", val); data.put ("index", Integer.$valueOf (i + 1)); info.put (label, data); } else { info.put (label, val); }} if (head.size () > 0) info.put ("header", head); if (!justHeader) { JSV.common.Parameters.putInfo (key, info, "titleLabel", this.getTitleLabel ()); JSV.common.Parameters.putInfo (key, info, "type", this.getDataType ()); JSV.common.Parameters.putInfo (key, info, "isHZToPPM", Boolean.$valueOf (this.$isHZtoPPM)); JSV.common.Parameters.putInfo (key, info, "subSpectrumCount", Integer.$valueOf (this.subSpectra == null ? 0 : this.subSpectra.size ())); }return info; }, "~S"); c$.fixInfoValue = Clazz.defineMethod (c$, "fixInfoValue", function (info) { try { return (Integer.$valueOf (info)); } catch (e) { if (Clazz.exceptionOf (e, Exception)) { } else { throw e; } } try { return (Double.$valueOf (info)); } catch (e) { if (Clazz.exceptionOf (e, Exception)) { } else { throw e; } } return info; }, "~S"); Clazz.overrideMethod (c$, "toString", function () { return this.getTitleLabel (); }); Clazz.defineMethod (c$, "findMatchingPeakInfo", function (pi) { for (var i = 0; i < this.peakList.size (); i++) if (this.peakList.get (i).checkTypeMatch (pi)) return this.peakList.get (i); return null; }, "JSV.common.PeakInfo"); Clazz.defineMethod (c$, "getBasePeakInfo", function () { return (this.peakList.size () == 0 ? new JSV.common.PeakInfo () : new JSV.common.PeakInfo (" baseModel=\"\" " + this.peakList.get (0))); }); Clazz.defineMethod (c$, "getAxisLabel", function (isX) { var units = (isX ? this.piUnitsX : this.piUnitsY); if (units == null) units = (isX ? this.xLabel : this.yLabel); if (units == null) units = (isX ? this.xUnits : this.yUnits); return (units == null ? "" : units.equalsIgnoreCase ("WAVENUMBERS") ? "1/cm" : units.equalsIgnoreCase ("nanometers") ? "nm" : units); }, "~B"); Clazz.defineMethod (c$, "findXForPeakNearest", function (x) { return JSV.common.Coordinate.findXForPeakNearest (this.xyCoords, x, this.isInverted ()); }, "~N"); Clazz.defineMethod (c$, "addSpecShift", function (dx) { if (dx != 0) { this.specShift += dx; JSV.common.Coordinate.shiftX (this.xyCoords, dx); if (this.subSpectra != null) for (var i = this.subSpectra.size (); --i >= 0; ) { var spec = this.subSpectra.get (i); if (spec !== this && spec !== this.parent) spec.addSpecShift (dx); } }return this.specShift; }, "~N"); c$.allowSubSpec = Clazz.defineMethod (c$, "allowSubSpec", function (s1, s2) { return (s1.is1D () == s2.is1D () && s1.xUnits.equalsIgnoreCase (s2.xUnits) && s1.isHNMR () == s2.isHNMR ()); }, "JSV.common.Spectrum,JSV.common.Spectrum"); c$.areXScalesCompatible = Clazz.defineMethod (c$, "areXScalesCompatible", function (s1, s2, isSubspecCheck, isLinkCheck) { var isNMR1 = s1.isNMR (); if (isNMR1 != s2.isNMR () || s1.isContinuous () != s2.isContinuous () || !isLinkCheck && !JSV.common.Spectrum.areUnitsCompatible (s1.xUnits, s2.xUnits)) return false; if (isSubspecCheck) { if (s1.is1D () != s2.is1D ()) return false; } else if (isLinkCheck) { if (!isNMR1) return true; } else if (!s1.is1D () || !s2.is1D ()) { return false; }return (!isNMR1 || s2.is1D () && s1.parent.nucleusX.equals (s2.parent.nucleusX)); }, "JSV.common.Spectrum,JSV.common.Spectrum,~B,~B"); c$.areUnitsCompatible = Clazz.defineMethod (c$, "areUnitsCompatible", function (u1, u2) { if (u1.equalsIgnoreCase (u2)) return true; u1 = u1.toUpperCase (); u2 = u2.toUpperCase (); return (u1.equals ("HZ") && u2.equals ("PPM") || u1.equals ("PPM") && u2.equals ("HZ")); }, "~S,~S"); c$.areLinkableX = Clazz.defineMethod (c$, "areLinkableX", function (s1, s2) { return (s1.isNMR () && s2.isNMR () && s1.nucleusX.equals (s2.nucleusX)); }, "JSV.common.Spectrum,JSV.common.Spectrum"); c$.areLinkableY = Clazz.defineMethod (c$, "areLinkableY", function (s1, s2) { return (s1.isNMR () && s2.isNMR () && s1.nucleusX.equals (s2.nucleusY)); }, "JSV.common.Spectrum,JSV.common.Spectrum"); Clazz.defineMethod (c$, "setNHydrogens", function (nH) { this.nH = nH; }, "~N"); Clazz.defineMethod (c$, "getPeakWidth", function () { var w = this.getLastX () - this.getFirstX (); return (w / 100); }); Clazz.defineMethod (c$, "setSimulated", function (filePath) { this.isSimulation = true; var s = this.sourceID; if (s.length == 0) s = JU.PT.rep (filePath, "http://SIMULATION/", ""); if (s.indexOf ("MOL=") >= 0) s = ""; this.title = "SIMULATED " + JU.PT.rep (s, "$", ""); }, "~S"); Clazz.defineMethod (c$, "setFillColor", function (color) { this.fillColor = color; if (this.convertedSpectrum != null) this.convertedSpectrum.fillColor = color; }, "javajs.api.GenericColor"); Clazz.pu$h(self.c$); c$ = Clazz.declareType (JSV.common.Spectrum, "IRMode", Enum); c$.getMode = Clazz.defineMethod (c$, "getMode", function (a) { switch (a == null ? 'I' : a.toUpperCase ().charAt (0)) { case 'A': return JSV.common.Spectrum.IRMode.TO_ABS; case 'T': return (a.equalsIgnoreCase ("TOGGLE") ? JSV.common.Spectrum.IRMode.TOGGLE : JSV.common.Spectrum.IRMode.TO_TRANS); case 'N': return JSV.common.Spectrum.IRMode.NO_CONVERT; default: return JSV.common.Spectrum.IRMode.TOGGLE; } }, "~S"); Clazz.defineEnumConstant (c$, "NO_CONVERT", 0, []); Clazz.defineEnumConstant (c$, "TO_TRANS", 1, []); Clazz.defineEnumConstant (c$, "TO_ABS", 2, []); Clazz.defineEnumConstant (c$, "TOGGLE", 3, []); c$ = Clazz.p0p (); Clazz.defineStatics (c$, "MAXABS", 4); });
davidbuzatto/CryProteinModelsComparisonLab
web/j2s/JSV/common/Spectrum.js
JavaScript
gpl-3.0
18,056
s = new ShardingTest( "diffservers1" , 2 ); assert.eq( 2 , s.config.shards.count() , "server count wrong" ); assert.eq( 2 , s._connections[0].getDB( "config" ).shards.count() , "where are servers!" ); assert.eq( 0 , s._connections[1].getDB( "config" ).shards.count() , "shouldn't be here" ); test1 = s.getDB( "test1" ).foo; test1.save( { a : 1 } ); test1.save( { a : 2 } ); test1.save( { a : 3 } ); assert( 3 , test1.count() ); assert( ! s.admin.runCommand( { addshard: "sdd$%" } ).ok , "bad hostname" ); assert( ! s.admin.runCommand( { addshard: "127.0.0.1:43415" } ).ok , "host not up" ); assert( ! s.admin.runCommand( { addshard: "10.0.0.1:43415" } ).ok , "allowed shard in IP when config is localhost" ); s.stop();
wvdd007/robomongo
src/third-party/mongodb/jstests/sharding/diffservers1.js
JavaScript
gpl-3.0
726
// ========================================== // RECESS // RULE: .js prefixes should not be styled // ========================================== // Copyright 2012 Twitter, Inc // Licensed under the Apache License v2.0 // http://www.apache.org/licenses/LICENSE-2.0 // ========================================== 'use strict' var util = require('../util') , RULE = { type: 'noJSPrefix' , exp: /^\.js\-/ , message: '.js prefixes should not be styled' } // validation method module.exports = function (def, data) { // default validation to true var isValid = true // return if no selector to validate if (!def.selectors) return isValid // loop over selectors def.selectors.forEach(function (selector) { // loop over selector entities selector.elements.forEach(function (element) { var extract // continue to next element if .js- prefix not styled if (!RULE.exp.test(element.value)) return // calculate line number for the extract extract = util.getLine(element.index - element.value.length, data) extract = util.padLine(extract) // highlight invalid styling of .js- prefix extract += element.value.replace(RULE.exp, '.js-'.magenta) // set invalid flag to false isValid = false // set error object on defintion token util.throwError(def, { type: RULE.type , message: RULE.message , extract: extract }) }) }) // return valid state return isValid }
jdsimcoe/briansimcoe
workspace/grunt/node_modules/grunt-recess/node_modules/recess/lib/lint/no-JS-prefix.js
JavaScript
mit
1,504
module.exports.twitter = function twitter(username) { // Creates the canonical twitter URL without the '@' return 'https://twitter.com/' + username.replace(/^@/, ''); }; module.exports.facebook = function facebook(username) { // Handles a starting slash, this shouldn't happen, but just in case return 'https://www.facebook.com/' + username.replace(/^\//, ''); };
EdwardStudy/myghostblog
versions/2.16.4/core/server/lib/social/urls.js
JavaScript
mit
381
var utils = exports; var uglify = require('uglify-js'); utils.extend = function extend(target, source) { Object.keys(source).forEach(function (key) { target[key] = source[key]; }); }; utils.beautify = function beautify(code) { var ast = uglify.parser.parse(code); return uglify.uglify.gen_code(ast, { beautify: true }); }; utils.expressionify = function expressionify(code) { try { var ast = uglify.parser.parse('(function(){\n' + code + '\n})'); } catch(e) { console.error(e.message + ' on ' + (e.line - 1) + ':' + e.pos); console.error('in'); console.error(code); throw e; } ast[1] = ast[1][0][1][3]; function traverse(ast) { if (!Array.isArray(ast)) return ast; switch (ast[0]) { case 'toplevel': if (ast[1].length === 1 && ast[1][0][0] !== 'block') { return ast; } else { var children = ast[1][0][0] === 'block' ? ast[1][0][1] : ast[1]; return ['toplevel', [[ 'call', [ 'dot', [ 'function', null, [], children.map(function(child, i, children) { return (i == children.length - 1) ? traverse(child) : child; }) ], 'call' ], [ ['name', 'this'] ] ]]]; } case 'block': // Empty blocks can't be processed if (ast[1].length <= 0) return ast; var last = ast[1][ast[1].length - 1]; return [ ast[0], ast[1].slice(0, -1).concat([traverse(last)]) ]; case 'while': case 'for': case 'switch': return ast; case 'if': return [ 'if', ast[1], traverse(ast[2]), traverse(ast[3]) ]; case 'stat': return [ 'stat', traverse(ast[1]) ]; default: if (ast[0] === 'return') return ast; return [ 'return', ast ] } return ast; } return uglify.uglify.gen_code(traverse(ast)).replace(/;$/, ''); }; utils.localify = function localify(code, id) { var ast = uglify.parser.parse(code); if (ast[1].length !== 1 || ast[1][0][0] !== 'stat') { throw new TypeError('Incorrect code for local: ' + code); } var vars = [], set = [], unset = []; function traverse(node) { if (node[0] === 'assign') { if (node[1] !== true) { throw new TypeError('Incorrect assignment in local'); } if (node[2][0] === 'dot' || node[2][0] === 'sub') { var host = ['name', '$l' + id++]; vars.push(host[1]); set.push(['assign', true, host, node[2][1]]); node[2][1] = host; if (node[2][0] === 'sub') { var property = ['name', '$l' + id++]; vars.push(property[1]); set.push(['assign', true, property, node[2][2]]); node[2][2] = property; } } var target = ['name', '$l' + id++]; vars.push(target[1]); set.push(['assign', true, target, node[2]]); set.push(['assign', true, node[2], node[3]]); unset.push(['assign', true, node[2], target]); } else if (node[0] === 'seq') { traverse(node[1]); traverse(node[2]); } else { throw new TypeError( 'Incorrect code for local (' + node[0] + '): ' + code ); } } traverse(ast[1][0][1]); function generate(seqs) { return uglify.uglify.gen_code(seqs.reduce(function (current, acc) { return ['seq', current, acc]; })); } return { vars: vars, before: generate(set.concat([['name', 'true']])), afterSuccess: generate(unset.concat([['name', 'true']])), afterFail: generate(unset.concat([['name', 'false']])) }; }; utils.merge = function merge(a, b) { Object.keys(b).forEach(function(key) { a[key] = b[key]; }); };
CoderPuppy/loke-lang
node_modules/ometajs/lib/ometajs/utils.js
JavaScript
mit
3,898
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ /* * Plugin to hide series in flot graphs. * * To activate, set legend.hideable to true in the flot options object. * To hide one or more series by default, set legend.hidden to an array of * label strings. * * At the moment, this only works with line and point graphs. * * Example: * * var plotdata = [ * { * data: [[1, 1], [2, 1], [3, 3], [4, 2], [5, 5]], * label: "graph 1" * }, * { * data: [[1, 0], [2, 1], [3, 0], [4, 4], [5, 3]], * label: "graph 2" * } * ]; * * plot = $.plot($("#placeholder"), plotdata, { * series: { * points: { show: true }, * lines: { show: true } * }, * legend: { * hideable: true, * hidden: ["graph 1", "graph 2"] * } * }); * */ (function ($) { var options = { }; var drawnOnce = false; function init(plot) { function findPlotSeries(label) { var plotdata = plot.getData(); for (var i = 0; i < plotdata.length; i++) { if (plotdata[i].label == label) { return plotdata[i]; } } return null; } function plotLabelClicked(label, mouseOut) { var series = findPlotSeries(label); if (!series) { return; } var switchedOff = false; if (typeof series.points.oldShow === "undefined") { series.points.oldShow = false; } if (typeof series.lines.oldShow === "undefined") { series.lines.oldShow = false; } if (series.points.show && !series.points.oldShow) { series.points.show = false; series.points.oldShow = true; switchedOff = true; } if (series.lines.show && !series.lines.oldShow) { series.lines.show = false; series.lines.oldShow = true; switchedOff = true; } if (switchedOff) { series.oldColor = series.color; series.color = "#fff"; } else { var switchedOn = false; if (!series.points.show && series.points.oldShow) { series.points.show = true; series.points.oldShow = false; switchedOn = true; } if (!series.lines.show && series.lines.oldShow) { series.lines.show = true; series.lines.oldShow = false; switchedOn = true; } if (switchedOn) { series.color = series.oldColor; } } // HACK: Reset the data, triggering recalculation of graph bounds plot.setData(plot.getData()); plot.setupGrid(); plot.draw(); } function plotLabelHandlers(plot, options) { $(".graphlabel").mouseenter(function() { $(this).css("cursor", "pointer"); }) .mouseleave(function() { $(this).css("cursor", "default"); }) .unbind("click").click(function() { plotLabelClicked($(this).parent().text()); }); if (!drawnOnce) { drawnOnce = true; if (options.legend.hidden) { for (var i = 0; i < options.legend.hidden.length; i++) { plotLabelClicked(options.legend.hidden[i], true); } } } } function checkOptions(plot, options) { if (!options.legend.hideable) { return; } options.legend.labelFormatter = function(label, series) { return '<span class="graphlabel">' + label + '</span>'; }; // Really just needed for initial draw; the mouse-enter/leave // functions will call plotLabelHandlers() directly, since they // only call setupGrid(). plot.hooks.draw.push(function (plot, ctx) { plotLabelHandlers(plot, options); }); } plot.hooks.processOptions.push(checkOptions); function hideDatapointsIfNecessary(plot, s, datapoints) { if (!plot.getOptions().legend.hideable) { return; } if (!s.points.show && !s.lines.show) { s.datapoints.format = [ null, null ]; } } plot.hooks.processDatapoints.push(hideDatapointsIfNecessary); } $.plot.plugins.push({ init: init, options: options, name: 'hiddenGraphs', version: '1.0' }); })(jQuery);
mehulsbhatt/torque
web/static/js/jquery.flot.hiddengraphs.js
JavaScript
mit
5,081
//DO NOT DELETE THIS, this is in use... angular.module('umbraco') .controller("Umbraco.PropertyEditors.MacroContainerController", function($scope, dialogService, entityResource, macroService){ $scope.renderModel = []; $scope.allowOpenButton = true; $scope.allowRemoveButton = true; $scope.sortableOptions = {}; if($scope.model.value){ var macros = $scope.model.value.split('>'); angular.forEach(macros, function(syntax, key){ if(syntax && syntax.length > 10){ //re-add the char we split on syntax = syntax + ">"; var parsed = macroService.parseMacroSyntax(syntax); if(!parsed){ parsed = {}; } parsed.syntax = syntax; collectDetails(parsed); $scope.renderModel.push(parsed); setSortingState($scope.renderModel); } }); } function collectDetails(macro){ macro.details = ""; macro.icon = "icon-settings-alt"; if(macro.macroParamsDictionary){ angular.forEach((macro.macroParamsDictionary), function(value, key){ macro.details += key + ": " + value + " "; }); } } function openDialog(index){ var dialogData = { allowedMacros: $scope.model.config.allowed }; if(index !== null && $scope.renderModel[index]) { var macro = $scope.renderModel[index]; dialogData["macroData"] = macro; } $scope.macroPickerOverlay = {}; $scope.macroPickerOverlay.view = "macropicker"; $scope.macroPickerOverlay.dialogData = dialogData; $scope.macroPickerOverlay.show = true; $scope.macroPickerOverlay.submit = function(model) { var macroObject = macroService.collectValueData(model.selectedMacro, model.macroParams, dialogData.renderingEngine); collectDetails(macroObject); //update the raw syntax and the list... if(index !== null && $scope.renderModel[index]) { $scope.renderModel[index] = macroObject; } else { $scope.renderModel.push(macroObject); } setSortingState($scope.renderModel); $scope.macroPickerOverlay.show = false; $scope.macroPickerOverlay = null; }; $scope.macroPickerOverlay.close = function(oldModel) { $scope.macroPickerOverlay.show = false; $scope.macroPickerOverlay = null; }; } $scope.edit =function(index){ openDialog(index); }; $scope.add = function () { if ($scope.model.config.max && $scope.model.config.max > 0 && $scope.renderModel.length >= $scope.model.config.max) { //cannot add more than the max return; } openDialog(); }; $scope.remove =function(index){ $scope.renderModel.splice(index, 1); setSortingState($scope.renderModel); }; $scope.clear = function() { $scope.model.value = ""; $scope.renderModel = []; }; var unsubscribe = $scope.$on("formSubmitting", function (ev, args) { var syntax = []; angular.forEach($scope.renderModel, function(value, key){ syntax.push(value.syntax); }); $scope.model.value = syntax.join(""); }); //when the scope is destroyed we need to unsubscribe $scope.$on('$destroy', function () { unsubscribe(); }); function trim(str, chr) { var rgxtrim = (!chr) ? new RegExp('^\\s+|\\s+$', 'g') : new RegExp('^'+chr+'+|'+chr+'+$', 'g'); return str.replace(rgxtrim, ''); } function setSortingState(items) { // disable sorting if the list only consist of one item if(items.length > 1) { $scope.sortableOptions.disabled = false; } else { $scope.sortableOptions.disabled = true; } } });
abryukhov/Umbraco-CMS
src/Umbraco.Web.UI.Client/src/views/propertyeditors/macrocontainer/macrocontainer.controller.js
JavaScript
mit
3,569
isClear = true; function context(description, spec) { describe(description, spec); }; function build() { $('body').append('<div id="element"></div>'); }; function buildDivTarget() { $('body').append('<div id="hint"></div>'); }; function buildComboboxTarget() { $('body').append( '<select id="hint">' + '<option value="Cancel this rating!">cancel hint default</option>' + '<option value="cancel-hint-custom">cancel hint custom</option>' + '<option value="">cancel number default</option>' + '<option value="0">cancel number custom</option>' + '<option value="bad">bad hint imutable</option>' + '<option value="1">bad number imutable</option>' + '<option value="targetText">targetText is setted without targetKeep</option>' + '<option value="score: bad">targetFormat</option>' + '</select>' ); }; function buildTextareaTarget() { $('body').append('<textarea id="hint"></textarea>'); }; function buildTextTarget() { $('body').append('<input id="hint" type="text" />'); }; function clear() { if (isClear) { $('#element').remove(); $('#hint').remove(); } }; describe('Raty', function() { beforeEach(function() { build(); }); afterEach(function() { clear(); }); it ('has the right values', function() { // given var raty = $.fn.raty // when var opt = raty.defaults // then expect(opt.cancel).toBeFalsy(); expect(opt.cancelHint).toEqual('Cancel this rating!'); expect(opt.cancelOff).toEqual('cancel-off.png'); expect(opt.cancelOn).toEqual('cancel-on.png'); expect(opt.cancelPlace).toEqual('left'); expect(opt.click).toBeUndefined(); expect(opt.half).toBeFalsy(); expect(opt.halfShow).toBeTruthy(); expect(opt.hints).toContain('bad', 'poor', 'regular', 'good', 'gorgeous'); expect(opt.iconRange).toBeUndefined(); expect(opt.mouseover).toBeUndefined(); expect(opt.noRatedMsg).toEqual('Not rated yet!'); expect(opt.number).toBe(5); expect(opt.path).toEqual(''); expect(opt.precision).toBeFalsy(); expect(opt.readOnly).toBeFalsy(); expect(opt.round.down).toEqual(.25); expect(opt.round.full).toEqual(.6); expect(opt.round.up).toEqual(.76); expect(opt.score).toBeUndefined(); expect(opt.scoreName).toEqual('score'); expect(opt.single).toBeFalsy(); expect(opt.size).toBe(16); expect(opt.space).toBeTruthy(); expect(opt.starHalf).toEqual('star-half.png'); expect(opt.starOff).toEqual('star-off.png'); expect(opt.starOn).toEqual('star-on.png'); expect(opt.target).toBeUndefined(); expect(opt.targetFormat).toEqual('{score}'); expect(opt.targetKeep).toBeFalsy(); expect(opt.targetText).toEqual(''); expect(opt.targetType).toEqual('hint'); expect(opt.width).toBeUndefined(); }); describe('common features', function() { it ('is chainable', function() { // given var self = $('#element'); // when var ref = self.raty(); // then expect(ref).toBe(self); }); it ('creates the default markup', function() { // given var self = $('#element'); // when self.raty(); // then var imgs = self.children('img'), score = self.children('input'); expect(imgs.eq(0)).toHaveAttr('title', 'bad'); expect(imgs.eq(1)).toHaveAttr('title', 'poor'); expect(imgs.eq(2)).toHaveAttr('title', 'regular'); expect(imgs.eq(3)).toHaveAttr('title', 'good'); expect(imgs.eq(4)).toHaveAttr('title', 'gorgeous'); expect(imgs).toHaveAttr('src', 'star-off.png'); expect(score).toHaveAttr('type', 'hidden'); expect(score).toHaveAttr('name', 'score'); expect(score.val()).toEqual(''); }); }); describe('#star', function() { it ('starts all off', function() { // given var self = $('#element'); // when self.raty(); // then expect(self.children('img')).toHaveAttr('src', 'star-off.png'); }); context('on :mouseover', function() { it ('turns on the stars', function() { // given var self = $('#element').raty(), imgs = self.children('img'); // when imgs.eq(4).mouseover(); // then expect(imgs).toHaveAttr('src', 'star-on.png'); }); context('and :mouseout', function() { it ('clears all stars', function() { // given var self = $('#element').raty(), imgs = self.children('img'); // when imgs.eq(4).mouseover().mouseout(); // then expect(imgs).toHaveAttr('src', 'star-off.png'); }); }); }); context('on rating', function() { it ('changes the score', function() { // given var self = $('#element').raty(), imgs = self.children('img'); // when imgs.eq(1).mouseover().click(); // then expect(self.children('input')).toHaveValue(2); }); context('on :mouseout', function() { it ('keeps the stars on', function() { // given var self = $('#element').raty(), imgs = self.children('img'); // when imgs.eq(4).mouseover().click().mouseout(); // then expect(imgs).toHaveAttr('src', 'star-on.png'); }); }); }); }); describe('options', function() { describe('#numberMax', function() { it ('limits to 20 stars', function() { // given var self = $('#element').raty({ number: 50, score: 50 }); // when var score = self.raty('score'); // then expect(self.children('img').length).toEqual(20); expect(self.children('input')).toHaveValue(20); }); context('with custom numberMax', function() { it ('chages the limit', function() { // given var self = $('#element').raty({ numberMax: 10, number: 50, score: 50 }); // when var score = self.raty('score'); // then expect(self.children('img').length).toEqual(10); expect(self.children('input')).toHaveValue(10); }); }); }); describe('#starOff', function() { it ('changes the icons', function() { // given var self = $('#element'); // when self.raty({ starOff: 'icon.png' }); // then expect(self.children('img')).toHaveAttr('src', 'icon.png'); }); }); describe('#starOn', function() { it ('changes the icons', function() { // given var self = $('#element').raty({ starOn: 'icon.png' }), imgs = self.children('img'); // when imgs.eq(3).mouseover(); // then expect(imgs.eq(0)).toHaveAttr('src', 'icon.png'); expect(imgs.eq(1)).toHaveAttr('src', 'icon.png'); expect(imgs.eq(2)).toHaveAttr('src', 'icon.png'); expect(imgs.eq(3)).toHaveAttr('src', 'icon.png'); expect(imgs.eq(4)).toHaveAttr('src', 'star-off.png'); }); }); describe('#iconRange', function() { it ('uses icon intervals', function() { // given var self = $('#element'); // when self.raty({ iconRange: [ { range: 2, on: 'a.png', off: 'a-off.png' }, { range: 3, on: 'b.png', off: 'b-off.png' }, { range: 4, on: 'c.png', off: 'c-off.png' }, { range: 5, on: 'd.png', off: 'd-off.png' } ] }); // then var imgs = self.children('img'); expect(imgs.eq(0)).toHaveAttr('src', 'a-off.png'); expect(imgs.eq(1)).toHaveAttr('src', 'a-off.png'); expect(imgs.eq(2)).toHaveAttr('src', 'b-off.png'); expect(imgs.eq(3)).toHaveAttr('src', 'c-off.png'); expect(imgs.eq(4)).toHaveAttr('src', 'd-off.png'); }); context('when off icon is not especified', function() { it ('uses the :starOff icon', function() { // given var self = $('#element'); // when self.raty({ iconRange: [ { range: 2, on: 'on.png', off: 'off.png' }, { range: 3, on: 'on.png', off: 'off.png' }, { range: 4, on: 'on.png', off: 'off.png' }, { range: 5, on: 'on.png' } ] }); // then expect(self.children('img').eq(4)).toHaveAttr('src', 'star-off.png'); }); }); context('on mouseover', function() { it ('uses the on icon', function() { // given var self = $('#element').raty({ iconRange: [ { range: 2, on: 'a.png', off: 'a-off.png' }, { range: 3, on: 'b.png', off: 'b-off.png' }, { range: 4, on: 'c.png', off: 'c-off.png' }, { range: 5, on: 'd.png', off: 'd-off.png' } ] }), imgs = self.children('img'); // when imgs.eq(4).mouseover(); // then expect(imgs.eq(0)).toHaveAttr('src', 'a.png'); expect(imgs.eq(1)).toHaveAttr('src', 'a.png'); expect(imgs.eq(2)).toHaveAttr('src', 'b.png'); expect(imgs.eq(3)).toHaveAttr('src', 'c.png'); expect(imgs.eq(4)).toHaveAttr('src', 'd.png'); }); context('when on icon is not especified', function() { it ('uses the :starOn icon', function() { // given var self = $('#element').raty({ iconRange: [ { range: 2, off: 'off.png', on: 'on.png' }, { range: 3, off: 'off.png', on: 'on.png' }, { range: 4, off: 'off.png', on: 'on.png' }, { range: 5, off: 'off.png' } ] }), imgs = self.children('img'); // when imgs.eq(4).mouseover(); // then expect(imgs.eq(0)).toHaveAttr('src', 'on.png'); expect(imgs.eq(1)).toHaveAttr('src', 'on.png'); expect(imgs.eq(2)).toHaveAttr('src', 'on.png'); expect(imgs.eq(3)).toHaveAttr('src', 'on.png'); expect(imgs.eq(4)).toHaveAttr('src', 'star-on.png'); }); }); }); context('on mouseout', function() { it ('changes to off icons', function() { // given var self = $('#element').raty({ iconRange: [ { range: 2, on: 'a.png', off: 'a-off.png' }, { range: 3, on: 'b.png', off: 'b-off.png' }, { range: 4, on: 'c.png', off: 'c-off.png' }, { range: 5, on: 'd.png', off: 'd-off.png' }, ] }), imgs = self.children('img'); // when imgs.eq(4).mouseover(); self.mouseleave(); // then expect(imgs.eq(0)).toHaveAttr('src', 'a-off.png'); expect(imgs.eq(1)).toHaveAttr('src', 'a-off.png'); expect(imgs.eq(2)).toHaveAttr('src', 'b-off.png'); expect(imgs.eq(3)).toHaveAttr('src', 'c-off.png'); expect(imgs.eq(4)).toHaveAttr('src', 'd-off.png'); }); it ('keeps the score value', function() { // given var self = $('#element').raty({ iconRange : [ { range: 2, on: 'a.png', off: 'a-off.png' }, { range: 3, on: 'b.png', off: 'b-off.png' }, { range: 4, on: 'c.png', off: 'c-off.png' }, { range: 5, on: 'd.png', off: 'd-off.png' } ], score : 1 }); // when self.children('img').eq(4).mouseover(); self.mouseleave(); // then expect(self.children('input')).toHaveValue(1); }); context('when off icon is not especified', function() { it ('uses the :starOff icon', function() { // given var self = $('#element').raty({ iconRange: [ { range: 2, on: 'on.png', off: 'off.png' }, { range: 3, on: 'on.png', off: 'off.png' }, { range: 4, on: 'on.png', off: 'off.png' }, { range: 5, on: 'on.png' } ] }), img = self.children('img').eq(4); // when img.mouseover(); self.mouseleave(); // then expect(img).toHaveAttr('src', 'star-off.png'); }); }); }); }); describe('#click', function() { it ('has `this` as the self element', function() { // given var self = $('#element').raty({ click: function() { $(this).data('self', this); } }); // when self.children('img:first').mouseover().click(); // then expect(self.data('self')).toBe(self); }); it ('is called on star click', function() { // given var self = $('#element').raty({ click: function() { $(this).data('clicked', true); } }); // when self.children('img:first').mouseover().click(); // then expect(self.data('clicked')).toBeTruthy(); }); it ('receives the score', function() { // given var self = $('#element').raty({ click: function(score) { $(this).data('score', score); } }); // when self.children('img:first').mouseover().click(); // then expect(self.data('score')).toEqual(1); }); context('with :cancel', function() { it ('executes cancel click callback', function() { // given var self = $('#element').raty({ cancel: true, click : function(score) { $(this).data('score', null); } }); // when self.children('.raty-cancel').mouseover().click().mouseleave(); // then expect(self.data('score')).toBeNull(); }); }); }); describe('#score', function() { it ('starts with value', function() { // given var self = $('#element'); // when self.raty({ score: 1 }); // then expect(self.children('input')).toHaveValue(1); }); it ('turns on 1 stars', function() { // given var self = $('#element'); // when self.raty({ score: 1 }); // then var imgs = self.children('img'); expect(imgs.eq(0)).toHaveAttr('src', 'star-on.png'); expect(imgs.eq(1)).toHaveAttr('src', 'star-off.png'); expect(imgs.eq(2)).toHaveAttr('src', 'star-off.png'); expect(imgs.eq(3)).toHaveAttr('src', 'star-off.png'); expect(imgs.eq(4)).toHaveAttr('src', 'star-off.png'); }); it ('accepts callback', function() { // given var self = $('#element'); // when self.raty({ score: function() { return 1; } }); // then expect(self.raty('score')).toEqual(1); }); context('with negative number', function() { it ('gets none score', function() { // given var self = $('#element'); // when self.raty({ score: -1 }); // then expect(self.children('input').val()).toEqual(''); }); }); context('with :readOnly', function() { it ('becomes readOnly too', function() { // given var self = $('#element'); // when self.raty({ readOnly: true }); // then expect(self.children('input')).toHaveAttr('readonly', 'readonly'); }); }); }); describe('#scoreName', function() { it ('changes the score field name', function() { // given var self = $('#element'); // when self.raty({ scoreName: 'entity.score' }); // then expect(self.children('input')).toHaveAttr('name', 'entity.score'); }); }); it ('accepts callback', function() { // given var self = $('#element'); // when self.raty({ scoreName: function() { return 'custom'; } }); // then expect(self.data('settings').scoreName).toEqual('custom'); }); describe('#readOnly', function() { it ('Applies "Not rated yet!" on stars', function() { // given var self = $('#element'); // when self.raty({ readOnly: true }); // then expect(self.children('img')).toHaveAttr('title', 'Not rated yet!'); }); it ('removes the pointer cursor', function() { // given var self = $('#element'); // when self.raty({ readOnly: true }); // then expect(self).not.toHaveCss({ cursor: 'pointer' }); expect(self).not.toHaveCss({ cursor: 'default' }); }); it ('accepts callback', function() { // given var self = $('#element'); // when self.raty({ readOnly: function() { return true; } }); // then expect(self.data('settings').readOnly).toEqual(true); }); it ('avoids trigger mouseover', function() { // given var self = $('#element').raty({ readOnly: true }), imgs = self.children('img'); // when imgs.eq(1).mouseover(); // then expect(imgs).toHaveAttr('src', 'star-off.png'); }); it ('avoids trigger click', function() { // given var self = $('#element').raty({ readOnly: true }), imgs = self.children('img'); // when imgs.eq(1).mouseover().click().mouseleave(); // then expect(imgs).toHaveAttr('src', 'star-off.png'); expect(self.children('input').val()).toEqual(''); }); it ('avoids trigger mouseleave', function() { // given var self = $('#element').raty({ readOnly: true, mouseout: function() { $(this).data('mouseleave', true); } }), imgs = self.children('img'); imgs.eq(1).mouseover(); // when self.mouseleave(); // then expect(self.data('mouseleave')).toBeFalsy(); }); context('with :score', function() { context('as integer', function() { it ('applies the score title on stars', function() { // given var self = $('#element'); // when self.raty({ readOnly: true, score: 3 }); // then expect(self.children('img')).toHaveAttr('title', 'regular'); }); }); context('as float', function() { it ('applies the integer score title on stars', function() { // given var self = $('#element'); // when self.raty({ readOnly: true, score: 3.1 }); // then expect(self.children('img')).toHaveAttr('title', 'regular'); }); }); }); context('with :cancel', function() { it ('hides the button', function() { // given var self = $('#element'); // when self.raty({ cancel: true, readOnly: true, path: '../lib/img' }); // then expect(self.children('.raty-cancel')).toBeHidden(); }); }); }); describe('#hints', function() { it ('changes the hints', function() { // given var self = $('#element'); // when self.raty({ hints: ['1', '/', 'c', '-', '#'] }); // then var imgs = self.children('img'); expect(imgs.eq(0)).toHaveAttr('title', 1); expect(imgs.eq(1)).toHaveAttr('title', '/'); expect(imgs.eq(2)).toHaveAttr('title', 'c'); expect(imgs.eq(3)).toHaveAttr('title', '-'); expect(imgs.eq(4)).toHaveAttr('title', '#'); }); it ('receives the number of the star when is undefined', function() { // given var self = $('#element'); // when self.raty({ hints: [undefined, 'a', 'b', 'c', 'd'] }); // then var imgs = self.children('img'); expect(imgs.eq(0)).toHaveAttr('title', 'bad'); expect(imgs.eq(1)).toHaveAttr('title', 'a'); expect(imgs.eq(2)).toHaveAttr('title', 'b'); expect(imgs.eq(3)).toHaveAttr('title', 'c'); expect(imgs.eq(4)).toHaveAttr('title', 'd'); }); it ('receives empty when is empty string', function() { // given var self = $('#element'); // when self.raty({ hints: ['', 'a', 'b', 'c', 'd'] }); // then var imgs = self.children('img'); expect(imgs.eq(0)).toHaveAttr('title', ''); expect(imgs.eq(1)).toHaveAttr('title', 'a'); expect(imgs.eq(2)).toHaveAttr('title', 'b'); expect(imgs.eq(3)).toHaveAttr('title', 'c'); expect(imgs.eq(4)).toHaveAttr('title', 'd'); }); it ('receives the number of the star when is null', function() { // given var self = $('#element'); // when self.raty({ hints: [null, 'a', 'b', 'c', 'd'] }); // then var imgs = self.children('img'); expect(imgs.eq(0)).toHaveAttr('title', 1); expect(imgs.eq(1)).toHaveAttr('title', 'a'); expect(imgs.eq(2)).toHaveAttr('title', 'b'); expect(imgs.eq(3)).toHaveAttr('title', 'c'); expect(imgs.eq(4)).toHaveAttr('title', 'd'); }); context('whe has less hint than stars', function() { it ('receives the default hint index', function() { // given var self = $('#element'); // when self.raty({ hints: ['1', '2', '3', '4'] }); // then var imgs = self.children('img'); expect(imgs.eq(0)).toHaveAttr('title', 1); expect(imgs.eq(1)).toHaveAttr('title', 2); expect(imgs.eq(2)).toHaveAttr('title', 3); expect(imgs.eq(3)).toHaveAttr('title', 4); expect(imgs.eq(4)).toHaveAttr('title', 'gorgeous'); }); }); context('whe has more stars than hints', function() { it ('sets star number', function() { // given var self = $('#element'); // when self.raty({ number: 6, hints: ['a', 'b', 'c', 'd', 'e'] }); // then var imgs = self.children('img'); expect(imgs.eq(0)).toHaveAttr('title', 'a'); expect(imgs.eq(1)).toHaveAttr('title', 'b'); expect(imgs.eq(2)).toHaveAttr('title', 'c'); expect(imgs.eq(3)).toHaveAttr('title', 'd'); expect(imgs.eq(4)).toHaveAttr('title', 'e'); expect(imgs.eq(5)).toHaveAttr('title', 6); }); }); }); describe('#mouseover', function() { it ('receives the score as int', function() { // given var self = $('#element').raty({ mouseover: function(score) { $(this).data('score', score); } }); // when self.children('img:first').mouseover(); // then expect(self.data('score')).toEqual(1); }); it ('receives the event', function() { // given var self = $('#element').raty({ mouseover: function(score, evt) { $(this).data('evt', evt); } }); // when self.children('img:first').mouseover(); // then expect(self.data('evt').type).toEqual('mouseover'); }); context('with :cancel', function() { it ('receives null as score', function() { // given var self = $('#element').raty({ cancel : true, mouseover : function(score) { self.data('null', score); } }); // when self.children('.raty-cancel').mouseover(); // then expect(self.data('null')).toBeNull(); }); }); }); describe('#mouseout', function() { it ('receives the score as int', function() { // given var self = $('#element').raty({ mouseout: function(score) { $(this).data('score', score); } }); // when self.children('img:first').mouseover().click().mouseout(); // then expect(self.data('score')).toEqual(1); }); it ('receives the event', function() { // given var self = $('#element').raty({ mouseout: function(score, evt) { $(this).data('evt', evt); } }); // when self.children('img:first').mouseover().click().mouseout(); // then expect(self.data('evt').type).toEqual('mouseout'); }); context('without score setted', function() { it ('pass undefined on callback', function() { // given var self = $('#element').raty({ cancel : true, mouseout: function(score) { self.data('undefined', score === undefined); } }); // when self.children('img:first').mouseenter().mouseleave(); // then expect(self.data('undefined')).toBeTruthy(); }); }); context('with :score rated', function() { it ('pass the score on callback', function() { // given var self = $('#element').raty({ score : 1, mouseout: function(score) { self.data('score', score); } }); // when self.children('img:first').mouseenter().mouseleave(); // then expect(self.data('score')).toEqual(1); }); }); context('with :cancel', function() { it ('receives the event', function() { // given var self = $('#element').raty({ cancel : true, mouseout: function(score, evt) { $(this).data('evt', evt); } }); // when self.children('.raty-cancel').mouseover().click().mouseout(); // then expect(self.data('evt').type).toEqual('mouseout'); }); context('without score setted', function() { it ('pass undefined on callback', function() { // given var self = $('#element').raty({ mouseout: function(score) { self.data('undefined', score === undefined); }, cancel : true }); // when self.children('.raty-cancel').mouseenter().mouseleave(); // then expect(self.data('undefined')).toBeTruthy(); }); }); context('with :score rated', function() { it ('pass the score on callback', function() { // given var self = $('#element').raty({ mouseout: function(score) { self.data('score', score); }, cancel : true, score : 1 }); // when self.children('.raty-cancel').mouseenter().mouseleave(); // then expect(self.data('score')).toEqual(1); }); }); }); }); describe('#number', function() { it ('changes the number of stars', function() { // given var self = $('#element'); // when self.raty({ number: 1 }); // then expect(self.children('img').length).toEqual(1); }); it ('accepts number as string', function() { // given var self = $('#element'); // when self.raty({ number: '10' }); // then expect(self.children('img').length).toEqual(10); }); it ('accepts callback', function() { // given var self = $('#element'); // when self.raty({ number: function() { return 1; } }); // then expect(self.children('img').length).toEqual(1); }); }); describe('#path', function() { context('without last slash', function() { it ('receives the slash', function() { // given var self = $('#element'); // when self.raty({ path: 'path' }); // then expect(self[0].opt.path).toEqual('path/'); }); }); context('with last slash', function() { it ('keeps it', function() { // given var self = $('#element'); // when self.raty({ path: 'path/' }); // then expect(self[0].opt.path).toEqual('path/'); }); }); it ('changes the path', function() { // given var self = $('#element'); // when self.raty({ path: 'path' }); // then expect(self.children('img')).toHaveAttr('src', 'path/star-off.png'); }); context('without path', function() { it ('sets receives empty', function() { // given var self = $('#element'); // when self.raty({ path: null }); // then expect(self.children('img')).toHaveAttr('src', 'star-off.png'); }); }); context('with :cancel', function() { it ('changes the path', function() { // given var self = $('#element'); // when self.raty({ cancel: true, path: 'path' }) // then expect(self.children('.raty-cancel')).toHaveAttr('src', 'path/cancel-off.png'); }); }); context('with :iconRange', function() { it ('changes the path', function() { // given var self = $('#element'); // when self.raty({ path : 'path', iconRange: [{ range: 5 }] }); // then expect(self.children('img')).toHaveAttr('src', 'path/star-off.png'); }); }); }); describe('#cancelOff', function() { it ('changes the icon', function() { // given var self = $('#element'); // when self.raty({ cancel: true, cancelOff: 'off.png' }); // then expect(self.children('.raty-cancel')).toHaveAttr('src', 'off.png'); }); }); describe('#cancelOn', function() { it ('changes the icon', function() { // given var self = $('#element').raty({ cancel: true, cancelOn: 'icon.png' }); // when var cancel = self.children('.raty-cancel').mouseover(); // then expect(cancel).toHaveAttr('src', 'icon.png'); }); }); describe('#cancelHint', function() { it ('changes the cancel hint', function() { // given var self = $('#element'); // when self.raty({ cancel: true, cancelHint: 'hint' }); // then expect(self.children('.raty-cancel')).toHaveAttr('title', 'hint'); }); }); describe('#cancelPlace', function() { it ('changes the place off cancel button', function() { // given var self = $('#element'); // when self.raty({ cancel: true, cancelPlace: 'right' }); // then var cancel = self.children('img:last'); expect(cancel).toHaveClass('raty-cancel'); expect(cancel).toHaveAttr('title', 'Cancel this rating!'); expect(cancel).toHaveAttr('alt', 'x'); expect(cancel).toHaveAttr('src', 'cancel-off.png'); }); }); describe('#cancel', function() { it ('creates the element', function() { // given var self = $('#element'); // when self.raty({ cancel: true }); // then var cancel = self.children('.raty-cancel'); expect(cancel).toHaveClass('raty-cancel'); expect(cancel).toHaveAttr('title', 'Cancel this rating!'); expect(cancel).toHaveAttr('alt', 'x'); expect(cancel).toHaveAttr('src', 'cancel-off.png'); }); context('on mouseover', function() { it ('turns on', function() { // given var self = $('#element').raty({ cancel: true }); // when var cancel = self.children('.raty-cancel').mouseover(); // then expect(cancel).toHaveAttr('src', 'cancel-on.png'); }); context('with :score', function() { it ('turns off the stars', function() { // given var self = $('#element').raty({ score: 3, cancel: true }), imgs = self.children('img:not(.raty-cancel)'); // when self.children('.raty-cancel').mouseover(); // then expect(imgs).toHaveAttr('src', 'star-off.png'); }); }); }); context('when :mouseout', function() { it ('turns on', function() { // given var self = $('#element').raty({ cancel: true }); // when var cancel = self.children('.raty-cancel').mouseover().mouseout(); // then expect(cancel).toHaveAttr('src', 'cancel-off.png'); }); context('with :score', function() { it ('turns the star on again', function() { // given var self = $('#element').raty({ score: 4, cancel: true }), imgs = self.children('img:not(.raty-cancel)'); // when self.children('.raty-cancel').mouseover().mouseout(); // then expect(imgs.eq(0)).toHaveAttr('src', 'star-on.png'); expect(imgs.eq(1)).toHaveAttr('src', 'star-on.png'); expect(imgs.eq(2)).toHaveAttr('src', 'star-on.png'); expect(imgs.eq(3)).toHaveAttr('src', 'star-on.png'); expect(imgs.eq(4)).toHaveAttr('src', 'star-off.png'); }); }); }); context('on click', function() { it ('cancel the rating', function() { // given var self = $('#element').raty({ cancel: true, score: 1 }); // when self.children('.raty-cancel').click().mouseout(); // then var stars = self.children('img:not(.raty-cancel)'); expect(stars).toHaveAttr('src', 'star-off.png'); expect(self.children('input').val()).toEqual(''); }); }); context('when starts :readOnly', function() { it ('starts hidden', function() { // given var self = $('#element').raty({ cancel: true, readOnly: true, path: '../img' }); // when self.raty('readOnly', true); // then expect(self.children('.raty-cancel')).toBeHidden(); }); context('on click', function() { it ('does not cancel the rating', function() { // given var self = $('#element').raty({ cancel: true, readOnly: true, score: 5 }); // when self.children('.raty-cancel').click().mouseout(); // then var stars = self.children('img:not(.raty-cancel)'); expect(stars).toHaveAttr('src', 'star-on.png'); expect(self.children('input').val()).toEqual('5'); }); }); }); context('when become :readOnly', function() { it ('becomes hidden', function() { // given var self = $('#element').raty({ cancel: true, path: '../img' }); // when self.raty('readOnly', true); // then expect(self.children('.raty-cancel')).toBeHidden(); }); }); }); describe('#targetType', function() { beforeEach(function() { buildDivTarget(); }); context('with missing target', function() { it ('throws error', function() { // given var self = $('#element'); // when var lambda = function() { self.raty({ target: 'missing' }); }; // then expect(lambda).toThrow(new Error('Target selector invalid or missing!')); }); }); context('as hint', function() { it ('receives the hint', function() { // given var self = $('#element').raty({ target: '#hint', targetType: 'hint' }); // when self.children('img:first').mouseover(); // then expect($('#hint')).toHaveHtml('bad'); }); context('with :cancel', function() { it ('receives the :cancelHint', function() { // given var self = $('#element').raty({ cancel: true, target: '#hint', targetType: 'hint' }); // when self.children('.raty-cancel').mouseover(); // then expect($('#hint')).toHaveHtml('Cancel this rating!'); }); }); }); context('as score', function() { it ('receives the score', function() { // given var self = $('#element').raty({ target: '#hint', targetType: 'score' }); // when self.children('img:first').mouseover(); // then expect($('#hint')).toHaveHtml(1); }); context('with :cancel', function() { it ('receives the :cancelHint', function() { // given var self = $('#element').raty({ cancel: true, target: '#hint', targetType: 'score' }); // when self.children('.raty-cancel').mouseover(); // then expect($('#hint')).toHaveHtml('Cancel this rating!'); }); }); }); }); describe('#targetText', function() { beforeEach(function() { buildDivTarget(); }); it ('set target with none value', function() { // given var self = $('#element'); // when self.raty({ target: '#hint', targetText: 'none' }); // then expect($('#hint')).toHaveHtml('none'); }); }); describe('#targetFormat', function() { context('with :target', function() { beforeEach(function() { buildDivTarget(); }); it ('stars empty', function() { // given var self = $('#element'); // when self.raty({ target: '#hint', targetFormat: 'score: {score}' }); // then expect($('#hint')).toBeEmpty(); }); context('with missing score key', function() { it ('throws error', function() { // given var self = $('#element'); // when var lambda = function() { self.raty({ target: '#hint', targetFormat: '' }); }; // then expect(lambda).toThrow(new Error('Template "{score}" missing!')); }); }); context('on mouseover', function() { it ('set target with format on mouseover', function() { // given var self = $('#element').raty({ target: '#hint', targetFormat: 'score: {score}' }); // when self.children('img:first').mouseover(); // then expect($('#hint')).toHaveHtml('score: bad'); }); }); context('on mouseout', function() { it ('clears the target', function() { // given var self = $('#element').raty({ target : '#hint', targetFormat: 'score: {score}' }); // when self.children('img:first').mouseover().mouseout(); // then expect($('#hint')).toBeEmpty(); }); context('with :targetKeep', function() { context('without score', function() { it ('clears the target', function() { // given var self = $('#element').raty({ target : '#hint', targetFormat: 'score: {score}', targetKeep : true }); // when self.children('img:first').mouseover().mouseleave(); // then expect($('#hint')).toBeEmpty(); }); }); context('with score', function() { it ('keeps the template', function() { // given var self = $('#element').raty({ score : 1, target : '#hint', targetFormat: 'score: {score}', targetKeep : true }); // when self.children('img:first').mouseover().mouseleave(); // then expect($('#hint')).toHaveHtml('score: bad'); }); }); }); }); }); }); describe('#precision', function() { beforeEach(function() { buildDivTarget(); }); it ('enables the :half options', function() { // given var self = $('#element'); // when self.raty({ precision: true }); // then expect(self.data('settings').half).toBeTruthy(); }); it ('changes the :targetType to score', function() { // given var self = $('#element'); // when self.raty({ precision: true }); // then expect(self.data('settings').targetType).toEqual('score'); }); context('with :target', function() { context('with :targetKeep', function() { context('with :score', function() { it ('sets the float with one fractional number', function() { // given var self = $('#element'); // when self.raty({ precision : true, score : 1.23, target : '#hint', targetKeep: true, targetType: 'score' }); // then expect($('#hint')).toHaveHtml('1.2'); }); }); }); }); }); describe('#target', function() { context('on mouseover', function() { context('as div', function() { beforeEach(function() { buildDivTarget(); }); it ('sets the hint', function() { // given var self = $('#element').raty({ target: '#hint' }); // when self.children('img:first').mouseover(); // then expect($('#hint')).toHaveHtml('bad'); }); }); context('as text field', function() { beforeEach(function() { buildTextTarget(); }); it ('sets the hint', function() { // given var self = $('#element').raty({ target: '#hint' }); // when self.children('img:first').mouseover(); // then expect($('#hint')).toHaveValue('bad'); }); }); context('as textarea', function() { beforeEach(function() { buildTextareaTarget(); }); it ('sets the hint', function() { // given var self = $('#element').raty({ target: '#hint' }); // when self.children('img:first').mouseover(); // then expect($('#hint')).toHaveValue('bad'); }); }); context('as combobox', function() { beforeEach(function() { buildComboboxTarget(); }); it ('sets the hint', function() { // given var self = $('#element').raty({ target: '#hint' }); // when self.children('img:first').mouseover(); // then expect($('#hint')).toHaveValue('bad'); }); }); }); context('on mouseout', function() { context('as div', function() { beforeEach(function() { buildDivTarget(); }); it ('gets clear', function() { // given var self = $('#element').raty({ target: '#hint' }); // when self.children('img:first').mouseover().click().mouseleave(); // then expect($('#hint')).toBeEmpty(); }); }); context('as textarea', function() { beforeEach(function() { buildTextareaTarget(); }); it ('gets clear', function() { // given var self = $('#element').raty({ target: '#hint' }); // when self.children('img:first').click().mouseover().mouseleave(); // then expect($('#hint')).toHaveValue(''); }); }); context('as text field', function() { beforeEach(function() { buildTextTarget(); }); it ('gets clear', function() { // given var self = $('#element').raty({ target: '#hint' }); // when self.children('img:first').click().mouseover().mouseleave(); // then expect($('#hint')).toHaveValue(''); }); }); context('as combobox', function() { beforeEach(function() { buildComboboxTarget(); }); it ('gets clear', function() { // given var self = $('#element').raty({ target: '#hint' }); // when self.children('img:first').click().mouseover().mouseleave(); // then expect($('#hint')).toHaveValue(''); }); }); }); }); describe('#size', function() { it ('calculate the right icon size', function() { // given var self = $('#element'), size = 24, stars = 5, space = 4; // when self.raty({ size: size }); // then expect(self.width()).toEqual((stars * size) + (stars * space)); }); context('with :cancel', function() { it ('addes the cancel and space witdh', function() { // given var self = $('#element'), size = 24, stars = 5, cancel = size, space = 4; // when self.raty({ cancel: true, size: size }); // then expect(self.width()).toEqual(cancel + space + (stars * size) + (stars * space)); }); }); }); describe('#space', function() { context('when off', function() { it ('takes off the space', function() { // given var self = $('#element'); size = 16, stars = 5; // when self.raty({ space: false }); // then expect(self.width()).toEqual(size * stars); }); context('with :cancel', function() { it ('takes off the space', function() { // given var self = $('#element'); size = 16, stars = 5, cancel = size; // when self.raty({ cancel: true, space: false }); // then expect(self.width()).toEqual(cancel + (size * stars)); }); }); }); }); describe('#single', function() { context('on mouseover', function() { it ('turns on just one icon', function() { // given var self = $('#element').raty({ single: true }), imgs = self.children('img'); // when imgs.eq(2).mouseover(); // then expect(imgs.eq(0)).toHaveAttr('src', 'star-off.png'); expect(imgs.eq(1)).toHaveAttr('src', 'star-off.png'); expect(imgs.eq(2)).toHaveAttr('src', 'star-on.png'); expect(imgs.eq(3)).toHaveAttr('src', 'star-off.png'); expect(imgs.eq(4)).toHaveAttr('src', 'star-off.png'); }); context('with :iconRange', function() { it ('shows just on icon', function() { // given var self = $('#element').raty({ single : true, iconRange : [ { range: 2, on: 'a.png', off: 'a-off.png' }, { range: 3, on: 'b.png', off: 'b-off.png' }, { range: 4, on: 'c.png', off: 'c-off.png' }, { range: 5, on: 'd.png', off: 'd-off.png' } ] }), imgs = self.children('img'); // when imgs.eq(3).mouseover(); // then expect(imgs.eq(0)).toHaveAttr('src', 'a-off.png'); expect(imgs.eq(1)).toHaveAttr('src', 'a-off.png'); expect(imgs.eq(2)).toHaveAttr('src', 'b-off.png'); expect(imgs.eq(3)).toHaveAttr('src', 'c.png'); expect(imgs.eq(4)).toHaveAttr('src', 'd-off.png'); }); }); }); context('on click', function() { context('on mouseout', function() { it ('keeps the score', function() { // given var self = $('#element').raty({ single: true }) imgs = self.children('img'); // when imgs.eq(2).mouseover().click().mouseleave(); // then expect(imgs.eq(0)).toHaveAttr('src', 'star-off.png'); expect(imgs.eq(1)).toHaveAttr('src', 'star-off.png'); expect(imgs.eq(2)).toHaveAttr('src', 'star-on.png'); expect(imgs.eq(3)).toHaveAttr('src', 'star-off.png'); expect(imgs.eq(4)).toHaveAttr('src', 'star-off.png'); }); context('and :iconRange', function() { it ('keeps the score', function() { // given var self = $('#element').raty({ single : true, iconRange : [ { range: 2, on: 'a.png', off: 'a-off.png' }, { range: 3, on: 'b.png', off: 'b-off.png' }, { range: 4, on: 'c.png', off: 'c-off.png' }, { range: 5, on: 'd.png', off: 'd-off.png' } ] }), imgs = self.children('img'); // when imgs.eq(3).mouseover().click().mouseleave(); // then expect(imgs.eq(0)).toHaveAttr('src', 'a-off.png'); expect(imgs.eq(1)).toHaveAttr('src', 'a-off.png'); expect(imgs.eq(2)).toHaveAttr('src', 'b-off.png'); expect(imgs.eq(3)).toHaveAttr('src', 'c.png'); expect(imgs.eq(4)).toHaveAttr('src', 'd-off.png'); }); }); }); }); }); describe('#width', function() { it ('set custom width', function() { // given var self = $('#element'); // when self.raty({ width: 200 }); // then expect(self.width()).toEqual(200); }); describe('when it is false', function() { it ('does not apply the style', function() { // given var self = $('#element'); // when self.raty({ width: false }); // then expect(self).not.toHaveCss({ width: '100px' }); }); }); describe('when :readOnly', function() { it ('set custom width when readOnly', function() { // given var self = $('#element'); // when self.raty({ readOnly: true, width: 200 }); // then expect(self.width()).toEqual(200); }); }); }); describe('#half', function() { context('as false', function() { context('#halfShow', function() { context('as false', function() { it ('rounds down while less the full limit', function() { // given var self = $('#element'); // when self.raty({ half : false, halfShow: false, round : { down: .25, full: .6, up: .76 }, score : .5 // score.5 < full.6 === 0 }); var imgs = self.children('img'); // then expect(imgs.eq(0)).toHaveAttr('src', 'star-off.png'); expect(imgs.eq(1)).toHaveAttr('src', 'star-off.png'); }); it ('rounds full when equal the full limit', function() { // given var self = $('#element'); // when self.raty({ half : false, halfShow: false, round : { down: .25, full: .6, up: .76 }, score : .6 // score.6 == full.6 === 1 }); var imgs = self.children('img'); // then expect(imgs.eq(0)).toHaveAttr('src', 'star-on.png'); }); }); }); }); context('as true', function() { context('#halfShow', function() { context('as false', function() { it ('ignores round down while less down limit', function() { // given var self = $('#element'); // when self.raty({ half : true, halfShow: false, round : { down: .25, full: .6, up: .76 }, score : .24 // score.24 < down.25 === 0 }); // then var imgs = self.children('img'); expect(imgs.eq(0)).toHaveAttr('src', 'star-off.png'); expect(self.children('input').val()).toEqual('0.24'); }); it ('ignores half while greater then down limit', function() { // given var self = $('#element'); // when self.raty({ half : true, halfShow: false, round : { down: .25, full: .6, up: .76 }, score : .26 // score.26 > down.25 and score.6 < up.76 === .5 }); // then var imgs = self.children('img'); expect(imgs.eq(0)).toHaveAttr('src', 'star-off.png'); expect(self.children('input').val()).toEqual('0.26'); }); it ('ignores half while equal full limit, ignoring it', function() { // given var self = $('#element'); // when self.raty({ half : true, halfShow: false, round : { down: .25, full: .6, up: .76 }, score : .6 // score.6 > down.25 and score.6 < up.76 === .5 }); // then var imgs = self.children('img'); expect(imgs.eq(0)).toHaveAttr('src', 'star-on.png'); expect(self.children('input').val()).toEqual('0.6'); }); it ('ignores half while greater than down limit and less than up limit', function() { // given var self = $('#element'); // when self.raty({ half : true, halfShow: false, round : { down: .25, full: .6, up: .76 }, score : .75 // score.75 > down.25 and score.75 < up.76 === .5 }); // then var imgs = self.children('img'); expect(imgs.eq(0)).toHaveAttr('src', 'star-on.png'); expect(self.children('input').val()).toEqual('0.75'); }); it ('ignores full while equal or greater than up limit', function() { // given var self = $('#element'); // when self.raty({ half : true, halfShow: false, round : { down: .25, full: .6, up: .76 }, score : .76 // score.76 == up.76 === 1 }); // then var imgs = self.children('img'); expect(imgs.eq(0)).toHaveAttr('src', 'star-on.png'); }); }); context('as true', function() { it ('rounds down while less down limit', function() { // given var self = $('#element'); // when self.raty({ half : true, halfShow: true, round : { down: .25, full: .6, up: .76 }, score : .24 // score.24 < down.25 === 0 }); // then var imgs = self.children('img'); expect(imgs.eq(0)).toHaveAttr('src', 'star-off.png'); }); it ('receives half while greater then down limit', function() { // given var self = $('#element'); // when self.raty({ half : true, halfShow: true, round : { down: .25, full: .6, up: .76 }, score : .26 // score.26 > down.25 and score.6 < up.76 === .5 }); // then var imgs = self.children('img'); expect(imgs.eq(0)).toHaveAttr('src', 'star-half.png'); }); it ('receives half while equal full limit, ignoring it', function() { // given var self = $('#element'); // when self.raty({ half : true, halfShow: true, round : { down: .25, full: .6, up: .76 }, score : .6 // score.6 > down.25 and score.6 < up.76 === .5 }); // then var imgs = self.children('img'); expect(imgs.eq(0)).toHaveAttr('src', 'star-half.png'); }); it ('receives half while greater than down limit and less than up limit', function() { // given var self = $('#element'); // when self.raty({ half : true, halfShow: true, round : { down: .25, full: .6, up: .76 }, score : .75 // score.75 > down.25 and score.75 < up.76 === .5 }); // then var imgs = self.children('img'); expect(imgs.eq(0)).toHaveAttr('src', 'star-half.png'); }); it ('receives full while equal or greater than up limit', function() { // given var self = $('#element'); // when self.raty({ half : true, halfShow: true, round : { down: .25, full: .6, up: .76 }, score : .76 // score.76 == up.76 === 1 }); // then var imgs = self.children('img'); expect(imgs.eq(0)).toHaveAttr('src', 'star-on.png'); }); }); }); context('with :target', function() { beforeEach(function() { buildDivTarget(); }); context('and :precision', function() { context('and :targetType as score', function() { context('and :targetKeep', function() { context('and :targetType as score', function() { it ('set .5 increment value target with half option and no precision', function() { // given var self = $('#element'); // when self.raty({ half : true, precision : false, score : 1.5, target : '#hint', targetKeep: true, targetType: 'score' }); // then expect($('#hint')).toHaveHtml('1.5'); }); }); }); }); }); }); }); }); }); describe('class bind', function() { beforeEach(function() { $('body').append('<div class="element"></div><div class="element"></div>'); }); afterEach(function() { $('.element').remove(); }); it ('is chainable', function() { // given var self = $('.element'); // when var refs = self.raty(); // then expect(refs.eq(0)).toBe(self.eq(0)); expect(refs.eq(1)).toBe(self.eq(1)); }); it ('creates the default markup', function() { // given var self = $('.element'); // when self.raty(); // then var imgs = self.eq(0).children('img'), score = self.eq(0).children('input'); expect(imgs.eq(0)).toHaveAttr('title', 'bad'); expect(imgs.eq(1)).toHaveAttr('title', 'poor'); expect(imgs.eq(2)).toHaveAttr('title', 'regular'); expect(imgs.eq(3)).toHaveAttr('title', 'good'); expect(imgs.eq(4)).toHaveAttr('title', 'gorgeous'); expect(imgs).toHaveAttr('src', 'star-off.png'); expect(score).toHaveAttr('type', 'hidden'); expect(score).toHaveAttr('name', 'score'); expect(score.val()).toEqual(''); imgs = self.eq(1).children('img'); score = self.eq(0).children('input'); expect(imgs.eq(0)).toHaveAttr('title', 'bad'); expect(imgs.eq(1)).toHaveAttr('title', 'poor'); expect(imgs.eq(2)).toHaveAttr('title', 'regular'); expect(imgs.eq(3)).toHaveAttr('title', 'good'); expect(imgs.eq(4)).toHaveAttr('title', 'gorgeous'); expect(imgs).toHaveAttr('src', 'star-off.png'); expect(score).toHaveAttr('type', 'hidden'); expect(score).toHaveAttr('name', 'score'); expect(score.val()).toEqual(''); }); }); describe('functions', function() { describe('GET #score', function() { it ('accepts number as string', function() { // given var self = $('#element'); // when self.raty({ score: '1' }); // then expect(self.children('input')).toHaveValue(1); }); it ('accepts float string', function() { // given var self = $('#element'); // when self.raty({ score: '1.5' }); // then expect(self.children('input')).toHaveValue(1.5); }); context('with integer score', function() { it ('gets as int', function() { // given var self = $('#element').raty({ score: 1 }); // when var score = self.raty('score'); // then expect(score).toEqual(1); }); }); context('with float score', function() { it ('gets as float', function() { // given var self = $('#element').raty({ score: 1.5 }); // when var score = self.raty('score'); // then expect(score).toEqual(1.5); }); }); context('with score zero', function() { it ('gets null to emulate cancel', function() { // given var self = $('#element').raty({ score: 0 }); // when var score = self.raty('score'); // then expect(score).toEqual(null); }); }); context('with score greater than :numberMax', function() { it ('gets the max', function() { // given var self = $('#element').raty({ number: 50, score: 50 }); // when var score = self.raty('score'); // then expect(score).toEqual(self.data('settings').numberMax); }); }); }); describe('SET #score', function() { it ('sets the score', function() { // given var self = $('#element'); // when self.raty({ score: 1 }); // then expect(self.raty('score')).toEqual(1); }); describe('with :click', function() { it ('calls the click callback', function() { // given var self = $('#element').raty({ click: function(score) { $(this).data('score', score); } }); // when self.raty('score', 5); // then expect(self.children('img')).toHaveAttr('src', 'star-on.png'); }); }); describe('without :click', function() { it ('does not throw exception', function() { // given var self = $('#element').raty(); // when var lambda = function() { self.raty('score', 1); }; // then expect(lambda).not.toThrow(new Error('You must add the "click: function(score, evt) { }" callback.')); }); }); describe('with :readOnly', function() { it ('does not set the score', function() { // given var self = $('#element').raty({ readOnly: true }); // when self.raty('score', 5); // then expect(self.children('img')).toHaveAttr('src', 'star-off.png'); }); }); }); describe('#set', function() { it ('is chainable', function() { // given var self = $('#element').raty(); // when var ref = self.raty('set', { number: 1 }); // then expect(ref).toBe(self); }); it ('changes the declared options', function() { // given var self = $('#element').raty(); // when var ref = self.raty('set', { scoreName: 'change-just-it' }); // then expect(ref.children('input')).toHaveAttr('name', 'change-just-it'); }); it ('does not change other none declared options', function() { // given var self = $('#element').raty({ number: 6 }); // when var ref = self.raty('set', { scoreName: 'change-just-it' }); // then expect(ref.children('img').length).toEqual(6); }); context('with external bind on wrapper', function() { it ('keeps it', function() { // given var self = $('#element').on('click', function() { $(this).data('externalClick', true); }).raty(); // when self.raty('set', {}).click(); // then expect(self.data('externalClick')).toBeTruthy(); }); }); context('when :readOnly by function', function() { it ('is removes the readonly data info', function() { // given var self = $('#element').raty().raty('readOnly', true); // when var ref = self.raty('set', { readOnly: false }); // then expect(self).not.toHaveData('readonly'); }); }); }); describe('#readOnly', function() { context('changes to true', function() { it ('sets score as readonly', function() { // given var self = $('#element').raty(); // when self.raty('readOnly', true); // then expect(self.children('input')).toHaveAttr('readonly', 'readonly'); }); it ('removes the pointer cursor', function() { // given var self = $('#element').raty(); // when self.raty('readOnly', true); // then expect(self).not.toHaveCss({ cursor: 'pointer' }); expect(self).not.toHaveCss({ cursor: 'default' }); }); it ('Applies "Not rated yet!" on stars', function() { // given var self = $('#element').raty(); // when self.raty('readOnly', true); // then expect(self.children('img')).toHaveAttr('title', 'Not rated yet!'); }); it ('avoids trigger mouseover', function() { // given var self = $('#element').raty(), imgs = self.children('img'); self.raty('readOnly', true); // when imgs.eq(0).mouseover(); // then expect(imgs).toHaveAttr('src', 'star-off.png'); }); it ('avoids trigger click', function() { // given var self = $('#element').raty(), imgs = self.children('img'); self.raty('readOnly', true); // when imgs.eq(0).mouseover().click().mouseleave(); // then expect(imgs).toHaveAttr('src', 'star-off.png'); expect(self.children('input').val()).toEqual(''); }); context('with :score', function() { it ('applies the score title on stars', function() { // given var self = $('#element').raty({ score: 1 }); // when self.raty('readOnly', true); // then expect(self.children('img')).toHaveAttr('title', 'bad'); }); }); context('with :cancel', function() { it ('hides the button', function() { // given var self = $('#element').raty({ cancel: true, path: '../lib/img' }); // when self.raty('readOnly', true); // then expect(self.children('.raty-cancel')).toBeHidden(); }); }); context('with external bind on wrapper', function() { it ('keeps it', function() { // given var self = $('#element').on('click', function() { $(this).data('externalClick', true); }).raty(); // when self.raty('readOnly', true).click(); // then expect(self.data('externalClick')).toBeTruthy(); }); }); context('with external bind on stars', function() { it ('keeps it', function() { // given var self = $('#element').raty(), star = self.children('img').first(); star.on('click', function() { self.data('externalClick', true); }); // when self.raty('readOnly', true); star.click(); // then expect(self.data('externalClick')).toBeTruthy(); }); }); }); context('changes to false', function() { it ('removes the :readOnly of the score', function() { // given var self = $('#element').raty(); // when self.raty('readOnly', false); // then expect(self.children('input')).not.toHaveAttr('readonly', 'readonly'); }); it ('applies the pointer cursor on wrapper', function() { // given var self = $('#element').raty(); // when self.raty('readOnly', false); // then expect(self).toHaveCss({ cursor: 'pointer' }); }); it ('Removes the "Not rated yet!" off the stars', function() { // given var self = $('#element').raty({ readOnly: true }), imgs = self.children('img'); // when self.raty('readOnly', false); // then expect(imgs.eq(0)).toHaveAttr('title', 'bad'); expect(imgs.eq(1)).toHaveAttr('title', 'poor'); expect(imgs.eq(2)).toHaveAttr('title', 'regular'); expect(imgs.eq(3)).toHaveAttr('title', 'good'); expect(imgs.eq(4)).toHaveAttr('title', 'gorgeous'); }); it ('triggers mouseover', function() { // given var self = $('#element').raty({ readOnly: true }), imgs = self.children('img'); self.raty('readOnly', false); // when imgs.eq(0).mouseover(); // then expect(imgs.eq(0)).toHaveAttr('src', 'star-on.png'); }); it ('triggers click', function() { // given var self = $('#element').raty({ readOnly: true }), imgs = self.children('img'); self.raty('readOnly', false); // when imgs.eq(0).mouseover().click().mouseleave(); // then expect(imgs).toHaveAttr('src', 'star-on.png'); expect(self.children('input')).toHaveValue('1'); }); context('with :score', function() { it ('removes the score title off the stars', function() { // given var self = $('#element').raty({ readOnly: true, score: 3 }); // when self.raty('readOnly', false); // then var imgs = self.children('img') expect(imgs.eq(0)).toHaveAttr('title', 'bad'); expect(imgs.eq(1)).toHaveAttr('title', 'poor'); expect(imgs.eq(2)).toHaveAttr('title', 'regular'); expect(imgs.eq(3)).toHaveAttr('title', 'good'); expect(imgs.eq(4)).toHaveAttr('title', 'gorgeous'); }); }); context('with :cancel', function() { it ('shows the button', function() { // given var self = $('#element').raty({ readOnly: true, cancel: true, path: '../lib/img' }); // when self.raty('readOnly', false); // then expect(self.children('.raty-cancel')).toBeVisible(); expect(self.children('.raty-cancel')).not.toHaveCss({ display: 'block' }); }); it ('rebinds the mouseover', function() { // given var self = $('#element').raty({ readOnly: true, cancel: true }), cancel = self.children('.raty-cancel'), imgs = self.children('img:not(.raty-cancel)'); // when self.raty('readOnly', false); cancel.mouseover(); // then expect(cancel).toHaveAttr('src', 'cancel-on.png'); expect(imgs).toHaveAttr('src', 'star-off.png'); }); it ('rebinds the click', function() { // given var self = $('#element').raty({ readOnly: true, cancel: true, score: 5 }), imgs = self.children('img:not(.raty-cancel)'); // when self.raty('readOnly', false); self.children('.raty-cancel').click().mouseout(); // then expect(imgs).toHaveAttr('src', 'star-off.png'); }); }); }); }); describe('#cancel', function() { describe('with :readOnly', function() { it ('does not cancel', function() { // given var self = $('#element').raty({ readOnly: true, score: 5 }); // when self.raty('cancel'); // then expect(self.children('img')).toHaveAttr('src', 'star-on.png'); }); }); context('without click trigger', function() { it ('cancel the rating', function() { // given var self = $('#element').raty({ score: 1, click: function() { $(this).data('clicked', true); } }); // when self.raty('cancel'); // then expect(self.children('img')).toHaveAttr('src', 'star-off.png'); expect(self.children('input').val()).toEqual(''); expect(self.data('clicked')).toBeFalsy(); }); }); context('with click trigger', function() { it ('cancel the rating', function() { // given var self = $('#element').raty({ score: 1, click: function() { $(this).data('clicked', true); } }); // when self.raty('cancel', true); // then expect(self.children('img')).toHaveAttr('src', 'star-off.png'); expect(self.children('input').val()).toEqual(''); expect(self.data('clicked')).toBeTruthy(); }); }); context('with :target', function() { beforeEach(function() { buildDivTarget(); }); context('and :targetKeep', function() { it ('sets the :targetText on target', function() { // given var hint = $('#hint').html('dirty'), self = $('#element').raty({ cancel : true, target : '#hint', targetKeep: true, targetText: 'targetText' }); // when self.raty('cancel'); // then expect(hint).toHaveHtml('targetText'); }); }); }); }); describe('#click', function() { it ('clicks on star', function() { // given var self = $('#element').raty({ click: function() { $(this).data('clicked', true); } }); // when self.raty('click', 1); // then expect(self.children('img')).toHaveAttr('src', 'star-on.png'); expect(self.data('clicked')).toBeTruthy(); }); it ('receives the score', function() { // given var self = $('#element').raty({ click: function(score) { $(this).data('score', score); } }); // when self.raty('click', 1); // then expect(self.data('score')).toEqual(1); }); it ('receives the event', function() { // given var self = $('#element').raty({ click: function(score, evt) { $(this).data('evt', evt); } }); // when self.raty('click', 1); // then expect(self.data('evt').type).toEqual('click'); }); describe('with :readOnly', function() { it ('does not set the score', function() { // given var self = $('#element').raty({ readOnly: true }); // when self.raty('click', 1); // then expect(self.children('img')).toHaveAttr('src', 'star-off.png'); }); }); context('without :click', function() { it ('throws error', function() { // given var self = $('#element').raty(); // when var lambda = function() { self.raty('click', 1); }; // then expect(lambda).toThrow(new Error('You must add the "click: function(score, evt) { }" callback.')); }); }); context('with :target', function() { beforeEach(function() { buildDivTarget(); }); context('and :targetKeep', function() { it ('sets the score on target', function() { // given var self = $('#element').raty({ target : '#hint', targetKeep: true, click : function() { } }); // when self.raty('click', 1); // then expect($('#hint')).toHaveHtml('bad'); }); }); }); }); describe('#reload', function() { it ('is chainable', function() { // given var self = $('#element').raty(); // when var ref = self.raty('reload'); // then expect(ref).toBe(self); }); it ('reloads with the same configuration', function() { // given var self = $('#element').raty({ number: 6 }); // when var ref = self.raty('reload'); // then expect(ref.children('img').length).toEqual(6); }); context('when :readOnly by function', function() { it ('is removes the readonly data info', function() { // given var self = $('#element').raty().raty('readOnly', true); // when var ref = self.raty('reload'); // then expect(self).not.toHaveData('readonly'); }); }); }); describe('#destroy', function() { it ('is chainable', function() { // given var self = $('#element').raty(); // when var ref = self.raty('destroy'); // then expect(ref).toBe(self); }); it ('clear the content', function() { // given var self = $('#element').raty(); // when self.raty('destroy'); // then expect(self).toBeEmpty(); }); it ('removes the trigger mouseleave', function() { // given var self = $('#element').raty({ mouseout: function() { console.log(this); $(this).data('mouseleave', true); } }); self.raty('destroy'); // when self.mouseleave(); // then expect(self.data('mouseleave')).toBeFalsy(); }); it ('resets the style attributes', function() { // given var self = $('#element').css({ cursor: 'help', width: 10 }).raty(); // when self.raty('destroy'); // then expect(self[0].style.cursor).toEqual('help'); expect(self[0].style.width).toEqual('10px'); }); }); }); });
cognitoedtech/assy
subdomain/offline/3rd_party/raty/spec/spec.js
JavaScript
apache-2.0
81,498
// Copyright 2014 The Oppia Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Unit tests for the editor prerequisites page. */ describe('Signup controller', function() { describe('SignupCtrl', function() { var scope, ctrl, $httpBackend, rootScope, mockAlertsService, urlParams; beforeEach(module('oppia', GLOBALS.TRANSLATOR_PROVIDER_FOR_TESTS)); beforeEach(inject(function(_$httpBackend_, $http, $rootScope, $controller) { $httpBackend = _$httpBackend_; $httpBackend.expectGET('/signuphandler/data').respond({ username: 'myUsername', has_agreed_to_latest_terms: false }); rootScope = $rootScope; mockAlertsService = { addWarning: function() {} }; spyOn(mockAlertsService, 'addWarning'); scope = { getUrlParams: function() { return { return_url: 'return_url' }; } }; ctrl = $controller('Signup', { $scope: scope, $http: $http, $rootScope: rootScope, alertsService: mockAlertsService }); })); it('should show warning if user has not agreed to terms', function() { scope.submitPrerequisitesForm(false, null); expect(mockAlertsService.addWarning).toHaveBeenCalledWith( 'I18N_SIGNUP_ERROR_MUST_AGREE_TO_TERMS'); }); it('should get data correctly from the server', function() { $httpBackend.flush(); expect(scope.username).toBe('myUsername'); expect(scope.hasAgreedToLatestTerms).toBe(false); }); it('should show a loading message until the data is retrieved', function() { expect(rootScope.loadingMessage).toBe('I18N_SIGNUP_LOADING'); $httpBackend.flush(); expect(rootScope.loadingMessage).toBeFalsy(); }); it('should show warning if terms are not agreed to', function() { scope.submitPrerequisitesForm(false, ''); expect(mockAlertsService.addWarning).toHaveBeenCalledWith( 'I18N_SIGNUP_ERROR_MUST_AGREE_TO_TERMS'); }); it('should show warning if no username provided', function() { scope.updateWarningText(''); expect(scope.warningI18nCode).toEqual('I18N_SIGNUP_ERROR_NO_USERNAME'); scope.submitPrerequisitesForm(false); expect(scope.warningI18nCode).toEqual('I18N_SIGNUP_ERROR_NO_USERNAME'); }); it('should show warning if username is too long', function() { scope.updateWarningText( 'abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba'); expect(scope.warningI18nCode).toEqual( 'I18N_SIGNUP_ERROR_USERNAME_MORE_50_CHARS'); }); it('should show warning if username has non-alphanumeric characters', function() { scope.updateWarningText('a-a'); expect(scope.warningI18nCode).toEqual( 'I18N_SIGNUP_ERROR_USERNAME_ONLY_ALPHANUM'); }); it('should show warning if username has \'admin\' in it', function() { scope.updateWarningText('administrator'); expect(scope.warningI18nCode).toEqual( 'I18N_SIGNUP_ERROR_USERNAME_WITH_ADMIN'); }); }); });
mit0110/oppia
core/templates/dev/head/profile/SignupSpec.js
JavaScript
apache-2.0
3,641
(function (enyo, scope) { /** * The {@link enyo.RepeaterChildSupport} [mixin]{@glossary mixin} contains methods and * properties that are automatically applied to all children of {@link enyo.DataRepeater} * to assist in selection support. (See {@link enyo.DataRepeater} for details on how to * use selection support.) This mixin also [adds]{@link enyo.Repeater#decorateEvent} the * `model`, `child` ([control]{@link enyo.Control} instance), and `index` properties to * all [events]{@glossary event} emitted from the repeater's children. * * @mixin enyo.RepeaterChildSupport * @public */ enyo.RepeaterChildSupport = { /* * @private */ name: 'RepeaterChildSupport', /** * Indicates whether the current child is selected in the [repeater]{@link enyo.DataRepeater}. * * @type {Boolean} * @default false * @public */ selected: false, /* * @method * @private */ selectedChanged: enyo.inherit(function (sup) { return function () { if (this.repeater.selection) { this.addRemoveClass(this.selectedClass || 'selected', this.selected); // for efficiency purposes, we now directly call this method as opposed to // forcing a synchronous event dispatch var idx = this.repeater.collection.indexOf(this.model); if (this.selected && !this.repeater.isSelected(this.model)) { this.repeater.select(idx); } else if (!this.selected && this.repeater.isSelected(this.model)) { this.repeater.deselect(idx); } } sup.apply(this, arguments); }; }), /* * @method * @private */ decorateEvent: enyo.inherit(function (sup) { return function (sender, event) { event.model = this.model; event.child = this; event.index = this.repeater.collection.indexOf(this.model); sup.apply(this, arguments); }; }), /* * @private */ _selectionHandler: function () { if (this.repeater.selection && !this.get('disabled')) { if (!this.repeater.groupSelection || !this.selected) { this.set('selected', !this.selected); } } }, /** * Deliberately used to supersede the default method and set * [owner]{@link enyo.Component#owner} to this [control]{@link enyo.Control} so that there * are no name collisions in the instance [owner]{@link enyo.Component#owner}, and also so * that [bindings]{@link enyo.Binding} will correctly map to names. * * @method * @private */ createClientComponents: enyo.inherit(function () { return function (components) { this.createComponents(components, {owner: this}); }; }), /** * Used so that we don't stomp on any built-in handlers for the `ontap` * {@glossary event}. * * @method * @private */ dispatchEvent: enyo.inherit(function (sup) { return function (name, event, sender) { if (!event._fromRepeaterChild) { if (!!~enyo.indexOf(name, this.repeater.selectionEvents)) { this._selectionHandler(); event._fromRepeaterChild = true; } } return sup.apply(this, arguments); }; }), /* * @method * @private */ constructed: enyo.inherit(function (sup) { return function () { sup.apply(this, arguments); var r = this.repeater, s = r.selectionProperty; // this property will only be set if the instance of the repeater needs // to track the selected state from the view and model and keep them in sync if (s) { var bnd = this.binding({ from: 'model.' + s, to: 'selected', oneWay: false/*, kind: enyo.BooleanBinding*/ }); this._selectionBindingId = bnd.euid; } }; }), /* * @method * @private */ destroy: enyo.inherit(function (sup) { return function () { if (this._selectionBindingId) { var b$ = enyo.Binding.find(this._selectionBindingId); if (b$) { b$.destroy(); } } sup.apply(this, arguments); }; }), /* * @private */ _selectionBindingId: null }; })(enyo, this);
KyleMaas/org.webosports.app.maps
enyo/source/ui/data/RepeaterChildSupport.js
JavaScript
apache-2.0
3,961
/*! * Copyright (c) 2015, Salesforce.com, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. 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. * * 3. Neither the name of Salesforce.com nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ 'use strict'; var vows = require('vows'); var assert = require('assert'); var async = require('async'); var tough = require('../lib/cookie'); var Cookie = tough.Cookie; var CookieJar = tough.CookieJar; var atNow = Date.now(); function at(offset) { return {now: new Date(atNow + offset)}; } vows .describe('Regression tests') .addBatch({ "Issue 1": { topic: function () { var cj = new CookieJar(); cj.setCookie('hello=world; path=/some/path/', 'http://domain/some/path/file', function (err, cookie) { this.callback(err, {cj: cj, cookie: cookie}); }.bind(this)); }, "stored a cookie": function (t) { assert.ok(t.cookie); }, "getting it back": { topic: function (t) { t.cj.getCookies('http://domain/some/path/file', function (err, cookies) { this.callback(err, {cj: t.cj, cookies: cookies || []}); }.bind(this)); }, "got one cookie": function (t) { assert.lengthOf(t.cookies, 1); }, "it's the right one": function (t) { var c = t.cookies[0]; assert.equal(c.key, 'hello'); assert.equal(c.value, 'world'); } } } }) .addBatch({ "trailing semi-colon set into cj": { topic: function () { var cb = this.callback; var cj = new CookieJar(); var ex = 'http://www.example.com'; var tasks = []; tasks.push(function (next) { cj.setCookie('broken_path=testme; path=/;', ex, at(-1), next); }); tasks.push(function (next) { cj.setCookie('b=2; Path=/;;;;', ex, at(-1), next); }); async.parallel(tasks, function (err, cookies) { cb(null, { cj: cj, cookies: cookies }); }); }, "check number of cookies": function (t) { assert.lengthOf(t.cookies, 2, "didn't set"); }, "check *broken_path* was set properly": function (t) { assert.equal(t.cookies[0].key, "broken_path"); assert.equal(t.cookies[0].value, "testme"); assert.equal(t.cookies[0].path, "/"); }, "check *b* was set properly": function (t) { assert.equal(t.cookies[1].key, "b"); assert.equal(t.cookies[1].value, "2"); assert.equal(t.cookies[1].path, "/"); }, "retrieve the cookie": { topic: function (t) { var cb = this.callback; t.cj.getCookies('http://www.example.com', {}, function (err, cookies) { t.cookies = cookies; cb(err, t); }); }, "get the cookie": function (t) { assert.lengthOf(t.cookies, 2); assert.equal(t.cookies[0].key, 'broken_path'); assert.equal(t.cookies[0].value, 'testme'); assert.equal(t.cookies[1].key, "b"); assert.equal(t.cookies[1].value, "2"); assert.equal(t.cookies[1].path, "/"); } } } }) .addBatch({ "tough-cookie throws exception on malformed URI (GH-32)": { topic: function () { var url = "http://www.example.com/?test=100%"; var cj = new CookieJar(); cj.setCookieSync("Test=Test", url); return cj.getCookieStringSync(url); }, "cookies are set": function (cookieStr) { assert.strictEqual(cookieStr, "Test=Test"); } } }) .export(module);
vendavo/yowie
yowie-web/node_modules/bower/node_modules/request/node_modules/tough-cookie/test/regression_test.js
JavaScript
mit
4,995
'use strict'; var _createClass = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var Promise = require('bluebird'); var MongoClient = require('mongodb'); function defaultSerializeFunction(session) { // Copy each property of the session to a new object var obj = {}; var prop = void 0; for (prop in session) { if (prop === 'cookie') { // Convert the cookie instance to an object, if possible // This gets rid of the duplicate object under session.cookie.data property obj.cookie = session.cookie.toJSON ? session.cookie.toJSON() : session.cookie; } else { obj[prop] = session[prop]; } } return obj; } function computeTransformFunctions(options, defaultStringify) { if (options.serialize || options.unserialize) { return { serialize: options.serialize || defaultSerializeFunction, unserialize: options.unserialize || function (x) { return x; } }; } if (options.stringify === false || defaultStringify === false) { return { serialize: defaultSerializeFunction, unserialize: function (x) { return x; } }; } if (options.stringify === true || defaultStringify === true) { return { serialize: JSON.stringify, unserialize: JSON.parse }; } } module.exports = function connectMongo(connect) { var Store = connect.Store || connect.session.Store; var MemoryStore = connect.MemoryStore || connect.session.MemoryStore; var MongoStore = function (_Store) { _inherits(MongoStore, _Store); function MongoStore(options) { _classCallCheck(this, MongoStore); options = options || {}; /* Fallback */ if (options.fallbackMemory && MemoryStore) { var _ret; return _ret = new MemoryStore(), _possibleConstructorReturn(_this, _ret); } /* Options */ var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(MongoStore).call(this, options)); _this.ttl = options.ttl || 1209600; // 14 days _this.collectionName = options.collection || 'sessions'; _this.autoRemove = options.autoRemove || 'native'; _this.autoRemoveInterval = options.autoRemoveInterval || 10; _this.transformFunctions = computeTransformFunctions(options, true); _this.options = options; _this.changeState('init'); var newConnectionCallback = function (err, db) { if (err) { _this.connectionFailed(err); } else { _this.handleNewConnectionAsync(db); } }; if (options.url) { // New native connection using url + mongoOptions MongoClient.connect(options.url, options.mongoOptions || {}, newConnectionCallback); } else if (options.mongooseConnection) { // Re-use existing or upcoming mongoose connection if (options.mongooseConnection.readyState === 1) { _this.handleNewConnectionAsync(options.mongooseConnection.db); } else { options.mongooseConnection.once('open', function () { return _this.handleNewConnectionAsync(options.mongooseConnection.db); }); } } else if (options.db && options.db.listCollections) { // Re-use existing or upcoming native connection if (options.db.openCalled || options.db.openCalled === undefined) { // openCalled is undefined in [email protected] _this.handleNewConnectionAsync(options.db); } else { options.db.open(newConnectionCallback); } } else if (options.dbPromise) { options.dbPromise.then(function (db) { return _this.handleNewConnectionAsync(db); }).catch(function (err) { return _this.connectionFailed(err); }); } else { throw new Error('Connection strategy not found'); } _this.changeState('connecting'); return _this; } _createClass(MongoStore, [{ key: 'connectionFailed', value: function connectionFailed(err) { this.changeState('disconnected'); throw err; } }, { key: 'handleNewConnectionAsync', value: function handleNewConnectionAsync(db) { var _this2 = this; this.db = db; return this.setCollection(db.collection(this.collectionName)).setAutoRemoveAsync().then(function () { return _this2.changeState('connected'); }); } }, { key: 'setAutoRemoveAsync', value: function setAutoRemoveAsync() { var _this3 = this; switch (this.autoRemove) { case 'native': return this.collection.ensureIndexAsync({ expires: 1 }, { expireAfterSeconds: 0 }); case 'interval': var removeQuery = { expires: { $lt: new Date() } }; this.timer = setInterval(function () { return _this3.collection.remove(removeQuery, { w: 0 }); }, this.autoRemoveInterval * 1000 * 60); this.timer.unref(); return Promise.resolve(); default: return Promise.resolve(); } } }, { key: 'changeState', value: function changeState(newState) { if (newState !== this.state) { this.state = newState; this.emit(newState); } } }, { key: 'setCollection', value: function setCollection(collection) { if (this.timer) { clearInterval(this.timer); } this.collectionReadyPromise = undefined; this.collection = collection; // Promisify used collection methods ['count', 'findOne', 'remove', 'drop', 'update', 'ensureIndex'].forEach(function (method) { collection[method + 'Async'] = Promise.promisify(collection[method], collection); }); return this; } }, { key: 'collectionReady', value: function collectionReady() { var _this4 = this; var promise = this.collectionReadyPromise; if (!promise) { promise = new Promise(function (resolve, reject) { switch (_this4.state) { case 'connected': resolve(_this4.collection); break; case 'connecting': _this4.once('connected', function () { return resolve(_this4.collection); }); break; case 'disconnected': reject(new Error('Not connected')); break; } }); this.collectionReadyPromise = promise; } return promise; } }, { key: 'computeStorageId', value: function computeStorageId(sessionId) { if (this.options.transformId && typeof this.options.transformId === 'function') { return this.options.transformId(sessionId); } else { return sessionId; } } /* Public API */ }, { key: 'get', value: function get(sid, callback) { var _this5 = this; return this.collectionReady().then(function (collection) { return collection.findOneAsync({ _id: _this5.computeStorageId(sid), $or: [{ expires: { $exists: false } }, { expires: { $gt: new Date() } }] }); }).then(function (session) { if (session) { var s = _this5.transformFunctions.unserialize(session.session); if (_this5.options.touchAfter > 0 && session.lastModified) { s.lastModified = session.lastModified; } _this5.emit('touch', sid); return s; } }).nodeify(callback); } }, { key: 'set', value: function set(sid, session, callback) { var _this6 = this; // removing the lastModified prop from the session object before update if (this.options.touchAfter > 0 && session && session.lastModified) { delete session.lastModified; } var s; try { s = { _id: this.computeStorageId(sid), session: this.transformFunctions.serialize(session) }; } catch (err) { return callback(err); } if (session && session.cookie && session.cookie.expires) { s.expires = new Date(session.cookie.expires); } else { // If there's no expiration date specified, it is // browser-session cookie or there is no cookie at all, // as per the connect docs. // // So we set the expiration to two-weeks from now // - as is common practice in the industry (e.g Django) - // or the default specified in the options. s.expires = new Date(Date.now() + this.ttl * 1000); } if (this.options.touchAfter > 0) { s.lastModified = new Date(); } return this.collectionReady().then(function (collection) { return collection.updateAsync({ _id: _this6.computeStorageId(sid) }, s, { upsert: true }); }).then(function () { return _this6.emit('set', sid); }).nodeify(callback); } }, { key: 'touch', value: function touch(sid, session, callback) { var _this7 = this; var updateFields = {}, touchAfter = this.options.touchAfter * 1000, lastModified = session.lastModified ? session.lastModified.getTime() : 0, currentDate = new Date(); // if the given options has a touchAfter property, check if the // current timestamp - lastModified timestamp is bigger than // the specified, if it's not, don't touch the session if (touchAfter > 0 && lastModified > 0) { var timeElapsed = currentDate.getTime() - session.lastModified; if (timeElapsed < touchAfter) { return callback(); } else { updateFields.lastModified = currentDate; } } if (session && session.cookie && session.cookie.expires) { updateFields.expires = new Date(session.cookie.expires); } else { updateFields.expires = new Date(Date.now() + this.ttl * 1000); } return this.collectionReady().then(function (collection) { return collection.updateAsync({ _id: _this7.computeStorageId(sid) }, { $set: updateFields }); }).then(function (result) { if (result.nModified === 0) { throw new Error('Unable to find the session to touch'); } else { _this7.emit('touch', sid); } }).nodeify(callback); } }, { key: 'destroy', value: function destroy(sid, callback) { var _this8 = this; return this.collectionReady().then(function (collection) { return collection.removeAsync({ _id: _this8.computeStorageId(sid) }); }).then(function () { return _this8.emit('destroy', sid); }).nodeify(callback); } }, { key: 'length', value: function length(callback) { return this.collectionReady().then(function (collection) { return collection.countAsync({}); }).nodeify(callback); } }, { key: 'clear', value: function clear(callback) { return this.collectionReady().then(function (collection) { return collection.dropAsync(); }).nodeify(callback); } }, { key: 'close', value: function close() { if (this.db) { this.db.close(); } } }]); return MongoStore; }(Store); return MongoStore; };
luoshichang/learnNode
node_modules/connect-mongo/src-es5/index.js
JavaScript
mit
15,400
import * as RSVP from 'rsvp'; import { backburner, _rsvpErrorQueue } from '@ember/runloop'; import { getDispatchOverride } from '@ember/-internals/error-handling'; import { assert } from '@ember/debug'; RSVP.configure('async', (callback, promise) => { backburner.schedule('actions', null, callback, promise); }); RSVP.configure('after', cb => { backburner.schedule(_rsvpErrorQueue, null, cb); }); RSVP.on('error', onerrorDefault); export function onerrorDefault(reason) { let error = errorFor(reason); if (error) { let overrideDispatch = getDispatchOverride(); if (overrideDispatch) { overrideDispatch(error); } else { throw error; } } } function errorFor(reason) { if (!reason) return; if (reason.errorThrown) { return unwrapErrorThrown(reason); } if (reason.name === 'UnrecognizedURLError') { assert(`The URL '${reason.message}' did not match any routes in your application`, false); return; } if (reason.name === 'TransitionAborted') { return; } return reason; } function unwrapErrorThrown(reason) { let error = reason.errorThrown; if (typeof error === 'string') { error = new Error(error); } Object.defineProperty(error, '__reason_with_error_thrown__', { value: reason, enumerable: false, }); return error; } export default RSVP;
bekzod/ember.js
packages/@ember/-internals/runtime/lib/ext/rsvp.js
JavaScript
mit
1,339
/** @module ember @submodule ember-runtime */ import Ember from 'ember-metal/core'; import { Mixin } from 'ember-metal/mixin'; import { get } from 'ember-metal/property_get'; import { deprecateProperty } from 'ember-metal/deprecate_property'; /** `Ember.ActionHandler` is available on some familiar classes including `Ember.Route`, `Ember.View`, `Ember.Component`, and `Ember.Controller`. (Internally the mixin is used by `Ember.CoreView`, `Ember.ControllerMixin`, and `Ember.Route` and available to the above classes through inheritance.) @class ActionHandler @namespace Ember @private */ var ActionHandler = Mixin.create({ mergedProperties: ['actions'], /** The collection of functions, keyed by name, available on this `ActionHandler` as action targets. These functions will be invoked when a matching `{{action}}` is triggered from within a template and the application's current route is this route. Actions can also be invoked from other parts of your application via `ActionHandler#send`. The `actions` hash will inherit action handlers from the `actions` hash defined on extended parent classes or mixins rather than just replace the entire hash, e.g.: ```js App.CanDisplayBanner = Ember.Mixin.create({ actions: { displayBanner: function(msg) { // ... } } }); App.WelcomeRoute = Ember.Route.extend(App.CanDisplayBanner, { actions: { playMusic: function() { // ... } } }); // `WelcomeRoute`, when active, will be able to respond // to both actions, since the actions hash is merged rather // then replaced when extending mixins / parent classes. this.send('displayBanner'); this.send('playMusic'); ``` Within a Controller, Route, View or Component's action handler, the value of the `this` context is the Controller, Route, View or Component object: ```js App.SongRoute = Ember.Route.extend({ actions: { myAction: function() { this.controllerFor("song"); this.transitionTo("other.route"); ... } } }); ``` It is also possible to call `this._super.apply(this, arguments)` from within an action handler if it overrides a handler defined on a parent class or mixin: Take for example the following routes: ```js App.DebugRoute = Ember.Mixin.create({ actions: { debugRouteInformation: function() { console.debug("trololo"); } } }); App.AnnoyingDebugRoute = Ember.Route.extend(App.DebugRoute, { actions: { debugRouteInformation: function() { // also call the debugRouteInformation of mixed in App.DebugRoute this._super.apply(this, arguments); // show additional annoyance window.alert(...); } } }); ``` ## Bubbling By default, an action will stop bubbling once a handler defined on the `actions` hash handles it. To continue bubbling the action, you must return `true` from the handler: ```js App.Router.map(function() { this.route("album", function() { this.route("song"); }); }); App.AlbumRoute = Ember.Route.extend({ actions: { startPlaying: function() { } } }); App.AlbumSongRoute = Ember.Route.extend({ actions: { startPlaying: function() { // ... if (actionShouldAlsoBeTriggeredOnParentRoute) { return true; } } } }); ``` @property actions @type Object @default null @public */ /** Triggers a named action on the `ActionHandler`. Any parameters supplied after the `actionName` string will be passed as arguments to the action target function. If the `ActionHandler` has its `target` property set, actions may bubble to the `target`. Bubbling happens when an `actionName` can not be found in the `ActionHandler`'s `actions` hash or if the action target function returns `true`. Example ```js App.WelcomeRoute = Ember.Route.extend({ actions: { playTheme: function() { this.send('playMusic', 'theme.mp3'); }, playMusic: function(track) { // ... } } }); ``` @method send @param {String} actionName The action to trigger @param {*} context a context to send with the action @public */ send(actionName, ...args) { var target; if (this.actions && this.actions[actionName]) { var shouldBubble = this.actions[actionName].apply(this, args) === true; if (!shouldBubble) { return; } } if (target = get(this, 'target')) { Ember.assert('The `target` for ' + this + ' (' + target + ') does not have a `send` method', typeof target.send === 'function'); target.send(...arguments); } } }); export default ActionHandler; export function deprecateUnderscoreActions(factory) { deprecateProperty(factory.prototype, '_actions', 'actions', { id: 'ember-runtime.action-handler-_actions', until: '3.0.0' }); }
artfuldodger/ember.js
packages/ember-runtime/lib/mixins/action_handler.js
JavaScript
mit
5,224
"use strict"; // copied from http://www.broofa.com/Tools/Math.uuid.js var CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split(''); exports.uuid = function () { var chars = CHARS, uuid = new Array(36), rnd=0, r; for (var i = 0; i < 36; i++) { if (i==8 || i==13 || i==18 || i==23) { uuid[i] = '-'; } else if (i==14) { uuid[i] = '4'; } else { if (rnd <= 0x02) rnd = 0x2000000 + (Math.random()*0x1000000)|0; r = rnd & 0xf; rnd = rnd >> 4; uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r]; } } return uuid.join(''); }; exports.in_array = function (item, array) { return (array.indexOf(item) != -1); }; exports.sort_keys = function (obj) { return Object.keys(obj).sort(); }; exports.uniq = function (arr) { var out = []; var o = 0; for (var i=0,l=arr.length; i < l; i++) { if (out.length === 0) { out.push(arr[i]); } else if (out[o] != arr[i]) { out.push(arr[i]); o++; } } return out; } exports.ISODate = function (d) { function pad(n) {return n<10 ? '0'+n : n} return d.getUTCFullYear()+'-' + pad(d.getUTCMonth()+1)+'-' + pad(d.getUTCDate())+'T' + pad(d.getUTCHours())+':' + pad(d.getUTCMinutes())+':' + pad(d.getUTCSeconds())+'Z' } var _daynames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; var _monnames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; function _pad (num, n, p) { var s = '' + num; p = p || '0'; while (s.length < n) s = p + s; return s; } exports.pad = _pad; exports.date_to_str = function (d) { return _daynames[d.getDay()] + ', ' + _pad(d.getDate(),2) + ' ' + _monnames[d.getMonth()] + ' ' + d.getFullYear() + ' ' + _pad(d.getHours(),2) + ':' + _pad(d.getMinutes(),2) + ':' + _pad(d.getSeconds(),2) + ' ' + d.toString().match(/\sGMT([+-]\d+)/)[1]; } exports.decode_qp = function (line) { line = line.replace(/\r\n/g,"\n").replace(/[ \t]+\r?\n/g,"\n"); if (! /=/.test(line)) { // this may be a pointless optimisation... return new Buffer(line); } line = line.replace(/=\n/mg, ''); var buf = new Buffer(line.length); var pos = 0; for (var i=0,l=line.length; i < l; i++) { if (line[i] === '=' && /=[0-9a-fA-F]{2}/.test(line[i] + line[i+1] + line[i+2])) { i++; buf[pos] = parseInt(line[i] + line[i+1], 16); i++; } else { buf[pos] = line.charCodeAt(i); } pos++; } return buf.slice(0, pos); } function _char_to_qp (ch) { return "=" + _pad(ch.charCodeAt(0).toString(16).toUpperCase(), 2); } // Shameless attempt to copy from Perl's MIME::QuotedPrint::Perl code. exports.encode_qp = function (str) { str = str.replace(/([^\ \t\n!"#\$%&'()*+,\-.\/0-9:;<>?\@A-Z\[\\\]^_`a-z{|}~])/g, function (orig, p1) { return _char_to_qp(p1); }).replace(/([ \t]+)$/gm, function (orig, p1) { return p1.split('').map(_char_to_qp).join(''); }); // Now shorten lines to 76 chars, but don't break =XX encodes. // Method: iterate over to char 73. // If char 74, 75 or 76 is = we need to break before the =. // Otherwise break at 76. var cur_length = 0; var out = ''; for (var i=0; i<str.length; i++) { if (str[i] === '\n') { out += '\n'; cur_length = 0; continue; } cur_length++; if (cur_length <= 73) { out += str[i]; } else if (cur_length > 73 && cur_length < 76) { if (str[i] === '=') { out += '=\n='; cur_length = 1; } else { out += str[i]; } } else { // Otherwise got to char 76 // Don't insert '=\n' if end of string or next char is already \n: if ((i === (str.length - 1)) || (str[i+1] === '\n')) { out += str[i]; } else { out += '=\n' + str[i]; cur_length = 1; } } } return out; } var versions = process.version.split('.'), version = Number(versions[0].substring(1)), subversion = Number(versions[1]); exports.existsSync = require((version > 0 || subversion >= 8) ? 'fs' : 'path').existsSync; exports.indexOfLF = function (buf, maxlength) { for (var i=0; i<buf.length; i++) { if (maxlength && (i === maxlength)) break; if (buf[i] === 0x0a) return i; } return -1; }
lucciano/Haraka
utils.js
JavaScript
mit
4,778
// Learn more about configuring this file at <https://theintern.github.io/intern/#configuration>. // These default settings work OK for most people. The options that *must* be changed below are the // packages, suites, excludeInstrumentation, and (if you want functional tests) functionalSuites define({ // Default desired capabilities for all environments. Individual capabilities can be overridden by any of the // specified browser environments in the `environments` array below as well. See // <https://theintern.github.io/intern/#option-capabilities> for links to the different capabilities options for // different services. // Maximum number of simultaneous integration tests that should be executed on the remote WebDriver service maxConcurrency: 2, // Non-functional test suite(s) to run in each browser suites: [ 'tests/plugin' ], // A regular expression matching URLs to files that should not be included in code coverage analysis excludeInstrumentation: /^(?:tests|node_modules)\// });
brendanlacroix/polish-no-added-typography
tests/intern.js
JavaScript
mit
1,011
import {LooseParser} from "./state" import {isDummy} from "./parseutil" import {tokTypes as tt} from ".." const lp = LooseParser.prototype lp.checkLVal = function(expr) { if (!expr) return expr switch (expr.type) { case "Identifier": case "MemberExpression": return expr case "ParenthesizedExpression": expr.expression = this.checkLVal(expr.expression) return expr default: return this.dummyIdent() } } lp.parseExpression = function(noIn) { let start = this.storeCurrentPos() let expr = this.parseMaybeAssign(noIn) if (this.tok.type === tt.comma) { let node = this.startNodeAt(start) node.expressions = [expr] while (this.eat(tt.comma)) node.expressions.push(this.parseMaybeAssign(noIn)) return this.finishNode(node, "SequenceExpression") } return expr } lp.parseParenExpression = function() { this.pushCx() this.expect(tt.parenL) let val = this.parseExpression() this.popCx() this.expect(tt.parenR) return val } lp.parseMaybeAssign = function(noIn) { if (this.toks.isContextual("yield")) { let node = this.startNode() this.next() if (this.semicolon() || this.canInsertSemicolon() || (this.tok.type != tt.star && !this.tok.type.startsExpr)) { node.delegate = false node.argument = null } else { node.delegate = this.eat(tt.star) node.argument = this.parseMaybeAssign() } return this.finishNode(node, "YieldExpression") } let start = this.storeCurrentPos() let left = this.parseMaybeConditional(noIn) if (this.tok.type.isAssign) { let node = this.startNodeAt(start) node.operator = this.tok.value node.left = this.tok.type === tt.eq ? this.toAssignable(left) : this.checkLVal(left) this.next() node.right = this.parseMaybeAssign(noIn) return this.finishNode(node, "AssignmentExpression") } return left } lp.parseMaybeConditional = function(noIn) { let start = this.storeCurrentPos() let expr = this.parseExprOps(noIn) if (this.eat(tt.question)) { let node = this.startNodeAt(start) node.test = expr node.consequent = this.parseMaybeAssign() node.alternate = this.expect(tt.colon) ? this.parseMaybeAssign(noIn) : this.dummyIdent() return this.finishNode(node, "ConditionalExpression") } return expr } lp.parseExprOps = function(noIn) { let start = this.storeCurrentPos() let indent = this.curIndent, line = this.curLineStart return this.parseExprOp(this.parseMaybeUnary(false), start, -1, noIn, indent, line) } lp.parseExprOp = function(left, start, minPrec, noIn, indent, line) { if (this.curLineStart != line && this.curIndent < indent && this.tokenStartsLine()) return left let prec = this.tok.type.binop if (prec != null && (!noIn || this.tok.type !== tt._in)) { if (prec > minPrec) { let node = this.startNodeAt(start) node.left = left node.operator = this.tok.value this.next() if (this.curLineStart != line && this.curIndent < indent && this.tokenStartsLine()) { node.right = this.dummyIdent() } else { let rightStart = this.storeCurrentPos() node.right = this.parseExprOp(this.parseMaybeUnary(false), rightStart, prec, noIn, indent, line) } this.finishNode(node, /&&|\|\|/.test(node.operator) ? "LogicalExpression" : "BinaryExpression") return this.parseExprOp(node, start, minPrec, noIn, indent, line) } } return left } lp.parseMaybeUnary = function(sawUnary) { let start = this.storeCurrentPos(), expr if (this.tok.type.prefix) { let node = this.startNode(), update = this.tok.type === tt.incDec if (!update) sawUnary = true node.operator = this.tok.value node.prefix = true this.next() node.argument = this.parseMaybeUnary(true) if (update) node.argument = this.checkLVal(node.argument) expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression") } else if (this.tok.type === tt.ellipsis) { let node = this.startNode() this.next() node.argument = this.parseMaybeUnary(sawUnary) expr = this.finishNode(node, "SpreadElement") } else { expr = this.parseExprSubscripts() while (this.tok.type.postfix && !this.canInsertSemicolon()) { let node = this.startNodeAt(start) node.operator = this.tok.value node.prefix = false node.argument = this.checkLVal(expr) this.next() expr = this.finishNode(node, "UpdateExpression") } } if (!sawUnary && this.eat(tt.starstar)) { let node = this.startNodeAt(start) node.operator = "**" node.left = expr node.right = this.parseMaybeUnary(false) return this.finishNode(node, "BinaryExpression") } return expr } lp.parseExprSubscripts = function() { let start = this.storeCurrentPos() return this.parseSubscripts(this.parseExprAtom(), start, false, this.curIndent, this.curLineStart) } lp.parseSubscripts = function(base, start, noCalls, startIndent, line) { for (;;) { if (this.curLineStart != line && this.curIndent <= startIndent && this.tokenStartsLine()) { if (this.tok.type == tt.dot && this.curIndent == startIndent) --startIndent else return base } if (this.eat(tt.dot)) { let node = this.startNodeAt(start) node.object = base if (this.curLineStart != line && this.curIndent <= startIndent && this.tokenStartsLine()) node.property = this.dummyIdent() else node.property = this.parsePropertyAccessor() || this.dummyIdent() node.computed = false base = this.finishNode(node, "MemberExpression") } else if (this.tok.type == tt.bracketL) { this.pushCx() this.next() let node = this.startNodeAt(start) node.object = base node.property = this.parseExpression() node.computed = true this.popCx() this.expect(tt.bracketR) base = this.finishNode(node, "MemberExpression") } else if (!noCalls && this.tok.type == tt.parenL) { let node = this.startNodeAt(start) node.callee = base node.arguments = this.parseExprList(tt.parenR) base = this.finishNode(node, "CallExpression") } else if (this.tok.type == tt.backQuote) { let node = this.startNodeAt(start) node.tag = base node.quasi = this.parseTemplate() base = this.finishNode(node, "TaggedTemplateExpression") } else { return base } } } lp.parseExprAtom = function() { let node switch (this.tok.type) { case tt._this: case tt._super: let type = this.tok.type === tt._this ? "ThisExpression" : "Super" node = this.startNode() this.next() return this.finishNode(node, type) case tt.name: let start = this.storeCurrentPos() let id = this.parseIdent() return this.eat(tt.arrow) ? this.parseArrowExpression(this.startNodeAt(start), [id]) : id case tt.regexp: node = this.startNode() let val = this.tok.value node.regex = {pattern: val.pattern, flags: val.flags} node.value = val.value node.raw = this.input.slice(this.tok.start, this.tok.end) this.next() return this.finishNode(node, "Literal") case tt.num: case tt.string: node = this.startNode() node.value = this.tok.value node.raw = this.input.slice(this.tok.start, this.tok.end) this.next() return this.finishNode(node, "Literal") case tt._null: case tt._true: case tt._false: node = this.startNode() node.value = this.tok.type === tt._null ? null : this.tok.type === tt._true node.raw = this.tok.type.keyword this.next() return this.finishNode(node, "Literal") case tt.parenL: let parenStart = this.storeCurrentPos() this.next() let inner = this.parseExpression() this.expect(tt.parenR) if (this.eat(tt.arrow)) { return this.parseArrowExpression(this.startNodeAt(parenStart), inner.expressions || (isDummy(inner) ? [] : [inner])) } if (this.options.preserveParens) { let par = this.startNodeAt(parenStart) par.expression = inner inner = this.finishNode(par, "ParenthesizedExpression") } return inner case tt.bracketL: node = this.startNode() node.elements = this.parseExprList(tt.bracketR, true) return this.finishNode(node, "ArrayExpression") case tt.braceL: return this.parseObj() case tt._class: return this.parseClass() case tt._function: node = this.startNode() this.next() return this.parseFunction(node, false) case tt._new: return this.parseNew() case tt.backQuote: return this.parseTemplate() default: return this.dummyIdent() } } lp.parseNew = function() { let node = this.startNode(), startIndent = this.curIndent, line = this.curLineStart let meta = this.parseIdent(true) if (this.options.ecmaVersion >= 6 && this.eat(tt.dot)) { node.meta = meta node.property = this.parseIdent(true) return this.finishNode(node, "MetaProperty") } let start = this.storeCurrentPos() node.callee = this.parseSubscripts(this.parseExprAtom(), start, true, startIndent, line) if (this.tok.type == tt.parenL) { node.arguments = this.parseExprList(tt.parenR) } else { node.arguments = [] } return this.finishNode(node, "NewExpression") } lp.parseTemplateElement = function() { let elem = this.startNode() elem.value = { raw: this.input.slice(this.tok.start, this.tok.end).replace(/\r\n?/g, '\n'), cooked: this.tok.value } this.next() elem.tail = this.tok.type === tt.backQuote return this.finishNode(elem, "TemplateElement") } lp.parseTemplate = function() { let node = this.startNode() this.next() node.expressions = [] let curElt = this.parseTemplateElement() node.quasis = [curElt] while (!curElt.tail) { this.next() node.expressions.push(this.parseExpression()) if (this.expect(tt.braceR)) { curElt = this.parseTemplateElement() } else { curElt = this.startNode() curElt.value = {cooked: '', raw: ''} curElt.tail = true } node.quasis.push(curElt) } this.expect(tt.backQuote) return this.finishNode(node, "TemplateLiteral") } lp.parseObj = function() { let node = this.startNode() node.properties = [] this.pushCx() let indent = this.curIndent + 1, line = this.curLineStart this.eat(tt.braceL) if (this.curIndent + 1 < indent) { indent = this.curIndent; line = this.curLineStart } while (!this.closes(tt.braceR, indent, line)) { let prop = this.startNode(), isGenerator, start if (this.options.ecmaVersion >= 6) { start = this.storeCurrentPos() prop.method = false prop.shorthand = false isGenerator = this.eat(tt.star) } this.parsePropertyName(prop) if (isDummy(prop.key)) { if (isDummy(this.parseMaybeAssign())) this.next(); this.eat(tt.comma); continue } if (this.eat(tt.colon)) { prop.kind = "init" prop.value = this.parseMaybeAssign() } else if (this.options.ecmaVersion >= 6 && (this.tok.type === tt.parenL || this.tok.type === tt.braceL)) { prop.kind = "init" prop.method = true prop.value = this.parseMethod(isGenerator) } else if (this.options.ecmaVersion >= 5 && prop.key.type === "Identifier" && !prop.computed && (prop.key.name === "get" || prop.key.name === "set") && (this.tok.type != tt.comma && this.tok.type != tt.braceR)) { prop.kind = prop.key.name this.parsePropertyName(prop) prop.value = this.parseMethod(false) } else { prop.kind = "init" if (this.options.ecmaVersion >= 6) { if (this.eat(tt.eq)) { let assign = this.startNodeAt(start) assign.operator = "=" assign.left = prop.key assign.right = this.parseMaybeAssign() prop.value = this.finishNode(assign, "AssignmentExpression") } else { prop.value = prop.key } } else { prop.value = this.dummyIdent() } prop.shorthand = true } node.properties.push(this.finishNode(prop, "Property")) this.eat(tt.comma) } this.popCx() if (!this.eat(tt.braceR)) { // If there is no closing brace, make the node span to the start // of the next token (this is useful for Tern) this.last.end = this.tok.start if (this.options.locations) this.last.loc.end = this.tok.loc.start } return this.finishNode(node, "ObjectExpression") } lp.parsePropertyName = function(prop) { if (this.options.ecmaVersion >= 6) { if (this.eat(tt.bracketL)) { prop.computed = true prop.key = this.parseExpression() this.expect(tt.bracketR) return } else { prop.computed = false } } let key = (this.tok.type === tt.num || this.tok.type === tt.string) ? this.parseExprAtom() : this.parseIdent() prop.key = key || this.dummyIdent() } lp.parsePropertyAccessor = function() { if (this.tok.type === tt.name || this.tok.type.keyword) return this.parseIdent() } lp.parseIdent = function() { let name = this.tok.type === tt.name ? this.tok.value : this.tok.type.keyword if (!name) return this.dummyIdent() let node = this.startNode() this.next() node.name = name return this.finishNode(node, "Identifier") } lp.initFunction = function(node) { node.id = null node.params = [] if (this.options.ecmaVersion >= 6) { node.generator = false node.expression = false } } // Convert existing expression atom to assignable pattern // if possible. lp.toAssignable = function(node, binding) { if (!node || node.type == "Identifier" || (node.type == "MemberExpression" && !binding)) { // Okay } else if (node.type == "ParenthesizedExpression") { node.expression = this.toAssignable(node.expression, binding) } else if (this.options.ecmaVersion < 6) { return this.dummyIdent() } else if (node.type == "ObjectExpression") { node.type = "ObjectPattern" let props = node.properties for (let i = 0; i < props.length; i++) props[i].value = this.toAssignable(props[i].value, binding) } else if (node.type == "ArrayExpression") { node.type = "ArrayPattern" this.toAssignableList(node.elements, binding) } else if (node.type == "SpreadElement") { node.type = "RestElement" node.argument = this.toAssignable(node.argument, binding) } else if (node.type == "AssignmentExpression") { node.type = "AssignmentPattern" delete node.operator } else { return this.dummyIdent() } return node } lp.toAssignableList = function(exprList, binding) { for (let i = 0; i < exprList.length; i++) exprList[i] = this.toAssignable(exprList[i], binding) return exprList } lp.parseFunctionParams = function(params) { params = this.parseExprList(tt.parenR) return this.toAssignableList(params, true) } lp.parseMethod = function(isGenerator) { let node = this.startNode() this.initFunction(node) node.params = this.parseFunctionParams() node.generator = isGenerator || false node.expression = this.options.ecmaVersion >= 6 && this.tok.type !== tt.braceL node.body = node.expression ? this.parseMaybeAssign() : this.parseBlock() return this.finishNode(node, "FunctionExpression") } lp.parseArrowExpression = function(node, params) { this.initFunction(node) node.params = this.toAssignableList(params, true) node.expression = this.tok.type !== tt.braceL node.body = node.expression ? this.parseMaybeAssign() : this.parseBlock() return this.finishNode(node, "ArrowFunctionExpression") } lp.parseExprList = function(close, allowEmpty) { this.pushCx() let indent = this.curIndent, line = this.curLineStart, elts = [] this.next() // Opening bracket while (!this.closes(close, indent + 1, line)) { if (this.eat(tt.comma)) { elts.push(allowEmpty ? null : this.dummyIdent()) continue } let elt = this.parseMaybeAssign() if (isDummy(elt)) { if (this.closes(close, indent, line)) break this.next() } else { elts.push(elt) } this.eat(tt.comma) } this.popCx() if (!this.eat(close)) { // If there is no closing brace, make the node span to the start // of the next token (this is useful for Tern) this.last.end = this.tok.start if (this.options.locations) this.last.loc.end = this.tok.loc.start } return elts }
eddyerburgh/free-code-camp-ziplines
react-projects/markdown-previewer/node_modules/is-expression/node_modules/acorn/src/loose/expression.js
JavaScript
mit
16,264
Proj4js.defs["EPSG:32666"] = "+proj=tmerc +lat_0=0 +lon_0=-87 +k=0.9996 +x_0=500000.001016002 +y_0=0 +ellps=WGS84 +datum=WGS84 +to_meter=0.3048006096012192 +no_defs";
MaxiReglisse/georchestra
mapfishapp/src/main/webapp/lib/proj4js/lib/defs/EPSG32666.js
JavaScript
gpl-3.0
166
/* * jQuery UI Effects Explode 1.8.7 * * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * http://docs.jquery.com/UI/Effects/Explode * * Depends: * jquery.effects.core.js */ (function(j){j.effects.explode=function(a){return this.queue(function(){var c=a.options.pieces?Math.round(Math.sqrt(a.options.pieces)):3,d=a.options.pieces?Math.round(Math.sqrt(a.options.pieces)):3;a.options.mode=a.options.mode=="toggle"?j(this).is(":visible")?"hide":"show":a.options.mode;var b=j(this).show().css("visibility","hidden"),g=b.offset();g.top-=parseInt(b.css("marginTop"),10)||0;g.left-=parseInt(b.css("marginLeft"),10)||0;for(var h=b.outerWidth(true),i=b.outerHeight(true),e=0;e<c;e++)for(var f= 0;f<d;f++)b.clone().appendTo("body").wrap("<div></div>").css({position:"absolute",visibility:"visible",left:-f*(h/d),top:-e*(i/c)}).parent().addClass("ui-effects-explode").css({position:"absolute",overflow:"hidden",width:h/d,height:i/c,left:g.left+f*(h/d)+(a.options.mode=="show"?(f-Math.floor(d/2))*(h/d):0),top:g.top+e*(i/c)+(a.options.mode=="show"?(e-Math.floor(c/2))*(i/c):0),opacity:a.options.mode=="show"?0:1}).animate({left:g.left+f*(h/d)+(a.options.mode=="show"?0:(f-Math.floor(d/2))*(h/d)),top:g.top+ e*(i/c)+(a.options.mode=="show"?0:(e-Math.floor(c/2))*(i/c)),opacity:a.options.mode=="show"?1:0},a.duration||500);setTimeout(function(){a.options.mode=="show"?b.css({visibility:"visible"}):b.css({visibility:"visible"}).hide();a.callback&&a.callback.apply(b[0]);b.dequeue();j("div.ui-effects-explode").remove()},a.duration||500)})}})(jQuery);
ieb/Shahnama
static/jquery-ui/development-bundle/ui/minified/jquery.effects.explode.min.js
JavaScript
agpl-3.0
1,643
/** * Shopware 4.0 * Copyright © 2012 shopware AG * * According to our dual licensing model, this program can be used either * under the terms of the GNU Affero General Public License, version 3, * or under a proprietary license. * * The texts of the GNU Affero General Public License with an additional * permission and of our proprietary license can be found at and * in the LICENSE file you have received along with this program. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * "Shopware" is a registered trademark of shopware AG. * The licensing of the program under the AGPLv3 does not imply a * trademark license. Therefore any rights, title and interest in * our trademarks remain entirely with us. * * @category Shopware * @package Login * @subpackage Model * @copyright Copyright (c) 2012, shopware AG (http://www.shopware.de) * @version $Id$ * @author shopware AG */ /** * Shopware Backend - ErrorReporter Main Model * * todo@all: Documentation */ Ext.define('Shopware.apps.UserManager.model.Locale', { extend: 'Ext.data.Model', fields: [ 'id', 'name' ] });
OliverZachau/shopware-4
templates/_default/backend/user_manager/model/locale.js
JavaScript
agpl-3.0
1,318
var Model; module("Ember.FilteredRecordArray", { setup: function() { Model = Ember.Model.extend({ id: Ember.attr(), name: Ember.attr() }); Model.adapter = Ember.FixtureAdapter.create(); Model.FIXTURES = [ {id: 1, name: 'Erik'}, {id: 2, name: 'Stefan'}, {id: 'abc', name: 'Charles'} ]; }, teardown: function() { } }); test("must be created with a modelClass property", function() { throws(function() { Ember.FilteredRecordArray.create(); }, /FilteredRecordArrays must be created with a modelClass/); }); test("must be created with a filterFunction property", function() { throws(function() { Ember.FilteredRecordArray.create({modelClass: Model}); }, /FilteredRecordArrays must be created with a filterFunction/); }); test("must be created with a filterProperties property", function() { throws(function() { Ember.FilteredRecordArray.create({modelClass: Model, filterFunction: Ember.K}); }, /FilteredRecordArrays must be created with filterProperties/); }); test("with a noop filter will return all the loaded records", function() { expect(1); Model.fetch().then(function() { start(); var recordArray = Ember.FilteredRecordArray.create({ modelClass: Model, filterFunction: Ember.K, filterProperties: [] }); equal(recordArray.get('length'), 3, "There are 3 records"); }); stop(); }); test("with a filter will return only the relevant loaded records", function() { expect(2); Model.fetch().then(function() { start(); var recordArray = Ember.FilteredRecordArray.create({ modelClass: Model, filterFunction: function(record) { return record.get('name') === 'Erik'; }, filterProperties: ['name'] }); equal(recordArray.get('length'), 1, "There is 1 record"); equal(recordArray.get('firstObject.name'), 'Erik', "The record data matches"); }); stop(); }); test("loading a record that doesn't match the filter after creating a FilteredRecordArray shouldn't change the content", function() { expect(2); Model.fetch().then(function() { start(); var recordArray = Ember.FilteredRecordArray.create({ modelClass: Model, filterFunction: function(record) { return record.get('name') === 'Erik'; }, filterProperties: ['name'] }); Model.create({id: 3, name: 'Kris'}).save().then(function(record) { start(); equal(recordArray.get('length'), 1, "There is still 1 record"); equal(recordArray.get('firstObject.name'), 'Erik', "The record data matches"); }); stop(); }); stop(); }); test("loading a record that matches the filter after creating a FilteredRecordArray should update the content of it", function() { expect(3); Model.fetch().then(function() { start(); var recordArray = Ember.FilteredRecordArray.create({ modelClass: Model, filterFunction: function(record) { return record.get('name') === 'Erik' || record.get('name') === 'Kris'; }, filterProperties: ['name'] }); Model.create({id: 3, name: 'Kris'}).save().then(function(record) { start(); equal(recordArray.get('length'), 2, "There are 2 records"); equal(recordArray.get('firstObject.name'), 'Erik', "The record data matches"); equal(recordArray.get('lastObject.name'), 'Kris', "The record data matches"); }); stop(); }); stop(); }); test("changing a property that matches the filter should update the FilteredRecordArray to include it", function() { expect(5); Model.fetch().then(function() { start(); var recordArray = Ember.FilteredRecordArray.create({ modelClass: Model, filterFunction: function(record) { return record.get('name').match(/^E/); }, filterProperties: ['name'] }); equal(recordArray.get('length'), 1, "There is 1 record initially"); equal(recordArray.get('firstObject.name'), 'Erik', "The record data matches"); Model.fetch(2).then(function(record) { start(); record.set('name', 'Estefan'); equal(recordArray.get('length'), 2, "There are 2 records after changing the name"); equal(recordArray.get('firstObject.name'), 'Erik', "The record data matches"); equal(recordArray.get('lastObject.name'), 'Estefan', "The record data matches"); }); stop(); }); stop(); }); test("adding a new record and changing a property that matches the filter should update the FilteredRecordArray to include it", function() { expect(8); Model.fetch().then(function() { start(); var recordArray = Ember.FilteredRecordArray.create({ modelClass: Model, filterFunction: function(record) { return record.get('name').match(/^E/); }, filterProperties: ['name'] }); equal(recordArray.get('length'), 1, "There is 1 record initially"); equal(recordArray.get('firstObject.name'), 'Erik', "The record data matches"); Model.create({id: 3, name: 'Kris'}).save().then(function(record) { start(); record.set('name', 'Ekris'); equal(recordArray.get('length'), 2, "There are 2 records after changing the name"); equal(recordArray.get('firstObject.name'), 'Erik', "The record data matches"); equal(recordArray.get('lastObject.name'), 'Ekris', "The record data matches"); record.set('name', 'Eskil'); equal(recordArray.get('length'), 2, "There are still 2 records after changing the name again"); equal(recordArray.get('firstObject.name'), 'Erik', "The record data still matches"); equal(recordArray.get('lastObject.name'), 'Eskil', "The record data still matches"); }); stop(); }); stop(); });
hypexr/grunt-version-copy-bower-components
test/fixtures/bower_components/ember-model/packages/ember-model/tests/filtered_record_array_test.js
JavaScript
mit
5,733
Ext.define('Ext.rtl.scroll.Indicator', { override: 'Ext.scroll.Indicator', privates: { translateX: function(value) { if (this.getScroller().getRtl()) { value = -value; } this.callParent([value]); } } });
sqlwang/my_wpblog
wp-content/themes/extjs/ext/classic/classic/src/rtl/scroll/Indicator.js
JavaScript
gpl-2.0
297
if (typeof process !== "undefined") { require("amd-loader"); require("../../test/setup_paths"); } define(function(require, exports, module) { var assert = require("assert"); var report = require("./linereport_base"); module.exports = { "test parse line" : function(next) { var results = report.parseOutput("1:2: 3"); console.log(results[0]); assert.equal(results[0].pos.sl, 0); assert.equal(results[0].pos.sc, 1); assert.equal(results[0].message, "3"); next(); }, "test parse two lines" : function(next) { var results = report.parseOutput("1:1: line 1\n1:2: line 2"); assert.equal(results.length, 2); next(); }, "test ignore lines" : function(next) { var results = report.parseOutput("1:1: line 1\n1:2: line 2\bmove zig"); assert.equal(results.length, 2); next(); } }; }); if (typeof module !== "undefined" && module === require.main) { require("asyncjs").test.testcase(module.exports).exec(); }
precise-partner/cloud9
plugins-client/ext.linereport/linereport_test.js
JavaScript
gpl-3.0
1,047
//// [wrappedAndRecursiveConstraints.ts] // no errors expected class C<T extends Date> { constructor(public data: T) { } foo<U extends T>(x: U) { return x; } } interface Foo extends Date { foo: string; } var y: Foo = null; var c = new C(y); var r = c.foo(y); //// [wrappedAndRecursiveConstraints.js] // no errors expected var C = /** @class */ (function () { function C(data) { this.data = data; } C.prototype.foo = function (x) { return x; }; return C; }()); var y = null; var c = new C(y); var r = c.foo(y);
weswigham/TypeScript
tests/baselines/reference/wrappedAndRecursiveConstraints.js
JavaScript
apache-2.0
591
//// [es6ClassTest8.ts] function f1(x:any) {return x;} class C { constructor() { var bar:any = (function() { return bar; // 'bar' should be resolvable }); var b = f1(f1(bar)); } } class Vector { static norm(v:Vector):Vector {return null;} static minus(v1:Vector, v2:Vector):Vector {return null;} static times(v1:Vector, v2:Vector):Vector {return null;} static cross(v1:Vector, v2:Vector):Vector {return null;} constructor(public x: number, public y: number, public z: number) { } static dot(v1:Vector, v2:Vector):Vector {return null;} } class Camera { public forward: Vector; public right: Vector; public up: Vector; constructor(public pos: Vector, lookAt: Vector) { var down = new Vector(0.0, -1.0, 0.0); this.forward = Vector.norm(Vector.minus(lookAt,this.pos)); this.right = Vector.times(down, Vector.norm(Vector.cross(this.forward, down))); this.up = Vector.times(down, Vector.norm(Vector.cross(this.forward, this.right))); } } //// [es6ClassTest8.js] function f1(x) { return x; } var C = /** @class */ (function () { function C() { var bar = (function () { return bar; // 'bar' should be resolvable }); var b = f1(f1(bar)); } return C; }()); var Vector = /** @class */ (function () { function Vector(x, y, z) { this.x = x; this.y = y; this.z = z; } Vector.norm = function (v) { return null; }; Vector.minus = function (v1, v2) { return null; }; Vector.times = function (v1, v2) { return null; }; Vector.cross = function (v1, v2) { return null; }; Vector.dot = function (v1, v2) { return null; }; return Vector; }()); var Camera = /** @class */ (function () { function Camera(pos, lookAt) { this.pos = pos; var down = new Vector(0.0, -1.0, 0.0); this.forward = Vector.norm(Vector.minus(lookAt, this.pos)); this.right = Vector.times(down, Vector.norm(Vector.cross(this.forward, down))); this.up = Vector.times(down, Vector.norm(Vector.cross(this.forward, this.right))); } return Camera; }());
donaldpipowitch/TypeScript
tests/baselines/reference/es6ClassTest8.js
JavaScript
apache-2.0
2,281
/* * Copyright (C) 2012 Google Inc. 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. */ /** * @constructor * @param {!Element} relativeToElement * @param {!WebInspector.DialogDelegate} delegate */ WebInspector.Dialog = function(relativeToElement, delegate) { this._delegate = delegate; this._relativeToElement = relativeToElement; this._glassPane = new WebInspector.GlassPane(/** @type {!Document} */ (relativeToElement.ownerDocument)); WebInspector.GlassPane.DefaultFocusedViewStack.push(this); // Install glass pane capturing events. this._glassPane.element.tabIndex = 0; this._glassPane.element.addEventListener("focus", this._onGlassPaneFocus.bind(this), false); this._element = this._glassPane.element.createChild("div"); this._element.tabIndex = 0; this._element.addEventListener("focus", this._onFocus.bind(this), false); this._element.addEventListener("keydown", this._onKeyDown.bind(this), false); this._closeKeys = [ WebInspector.KeyboardShortcut.Keys.Enter.code, WebInspector.KeyboardShortcut.Keys.Esc.code, ]; delegate.show(this._element); this._position(); this._delegate.focus(); } /** * @return {?WebInspector.Dialog} */ WebInspector.Dialog.currentInstance = function() { return WebInspector.Dialog._instance; } /** * @param {!Element} relativeToElement * @param {!WebInspector.DialogDelegate} delegate */ WebInspector.Dialog.show = function(relativeToElement, delegate) { if (WebInspector.Dialog._instance) return; WebInspector.Dialog._instance = new WebInspector.Dialog(relativeToElement, delegate); } WebInspector.Dialog.hide = function() { if (!WebInspector.Dialog._instance) return; WebInspector.Dialog._instance._hide(); } WebInspector.Dialog.prototype = { focus: function() { this._element.focus(); }, _hide: function() { if (this._isHiding) return; this._isHiding = true; this._delegate.willHide(); delete WebInspector.Dialog._instance; WebInspector.GlassPane.DefaultFocusedViewStack.pop(); this._glassPane.dispose(); }, _onGlassPaneFocus: function(event) { this._hide(); }, _onFocus: function(event) { this._delegate.focus(); }, _position: function() { this._delegate.position(this._element, this._relativeToElement); }, _onKeyDown: function(event) { if (event.keyCode === WebInspector.KeyboardShortcut.Keys.Tab.code) { event.preventDefault(); return; } if (event.keyCode === WebInspector.KeyboardShortcut.Keys.Enter.code) this._delegate.onEnter(event); if (!event.handled && this._closeKeys.indexOf(event.keyCode) >= 0) { this._hide(); event.consume(true); } } }; /** * @constructor * @extends {WebInspector.Object} */ WebInspector.DialogDelegate = function() { /** @type {!Element} */ this.element; } WebInspector.DialogDelegate.prototype = { /** * @param {!Element} element */ show: function(element) { element.appendChild(this.element); this.element.classList.add("dialog-contents"); element.classList.add("dialog"); }, /** * @param {!Element} element * @param {!Element} relativeToElement */ position: function(element, relativeToElement) { var container = WebInspector.Dialog._modalHostView.element; var box = relativeToElement.boxInWindow(window).relativeToElement(container); var positionX = box.x + (relativeToElement.offsetWidth - element.offsetWidth) / 2; positionX = Number.constrain(positionX, 0, container.offsetWidth - element.offsetWidth); var positionY = box.y + (relativeToElement.offsetHeight - element.offsetHeight) / 2; positionY = Number.constrain(positionY, 0, container.offsetHeight - element.offsetHeight); element.style.position = "absolute"; element.positionAt(positionX, positionY, container); }, focus: function() { }, onEnter: function(event) { }, willHide: function() { }, __proto__: WebInspector.Object.prototype } /** @type {?WebInspector.View} */ WebInspector.Dialog._modalHostView = null; /** * @param {!WebInspector.View} view */ WebInspector.Dialog.setModalHostView = function(view) { WebInspector.Dialog._modalHostView = view; }; /** * FIXME: make utility method in Dialog, so clients use it instead of this getter. * Method should be like Dialog.showModalElement(position params, reposition callback). * @return {?WebInspector.View} */ WebInspector.Dialog.modalHostView = function() { return WebInspector.Dialog._modalHostView; }; WebInspector.Dialog.modalHostRepositioned = function() { if (WebInspector.Dialog._instance) WebInspector.Dialog._instance._position(); };
CTSRD-SOAAP/chromium-42.0.2311.135
third_party/WebKit/Source/devtools/front_end/ui/Dialog.js
JavaScript
bsd-3-clause
6,428
var fs = require('fs') , child_process = require('child_process') , _glob = require('glob') , bunch = require('./bunch') ; exports.loadEnv = function loadEnv(env, cb) { var loaders = [] function load(name, cb) { fs.readFile(env[name], function(error, data) { env[name] = env[name].match(/.*\.json$/) ? JSON.parse(data) : data; cb(error, data) }) } for (var name in env) { loaders.push([load, name]) } bunch(loaders, cb) } exports.commandActor = function command(executable) { return function command(args, opts, cb) { if (!cb) { cb = opts; opts = {} } var cmd = child_process.spawn(executable, args, opts); function log(b) { console.log(b.toString()) } cmd.stdout.on('data', log); cmd.stderr.on('data', log); cmd.on('exit', function(code) { if (code) { cb(new Error(executable + ' exited with status ' + code)); } else { cb(); } }); return cmd; } } exports.jsonParse = function(str, cb) { try { cb(null, JSON.parse(str)); } catch (ex) { cb(ex); } } exports.jsonStringify = function(obj, cb) { try { cb(null, JSON.stringify(obj)); } catch (ex) { cb(ex); } } exports.glob = function glob(pattern, cb) { console.log('pattern', pattern); _glob(pattern, function(error, files) { cb(error, [files]); }); }
KhaosT/node_mdns
utils/lib/actors.js
JavaScript
mit
1,375
Function.prototype.bind = Function.prototype.bind || function (target) { var self = this; return function (args) { if (!(args instanceof Array)) { args = [args]; } self.apply(target, args); }; };
ThatSonnyD/brad-pitt-2048
tile-sets/brad pitt/js/bind_polyfill.js
JavaScript
mit
229
// DATA_TEMPLATE: js_data oTest.fnStart( "oLanguage.oPaginate" ); /* Note that the paging language information only has relevence in full numbers */ $(document).ready( function () { /* Check the default */ var oTable = $('#example').dataTable( { "aaData": gaaData, "sPaginationType": "full_numbers" } ); var oSettings = oTable.fnSettings(); oTest.fnTest( "oLanguage.oPaginate defaults", null, function () { var bReturn = oSettings.oLanguage.oPaginate.sFirst == "First" && oSettings.oLanguage.oPaginate.sPrevious == "Previous" && oSettings.oLanguage.oPaginate.sNext == "Next" && oSettings.oLanguage.oPaginate.sLast == "Last"; return bReturn; } ); oTest.fnTest( "oLanguage.oPaginate defaults are in the DOM", null, function () { var bReturn = $('#example_paginate .first').html() == "First" && $('#example_paginate .previous').html() == "Previous" && $('#example_paginate .next').html() == "Next" && $('#example_paginate .last').html() == "Last"; return bReturn; } ); oTest.fnTest( "oLanguage.oPaginate can be defined", function () { oSession.fnRestore(); oTable = $('#example').dataTable( { "aaData": gaaData, "sPaginationType": "full_numbers", "oLanguage": { "oPaginate": { "sFirst": "unit1", "sPrevious": "test2", "sNext": "unit3", "sLast": "test4" } } } ); oSettings = oTable.fnSettings(); }, function () { var bReturn = oSettings.oLanguage.oPaginate.sFirst == "unit1" && oSettings.oLanguage.oPaginate.sPrevious == "test2" && oSettings.oLanguage.oPaginate.sNext == "unit3" && oSettings.oLanguage.oPaginate.sLast == "test4"; return bReturn; } ); oTest.fnTest( "oLanguage.oPaginate definitions are in the DOM", null, function () { var bReturn = $('#example_paginate .first').html() == "unit1" && $('#example_paginate .previous').html() == "test2" && $('#example_paginate .next').html() == "unit3" && $('#example_paginate .last').html() == "test4"; return bReturn; } ); oTest.fnComplete(); } );
desarrollotissat/web-interface
web/js/DataTables-1.9.4/media/unit_testing/tests_onhold/2_js/oLanguage.oPaginate.js
JavaScript
mit
2,212
module.exports={title:"Google Hangouts",hex:"0C9D58",source:"https://material.google.com/resources/sticker-sheets-icons.html#sticker-sheets-icons-components",svg:'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Google Hangouts icon</title><path d="M12 0C6.2 0 1.5 4.7 1.5 10.5c0 5.5 5 10 10.5 10V24c6.35-3.1 10.5-8.2 10.5-13.5C22.5 4.7 17.8 0 12 0zm-.5 12c0 1.4-.9 2.5-2 2.5V12H7V7.5h4.5V12zm6 0c0 1.4-.9 2.5-2 2.5V12H13V7.5h4.5V12z"/></svg>'};
cdnjs/cdnjs
ajax/libs/simple-icons/1.9.28/googlehangouts.min.js
JavaScript
mit
474
/** * Notification.js * * Released under LGPL License. * Copyright (c) 1999-2015 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ /** * Creates a notification instance. * * @-x-less Notification.less * @class tinymce.ui.Notification * @extends tinymce.ui.Container * @mixes tinymce.ui.Movable */ define("tinymce/ui/Notification", [ "tinymce/ui/Control", "tinymce/ui/Movable", "tinymce/ui/Progress", "tinymce/util/Delay" ], function(Control, Movable, Progress, Delay) { return Control.extend({ Mixins: [Movable], Defaults: { classes: 'widget notification' }, init: function(settings) { var self = this; self._super(settings); if (settings.text) { self.text(settings.text); } if (settings.icon) { self.icon = settings.icon; } if (settings.color) { self.color = settings.color; } if (settings.type) { self.classes.add('notification-' + settings.type); } if (settings.timeout && (settings.timeout < 0 || settings.timeout > 0) && !settings.closeButton) { self.closeButton = false; } else { self.classes.add('has-close'); self.closeButton = true; } if (settings.progressBar) { self.progressBar = new Progress(); } self.on('click', function(e) { if (e.target.className.indexOf(self.classPrefix + 'close') != -1) { self.close(); } }); }, /** * Renders the control as a HTML string. * * @method renderHtml * @return {String} HTML representing the control. */ renderHtml: function() { var self = this, prefix = self.classPrefix, icon = '', closeButton = '', progressBar = '', notificationStyle = ''; if (self.icon) { icon = '<i class="' + prefix + 'ico' + ' ' + prefix + 'i-' + self.icon + '"></i>'; } if (self.color) { notificationStyle = ' style="background-color: ' + self.color + '"'; } if (self.closeButton) { closeButton = '<button type="button" class="' + prefix + 'close" aria-hidden="true">\u00d7</button>'; } if (self.progressBar) { progressBar = self.progressBar.renderHtml(); } return ( '<div id="' + self._id + '" class="' + self.classes + '"' + notificationStyle + ' role="presentation">' + icon + '<div class="' + prefix + 'notification-inner">' + self.state.get('text') + '</div>' + progressBar + closeButton + '</div>' ); }, postRender: function() { var self = this; Delay.setTimeout(function() { self.$el.addClass(self.classPrefix + 'in'); }); return self._super(); }, bindStates: function() { var self = this; self.state.on('change:text', function(e) { self.getEl().childNodes[1].innerHTML = e.value; }); if (self.progressBar) { self.progressBar.bindStates(); } return self._super(); }, close: function() { var self = this; if (!self.fire('close').isDefaultPrevented()) { self.remove(); } return self; }, /** * Repaints the control after a layout operation. * * @method repaint */ repaint: function() { var self = this, style, rect; style = self.getEl().style; rect = self._layoutRect; style.left = rect.x + 'px'; style.top = rect.y + 'px'; // Hardcoded arbitrary z-value because we want the // notifications under the other windows style.zIndex = 0xFFFF - 1; } }); });
luis-knd/technoMvc
views/tinymce/js/tinymce/classes/ui/Notification.js
JavaScript
gpl-2.0
3,429
const path = require('path'); const fs = require('fs'); const EventEmitter = require('events').EventEmitter; const Shard = require('./Shard'); const Collection = require('../util/Collection'); const Util = require('../util/Util'); /** * This is a utility class that can be used to help you spawn shards of your client. Each shard is completely separate * from the other. The Shard Manager takes a path to a file and spawns it under the specified amount of shards safely. * If you do not select an amount of shards, the manager will automatically decide the best amount. * @extends {EventEmitter} */ class ShardingManager extends EventEmitter { /** * @param {string} file Path to your shard script file * @param {Object} [options] Options for the sharding manager * @param {number|string} [options.totalShards='auto'] Number of shards to spawn, or "auto" * @param {boolean} [options.respawn=true] Whether shards should automatically respawn upon exiting * @param {string[]} [options.shardArgs=[]] Arguments to pass to the shard script when spawning * @param {string} [options.token] Token to use for automatic shard count and passing to shards */ constructor(file, options = {}) { super(); options = Util.mergeDefault({ totalShards: 'auto', respawn: true, shardArgs: [], token: null, }, options); /** * Path to the shard script file * @type {string} */ this.file = file; if (!file) throw new Error('File must be specified.'); if (!path.isAbsolute(file)) this.file = path.resolve(process.cwd(), file); const stats = fs.statSync(this.file); if (!stats.isFile()) throw new Error('File path does not point to a file.'); /** * Amount of shards that this manager is going to spawn * @type {number|string} */ this.totalShards = options.totalShards; if (this.totalShards !== 'auto') { if (typeof this.totalShards !== 'number' || isNaN(this.totalShards)) { throw new TypeError('Amount of shards must be a number.'); } if (this.totalShards < 1) throw new RangeError('Amount of shards must be at least 1.'); if (this.totalShards !== Math.floor(this.totalShards)) { throw new RangeError('Amount of shards must be an integer.'); } } /** * Whether shards should automatically respawn upon exiting * @type {boolean} */ this.respawn = options.respawn; /** * An array of arguments to pass to shards * @type {string[]} */ this.shardArgs = options.shardArgs; /** * Token to use for obtaining the automatic shard count, and passing to shards * @type {?string} */ this.token = options.token ? options.token.replace(/^Bot\s*/i, '') : null; /** * A collection of shards that this manager has spawned * @type {Collection<number, Shard>} */ this.shards = new Collection(); } /** * Spawns a single shard. * @param {number} id The ID of the shard to spawn. **This is usually not necessary** * @returns {Promise<Shard>} */ createShard(id = this.shards.size) { const shard = new Shard(this, id, this.shardArgs); this.shards.set(id, shard); /** * Emitted upon launching a shard. * @event ShardingManager#launch * @param {Shard} shard Shard that was launched */ this.emit('launch', shard); return Promise.resolve(shard); } /** * Spawns multiple shards. * @param {number} [amount=this.totalShards] Number of shards to spawn * @param {number} [delay=7500] How long to wait in between spawning each shard (in milliseconds) * @returns {Promise<Collection<number, Shard>>} */ spawn(amount = this.totalShards, delay = 7500) { if (amount === 'auto') { return Util.fetchRecommendedShards(this.token).then(count => { this.totalShards = count; return this._spawn(count, delay); }); } else { if (typeof amount !== 'number' || isNaN(amount)) throw new TypeError('Amount of shards must be a number.'); if (amount < 1) throw new RangeError('Amount of shards must be at least 1.'); if (amount !== Math.floor(amount)) throw new TypeError('Amount of shards must be an integer.'); return this._spawn(amount, delay); } } /** * Actually spawns shards, unlike that poser above >:( * @param {number} amount Number of shards to spawn * @param {number} delay How long to wait in between spawning each shard (in milliseconds) * @returns {Promise<Collection<number, Shard>>} * @private */ _spawn(amount, delay) { return new Promise(resolve => { if (this.shards.size >= amount) throw new Error(`Already spawned ${this.shards.size} shards.`); this.totalShards = amount; this.createShard(); if (this.shards.size >= this.totalShards) { resolve(this.shards); return; } if (delay <= 0) { while (this.shards.size < this.totalShards) this.createShard(); resolve(this.shards); } else { const interval = setInterval(() => { this.createShard(); if (this.shards.size >= this.totalShards) { clearInterval(interval); resolve(this.shards); } }, delay); } }); } /** * Send a message to all shards. * @param {*} message Message to be sent to the shards * @returns {Promise<Shard[]>} */ broadcast(message) { const promises = []; for (const shard of this.shards.values()) promises.push(shard.send(message)); return Promise.all(promises); } /** * Evaluates a script on all shards, in the context of the Clients. * @param {string} script JavaScript to run on each shard * @returns {Promise<Array>} Results of the script execution */ broadcastEval(script) { const promises = []; for (const shard of this.shards.values()) promises.push(shard.eval(script)); return Promise.all(promises); } /** * Fetches a client property value of each shard. * @param {string} prop Name of the client property to get, using periods for nesting * @returns {Promise<Array>} * @example * manager.fetchClientValues('guilds.size') * .then(results => { * console.log(`${results.reduce((prev, val) => prev + val, 0)} total guilds`); * }) * .catch(console.error); */ fetchClientValues(prop) { if (this.shards.size === 0) return Promise.reject(new Error('No shards have been spawned.')); if (this.shards.size !== this.totalShards) return Promise.reject(new Error('Still spawning shards.')); const promises = []; for (const shard of this.shards.values()) promises.push(shard.fetchClientValue(prop)); return Promise.all(promises); } } module.exports = ShardingManager;
willkiller13/RivoBot
sharding/ShardingManager.js
JavaScript
apache-2.0
6,803
/** * Copyright (c) 2015-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. */ 'use strict'; const path = require('../fastpath'); const getPlatformExtension = require('./getPlatformExtension'); function getAssetDataFromName(filename, platforms) { const ext = path.extname(filename); const platformExt = getPlatformExtension(filename, platforms); let pattern = '@([\\d\\.]+)x'; if (platformExt != null) { pattern += '(\\.' + platformExt + ')?'; } pattern += '\\' + ext + '$'; const re = new RegExp(pattern); const match = filename.match(re); let resolution; if (!(match && match[1])) { resolution = 1; } else { resolution = parseFloat(match[1], 10); if (isNaN(resolution)) { resolution = 1; } } let assetName; if (match) { assetName = filename.replace(re, ext); } else if (platformExt != null) { assetName = filename.replace(new RegExp(`\\.${platformExt}\\${ext}`), ext); } else { assetName = filename; } return { resolution: resolution, assetName: assetName, type: ext.slice(1), name: path.basename(assetName, ext), platform: platformExt, }; } module.exports = getAssetDataFromName;
facebook/node-haste
src/lib/getAssetDataFromName.js
JavaScript
bsd-3-clause
1,418
var utils = require('../../lib/utils'); // if they agree to the ULA, notify hubspot, create a trial and send verification link module.exports = function trialSignup(request, reply) { var postToHubspot = request.server.methods.npme.sendData, getCustomer = request.server.methods.npme.getCustomer; var opts = {}; var data = { hs_context: { pageName: "enterprise-trial-signup", ipAddress: utils.getUserIP(request) }, // we can trust the email is fine because we've verified it in the show-ula handler email: request.payload.customer_email, }; postToHubspot(process.env.HUBSPOT_FORM_NPME_AGREED_ULA, data, function(er) { if (er) { request.logger.error('Could not hit ULA notification form on Hubspot'); request.logger.error(er); reply.view('errors/internal', opts).code(500); return; } getCustomer(data.email, function(err, customer) { if (err) { request.logger.error('Unknown problem with customer record'); request.logger.error(err); reply.view('errors/internal', opts).code(500); return; } if (!customer) { request.logger.error('Unable to locate customer error ' + data.email); reply.view('errors/internal', opts).code(500); return; } if (customer && customer.id + '' === request.payload.customer_id + '') { return createTrialAccount(request, reply, customer); } request.logger.error('Unable to verify customer record ', data.email); reply.view('errors/internal', opts).code(500); }); }); }; function createTrialAccount(request, reply, customer) { var createTrial = request.server.methods.npme.createTrial; var opts = {}; createTrial(customer, function(er, trial) { if (er) { request.logger.error('There was an error with creating a trial for ', customer.id); request.logger.error(er); reply.view('errors/internal', opts).code(500); return; } return sendVerificationEmail(request, reply, customer, trial); }); } function sendVerificationEmail(request, reply, customer, trial) { var opts = {}; var sendEmail = request.server.methods.email.send; var user = { name: customer.name, email: customer.email, verification_key: trial.verification_key }; sendEmail('npme-trial-verification', user, request.redis) .catch(function(er) { request.logger.error('Unable to send verification email to ', customer); request.logger.error(er); reply.view('errors/internal', opts).code(500); return; }) .then(function() { return reply.view('enterprise/thanks', opts); }); }
AgtLucas/newww
facets/enterprise/show-trial-signup.js
JavaScript
isc
2,680
var insert = require('./insert') var concat = require('concat-stream') insert('aggregate', [{ name: 'Squirtle', type: 'water' }, { name: 'Starmie', type: 'water' }, { name: 'Charmander', type: 'fire' }, { name: 'Lapras', type: 'water' }], function (db, t, done) { db.a.aggregate([{$group: {_id: '$type'}}, {$project: { _id: 0, foo: '$_id' }}], function (err, types) { console.log(err, types) var arr = types.map(function (x) {return x.foo}) console.log('arr', arr) t.equal(types.length, 2) console.log('here') t.notEqual(arr.indexOf('fire'), -1) console.log('there') t.notEqual(arr.indexOf('water'), -1) console.log('where') // test as a stream var strm = db.a.aggregate([{$group: {_id: '$type'}}, {$project: {_id: 0, foo: '$_id'}}]) strm.pipe(concat(function (types) { var arr = types.map(function (x) {return x.foo}) t.equal(types.length, 2) t.notEqual(arr.indexOf('fire'), -1) t.notEqual(arr.indexOf('water'), -1) t.end() })) strm.on('error', function (err) { // Aggregation cursors are only supported on mongodb 2.6+ // this shouldn't fail the tests for other versions of mongodb if (err.message === 'unrecognized field "cursor') t.ok(1) else t.fail(err) t.end() }) }) })
AMKohn/mongojs
test/test-aggregate-pipeline.js
JavaScript
mit
1,310
import {addClass, hasClass, empty} from './../helpers/dom/element'; import {eventManager as eventManagerObject} from './../eventManager'; import {getRenderer, registerRenderer} from './../renderers'; import {WalkontableCellCoords} from './../3rdparty/walkontable/src/cell/coords'; var clonableWRAPPER = document.createElement('DIV'); clonableWRAPPER.className = 'htAutocompleteWrapper'; var clonableARROW = document.createElement('DIV'); clonableARROW.className = 'htAutocompleteArrow'; // workaround for https://github.com/handsontable/handsontable/issues/1946 // this is faster than innerHTML. See: https://github.com/handsontable/handsontable/wiki/JavaScript-&-DOM-performance-tips clonableARROW.appendChild(document.createTextNode(String.fromCharCode(9660))); var wrapTdContentWithWrapper = function(TD, WRAPPER) { WRAPPER.innerHTML = TD.innerHTML; empty(TD); TD.appendChild(WRAPPER); }; /** * Autocomplete renderer * * @private * @renderer AutocompleteRenderer * @param {Object} instance Handsontable instance * @param {Element} TD Table cell where to render * @param {Number} row * @param {Number} col * @param {String|Number} prop Row object property name * @param value Value to render (remember to escape unsafe HTML before inserting to DOM!) * @param {Object} cellProperties Cell properites (shared by cell renderer and editor) */ function autocompleteRenderer(instance, TD, row, col, prop, value, cellProperties) { var WRAPPER = clonableWRAPPER.cloneNode(true); //this is faster than createElement var ARROW = clonableARROW.cloneNode(true); //this is faster than createElement getRenderer('text')(instance, TD, row, col, prop, value, cellProperties); TD.appendChild(ARROW); addClass(TD, 'htAutocomplete'); if (!TD.firstChild) { //http://jsperf.com/empty-node-if-needed //otherwise empty fields appear borderless in demo/renderers.html (IE) TD.appendChild(document.createTextNode(String.fromCharCode(160))); // workaround for https://github.com/handsontable/handsontable/issues/1946 //this is faster than innerHTML. See: https://github.com/handsontable/handsontable/wiki/JavaScript-&-DOM-performance-tips } if (!instance.acArrowListener) { var eventManager = eventManagerObject(instance); //not very elegant but easy and fast instance.acArrowListener = function(event) { if (hasClass(event.target, 'htAutocompleteArrow')) { instance.view.wt.getSetting('onCellDblClick', null, new WalkontableCellCoords(row, col), TD); } }; eventManager.addEventListener(instance.rootElement, 'mousedown', instance.acArrowListener); //We need to unbind the listener after the table has been destroyed instance.addHookOnce('afterDestroy', function() { eventManager.destroy(); }); } } export {autocompleteRenderer}; registerRenderer('autocomplete', autocompleteRenderer);
pingyuanChen/handsontable
src/renderers/autocompleteRenderer.js
JavaScript
mit
2,882
var one = { name: 'one' };
inodient/summer-mvc
node_modules/dojo/tests/functional/_base/loader/requirejs/urlfetch/one.js
JavaScript
mit
28
var crypto = require('crypto'); var scmp = require('scmp'); var utils = require('keystone-utils'); // The DISABLE_CSRF environment variable is available to automatically pass // CSRF validation. This is useful in development scenarios where you want to // restart the node process and aren't using a persistent session store, but // should NEVER be set in production environments!! var DISABLE_CSRF = process.env.DISABLE_CSRF === 'true'; exports.TOKEN_KEY = '_csrf'; exports.LOCAL_KEY = 'csrf_token_key'; exports.LOCAL_VALUE = 'csrf_token_value'; exports.SECRET_KEY = exports.TOKEN_KEY + '_secret'; exports.SECRET_LENGTH = 10; exports.CSRF_HEADER_KEY = 'x-csrf-token'; exports.XSRF_HEADER_KEY = 'x-xsrf-token'; exports.XSRF_COOKIE_KEY = 'XSRF-TOKEN'; function tokenize (salt, secret) { return salt + crypto.createHash('sha1').update(salt + secret).digest('hex'); } exports.createSecret = function () { return crypto.pseudoRandomBytes(exports.SECRET_LENGTH).toString('base64'); }; exports.getSecret = function (req) { return req.session[exports.SECRET_KEY] || (req.session[exports.SECRET_KEY] = exports.createSecret()); }; exports.createToken = function (req) { return tokenize(utils.randomString(exports.SECRET_LENGTH), exports.getSecret(req)); }; exports.getToken = function (req, res) { res.locals[exports.LOCAL_VALUE] = res.locals[exports.LOCAL_VALUE] || exports.createToken(req); res.cookie(exports.XSRF_COOKIE_KEY, res.locals[exports.LOCAL_VALUE]); return res.locals[exports.LOCAL_VALUE]; }; exports.requestToken = function (req) { if (req.body && req.body[exports.TOKEN_KEY]) { return req.body[exports.TOKEN_KEY]; } else if (req.query && req.query[exports.TOKEN_KEY]) { return req.query[exports.TOKEN_KEY]; } else if (req.headers && req.headers[exports.XSRF_HEADER_KEY]) { return req.headers[exports.XSRF_HEADER_KEY]; } else if (req.headers && req.headers[exports.CSRF_HEADER_KEY]) { return req.headers[exports.CSRF_HEADER_KEY]; } return ''; }; exports.validate = function (req, token) { // Allow environment variable to disable check if (DISABLE_CSRF) return true; if (arguments.length === 1) { token = exports.requestToken(req); } if (typeof token !== 'string') { return false; } return scmp(token, tokenize(token.slice(0, exports.SECRET_LENGTH), req.session[exports.SECRET_KEY])); }; exports.middleware = { init: function (req, res, next) { res.locals[exports.LOCAL_KEY] = exports.LOCAL_VALUE; exports.getToken(req, res); next(); }, validate: function (req, res, next) { // Allow environment variable to disable check if (DISABLE_CSRF) return next(); // Bail on safe methods if (req.method === 'GET' || req.method === 'HEAD' || req.method === 'OPTIONS') { return next(); } // Validate token if (exports.validate(req)) { next(); } else { res.statusCode = 403; next(new Error('CSRF token mismatch')); } }, };
alobodig/keystone
lib/security/csrf.js
JavaScript
mit
2,898
module.exports = require("./mime-functions"); module.exports.contentTypes = require("./content-types");
stephentcannon/anonistreamr
public/node_modules/nodemailer/node_modules/mailcomposer/node_modules/mimelib-noiconv/index.js
JavaScript
apache-2.0
104
/** * @license Highstock JS v2.1.4 (2015-03-10) * Plugin for displaying a message when there is no data visible in chart. * * (c) 2010-2014 Highsoft AS * Author: Oystein Moseng * * License: www.highcharts.com/license */ (function (H) { var seriesTypes = H.seriesTypes, chartPrototype = H.Chart.prototype, defaultOptions = H.getOptions(), extend = H.extend, each = H.each; // Add language option extend(defaultOptions.lang, { noData: 'No data to display' }); // Add default display options for message defaultOptions.noData = { position: { x: 0, y: 0, align: 'center', verticalAlign: 'middle' }, attr: { }, style: { fontWeight: 'bold', fontSize: '12px', color: '#60606a' } }; /** * Define hasData functions for series. These return true if there are data points on this series within the plot area */ function hasDataPie() { return !!this.points.length; /* != 0 */ } each(['pie', 'gauge', 'waterfall', 'bubble'], function (type) { if (seriesTypes[type]) { seriesTypes[type].prototype.hasData = hasDataPie; } }); H.Series.prototype.hasData = function () { return this.visible && this.dataMax !== undefined && this.dataMin !== undefined; // #3703 }; /** * Display a no-data message. * * @param {String} str An optional message to show in place of the default one */ chartPrototype.showNoData = function (str) { var chart = this, options = chart.options, text = str || options.lang.noData, noDataOptions = options.noData; if (!chart.noDataLabel) { chart.noDataLabel = chart.renderer.label(text, 0, 0, null, null, null, null, null, 'no-data') .attr(noDataOptions.attr) .css(noDataOptions.style) .add(); chart.noDataLabel.align(extend(chart.noDataLabel.getBBox(), noDataOptions.position), false, 'plotBox'); } }; /** * Hide no-data message */ chartPrototype.hideNoData = function () { var chart = this; if (chart.noDataLabel) { chart.noDataLabel = chart.noDataLabel.destroy(); } }; /** * Returns true if there are data points within the plot area now */ chartPrototype.hasData = function () { var chart = this, series = chart.series, i = series.length; while (i--) { if (series[i].hasData() && !series[i].options.isInternal) { return true; } } return false; }; /** * Show no-data message if there is no data in sight. Otherwise, hide it. */ function handleNoData() { var chart = this; if (chart.hasData()) { chart.hideNoData(); } else { chart.showNoData(); } } /** * Add event listener to handle automatic display of no-data message */ chartPrototype.callbacks.push(function (chart) { H.addEvent(chart, 'load', handleNoData); H.addEvent(chart, 'redraw', handleNoData); }); }(Highcharts));
syscart/syscart
web/media/js/jquery/plugins/Highstock/2.1.4/js/modules/no-data-to-display.src.js
JavaScript
gpl-2.0
2,826
#!/usr/bin/env node /* global cat:true, cd:true, echo:true, exec:true, exit:true */ // Usage: // stable release: node release.js // pre-release: node release.js --pre-release {version} // test run: node release.js --remote={repo} // - repo: "/tmp/repo" (filesystem), "user/repo" (github), "http://mydomain/repo.git" (another domain) "use strict"; var baseDir, downloadBuilder, repoDir, prevVersion, newVersion, nextVersion, tagTime, preRelease, repo, fs = require( "fs" ), path = require( "path" ), rnewline = /\r?\n/, branch = "master"; walk([ bootstrap, section( "setting up repo" ), cloneRepo, checkState, section( "calculating versions" ), getVersions, confirm, section( "building release" ), buildReleaseBranch, buildPackage, section( "pushing tag" ), confirmReview, pushRelease, section( "updating branch version" ), updateBranchVersion, section( "pushing " + branch ), confirmReview, pushBranch, section( "generating changelog" ), generateChangelog, section( "gathering contributors" ), gatherContributors, section( "updating trac" ), updateTrac, confirm ]); function cloneRepo() { echo( "Cloning " + repo.cyan + "..." ); git( "clone " + repo + " " + repoDir, "Error cloning repo." ); cd( repoDir ); echo( "Checking out " + branch.cyan + " branch..." ); git( "checkout " + branch, "Error checking out branch." ); echo(); echo( "Installing dependencies..." ); if ( exec( "npm install" ).code !== 0 ) { abort( "Error installing dependencies." ); } echo(); } function checkState() { echo( "Checking AUTHORS.txt..." ); var result, lastActualAuthor, lastListedAuthor = cat( "AUTHORS.txt" ).trim().split( rnewline ).pop(); result = exec( "grunt authors", { silent: true }); if ( result.code !== 0 ) { abort( "Error getting list of authors." ); } lastActualAuthor = result.output.split( rnewline ).splice( -4, 1 )[ 0 ]; if ( lastListedAuthor !== lastActualAuthor ) { echo( "Last listed author is " + lastListedAuthor.red + "." ); echo( "Last actual author is " + lastActualAuthor.green + "." ); abort( "Please update AUTHORS.txt." ); } echo( "Last listed author (" + lastListedAuthor.cyan + ") is correct." ); } function getVersions() { // prevVersion, newVersion, nextVersion are defined in the parent scope var parts, major, minor, patch, currentVersion = readPackage().version; echo( "Validating current version..." ); if ( currentVersion.substr( -3, 3 ) !== "pre" ) { echo( "The current version is " + currentVersion.red + "." ); abort( "The version must be a pre version." ); } if ( preRelease ) { newVersion = preRelease; // Note: prevVersion is not currently used for pre-releases. prevVersion = nextVersion = currentVersion; } else { newVersion = currentVersion.substr( 0, currentVersion.length - 3 ); parts = newVersion.split( "." ); major = parseInt( parts[ 0 ], 10 ); minor = parseInt( parts[ 1 ], 10 ); patch = parseInt( parts[ 2 ], 10 ); if ( minor === 0 && patch === 0 ) { abort( "This script is not smart enough to handle major release (eg. 2.0.0)." ); } else if ( patch === 0 ) { prevVersion = git( "for-each-ref --count=1 --sort=-authordate --format='%(refname:short)' refs/tags/" + [ major, minor - 1 ].join( "." ) + "*" ).trim(); } else { prevVersion = [ major, minor, patch - 1 ].join( "." ); } nextVersion = [ major, minor, patch + 1 ].join( "." ) + "pre"; } echo( "We are going from " + prevVersion.cyan + " to " + newVersion.cyan + "." ); echo( "After the release, the version will be " + nextVersion.cyan + "." ); } function buildReleaseBranch() { var pkg; echo( "Creating " + "release".cyan + " branch..." ); git( "checkout -b release", "Error creating release branch." ); echo(); echo( "Updating package.json..." ); pkg = readPackage(); pkg.version = newVersion; pkg.author.url = pkg.author.url.replace( "master", newVersion ); pkg.licenses.forEach(function( license ) { license.url = license.url.replace( "master", newVersion ); }); writePackage( pkg ); echo( "Generating manifest files..." ); if ( exec( "grunt manifest" ).code !== 0 ) { abort( "Error generating manifest files." ); } echo(); echo( "Committing release artifacts..." ); git( "add *.jquery.json", "Error adding manifest files to git." ); git( "commit -am 'Tagging the " + newVersion + " release.'", "Error committing release changes." ); echo(); echo( "Tagging release..." ); git( "tag " + newVersion, "Error tagging " + newVersion + "." ); tagTime = git( "log -1 --format='%ad'", "Error getting tag timestamp." ).trim(); } function buildPackage( callback ) { if( preRelease ) { return buildPreReleasePackage( callback ); } else { return buildCDNPackage( callback ); } } function buildPreReleasePackage( callback ) { var build, files, jqueryUi, packer, target, targetZip; echo( "Build pre-release Package" ); jqueryUi = new downloadBuilder.JqueryUi( path.resolve( "." ) ); build = new downloadBuilder.Builder( jqueryUi, ":all:" ); packer = new downloadBuilder.Packer( build, null, { addTests: true, bundleSuffix: "", skipDocs: true, skipTheme: true }); target = "../" + jqueryUi.pkg.name + "-" + jqueryUi.pkg.version; targetZip = target + ".zip"; return walk([ function( callback ) { echo( "Building release files" ); packer.pack(function( error, _files ) { if( error ) { abort( error.stack ); } files = _files.map(function( file ) { // Strip first path file.path = file.path.replace( /^[^\/]*\//, "" ); return file; }).filter(function( file ) { // Filter development-bundle content only return (/^development-bundle/).test( file.path ); }).map(function( file ) { // Strip development-bundle file.path = file.path.replace( /^development-bundle\//, "" ); return file; }); return callback(); }); }, function() { downloadBuilder.util.createZip( files, targetZip, function( error ) { if ( error ) { abort( error.stack ); } echo( "Built zip package at " + path.relative( "../..", targetZip ).cyan ); return callback(); }); } ]); } function buildCDNPackage( callback ) { var build, output, target, targetZip, add = function( file ) { output.push( file ); }, jqueryUi = new downloadBuilder.JqueryUi( path.resolve( "." ) ), themeGallery = downloadBuilder.themeGallery( jqueryUi ); echo( "Build CDN Package" ); build = new downloadBuilder.Builder( jqueryUi, ":all:" ); output = []; target = "../" + jqueryUi.pkg.name + "-" + jqueryUi.pkg.version + "-cdn"; targetZip = target + ".zip"; [ "AUTHORS.txt", "MIT-LICENSE.txt", "package.json" ].map(function( name ) { return build.get( name ); }).forEach( add ); // "ui/*.js" build.componentFiles.filter(function( file ) { return (/^ui\//).test( file.path ); }).forEach( add ); // "ui/*.min.js" build.componentMinFiles.filter(function( file ) { return (/^ui\//).test( file.path ); }).forEach( add ); // "i18n/*.js" build.i18nFiles.rename( /^ui\//, "" ).forEach( add ); build.i18nMinFiles.rename( /^ui\//, "" ).forEach( add ); build.bundleI18n.into( "i18n/" ).forEach( add ); build.bundleI18nMin.into( "i18n/" ).forEach( add ); build.bundleJs.forEach( add ); build.bundleJsMin.forEach( add ); walk( themeGallery.map(function( theme ) { return function( callback ) { var themeCssOnlyRe, themeDirRe, folderName = theme.folderName(), packer = new downloadBuilder.Packer( build, theme, { skipDocs: true }); // TODO improve code by using custom packer instead of download packer (Packer) themeCssOnlyRe = new RegExp( "development-bundle/themes/" + folderName + "/jquery.ui.theme.css" ); themeDirRe = new RegExp( "css/" + folderName ); packer.pack(function( error, files ) { if ( error ) { abort( error.stack ); } // Add theme files. files // Pick only theme files we need on the bundle. .filter(function( file ) { if ( themeCssOnlyRe.test( file.path ) || themeDirRe.test( file.path ) ) { return true; } return false; }) // Convert paths the way bundle needs .map(function( file ) { file.path = file.path // Remove initial package name eg. "jquery-ui-1.10.0.custom" .split( "/" ).slice( 1 ).join( "/" ) .replace( /development-bundle\/themes/, "css" ) .replace( /css/, "themes" ) // Make jquery-ui-1.10.0.custom.css into jquery-ui.css, or jquery-ui-1.10.0.custom.min.css into jquery-ui.min.css .replace( /jquery-ui-.*?(\.min)*\.css/, "jquery-ui$1.css" ); return file; }).forEach( add ); return callback(); }); }; }).concat([function() { var crypto = require( "crypto" ); // Create MD5 manifest output.push({ path: "MANIFEST", data: output.sort(function( a, b ) { return a.path.localeCompare( b.path ); }).map(function( file ) { var md5 = crypto.createHash( "md5" ); md5.update( file.data ); return file.path + " " + md5.digest( "hex" ); }).join( "\n" ) }); downloadBuilder.util.createZip( output, targetZip, function( error ) { if ( error ) { abort( error.stack ); } echo( "Built zip CDN package at " + path.relative( "../..", targetZip ).cyan ); return callback(); }); }])); } function pushRelease() { echo( "Pushing release to GitHub..." ); git( "push --tags", "Error pushing tags to GitHub." ); } function updateBranchVersion() { // Pre-releases don't change the master version if ( preRelease ) { return; } var pkg; echo( "Checking out " + branch.cyan + " branch..." ); git( "checkout " + branch, "Error checking out " + branch + " branch." ); echo( "Updating package.json..." ); pkg = readPackage(); pkg.version = nextVersion; writePackage( pkg ); echo( "Committing version update..." ); git( "commit -am 'Updating the " + branch + " version to " + nextVersion + ".'", "Error committing package.json." ); } function pushBranch() { // Pre-releases don't change the master version if ( preRelease ) { return; } echo( "Pushing " + branch.cyan + " to GitHub..." ); git( "push", "Error pushing to GitHub." ); } function generateChangelog() { if ( preRelease ) { return; } var commits, changelogPath = baseDir + "/changelog", changelog = cat( "build/release/changelog-shell" ) + "\n", fullFormat = "* %s (TICKETREF, [%h](http://github.com/jquery/jquery-ui/commit/%H))"; changelog = changelog.replace( "{title}", "jQuery UI " + newVersion + " Changelog" ); echo ( "Adding commits..." ); commits = gitLog( fullFormat ); echo( "Adding links to tickets..." ); changelog += commits // Add ticket references .map(function( commit ) { var tickets = []; commit.replace( /Fixe[sd] #(\d+)/g, function( match, ticket ) { tickets.push( ticket ); }); return tickets.length ? commit.replace( "TICKETREF", tickets.map(function( ticket ) { return "[#" + ticket + "](http://bugs.jqueryui.com/ticket/" + ticket + ")"; }).join( ", " ) ) : // Leave TICKETREF token in place so it's easy to find commits without tickets commit; }) // Sort commits so that they're grouped by component .sort() .join( "\n" ) + "\n"; echo( "Adding Trac tickets..." ); changelog += trac( "/query?milestone=" + newVersion + "&resolution=fixed" + "&col=id&col=component&col=summary&order=component" ) + "\n"; fs.writeFileSync( changelogPath, changelog ); echo( "Stored changelog in " + changelogPath.cyan + "." ); } function gatherContributors() { if ( preRelease ) { return; } var contributors, contributorsPath = baseDir + "/contributors"; echo( "Adding committers and authors..." ); contributors = gitLog( "%aN%n%cN" ); echo( "Adding reporters and commenters from Trac..." ); contributors = contributors.concat( trac( "/report/22?V=" + newVersion + "&max=-1" ) .split( rnewline ) // Remove header and trailing newline .slice( 1, -1 ) ); echo( "Sorting contributors..." ); contributors = unique( contributors ).sort(function( a, b ) { return a.toLowerCase() < b.toLowerCase() ? -1 : 1; }); echo ( "Adding people thanked in commits..." ); contributors = contributors.concat( gitLog( "%b%n%s" ).filter(function( line ) { return (/thank/i).test( line ); })); fs.writeFileSync( contributorsPath, contributors.join( "\n" ) ); echo( "Stored contributors in " + contributorsPath.cyan + "." ); } function updateTrac() { echo( newVersion.cyan + " was tagged at " + tagTime.cyan + "." ); if ( !preRelease ) { echo( "Close the " + newVersion.cyan + " Milestone." ); } echo( "Create the " + newVersion.cyan + " Version." ); echo( "When Trac asks for date and time, match the above. Should only change minutes and seconds." ); echo( "Create a Milestone for the next minor release." ); } // ===== HELPER FUNCTIONS ====================================================== function git( command, errorMessage ) { var result = exec( "git " + command ); if ( result.code !== 0 ) { abort( errorMessage ); } return result.output; } function gitLog( format ) { var result = exec( "git log " + prevVersion + ".." + newVersion + " " + "--format='" + format + "'", { silent: true }); if ( result.code !== 0 ) { abort( "Error getting git log." ); } result = result.output.split( rnewline ); if ( result[ result.length - 1 ] === "" ) { result.pop(); } return result; } function trac( path ) { var result = exec( "curl -s 'http://bugs.jqueryui.com" + path + "&format=tab'", { silent: true }); if ( result.code !== 0 ) { abort( "Error getting Trac data." ); } return result.output; } function unique( arr ) { var obj = {}; arr.forEach(function( item ) { obj[ item ] = 1; }); return Object.keys( obj ); } function readPackage() { return JSON.parse( fs.readFileSync( repoDir + "/package.json" ) ); } function writePackage( pkg ) { fs.writeFileSync( repoDir + "/package.json", JSON.stringify( pkg, null, "\t" ) + "\n" ); } function bootstrap( fn ) { getRemote(function( remote ) { if ( (/:/).test( remote ) || fs.existsSync( remote ) ) { repo = remote; } else { repo = "[email protected]:" + remote + ".git"; } _bootstrap( fn ); }); } function getRemote( fn ) { var matches, remote; console.log( "Determining remote repo..." ); process.argv.forEach(function( arg ) { matches = /--remote=(.+)/.exec( arg ); if ( matches ) { remote = matches[ 1 ]; } }); if ( remote ) { fn( remote ); return; } console.log(); console.log( " !!!!!!!!!!!!!!!!!!!!!!!!!!!!" ); console.log( " !!!!!!!!!!!!!!!!!!!!!!!!!!!!" ); console.log( " !! !!" ); console.log( " !! Using jquery/jquery-ui !!" ); console.log( " !! !!" ); console.log( " !!!!!!!!!!!!!!!!!!!!!!!!!!!!" ); console.log( " !!!!!!!!!!!!!!!!!!!!!!!!!!!!" ); console.log(); console.log( "Press enter to continue, or ctrl+c to cancel." ); prompt(function() { fn( "jquery/jquery-ui" ); }); } function _bootstrap( fn ) { console.log( "Determining release type..." ); preRelease = process.argv.indexOf( "--pre-release" ); if ( preRelease !== -1 ) { preRelease = process.argv[ preRelease + 1 ]; console.log( "pre-release" ); } else { preRelease = null; console.log( "stable release" ); } console.log( "Determining directories..." ); baseDir = process.cwd() + "/__release"; repoDir = baseDir + "/repo"; if ( fs.existsSync( baseDir ) ) { console.log( "The directory '" + baseDir + "' already exists." ); console.log( "Aborting." ); process.exit( 1 ); } console.log( "Creating directory..." ); fs.mkdirSync( baseDir ); console.log( "Installing dependencies..." ); require( "child_process" ).exec( "npm install shelljs colors [email protected]", function( error ) { if ( error ) { console.log( error ); return process.exit( 1 ); } require( "shelljs/global" ); require( "colors" ); downloadBuilder = require( "download.jqueryui.com" ); fn(); }); } function section( name ) { return function() { echo(); echo( "##" ); echo( "## " + name.toUpperCase().magenta ); echo( "##" ); echo(); }; } function prompt( fn ) { process.stdin.once( "data", function( chunk ) { process.stdin.pause(); fn( chunk.toString().trim() ); }); process.stdin.resume(); } function confirm( fn ) { echo( "Press enter to continue, or ctrl+c to cancel.".yellow ); prompt( fn ); } function confirmReview( fn ) { echo( "Please review the output and generated files as a sanity check.".yellow ); confirm( fn ); } function abort( msg ) { echo( msg.red ); echo( "Aborting.".red ); exit( 1 ); } function walk( methods ) { var method = methods.shift(); function next() { if ( methods.length ) { walk( methods ); } } if ( !method.length ) { method(); next(); } else { method( next ); } }
yuyang545262477/Resume
项目三jQueryMobile/bower_components/jquery-ui/build/release/release.js
JavaScript
mit
16,898
(function ($) { $.Redactor.opts.langs['el'] = { html: 'HTML', video: 'Εισαγωγή βίντεο...', image: 'Εισαγωγή εικόνας...', table: 'Πίνακας', link: 'Σύνδεσμος', link_insert: 'Εισαγωγή συνδέσμου...', link_edit: 'Edit link', unlink: 'Ακύρωση συνδέσμου', formatting: 'Μορφοποίηση', paragraph: 'Παράγραφος', quote: 'Παράθεση', code: 'Κώδικας', header1: 'Κεφαλίδα 1', header2: 'Κεφαλίδα 2', header3: 'Κεφαλίδα 3', header4: 'Κεφαλίδα 4', bold: 'Έντονα', italic: 'Πλάγια', fontcolor: 'Χρώμα γραμματοσειράς', backcolor: 'Χρώμα επισήμανσης κειμένου', unorderedlist: 'Κουκκίδες', orderedlist: 'Αρίθμηση', outdent: 'Μείωση εσοχής', indent: 'Αύξηση εσοχής', cancel: 'Ακύρωση', insert: 'Εισαγωγή', save: 'Αποθήκευση', _delete: 'Διαγραφή', insert_table: 'Εισαγωγή πίνακα...', insert_row_above: 'Προσθήκη σειράς επάνω', insert_row_below: 'Προσθήκη σειράς κάτω', insert_column_left: 'Προσθήκη στήλης αριστερά', insert_column_right: 'Προσθήκη στήλης δεξιά', delete_column: 'Διαγραφή στήλης', delete_row: 'Διαγραφή σειράς', delete_table: 'Διαγραφή πίνακα', rows: 'Γραμμές', columns: 'Στήλες', add_head: 'Προσθήκη κεφαλίδας', delete_head: 'Διαγραφή κεφαλίδας', title: 'Τίτλος', image_position: 'Θέση', none: 'Καμία', left: 'Αριστερά', right: 'Δεξιά', image_web_link: 'Υπερσύνδεσμος εικόνας', text: 'Κείμενο', mailto: 'Email', web: 'URL', video_html_code: 'Video Embed Code', file: 'Εισαγωγή αρχείου...', upload: 'Upload', download: 'Download', choose: 'Επέλεξε', or_choose: 'ή επέλεξε', drop_file_here: 'Σύρατε αρχεία εδώ', align_left: 'Στοίχιση αριστερά', align_center: 'Στοίχιση στο κέντρο', align_right: 'Στοίχιση δεξιά', align_justify: 'Πλήρησ στοίχηση', horizontalrule: 'Εισαγωγή οριζόντιας γραμμής', deleted: 'Διαγράφτηκε', anchor: 'Anchor', link_new_tab: 'Open link in new tab', underline: 'Underline', alignment: 'Alignment', filename: 'Name (optional)', edit: 'Edit' }; })( jQuery );
sho-wtag/catarse-2.0
vendor/cache/redactor-rails-e79c3b8359b4/vendor/assets/javascripts/redactor-rails/langs/el.js
JavaScript
mit
2,592
import Ember from 'ember-metal/core'; import { get } from 'ember-metal/property_get'; import { internal } from 'htmlbars-runtime'; import { read } from 'ember-metal/streams/utils'; export default { setupState(state, env, scope, params, hash) { var controller = hash.controller; if (controller) { if (!state.controller) { var context = params[0]; var controllerFactory = env.container.lookupFactory('controller:' + controller); var parentController = null; if (scope.locals.controller) { parentController = read(scope.locals.controller); } else if (scope.locals.view) { parentController = get(read(scope.locals.view), 'context'); } var controllerInstance = controllerFactory.create({ model: env.hooks.getValue(context), parentController: parentController, target: parentController }); params[0] = controllerInstance; return { controller: controllerInstance }; } return state; } return { controller: null }; }, isStable() { return true; }, isEmpty(state) { return false; }, render(morph, env, scope, params, hash, template, inverse, visitor) { if (morph.state.controller) { morph.addDestruction(morph.state.controller); hash.controller = morph.state.controller; } Ember.assert( '{{#with foo}} must be called with a single argument or the use the ' + '{{#with foo as |bar|}} syntax', params.length === 1 ); Ember.assert( 'The {{#with}} helper must be called with a block', !!template ); internal.continueBlock(morph, env, scope, 'with', params, hash, template, inverse, visitor); }, rerender(morph, env, scope, params, hash, template, inverse, visitor) { internal.continueBlock(morph, env, scope, 'with', params, hash, template, inverse, visitor); } };
cjc343/ember.js
packages/ember-htmlbars/lib/keywords/with.js
JavaScript
mit
1,930
Prism.languages.bbcode={tag:{pattern:/\[\/?[^\s=\]]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'"\]=]+))?(?:\s+[^\s=\]]+\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'"\]=]+))*\s*\]/,inside:{tag:{pattern:/^\[\/?[^\s=\]]+/,inside:{punctuation:/^\[\/?/}},"attr-value":{pattern:/=\s*(?:"[^"]*"|'[^']*'|[^\s'"\]=]+)/i,inside:{punctuation:[/^=/,{pattern:/^(\s*)["']|["']$/,lookbehind:!0}]}},punctuation:/\]/,"attr-name":/[^\s=\]]+/}}},Prism.languages.shortcode=Prism.languages.bbcode;
BigBoss424/portfolio
v7/development/node_modules/prismjs/components/prism-bbcode.min.js
JavaScript
apache-2.0
453
/** * Copyright 2017 The AMP HTML Authors. All Rights Reserved. * * 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. */ const POST_PARAMS = { 'embedtype': 'post', 'hash': 'Yc8_Z9pnpg8aKMZbVcD-jK45eAk', 'owner-id': '1', 'post-id': '45616', }; const POLL_PARAMS = { 'embedtype': 'poll', 'api-id': '6183531', 'poll-id': '274086843_1a2a465f60fff4699f', }; import '../amp-vk'; import {Layout} from '../../../../src/layout'; import {Resource} from '../../../../src/service/resource'; describes.realWin('amp-vk', { amp: { extensions: ['amp-vk'], }, }, env => { let win, doc; beforeEach(() => { win = env.win; doc = win.document; }); function createAmpVkElement(dataParams, layout) { const element = doc.createElement('amp-vk'); for (const param in dataParams) { element.setAttribute(`data-${param}`, dataParams[param]); } element.setAttribute('width', 500); element.setAttribute('height', 300); if (layout) { element.setAttribute('layout', layout); } doc.body.appendChild(element); return element.build().then(() => { const resource = Resource.forElement(element); resource.measure(); return element.layoutCallback(); }).then(() => element); } it('requires data-embedtype', () => { const params = Object.assign({}, POST_PARAMS); delete params['embedtype']; return createAmpVkElement(params).should.eventually.be.rejectedWith( /The data-embedtype attribute is required for/); }); it('removes iframe after unlayoutCallback', () => { return createAmpVkElement(POST_PARAMS).then(vkPost => { const iframe = vkPost.querySelector('iframe'); expect(iframe).to.not.be.null; const obj = vkPost.implementation_; obj.unlayoutCallback(); expect(vkPost.querySelector('iframe')).to.be.null; expect(obj.iframe_).to.be.null; expect(obj.unlayoutOnPause()).to.be.true; }); }); // Post tests it('post::requires data-hash', () => { const params = Object.assign({}, POST_PARAMS); delete params['hash']; return createAmpVkElement(params).should.eventually.be.rejectedWith( /The data-hash attribute is required for/); }); it('post::requires data-owner-id', () => { const params = Object.assign({}, POST_PARAMS); delete params['owner-id']; return createAmpVkElement(params).should.eventually.be.rejectedWith( /The data-owner-id attribute is required for/); }); it('post::requires data-post-id', () => { const params = Object.assign({}, POST_PARAMS); delete params['post-id']; return createAmpVkElement(params).should.eventually.be.rejectedWith( /The data-post-id attribute is required for/); }); it('post::renders iframe in amp-vk', () => { return createAmpVkElement(POST_PARAMS).then(vkPost => { const iframe = vkPost.querySelector('iframe'); expect(iframe).to.not.be.null; }); }); it('post::renders responsively', () => { return createAmpVkElement(POST_PARAMS, Layout.RESPONSIVE).then(vkPost => { const iframe = vkPost.querySelector('iframe'); expect(iframe).to.not.be.null; expect(iframe.className).to.match(/i-amphtml-fill-content/); }); }); it('post::sets correct src url to the vk iFrame', () => { return createAmpVkElement(POST_PARAMS, Layout.RESPONSIVE).then(vkPost => { const impl = vkPost.implementation_; const iframe = vkPost.querySelector('iframe'); const referrer = encodeURIComponent(vkPost.ownerDocument.referrer); const url = encodeURIComponent( vkPost.ownerDocument.location.href.replace(/#.*$/, '') ); impl.onLayoutMeasure(); const startWidth = impl.getLayoutWidth(); const correctIFrameSrc = `https://vk.com/widget_post.php?app=0&width=100%25\ &_ver=1&owner_id=1&post_id=45616&hash=Yc8_Z9pnpg8aKMZbVcD-jK45eAk&amp=1\ &startWidth=${startWidth}&url=${url}&referrer=${referrer}&title=AMP%20Post`; expect(iframe).to.not.be.null; const timeArgPosition = iframe.src.lastIndexOf('&'); const iframeSrcWithoutTime = iframe.src.substr(0, timeArgPosition); expect(iframeSrcWithoutTime).to.equal(correctIFrameSrc); }); }); // Poll tests it('poll::requires data-api-id', () => { const params = Object.assign({}, POLL_PARAMS); delete params['api-id']; return createAmpVkElement(params).should.eventually.be.rejectedWith( /The data-api-id attribute is required for/); }); it('poll::requires data-poll-id', () => { const params = Object.assign({}, POLL_PARAMS); delete params['poll-id']; return createAmpVkElement(params).should.eventually.be.rejectedWith( /The data-poll-id attribute is required for/); }); it('poll::renders iframe in amp-vk', () => { return createAmpVkElement(POLL_PARAMS).then(vkPoll => { const iframe = vkPoll.querySelector('iframe'); expect(iframe).to.not.be.null; }); }); it('poll::renders responsively', () => { return createAmpVkElement(POLL_PARAMS, Layout.RESPONSIVE).then(vkPoll => { const iframe = vkPoll.querySelector('iframe'); expect(iframe).to.not.be.null; expect(iframe.className).to.match(/i-amphtml-fill-content/); }); }); it('poll::sets correct src url to the vk iFrame', () => { return createAmpVkElement(POLL_PARAMS, Layout.RESPONSIVE).then(vkPoll => { const iframe = vkPoll.querySelector('iframe'); const referrer = encodeURIComponent(vkPoll.ownerDocument.referrer); const url = encodeURIComponent( vkPoll.ownerDocument.location.href.replace(/#.*$/, '') ); const correctIFrameSrc = `https://vk.com/al_widget_poll.php?\ app=6183531&width=100%25&_ver=1&poll_id=274086843_1a2a465f60fff4699f&amp=1\ &url=${url}&title=AMP%20Poll&description=&referrer=${referrer}`; expect(iframe).to.not.be.null; const timeArgPosition = iframe.src.lastIndexOf('&'); const iframeSrcWithoutTime = iframe.src.substr(0, timeArgPosition); expect(iframeSrcWithoutTime).to.equal(correctIFrameSrc); }); }); it('both::resizes amp-vk element in response to postmessages', () => { return createAmpVkElement(POLL_PARAMS).then(vkPoll => { const impl = vkPoll.implementation_; const iframe = vkPoll.querySelector('iframe'); const changeHeight = sandbox.spy(impl, 'changeHeight'); const fakeHeight = 555; expect(iframe).to.not.be.null; generatePostMessage(vkPoll, iframe, fakeHeight); expect(changeHeight).to.be.calledOnce; expect(changeHeight.firstCall.args[0]).to.equal(fakeHeight); }); }); function generatePostMessage(ins, iframe, height) { ins.implementation_.handleVkIframeMessage_({ origin: 'https://vk.com', source: iframe.contentWindow, data: JSON.stringify([ 'resize', [height], ]), }); } });
engtat/amphtml
extensions/amp-vk/0.1/test/test-amp-vk.js
JavaScript
apache-2.0
7,420
/* Copyright 2013 10gen Inc. * * 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. */ /* global describe, expect, it, mongo */ describe('The const module', function () { it('stores keycode constants', function () { var key = mongo.config.keycodes; expect(key.enter).toBe(13); expect(key.left).toBe(37); expect(key.up).toBe(38); expect(key.right).toBe(39); expect(key.down).toBe(40); }); it('stores the keep alive timeout', function () { expect(mongo.config.keepAliveTime).toBeDefined(); }); it('stores the root element CSS selector', function () { expect(mongo.config.rootElementSelector).toBeDefined(); }); it('stores the script name', function () { expect(mongo.config.scriptName).toBeDefined(); }); it('stores the shell batch size', function () { expect(mongo.config.shellBatchSize).toBeDefined(); }); it('gets and stores the MWS host', function () { expect(mongo.config.mwsHost).toEqual('http://mwshost.example.com'); }); it('generates and stores the baseUrl', function(){ expect(mongo.config.baseUrl).toBeDefined(); expect(mongo.config.baseUrl.indexOf(mongo.config.mwsHost) > -1).toBe(true); }); });
greinerb/mongo-web-shell
frontend/spec/mws/config.spec.js
JavaScript
apache-2.0
1,723
// Copyright 2014 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. 'use strict'; // This file relies on the fact that the following declaration has been made // in runtime.js: // var $Array = global.Array; // ------------------------------------------------------------------- // Proposed for ES7 // https://github.com/tc39/Array.prototype.includes // 6e3b78c927aeda20b9d40e81303f9d44596cd904 function ArrayIncludes(searchElement, fromIndex) { var array = ToObject(this); var len = ToLength(array.length); if (len === 0) { return false; } var n = ToInteger(fromIndex); var k; if (n >= 0) { k = n; } else { k = len + n; if (k < 0) { k = 0; } } while (k < len) { var elementK = array[k]; if (SameValueZero(searchElement, elementK)) { return true; } ++k; } return false; } // ------------------------------------------------------------------- function HarmonyArrayIncludesExtendArrayPrototype() { %CheckIsBootstrapping(); %FunctionSetLength(ArrayIncludes, 1); // Set up the non-enumerable functions on the Array prototype object. InstallFunctions($Array.prototype, DONT_ENUM, $Array( "includes", ArrayIncludes )); } HarmonyArrayIncludesExtendArrayPrototype();
sgraham/nope
v8/src/harmony-array-includes.js
JavaScript
bsd-3-clause
1,359
/* LumX v1.5.14 (c) 2014-2017 LumApps http://ui.lumapps.com License: MIT */ (function() { 'use strict'; angular.module('lumx.utils.depth', []); angular.module('lumx.utils.event-scheduler', []); angular.module('lumx.utils.transclude-replace', []); angular.module('lumx.utils.utils', []); angular.module('lumx.utils', [ 'lumx.utils.depth', 'lumx.utils.event-scheduler', 'lumx.utils.transclude-replace', 'lumx.utils.utils' ]); angular.module('lumx.button', []); angular.module('lumx.checkbox', []); angular.module('lumx.data-table', []); angular.module('lumx.date-picker', []); angular.module('lumx.dialog', ['lumx.utils.event-scheduler']); angular.module('lumx.dropdown', ['lumx.utils.event-scheduler']); angular.module('lumx.fab', []); angular.module('lumx.file-input', []); angular.module('lumx.icon', []); angular.module('lumx.notification', ['lumx.utils.event-scheduler']); angular.module('lumx.progress', []); angular.module('lumx.radio-button', []); angular.module('lumx.ripple', []); angular.module('lumx.search-filter', []); angular.module('lumx.select', []); angular.module('lumx.stepper', []); angular.module('lumx.switch', []); angular.module('lumx.tabs', []); angular.module('lumx.text-field', []); angular.module('lumx.tooltip', []); angular.module('lumx', [ 'lumx.button', 'lumx.checkbox', 'lumx.data-table', 'lumx.date-picker', 'lumx.dialog', 'lumx.dropdown', 'lumx.fab', 'lumx.file-input', 'lumx.icon', 'lumx.notification', 'lumx.progress', 'lumx.radio-button', 'lumx.ripple', 'lumx.search-filter', 'lumx.select', 'lumx.stepper', 'lumx.switch', 'lumx.tabs', 'lumx.text-field', 'lumx.tooltip', 'lumx.utils' ]); })(); (function() { 'use strict'; angular .module('lumx.utils.depth') .service('LxDepthService', LxDepthService); function LxDepthService() { var service = this; var depth = 1000; service.getDepth = getDepth; service.register = register; //////////// function getDepth() { return depth; } function register() { depth++; } } })(); (function() { 'use strict'; angular .module('lumx.utils.event-scheduler') .service('LxEventSchedulerService', LxEventSchedulerService); LxEventSchedulerService.$inject = ['$document', 'LxUtils']; function LxEventSchedulerService($document, LxUtils) { var service = this; var handlers = {}; var schedule = {}; service.register = register; service.unregister = unregister; //////////// function handle(event) { var scheduler = schedule[event.type]; if (angular.isDefined(scheduler)) { for (var i = 0, length = scheduler.length; i < length; i++) { var handler = scheduler[i]; if (angular.isDefined(handler) && angular.isDefined(handler.callback) && angular.isFunction(handler.callback)) { handler.callback(event); if (event.isPropagationStopped()) { break; } } } } } function register(eventName, callback) { var handler = { eventName: eventName, callback: callback }; var id = LxUtils.generateUUID(); handlers[id] = handler; if (angular.isUndefined(schedule[eventName])) { schedule[eventName] = []; $document.on(eventName, handle); } schedule[eventName].unshift(handlers[id]); return id; } function unregister(id) { var found = false; var handler = handlers[id]; if (angular.isDefined(handler) && angular.isDefined(schedule[handler.eventName])) { var index = schedule[handler.eventName].indexOf(handler); if (angular.isDefined(index) && index > -1) { schedule[handler.eventName].splice(index, 1); delete handlers[id]; found = true; } if (schedule[handler.eventName].length === 0) { delete schedule[handler.eventName]; $document.off(handler.eventName, handle); } } return found; } } })(); (function() { 'use strict'; angular .module('lumx.utils.transclude-replace') .directive('ngTranscludeReplace', ngTranscludeReplace); ngTranscludeReplace.$inject = ['$log']; function ngTranscludeReplace($log) { return { terminal: true, restrict: 'EA', link: link }; function link(scope, element, attrs, ctrl, transclude) { if (!transclude) { $log.error('orphan', 'Illegal use of ngTranscludeReplace directive in the template! ' + 'No parent directive that requires a transclusion found. '); return; } transclude(function(clone) { if (clone.length) { element.replaceWith(clone); } else { element.remove(); } }); } } })(); (function() { 'use strict'; angular .module('lumx.utils.utils') .service('LxUtils', LxUtils); function LxUtils() { var service = this; service.debounce = debounce; service.generateUUID = generateUUID; service.disableBodyScroll = disableBodyScroll; //////////// // http://underscorejs.org/#debounce (1.8.3) function debounce(func, wait, immediate) { var timeout, args, context, timestamp, result; wait = wait || 500; var later = function() { var last = Date.now() - timestamp; if (last < wait && last >= 0) { timeout = setTimeout(later, wait - last); } else { timeout = null; if (!immediate) { result = func.apply(context, args); if (!timeout) { context = args = null; } } } }; var debounced = function() { context = this; args = arguments; timestamp = Date.now(); var callNow = immediate && !timeout; if (!timeout) { timeout = setTimeout(later, wait); } if (callNow) { result = func.apply(context, args); context = args = null; } return result; }; debounced.clear = function() { clearTimeout(timeout); timeout = context = args = null; }; return debounced; } function generateUUID() { var d = new Date().getTime(); var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = (d + Math.random() * 16) % 16 | 0; d = Math.floor(d / 16); return (c == 'x' ? r : (r & 0x3 | 0x8)) .toString(16); }); return uuid.toUpperCase(); } function disableBodyScroll() { var body = document.body; var documentElement = document.documentElement; var prevDocumentStyle = documentElement.style.cssText || ''; var prevBodyStyle = body.style.cssText || ''; var viewportTop = window.scrollY || window.pageYOffset || 0; var clientWidth = body.clientWidth; var hasVerticalScrollbar = body.scrollHeight > window.innerHeight + 1; if (hasVerticalScrollbar) { angular.element('body').css({ position: 'fixed', width: '100%', top: -viewportTop + 'px' }); } if (body.clientWidth < clientWidth) { body.style.overflow = 'hidden'; } // This should be applied after the manipulation to the body, because // adding a scrollbar can potentially resize it, causing the measurement // to change. if (hasVerticalScrollbar) { documentElement.style.overflowY = 'scroll'; } return function restoreScroll() { // Reset the inline style CSS to the previous. body.style.cssText = prevBodyStyle; documentElement.style.cssText = prevDocumentStyle; // The body loses its scroll position while being fixed. body.scrollTop = viewportTop; }; } } })(); (function() { 'use strict'; angular .module('lumx.button') .directive('lxButton', lxButton); function lxButton() { var buttonClass; return { restrict: 'E', templateUrl: getTemplateUrl, compile: compile, replace: true, transclude: true }; function compile(element, attrs) { setButtonStyle(element, attrs.lxSize, attrs.lxColor, attrs.lxType); return function(scope, element, attrs) { attrs.$observe('lxSize', function(lxSize) { setButtonStyle(element, lxSize, attrs.lxColor, attrs.lxType); }); attrs.$observe('lxColor', function(lxColor) { setButtonStyle(element, attrs.lxSize, lxColor, attrs.lxType); }); attrs.$observe('lxType', function(lxType) { setButtonStyle(element, attrs.lxSize, attrs.lxColor, lxType); }); element.on('click', function(event) { if (attrs.disabled === true) { event.preventDefault(); event.stopImmediatePropagation(); } }); }; } function getTemplateUrl(element, attrs) { return isAnchor(attrs) ? 'link.html' : 'button.html'; } function isAnchor(attrs) { return angular.isDefined(attrs.href) || angular.isDefined(attrs.ngHref) || angular.isDefined(attrs.ngLink) || angular.isDefined(attrs.uiSref); } function setButtonStyle(element, size, color, type) { var buttonBase = 'btn'; var buttonSize = angular.isDefined(size) ? size : 'm'; var buttonColor = angular.isDefined(color) ? color : 'primary'; var buttonType = angular.isDefined(type) ? type : 'raised'; element.removeClass(buttonClass); buttonClass = buttonBase + ' btn--' + buttonSize + ' btn--' + buttonColor + ' btn--' + buttonType; element.addClass(buttonClass); } } })(); (function() { 'use strict'; angular .module('lumx.checkbox') .directive('lxCheckbox', lxCheckbox) .directive('lxCheckboxLabel', lxCheckboxLabel) .directive('lxCheckboxHelp', lxCheckboxHelp); function lxCheckbox() { return { restrict: 'E', templateUrl: 'checkbox.html', scope: { lxColor: '@?', name: '@?', ngChange: '&?', ngDisabled: '=?', ngFalseValue: '@?', ngModel: '=', ngTrueValue: '@?', theme: '@?lxTheme' }, controller: LxCheckboxController, controllerAs: 'lxCheckbox', bindToController: true, transclude: true, replace: true }; } LxCheckboxController.$inject = ['$scope', '$timeout', 'LxUtils']; function LxCheckboxController($scope, $timeout, LxUtils) { var lxCheckbox = this; var checkboxId; var checkboxHasChildren; var timer; lxCheckbox.getCheckboxId = getCheckboxId; lxCheckbox.getCheckboxHasChildren = getCheckboxHasChildren; lxCheckbox.setCheckboxId = setCheckboxId; lxCheckbox.setCheckboxHasChildren = setCheckboxHasChildren; lxCheckbox.triggerNgChange = triggerNgChange; $scope.$on('$destroy', function() { $timeout.cancel(timer); }); init(); //////////// function getCheckboxId() { return checkboxId; } function getCheckboxHasChildren() { return checkboxHasChildren; } function init() { setCheckboxId(LxUtils.generateUUID()); setCheckboxHasChildren(false); lxCheckbox.ngTrueValue = angular.isUndefined(lxCheckbox.ngTrueValue) ? true : lxCheckbox.ngTrueValue; lxCheckbox.ngFalseValue = angular.isUndefined(lxCheckbox.ngFalseValue) ? false : lxCheckbox.ngFalseValue; lxCheckbox.lxColor = angular.isUndefined(lxCheckbox.lxColor) ? 'accent' : lxCheckbox.lxColor; } function setCheckboxId(_checkboxId) { checkboxId = _checkboxId; } function setCheckboxHasChildren(_checkboxHasChildren) { checkboxHasChildren = _checkboxHasChildren; } function triggerNgChange() { timer = $timeout(lxCheckbox.ngChange); } } function lxCheckboxLabel() { return { restrict: 'AE', require: ['^lxCheckbox', '^lxCheckboxLabel'], templateUrl: 'checkbox-label.html', link: link, controller: LxCheckboxLabelController, controllerAs: 'lxCheckboxLabel', bindToController: true, transclude: true, replace: true }; function link(scope, element, attrs, ctrls) { ctrls[0].setCheckboxHasChildren(true); ctrls[1].setCheckboxId(ctrls[0].getCheckboxId()); } } function LxCheckboxLabelController() { var lxCheckboxLabel = this; var checkboxId; lxCheckboxLabel.getCheckboxId = getCheckboxId; lxCheckboxLabel.setCheckboxId = setCheckboxId; //////////// function getCheckboxId() { return checkboxId; } function setCheckboxId(_checkboxId) { checkboxId = _checkboxId; } } function lxCheckboxHelp() { return { restrict: 'AE', require: '^lxCheckbox', templateUrl: 'checkbox-help.html', transclude: true, replace: true }; } })(); (function() { 'use strict'; angular .module('lumx.data-table') .directive('lxDataTable', lxDataTable); function lxDataTable() { return { restrict: 'E', templateUrl: 'data-table.html', scope: { border: '=?lxBorder', selectable: '=?lxSelectable', thumbnail: '=?lxThumbnail', tbody: '=lxTbody', thead: '=lxThead' }, link: link, controller: LxDataTableController, controllerAs: 'lxDataTable', bindToController: true, transclude: true, replace: true }; function link(scope, element, attrs, ctrl) { attrs.$observe('id', function(_newId) { ctrl.id = _newId; }); } } LxDataTableController.$inject = ['$rootScope', '$sce', '$scope']; function LxDataTableController($rootScope, $sce, $scope) { var lxDataTable = this; lxDataTable.areAllRowsSelected = areAllRowsSelected; lxDataTable.border = angular.isUndefined(lxDataTable.border) ? true : lxDataTable.border; lxDataTable.sort = sort; lxDataTable.toggle = toggle; lxDataTable.toggleAllSelected = toggleAllSelected; lxDataTable.$sce = $sce; lxDataTable.allRowsSelected = false; lxDataTable.selectedRows = []; $scope.$on('lx-data-table__select', function(event, id, row) { if (id === lxDataTable.id && angular.isDefined(row)) { if (angular.isArray(row) && row.length > 0) { row = row[0]; } _select(row); } }); $scope.$on('lx-data-table__select-all', function(event, id) { if (id === lxDataTable.id) { _selectAll(); } }); $scope.$on('lx-data-table__unselect', function(event, id, row) { if (id === lxDataTable.id && angular.isDefined(row)) { if (angular.isArray(row) && row.length > 0) { row = row[0]; } _unselect(row); } }); $scope.$on('lx-data-table__unselect-all', function(event, id) { if (id === lxDataTable.id) { _unselectAll(); } }); //////////// function _selectAll() { lxDataTable.selectedRows.length = 0; for (var i = 0, len = lxDataTable.tbody.length; i < len; i++) { if (!lxDataTable.tbody[i].lxDataTableDisabled) { lxDataTable.tbody[i].lxDataTableSelected = true; lxDataTable.selectedRows.push(lxDataTable.tbody[i]); } } lxDataTable.allRowsSelected = true; $rootScope.$broadcast('lx-data-table__unselected', lxDataTable.id, lxDataTable.selectedRows); } function _select(row) { toggle(row, true); } function _unselectAll() { for (var i = 0, len = lxDataTable.tbody.length; i < len; i++) { if (!lxDataTable.tbody[i].lxDataTableDisabled) { lxDataTable.tbody[i].lxDataTableSelected = false; } } lxDataTable.allRowsSelected = false; lxDataTable.selectedRows.length = 0; $rootScope.$broadcast('lx-data-table__selected', lxDataTable.id, lxDataTable.selectedRows); } function _unselect(row) { toggle(row, false); } //////////// function areAllRowsSelected() { var displayedRows = 0; for (var i = 0, len = lxDataTable.tbody.length; i < len; i++) { if (!lxDataTable.tbody[i].lxDataTableDisabled) { displayedRows++; } } if (displayedRows === lxDataTable.selectedRows.length) { lxDataTable.allRowsSelected = true; } else { lxDataTable.allRowsSelected = false; } } function sort(_column) { if (!_column.sortable) { return; } for (var i = 0, len = lxDataTable.thead.length; i < len; i++) { if (lxDataTable.thead[i].sortable && lxDataTable.thead[i].name !== _column.name) { lxDataTable.thead[i].sort = undefined; } } if (!_column.sort || _column.sort === 'desc') { _column.sort = 'asc'; } else { _column.sort = 'desc'; } $rootScope.$broadcast('lx-data-table__sorted', lxDataTable.id, _column); } function toggle(_row, _newSelectedStatus) { if (_row.lxDataTableDisabled || !lxDataTable.selectable) { return; } _row.lxDataTableSelected = angular.isDefined(_newSelectedStatus) ? _newSelectedStatus : !_row.lxDataTableSelected; if (_row.lxDataTableSelected) { // Make sure it's not already in. if (lxDataTable.selectedRows.length === 0 || (lxDataTable.selectedRows.length && lxDataTable.selectedRows.indexOf(_row) === -1)) { lxDataTable.selectedRows.push(_row); lxDataTable.areAllRowsSelected(); $rootScope.$broadcast('lx-data-table__selected', lxDataTable.id, lxDataTable.selectedRows); } } else { if (lxDataTable.selectedRows.length && lxDataTable.selectedRows.indexOf(_row) > -1) { lxDataTable.selectedRows.splice(lxDataTable.selectedRows.indexOf(_row), 1); lxDataTable.allRowsSelected = false; $rootScope.$broadcast('lx-data-table__unselected', lxDataTable.id, lxDataTable.selectedRows); } } } function toggleAllSelected() { if (lxDataTable.allRowsSelected) { _unselectAll(); } else { _selectAll(); } } } })(); (function() { 'use strict'; angular .module('lumx.data-table') .service('LxDataTableService', LxDataTableService); LxDataTableService.$inject = ['$rootScope']; function LxDataTableService($rootScope) { var service = this; service.select = select; service.selectAll = selectAll; service.unselect = unselect; service.unselectAll = unselectAll; //////////// function select(_dataTableId, row) { $rootScope.$broadcast('lx-data-table__select', _dataTableId, row); } function selectAll(_dataTableId) { $rootScope.$broadcast('lx-data-table__select-all', _dataTableId); } function unselect(_dataTableId, row) { $rootScope.$broadcast('lx-data-table__unselect', _dataTableId, row); } function unselectAll(_dataTableId) { $rootScope.$broadcast('lx-data-table__unselect-all', _dataTableId); } } })(); (function() { 'use strict'; angular .module('lumx.date-picker') .directive('lxDatePicker', lxDatePicker); lxDatePicker.$inject = ['LxDatePickerService', 'LxUtils']; function lxDatePicker(LxDatePickerService, LxUtils) { return { restrict: 'AE', templateUrl: 'date-picker.html', scope: { autoClose: '=?lxAutoClose', callback: '&?lxCallback', color: '@?lxColor', escapeClose: '=?lxEscapeClose', inputFormat: '@?lxInputFormat', maxDate: '=?lxMaxDate', ngModel: '=', minDate: '=?lxMinDate', locale: '@lxLocale' }, link: link, controller: LxDatePickerController, controllerAs: 'lxDatePicker', bindToController: true, replace: true, transclude: true }; function link(scope, element, attrs) { if (angular.isDefined(attrs.id)) { attrs.$observe('id', function(_newId) { scope.lxDatePicker.pickerId = _newId; LxDatePickerService.registerScope(scope.lxDatePicker.pickerId, scope); }); } else { scope.lxDatePicker.pickerId = LxUtils.generateUUID(); LxDatePickerService.registerScope(scope.lxDatePicker.pickerId, scope); } } } LxDatePickerController.$inject = ['$element', '$scope', '$timeout', '$transclude', 'LxDatePickerService', 'LxUtils']; function LxDatePickerController($element, $scope, $timeout, $transclude, LxDatePickerService, LxUtils) { var lxDatePicker = this; var input; var modelController; var timer1; var timer2; var watcher1; var watcher2; lxDatePicker.closeDatePicker = closeDatePicker; lxDatePicker.displayYearSelection = displayYearSelection; lxDatePicker.hideYearSelection = hideYearSelection; lxDatePicker.getDateFormatted = getDateFormatted; lxDatePicker.nextMonth = nextMonth; lxDatePicker.openDatePicker = openDatePicker; lxDatePicker.previousMonth = previousMonth; lxDatePicker.select = select; lxDatePicker.selectYear = selectYear; lxDatePicker.autoClose = angular.isDefined(lxDatePicker.autoClose) ? lxDatePicker.autoClose : true; lxDatePicker.color = angular.isDefined(lxDatePicker.color) ? lxDatePicker.color : 'primary'; lxDatePicker.element = $element.find('.lx-date-picker'); lxDatePicker.escapeClose = angular.isDefined(lxDatePicker.escapeClose) ? lxDatePicker.escapeClose : true; lxDatePicker.isOpen = false; lxDatePicker.moment = moment; lxDatePicker.yearSelection = false; lxDatePicker.uuid = LxUtils.generateUUID(); $transclude(function(clone) { if (clone.length) { lxDatePicker.hasInput = true; timer1 = $timeout(function() { input = $element.find('.lx-date-input input'); modelController = input.data('$ngModelController'); watcher2 = $scope.$watch(function() { return modelController.$viewValue; }, function(newValue, oldValue) { if (angular.isUndefined(newValue)) { lxDatePicker.ngModel = undefined; } }); }); } }); watcher1 = $scope.$watch(function() { return lxDatePicker.ngModel; }, init); $scope.$on('$destroy', function() { $timeout.cancel(timer1); $timeout.cancel(timer2); if (angular.isFunction(watcher1)) { watcher1(); } if (angular.isFunction(watcher2)) { watcher2(); } }); //////////// function closeDatePicker() { LxDatePickerService.close(lxDatePicker.pickerId); } function displayYearSelection() { lxDatePicker.yearSelection = true; timer2 = $timeout(function() { var yearSelector = angular.element('.lx-date-picker__year-selector'); var activeYear = yearSelector.find('.lx-date-picker__year--is-active'); yearSelector.scrollTop(yearSelector.scrollTop() + activeYear.position().top - yearSelector.height() / 2 + activeYear.height() / 2); }); } function hideYearSelection() { lxDatePicker.yearSelection = false; } function generateCalendar() { lxDatePicker.days = []; var previousDay = angular.copy(lxDatePicker.ngModelMoment).date(0); var firstDayOfMonth = angular.copy(lxDatePicker.ngModelMoment).date(1); var lastDayOfMonth = firstDayOfMonth.clone().endOf('month'); var maxDays = lastDayOfMonth.date(); lxDatePicker.emptyFirstDays = []; for (var i = firstDayOfMonth.day() === 0 ? 6 : firstDayOfMonth.day() - 1; i > 0; i--) { lxDatePicker.emptyFirstDays.push( {}); } for (var j = 0; j < maxDays; j++) { var date = angular.copy(previousDay.add(1, 'days')); date.selected = angular.isDefined(lxDatePicker.ngModel) && date.isSame(lxDatePicker.ngModel, 'day'); date.today = date.isSame(moment(), 'day'); if (angular.isDefined(lxDatePicker.minDate) && date.toDate() < lxDatePicker.minDate) { date.disabled = true; } if (angular.isDefined(lxDatePicker.maxDate) && date.toDate() > lxDatePicker.maxDate) { date.disabled = true; } lxDatePicker.days.push(date); } lxDatePicker.emptyLastDays = []; for (var k = 7 - (lastDayOfMonth.day() === 0 ? 7 : lastDayOfMonth.day()); k > 0; k--) { lxDatePicker.emptyLastDays.push( {}); } } function getDateFormatted() { var dateFormatted = lxDatePicker.ngModelMoment.format('llll').replace(lxDatePicker.ngModelMoment.format('LT'), '').trim().replace(lxDatePicker.ngModelMoment.format('YYYY'), '').trim(); var dateFormattedLastChar = dateFormatted.slice(-1); if (dateFormattedLastChar === ',') { dateFormatted = dateFormatted.slice(0, -1); } return dateFormatted; } function init() { moment.locale(lxDatePicker.locale); lxDatePicker.ngModelMoment = angular.isDefined(lxDatePicker.ngModel) ? moment(angular.copy(lxDatePicker.ngModel)) : moment(); lxDatePicker.days = []; lxDatePicker.daysOfWeek = [moment.weekdaysMin(1), moment.weekdaysMin(2), moment.weekdaysMin(3), moment.weekdaysMin(4), moment.weekdaysMin(5), moment.weekdaysMin(6), moment.weekdaysMin(0)]; lxDatePicker.years = []; for (var y = moment().year() - 100; y <= moment().year() + 100; y++) { lxDatePicker.years.push(y); } generateCalendar(); } function nextMonth() { lxDatePicker.ngModelMoment = lxDatePicker.ngModelMoment.add(1, 'month'); generateCalendar(); } function openDatePicker() { LxDatePickerService.open(lxDatePicker.pickerId); } function previousMonth() { lxDatePicker.ngModelMoment = lxDatePicker.ngModelMoment.subtract(1, 'month'); generateCalendar(); } function select(_day) { if (!_day.disabled) { lxDatePicker.ngModel = _day.toDate(); lxDatePicker.ngModelMoment = angular.copy(_day); if (angular.isDefined(lxDatePicker.callback)) { lxDatePicker.callback( { newDate: lxDatePicker.ngModel }); } if (angular.isDefined(modelController) && lxDatePicker.inputFormat) { modelController.$setViewValue(angular.copy(_day).format(lxDatePicker.inputFormat)); modelController.$render(); } generateCalendar(); } } function selectYear(_year) { lxDatePicker.yearSelection = false; lxDatePicker.ngModelMoment = lxDatePicker.ngModelMoment.year(_year); generateCalendar(); } } })(); (function() { 'use strict'; angular .module('lumx.date-picker') .service('LxDatePickerService', LxDatePickerService); LxDatePickerService.$inject = ['$rootScope', '$timeout', 'LxDepthService', 'LxEventSchedulerService']; function LxDatePickerService($rootScope, $timeout, LxDepthService, LxEventSchedulerService) { var service = this; var activeDatePickerId; var datePickerFilter; var idEventScheduler; var scopeMap = {}; service.close = closeDatePicker; service.open = openDatePicker; service.registerScope = registerScope; //////////// function closeDatePicker(_datePickerId) { if (angular.isDefined(idEventScheduler)) { LxEventSchedulerService.unregister(idEventScheduler); idEventScheduler = undefined; } activeDatePickerId = undefined; $rootScope.$broadcast('lx-date-picker__close-start', _datePickerId); datePickerFilter.removeClass('lx-date-picker-filter--is-shown'); scopeMap[_datePickerId].element.removeClass('lx-date-picker--is-shown'); $timeout(function() { angular.element('body').removeClass('no-scroll-date-picker-' + scopeMap[_datePickerId].uuid); datePickerFilter.remove(); scopeMap[_datePickerId].element .hide() .appendTo(scopeMap[_datePickerId].elementParent); scopeMap[_datePickerId].isOpen = false; $rootScope.$broadcast('lx-date-picker__close-end', _datePickerId); }, 600); } function onKeyUp(_event) { if (_event.keyCode == 27 && angular.isDefined(activeDatePickerId)) { closeDatePicker(activeDatePickerId); } _event.stopPropagation(); } function openDatePicker(_datePickerId) { LxDepthService.register(); activeDatePickerId = _datePickerId; angular.element('body').addClass('no-scroll-date-picker-' + scopeMap[_datePickerId].uuid); datePickerFilter = angular.element('<div/>', { class: 'lx-date-picker-filter' }); datePickerFilter .css('z-index', LxDepthService.getDepth()) .appendTo('body'); if (scopeMap[activeDatePickerId].autoClose) { datePickerFilter.on('click', function() { closeDatePicker(activeDatePickerId); }); } if (scopeMap[activeDatePickerId].escapeClose) { idEventScheduler = LxEventSchedulerService.register('keyup', onKeyUp); } scopeMap[activeDatePickerId].element .css('z-index', LxDepthService.getDepth() + 1) .appendTo('body') .show(); $timeout(function() { $rootScope.$broadcast('lx-date-picker__open-start', activeDatePickerId); scopeMap[activeDatePickerId].isOpen = true; datePickerFilter.addClass('lx-date-picker-filter--is-shown'); scopeMap[activeDatePickerId].element.addClass('lx-date-picker--is-shown'); }, 100); $timeout(function() { $rootScope.$broadcast('lx-date-picker__open-end', activeDatePickerId); }, 700); } function registerScope(_datePickerId, _datePickerScope) { scopeMap[_datePickerId] = _datePickerScope.lxDatePicker; } } })(); (function() { 'use strict'; angular .module('lumx.dialog') .directive('lxDialog', lxDialog) .directive('lxDialogHeader', lxDialogHeader) .directive('lxDialogContent', lxDialogContent) .directive('lxDialogFooter', lxDialogFooter) .directive('lxDialogClose', lxDialogClose); function lxDialog() { return { restrict: 'E', template: '<div class="dialog" ng-class="{ \'dialog--l\': !lxDialog.size || lxDialog.size === \'l\', \'dialog--s\': lxDialog.size === \'s\', \'dialog--m\': lxDialog.size === \'m\' }"><div ng-if="lxDialog.isOpen" ng-transclude></div></div>', scope: { autoClose: '=?lxAutoClose', escapeClose: '=?lxEscapeClose', size: '@?lxSize' }, link: link, controller: LxDialogController, controllerAs: 'lxDialog', bindToController: true, replace: true, transclude: true }; function link(scope, element, attrs, ctrl) { attrs.$observe('id', function(_newId) { ctrl.id = _newId; }); } } LxDialogController.$inject = ['$element', '$interval', '$rootScope', '$scope', '$timeout', '$window', 'LxDepthService', 'LxEventSchedulerService', 'LxUtils']; function LxDialogController($element, $interval, $rootScope, $scope, $timeout, $window, LxDepthService, LxEventSchedulerService, LxUtils) { var lxDialog = this; var dialogFilter = angular.element('<div/>', { class: 'dialog-filter' }); var dialogHeight; var dialogInterval; var dialogScrollable; var elementParent = $element.parent(); var idEventScheduler; var resizeDebounce; var windowHeight; lxDialog.autoClose = angular.isDefined(lxDialog.autoClose) ? lxDialog.autoClose : true; lxDialog.escapeClose = angular.isDefined(lxDialog.escapeClose) ? lxDialog.escapeClose : true; lxDialog.isOpen = false; lxDialog.uuid = LxUtils.generateUUID(); $scope.$on('lx-dialog__open', function(event, id) { if (id === lxDialog.id) { open(); } }); $scope.$on('lx-dialog__close', function(event, id) { if (id === lxDialog.id) { close(); } }); $scope.$on('$destroy', function() { close(); }); //////////// function checkDialogHeight() { var dialog = $element; var dialogHeader = dialog.find('.dialog__header'); var dialogContent = dialog.find('.dialog__content'); var dialogFooter = dialog.find('.dialog__footer'); if (!dialogFooter.length) { dialogFooter = dialog.find('.dialog__actions'); } if (angular.isUndefined(dialogHeader)) { return; } var heightToCheck = 60 + dialogHeader.outerHeight() + dialogContent.outerHeight() + dialogFooter.outerHeight(); if (dialogHeight === heightToCheck && windowHeight === $window.innerHeight) { return; } dialogHeight = heightToCheck; windowHeight = $window.innerHeight; if (heightToCheck >= $window.innerHeight) { dialog.addClass('dialog--is-fixed'); dialogScrollable .css( { top: dialogHeader.outerHeight(), bottom: dialogFooter.outerHeight() }) .off('scroll', checkScrollEnd) .on('scroll', checkScrollEnd); } else { dialog.removeClass('dialog--is-fixed'); dialogScrollable .removeAttr('style') .off('scroll', checkScrollEnd); } } function checkDialogHeightOnResize() { if (resizeDebounce) { $timeout.cancel(resizeDebounce); } resizeDebounce = $timeout(function() { checkDialogHeight(); }, 200); } function checkScrollEnd() { if (dialogScrollable.scrollTop() + dialogScrollable.innerHeight() >= dialogScrollable[0].scrollHeight) { $rootScope.$broadcast('lx-dialog__scroll-end', lxDialog.id); dialogScrollable.off('scroll', checkScrollEnd); $timeout(function() { dialogScrollable.on('scroll', checkScrollEnd); }, 500); } } function onKeyUp(_event) { if (_event.keyCode == 27) { close(); } _event.stopPropagation(); } function open() { if (lxDialog.isOpen) { return; } LxDepthService.register(); angular.element('body').addClass('no-scroll-dialog-' + lxDialog.uuid); dialogFilter .css('z-index', LxDepthService.getDepth()) .appendTo('body'); if (lxDialog.autoClose) { dialogFilter.on('click', function() { close(); }); } if (lxDialog.escapeClose) { idEventScheduler = LxEventSchedulerService.register('keyup', onKeyUp); } $element .css('z-index', LxDepthService.getDepth() + 1) .appendTo('body') .show(); $timeout(function() { $rootScope.$broadcast('lx-dialog__open-start', lxDialog.id); lxDialog.isOpen = true; dialogFilter.addClass('dialog-filter--is-shown'); $element.addClass('dialog--is-shown'); }, 100); $timeout(function() { if ($element.find('.dialog__scrollable').length === 0) { $element.find('.dialog__content').wrap(angular.element('<div/>', { class: 'dialog__scrollable' })); } dialogScrollable = $element.find('.dialog__scrollable'); }, 200); $timeout(function() { $rootScope.$broadcast('lx-dialog__open-end', lxDialog.id); }, 700); dialogInterval = $interval(function() { checkDialogHeight(); }, 500); angular.element($window).on('resize', checkDialogHeightOnResize); } function close() { if (!lxDialog.isOpen) { return; } if (angular.isDefined(idEventScheduler)) { LxEventSchedulerService.unregister(idEventScheduler); idEventScheduler = undefined; } angular.element($window).off('resize', checkDialogHeightOnResize); $element.find('.dialog__scrollable').off('scroll', checkScrollEnd); $rootScope.$broadcast('lx-dialog__close-start', lxDialog.id); if (resizeDebounce) { $timeout.cancel(resizeDebounce); } $interval.cancel(dialogInterval); dialogFilter.removeClass('dialog-filter--is-shown'); $element.removeClass('dialog--is-shown'); $timeout(function() { angular.element('body').removeClass('no-scroll-dialog-' + lxDialog.uuid); dialogFilter.remove(); $element .hide() .removeClass('dialog--is-fixed') .appendTo(elementParent); lxDialog.isOpen = false; dialogHeight = undefined; $rootScope.$broadcast('lx-dialog__close-end', lxDialog.id); }, 600); } } function lxDialogHeader() { return { restrict: 'E', template: '<div class="dialog__header" ng-transclude></div>', replace: true, transclude: true }; } function lxDialogContent() { return { restrict: 'E', template: '<div class="dialog__scrollable"><div class="dialog__content" ng-transclude></div></div>', replace: true, transclude: true }; } function lxDialogFooter() { return { restrict: 'E', template: '<div class="dialog__footer" ng-transclude></div>', replace: true, transclude: true }; } lxDialogClose.$inject = ['LxDialogService']; function lxDialogClose(LxDialogService) { return { restrict: 'A', link: function(scope, element) { element.on('click', function() { LxDialogService.close(element.parents('.dialog').attr('id')); }); scope.$on('$destroy', function() { element.off(); }); } }; } })(); (function() { 'use strict'; angular .module('lumx.dialog') .service('LxDialogService', LxDialogService); LxDialogService.$inject = ['$rootScope']; function LxDialogService($rootScope) { var service = this; service.open = open; service.close = close; //////////// function open(_dialogId) { $rootScope.$broadcast('lx-dialog__open', _dialogId); } function close(_dialogId) { $rootScope.$broadcast('lx-dialog__close', _dialogId); } } })(); (function() { 'use strict'; angular .module('lumx.dropdown') .directive('lxDropdown', lxDropdown) .directive('lxDropdownToggle', lxDropdownToggle) .directive('lxDropdownMenu', lxDropdownMenu) .directive('lxDropdownFilter', lxDropdownFilter); function lxDropdown() { return { restrict: 'E', templateUrl: 'dropdown.html', scope: { depth: '@?lxDepth', effect: '@?lxEffect', escapeClose: '=?lxEscapeClose', hover: '=?lxHover', hoverDelay: '=?lxHoverDelay', offset: '@?lxOffset', overToggle: '=?lxOverToggle', position: '@?lxPosition', width: '@?lxWidth' }, link: link, controller: LxDropdownController, controllerAs: 'lxDropdown', bindToController: true, transclude: true }; function link(scope, element, attrs, ctrl) { var backwardOneWay = ['position', 'width']; var backwardTwoWay = ['escapeClose', 'overToggle']; angular.forEach(backwardOneWay, function(attribute) { if (angular.isDefined(attrs[attribute])) { attrs.$observe(attribute, function(newValue) { scope.lxDropdown[attribute] = newValue; }); } }); angular.forEach(backwardTwoWay, function(attribute) { if (angular.isDefined(attrs[attribute])) { scope.$watch(function() { return scope.$parent.$eval(attrs[attribute]); }, function(newValue) { scope.lxDropdown[attribute] = newValue; }); } }); attrs.$observe('id', function(_newId) { ctrl.uuid = _newId; }); scope.$on('$destroy', function() { if (ctrl.isOpen) { ctrl.closeDropdownMenu(); } }); } } LxDropdownController.$inject = ['$element', '$interval', '$scope', '$timeout', '$window', 'LxDepthService', 'LxDropdownService', 'LxEventSchedulerService', 'LxUtils' ]; function LxDropdownController($element, $interval, $scope, $timeout, $window, LxDepthService, LxDropdownService, LxEventSchedulerService, LxUtils) { var lxDropdown = this; var dropdownInterval; var dropdownMenu; var dropdownToggle; var idEventScheduler; var openTimeout; var positionTarget; var scrollMask = angular.element('<div/>', { class: 'scroll-mask' }); var enableBodyScroll; lxDropdown.closeDropdownMenu = closeDropdownMenu; lxDropdown.openDropdownMenu = openDropdownMenu; lxDropdown.registerDropdownMenu = registerDropdownMenu; lxDropdown.registerDropdownToggle = registerDropdownToggle; lxDropdown.toggle = toggle; lxDropdown.uuid = LxUtils.generateUUID(); lxDropdown.effect = angular.isDefined(lxDropdown.effect) ? lxDropdown.effect : 'expand'; lxDropdown.escapeClose = angular.isDefined(lxDropdown.escapeClose) ? lxDropdown.escapeClose : true; lxDropdown.hasToggle = false; lxDropdown.isOpen = false; lxDropdown.overToggle = angular.isDefined(lxDropdown.overToggle) ? lxDropdown.overToggle : false; lxDropdown.position = angular.isDefined(lxDropdown.position) ? lxDropdown.position : 'left'; $scope.$on('lx-dropdown__open', function(_event, _params) { if (_params.uuid === lxDropdown.uuid && !lxDropdown.isOpen) { LxDropdownService.closeActiveDropdown(); LxDropdownService.registerActiveDropdownUuid(lxDropdown.uuid); positionTarget = _params.target; registerDropdownToggle(angular.element(positionTarget)); openDropdownMenu(); } }); $scope.$on('lx-dropdown__close', function(_event, _params) { if (_params.uuid === lxDropdown.uuid && lxDropdown.isOpen) { closeDropdownMenu(); } }); $scope.$on('$destroy', function() { $timeout.cancel(openTimeout); }); //////////// function closeDropdownMenu() { $interval.cancel(dropdownInterval); LxDropdownService.resetActiveDropdownUuid(); var velocityProperties; var velocityEasing; scrollMask.remove(); if (angular.isFunction(enableBodyScroll)) { enableBodyScroll(); } enableBodyScroll = undefined; if (lxDropdown.hasToggle) { dropdownToggle .off('wheel') .css('z-index', ''); } dropdownMenu .off('wheel') .css( { overflow: 'hidden' }); if (lxDropdown.effect === 'expand') { velocityProperties = { width: 0, height: 0 }; velocityEasing = 'easeOutQuint'; } else if (lxDropdown.effect === 'fade') { velocityProperties = { opacity: 0 }; velocityEasing = 'linear'; } if (lxDropdown.effect === 'expand' || lxDropdown.effect === 'fade') { dropdownMenu.velocity(velocityProperties, { duration: 200, easing: velocityEasing, complete: function() { dropdownMenu .removeAttr('style') .removeClass('dropdown-menu--is-open') .appendTo($element.find('.dropdown')); $scope.$apply(function() { lxDropdown.isOpen = false; if (lxDropdown.escapeClose) { LxEventSchedulerService.unregister(idEventScheduler); idEventScheduler = undefined; } }); } }); } else if (lxDropdown.effect === 'none') { dropdownMenu .removeAttr('style') .removeClass('dropdown-menu--is-open') .appendTo($element.find('.dropdown')); lxDropdown.isOpen = false; if (lxDropdown.escapeClose) { LxEventSchedulerService.unregister(idEventScheduler); idEventScheduler = undefined; } } } function getAvailableHeight() { var availableHeightOnTop; var availableHeightOnBottom; var direction; var dropdownToggleHeight = dropdownToggle.outerHeight(); var dropdownToggleTop = dropdownToggle.offset().top - angular.element($window).scrollTop(); var windowHeight = $window.innerHeight; if (lxDropdown.overToggle) { availableHeightOnTop = dropdownToggleTop + dropdownToggleHeight; availableHeightOnBottom = windowHeight - dropdownToggleTop; } else { availableHeightOnTop = dropdownToggleTop; availableHeightOnBottom = windowHeight - (dropdownToggleTop + dropdownToggleHeight); } if (availableHeightOnTop > availableHeightOnBottom) { direction = 'top'; } else { direction = 'bottom'; } return { top: availableHeightOnTop, bottom: availableHeightOnBottom, direction: direction }; } function initDropdownPosition() { var availableHeight = getAvailableHeight(); var dropdownMenuWidth; var dropdownMenuLeft; var dropdownMenuRight; var dropdownToggleWidth = dropdownToggle.outerWidth(); var dropdownToggleHeight = dropdownToggle.outerHeight(); var dropdownToggleTop = dropdownToggle.offset().top - angular.element($window).scrollTop(); var windowWidth = $window.innerWidth; var windowHeight = $window.innerHeight; if (angular.isDefined(lxDropdown.width)) { if (lxDropdown.width.indexOf('%') > -1) { dropdownMenuWidth = dropdownToggleWidth * (lxDropdown.width.slice(0, -1) / 100); } else { dropdownMenuWidth = lxDropdown.width; } } else { dropdownMenuWidth = 'auto'; } if (lxDropdown.position === 'left') { dropdownMenuLeft = dropdownToggle.offset().left; dropdownMenuRight = 'auto'; } else if (lxDropdown.position === 'right') { dropdownMenuLeft = 'auto'; dropdownMenuRight = windowWidth - dropdownToggle.offset().left - dropdownToggleWidth; } else if (lxDropdown.position === 'center') { dropdownMenuLeft = (dropdownToggle.offset().left + (dropdownToggleWidth / 2)) - (dropdownMenuWidth / 2); dropdownMenuRight = 'auto'; } dropdownMenu.css( { left: dropdownMenuLeft, right: dropdownMenuRight, width: dropdownMenuWidth }); if (availableHeight.direction === 'top') { dropdownMenu.css( { bottom: lxDropdown.overToggle ? (windowHeight - dropdownToggleTop - dropdownToggleHeight) : (windowHeight - dropdownToggleTop + ~~lxDropdown.offset) }); return availableHeight.top; } else if (availableHeight.direction === 'bottom') { dropdownMenu.css( { top: lxDropdown.overToggle ? dropdownToggleTop : (dropdownToggleTop + dropdownToggleHeight + ~~lxDropdown.offset) }); return availableHeight.bottom; } } function openDropdownMenu() { lxDropdown.isOpen = true; LxDepthService.register(); scrollMask .css('z-index', LxDepthService.getDepth()) .appendTo('body'); scrollMask.on('wheel', function preventDefault(e) { e.preventDefault(); }); enableBodyScroll = LxUtils.disableBodyScroll(); if (lxDropdown.hasToggle) { dropdownToggle .css('z-index', LxDepthService.getDepth() + 1) .on('wheel', function preventDefault(e) { e.preventDefault(); }); } dropdownMenu .addClass('dropdown-menu--is-open') .css('z-index', LxDepthService.getDepth() + 1) .appendTo('body'); dropdownMenu.on('wheel', function preventDefault(e) { var d = e.originalEvent.deltaY; if (d < 0 && dropdownMenu.scrollTop() === 0) { e.preventDefault(); } else { if (d > 0 && (dropdownMenu.scrollTop() == dropdownMenu.get(0).scrollHeight - dropdownMenu.innerHeight())) { e.preventDefault(); } } }); if (lxDropdown.escapeClose) { idEventScheduler = LxEventSchedulerService.register('keyup', onKeyUp); } openTimeout = $timeout(function() { var availableHeight = initDropdownPosition() - ~~lxDropdown.offset; var dropdownMenuHeight = dropdownMenu.outerHeight(); var dropdownMenuWidth = dropdownMenu.outerWidth(); var enoughHeight = true; if (availableHeight < dropdownMenuHeight) { enoughHeight = false; dropdownMenuHeight = availableHeight; } if (lxDropdown.effect === 'expand') { dropdownMenu.css( { width: 0, height: 0, opacity: 1, overflow: 'hidden' }); dropdownMenu.find('.dropdown-menu__content').css( { width: dropdownMenuWidth, height: dropdownMenuHeight }); dropdownMenu.velocity( { width: dropdownMenuWidth }, { duration: 200, easing: 'easeOutQuint', queue: false }); dropdownMenu.velocity( { height: dropdownMenuHeight }, { duration: 500, easing: 'easeOutQuint', queue: false, complete: function() { dropdownMenu.css( { overflow: 'auto' }); if (angular.isUndefined(lxDropdown.width)) { dropdownMenu.css( { width: 'auto' }); } $timeout(updateDropdownMenuHeight); dropdownMenu.find('.dropdown-menu__content').removeAttr('style'); dropdownInterval = $interval(updateDropdownMenuHeight, 500); } }); } else if (lxDropdown.effect === 'fade') { dropdownMenu.css( { height: dropdownMenuHeight }); dropdownMenu.velocity( { opacity: 1, }, { duration: 200, easing: 'linear', queue: false, complete: function() { $timeout(updateDropdownMenuHeight); dropdownInterval = $interval(updateDropdownMenuHeight, 500); } }); } else if (lxDropdown.effect === 'none') { dropdownMenu.css( { opacity: 1 }); $timeout(updateDropdownMenuHeight); dropdownInterval = $interval(updateDropdownMenuHeight, 500); } }); } function onKeyUp(_event) { if (_event.keyCode == 27) { closeDropdownMenu(); } _event.stopPropagation(); } function registerDropdownMenu(_dropdownMenu) { dropdownMenu = _dropdownMenu; } function registerDropdownToggle(_dropdownToggle) { if (!positionTarget) { lxDropdown.hasToggle = true; } dropdownToggle = _dropdownToggle; } function toggle() { if (!lxDropdown.isOpen) { openDropdownMenu(); } else { closeDropdownMenu(); } } function updateDropdownMenuHeight() { if (positionTarget) { registerDropdownToggle(angular.element(positionTarget)); } var availableHeight = getAvailableHeight(); var dropdownMenuHeight = dropdownMenu.find('.dropdown-menu__content').outerHeight(); dropdownMenu.css( { height: 'auto' }); if ((availableHeight[availableHeight.direction] - ~~lxDropdown.offset) < dropdownMenuHeight) { if (availableHeight.direction === 'top') { dropdownMenu.css( { top: 0 }); } else if (availableHeight.direction === 'bottom') { dropdownMenu.css( { bottom: 0 }); } } else { if (availableHeight.direction === 'top') { dropdownMenu.css( { top: 'auto' }); } else if (availableHeight.direction === 'bottom') { dropdownMenu.css( { bottom: 'auto' }); } } } } lxDropdownToggle.$inject = ['$timeout', 'LxDropdownService']; function lxDropdownToggle($timeout, LxDropdownService) { return { restrict: 'AE', templateUrl: 'dropdown-toggle.html', require: '^lxDropdown', scope: true, link: link, replace: true, transclude: true }; function link(scope, element, attrs, ctrl) { var hoverTimeout = []; var mouseEvent = ctrl.hover ? 'mouseenter' : 'click'; ctrl.registerDropdownToggle(element); element.on(mouseEvent, function(_event) { if (mouseEvent === 'mouseenter' && 'ontouchstart' in window) { return; } if (!ctrl.hover) { _event.stopPropagation(); } LxDropdownService.closeActiveDropdown(); LxDropdownService.registerActiveDropdownUuid(ctrl.uuid); if (ctrl.hover) { ctrl.mouseOnToggle = true; if (!ctrl.isOpen) { hoverTimeout[0] = $timeout(function() { scope.$apply(function() { ctrl.openDropdownMenu(); }); }, ctrl.hoverDelay); } } else { scope.$apply(function() { ctrl.toggle(); }); } }); if (ctrl.hover) { element.on('mouseleave', function() { ctrl.mouseOnToggle = false; $timeout.cancel(hoverTimeout[0]); hoverTimeout[1] = $timeout(function() { if (!ctrl.mouseOnMenu) { scope.$apply(function() { ctrl.closeDropdownMenu(); }); } }, ctrl.hoverDelay); }); } scope.$on('$destroy', function() { element.off(); if (ctrl.hover) { $timeout.cancel(hoverTimeout[0]); $timeout.cancel(hoverTimeout[1]); } }); } } lxDropdownMenu.$inject = ['$timeout']; function lxDropdownMenu($timeout) { return { restrict: 'E', templateUrl: 'dropdown-menu.html', require: ['lxDropdownMenu', '^lxDropdown'], scope: true, link: link, controller: LxDropdownMenuController, controllerAs: 'lxDropdownMenu', bindToController: true, replace: true, transclude: true }; function link(scope, element, attrs, ctrls) { var hoverTimeout; ctrls[1].registerDropdownMenu(element); ctrls[0].setParentController(ctrls[1]); if (ctrls[1].hover) { element.on('mouseenter', function() { ctrls[1].mouseOnMenu = true; }); element.on('mouseleave', function() { ctrls[1].mouseOnMenu = false; hoverTimeout = $timeout(function() { if (!ctrls[1].mouseOnToggle) { scope.$apply(function() { ctrls[1].closeDropdownMenu(); }); } }, ctrls[1].hoverDelay); }); } scope.$on('$destroy', function() { if (ctrls[1].hover) { element.off(); $timeout.cancel(hoverTimeout); } }); } } LxDropdownMenuController.$inject = ['$element']; function LxDropdownMenuController($element) { var lxDropdownMenu = this; lxDropdownMenu.setParentController = setParentController; //////////// function addDropdownDepth() { if (lxDropdownMenu.parentCtrl.depth) { $element.addClass('dropdown-menu--depth-' + lxDropdownMenu.parentCtrl.depth); } else { $element.addClass('dropdown-menu--depth-1'); } } function setParentController(_parentCtrl) { lxDropdownMenu.parentCtrl = _parentCtrl; addDropdownDepth(); } } lxDropdownFilter.$inject = ['$timeout']; function lxDropdownFilter($timeout) { return { restrict: 'A', link: link }; function link(scope, element) { var focusTimeout; element.on('click', function(_event) { _event.stopPropagation(); }); focusTimeout = $timeout(function() { element.find('input').focus(); }, 200); scope.$on('$destroy', function() { $timeout.cancel(focusTimeout); element.off(); }); } } })(); (function() { 'use strict'; angular .module('lumx.dropdown') .service('LxDropdownService', LxDropdownService); LxDropdownService.$inject = ['$document', '$rootScope', '$timeout']; function LxDropdownService($document, $rootScope, $timeout) { var service = this; var activeDropdownUuid; service.close = close; service.closeActiveDropdown = closeActiveDropdown; service.open = open; service.isOpen = isOpen; service.registerActiveDropdownUuid = registerActiveDropdownUuid; service.resetActiveDropdownUuid = resetActiveDropdownUuid; $document.on('click', closeActiveDropdown); //////////// function close(_uuid) { $rootScope.$broadcast('lx-dropdown__close', { uuid: _uuid }); } function closeActiveDropdown() { $rootScope.$broadcast('lx-dropdown__close', { uuid: activeDropdownUuid }); } function open(_uuid, _target) { $rootScope.$broadcast('lx-dropdown__open', { uuid: _uuid, target: _target }); } function isOpen(_uuid) { return activeDropdownUuid === _uuid; } function registerActiveDropdownUuid(_uuid) { activeDropdownUuid = _uuid; } function resetActiveDropdownUuid() { activeDropdownUuid = undefined; } } })(); (function() { 'use strict'; angular .module('lumx.fab') .directive('lxFab', lxFab) .directive('lxFabTrigger', lxFabTrigger) .directive('lxFabActions', lxFabActions); function lxFab() { return { restrict: 'E', templateUrl: 'fab.html', scope: true, link: link, controller: LxFabController, controllerAs: 'lxFab', bindToController: true, transclude: true, replace: true }; function link(scope, element, attrs, ctrl) { attrs.$observe('lxDirection', function(newDirection) { ctrl.setFabDirection(newDirection); }); } } function LxFabController() { var lxFab = this; lxFab.setFabDirection = setFabDirection; //////////// function setFabDirection(_direction) { lxFab.lxDirection = _direction; } } function lxFabTrigger() { return { restrict: 'E', require: '^lxFab', templateUrl: 'fab-trigger.html', transclude: true, replace: true }; } function lxFabActions() { return { restrict: 'E', require: '^lxFab', templateUrl: 'fab-actions.html', link: link, transclude: true, replace: true }; function link(scope, element, attrs, ctrl) { scope.parentCtrl = ctrl; } } })(); (function() { 'use strict'; angular .module('lumx.file-input') .directive('lxFileInput', lxFileInput); function lxFileInput() { return { restrict: 'E', templateUrl: 'file-input.html', scope: { label: '@lxLabel', callback: '&?lxCallback' }, link: link, controller: LxFileInputController, controllerAs: 'lxFileInput', bindToController: true, replace: true }; function link(scope, element, attrs, ctrl) { var input = element.find('input'); input .on('change', ctrl.updateModel) .on('blur', function() { element.removeClass('input-file--is-focus'); }); scope.$on('$destroy', function() { input.off(); }); } } LxFileInputController.$inject = ['$element', '$scope', '$timeout']; function LxFileInputController($element, $scope, $timeout) { var lxFileInput = this; var input = $element.find('input'); var timer; lxFileInput.updateModel = updateModel; $scope.$on('$destroy', function() { $timeout.cancel(timer); }); //////////// function setFileName() { if (input.val()) { lxFileInput.fileName = input.val().replace(/C:\\fakepath\\/i, ''); $element.addClass('input-file--is-focus'); $element.addClass('input-file--is-active'); } else { lxFileInput.fileName = undefined; $element.removeClass('input-file--is-active'); } input.val(undefined); } function updateModel() { if (angular.isDefined(lxFileInput.callback)) { lxFileInput.callback( { newFile: input[0].files[0] }); } timer = $timeout(setFileName); } } })(); (function() { 'use strict'; angular .module('lumx.icon') .directive('lxIcon', lxIcon); function lxIcon() { return { restrict: 'E', templateUrl: 'icon.html', scope: { color: '@?lxColor', id: '@lxId', size: '@?lxSize', type: '@?lxType' }, controller: LxIconController, controllerAs: 'lxIcon', bindToController: true, replace: true }; } function LxIconController() { var lxIcon = this; lxIcon.getClass = getClass; //////////// function getClass() { var iconClass = []; iconClass.push('mdi-' + lxIcon.id); if (angular.isDefined(lxIcon.size)) { iconClass.push('icon--' + lxIcon.size); } if (angular.isDefined(lxIcon.color)) { iconClass.push('icon--' + lxIcon.color); } if (angular.isDefined(lxIcon.type)) { iconClass.push('icon--' + lxIcon.type); } return iconClass; } } })(); (function() { 'use strict'; angular .module('lumx.notification') .service('LxNotificationService', LxNotificationService); LxNotificationService.$inject = ['$injector', '$rootScope', '$timeout', 'LxDepthService', 'LxEventSchedulerService']; function LxNotificationService($injector, $rootScope, $timeout, LxDepthService, LxEventSchedulerService) { var service = this; var dialogFilter; var dialog; var idEventScheduler; var notificationList = []; var actionClicked = false; service.alert = showAlertDialog; service.confirm = showConfirmDialog; service.error = notifyError; service.info = notifyInfo; service.notify = notify; service.success = notifySuccess; service.warning = notifyWarning; //////////// // // NOTIFICATION // function deleteNotification(_notification, _callback) { _callback = (!angular.isFunction(_callback)) ? angular.noop : _callback; var notifIndex = notificationList.indexOf(_notification); var dnOffset = angular.isDefined(notificationList[notifIndex]) ? 24 + notificationList[notifIndex].height : 24; for (var idx = 0; idx < notifIndex; idx++) { if (notificationList.length > 1) { notificationList[idx].margin -= dnOffset; notificationList[idx].elem.css('marginBottom', notificationList[idx].margin + 'px'); } } _notification.elem.removeClass('notification--is-shown'); $timeout(function() { _notification.elem.remove(); // Find index again because notificationList may have changed notifIndex = notificationList.indexOf(_notification); if (notifIndex != -1) { notificationList.splice(notifIndex, 1); } _callback(actionClicked); actionClicked = false }, 400); } function getElementHeight(_elem) { return parseFloat(window.getComputedStyle(_elem, null).height); } function moveNotificationUp() { var newNotifIndex = notificationList.length - 1; notificationList[newNotifIndex].height = getElementHeight(notificationList[newNotifIndex].elem[0]); var upOffset = 0; for (var idx = newNotifIndex; idx >= 0; idx--) { if (notificationList.length > 1 && idx !== newNotifIndex) { upOffset = 24 + notificationList[newNotifIndex].height; notificationList[idx].margin += upOffset; notificationList[idx].elem.css('marginBottom', notificationList[idx].margin + 'px'); } } } function notify(_text, _icon, _sticky, _color, _action, _callback, _delay) { var $compile = $injector.get('$compile'); LxDepthService.register(); var notification = angular.element('<div/>', { class: 'notification' }); var notificationText = angular.element('<span/>', { class: 'notification__content', html: _text }); var notificationTimeout; var notificationDelay = _delay || 6000; if (angular.isDefined(_icon)) { var notificationIcon = angular.element('<i/>', { class: 'notification__icon mdi mdi-' + _icon }); notification .addClass('notification--has-icon') .append(notificationIcon); } if (angular.isDefined(_color)) { notification.addClass('notification--' + _color); } notification.append(notificationText); if (angular.isDefined(_action)) { var notificationAction = angular.element('<button/>', { class: 'notification__action btn btn--m btn--flat', html: _action }); if (angular.isDefined(_color)) { notificationAction.addClass('btn--' + _color); } else { notificationAction.addClass('btn--white'); } notificationAction.attr('lx-ripple', ''); $compile(notificationAction)($rootScope); notificationAction.bind('click', function() { actionClicked = true; }); notification .addClass('notification--has-action') .append(notificationAction); } notification .css('z-index', LxDepthService.getDepth()) .appendTo('body'); $timeout(function() { notification.addClass('notification--is-shown'); }, 100); var data = { elem: notification, margin: 0 }; notificationList.push(data); moveNotificationUp(); notification.bind('click', function() { deleteNotification(data, _callback); if (angular.isDefined(notificationTimeout)) { $timeout.cancel(notificationTimeout); } }); if (angular.isUndefined(_sticky) || !_sticky) { notificationTimeout = $timeout(function() { deleteNotification(data, _callback); }, notificationDelay); } } function notifyError(_text, _sticky) { notify(_text, 'alert-circle', _sticky, 'red'); } function notifyInfo(_text, _sticky) { notify(_text, 'information-outline', _sticky, 'blue'); } function notifySuccess(_text, _sticky) { notify(_text, 'check', _sticky, 'green'); } function notifyWarning(_text, _sticky) { notify(_text, 'alert', _sticky, 'orange'); } // // ALERT & CONFIRM // function buildDialogActions(_buttons, _callback, _unbind) { var $compile = $injector.get('$compile'); var dialogActions = angular.element('<div/>', { class: 'dialog__actions' }); var dialogLastBtn = angular.element('<button/>', { class: 'btn btn--m btn--blue btn--flat', text: _buttons.ok }); if (angular.isDefined(_buttons.cancel)) { var dialogFirstBtn = angular.element('<button/>', { class: 'btn btn--m btn--red btn--flat', text: _buttons.cancel }); dialogFirstBtn.attr('lx-ripple', ''); $compile(dialogFirstBtn)($rootScope); dialogActions.append(dialogFirstBtn); dialogFirstBtn.bind('click', function() { _callback(false); closeDialog(); }); } dialogLastBtn.attr('lx-ripple', ''); $compile(dialogLastBtn)($rootScope); dialogActions.append(dialogLastBtn); dialogLastBtn.bind('click', function() { _callback(true); closeDialog(); }); if (!_unbind) { idEventScheduler = LxEventSchedulerService.register('keyup', function(event) { if (event.keyCode == 13) { _callback(true); closeDialog(); } else if (event.keyCode == 27) { _callback(angular.isUndefined(_buttons.cancel)); closeDialog(); } event.stopPropagation(); }); } return dialogActions; } function buildDialogContent(_text) { var dialogContent = angular.element('<div/>', { class: 'dialog__content p++ pt0 tc-black-2', text: _text }); return dialogContent; } function buildDialogHeader(_title) { var dialogHeader = angular.element('<div/>', { class: 'dialog__header p++ fs-title', text: _title }); return dialogHeader; } function closeDialog() { if (angular.isDefined(idEventScheduler)) { $timeout(function() { LxEventSchedulerService.unregister(idEventScheduler); idEventScheduler = undefined; }, 1); } dialogFilter.removeClass('dialog-filter--is-shown'); dialog.removeClass('dialog--is-shown'); $timeout(function() { dialogFilter.remove(); dialog.remove(); }, 600); } function showAlertDialog(_title, _text, _button, _callback, _unbind) { LxDepthService.register(); dialogFilter = angular.element('<div/>', { class: 'dialog-filter' }); dialog = angular.element('<div/>', { class: 'dialog dialog--alert' }); var dialogHeader = buildDialogHeader(_title); var dialogContent = buildDialogContent(_text); var dialogActions = buildDialogActions( { ok: _button }, _callback, _unbind); dialogFilter .css('z-index', LxDepthService.getDepth()) .appendTo('body'); dialog .append(dialogHeader) .append(dialogContent) .append(dialogActions) .css('z-index', LxDepthService.getDepth() + 1) .appendTo('body') .show() .focus(); $timeout(function() { angular.element(document.activeElement).blur(); dialogFilter.addClass('dialog-filter--is-shown'); dialog.addClass('dialog--is-shown'); }, 100); } function showConfirmDialog(_title, _text, _buttons, _callback, _unbind) { LxDepthService.register(); dialogFilter = angular.element('<div/>', { class: 'dialog-filter' }); dialog = angular.element('<div/>', { class: 'dialog dialog--alert' }); var dialogHeader = buildDialogHeader(_title); var dialogContent = buildDialogContent(_text); var dialogActions = buildDialogActions(_buttons, _callback, _unbind); dialogFilter .css('z-index', LxDepthService.getDepth()) .appendTo('body'); dialog .append(dialogHeader) .append(dialogContent) .append(dialogActions) .css('z-index', LxDepthService.getDepth() + 1) .appendTo('body') .show() .focus(); $timeout(function() { angular.element(document.activeElement).blur(); dialogFilter.addClass('dialog-filter--is-shown'); dialog.addClass('dialog--is-shown'); }, 100); } } })(); (function() { 'use strict'; angular .module('lumx.progress') .directive('lxProgress', lxProgress); function lxProgress() { return { restrict: 'E', templateUrl: 'progress.html', scope: { lxColor: '@?', lxDiameter: '@?', lxType: '@', lxValue: '@' }, controller: LxProgressController, controllerAs: 'lxProgress', bindToController: true, replace: true }; } function LxProgressController() { var lxProgress = this; lxProgress.getCircularProgressValue = getCircularProgressValue; lxProgress.getLinearProgressValue = getLinearProgressValue; lxProgress.getProgressDiameter = getProgressDiameter; init(); //////////// function getCircularProgressValue() { if (angular.isDefined(lxProgress.lxValue)) { return { 'stroke-dasharray': lxProgress.lxValue * 1.26 + ',200' }; } } function getLinearProgressValue() { if (angular.isDefined(lxProgress.lxValue)) { return { 'transform': 'scale(' + lxProgress.lxValue / 100 + ', 1)' }; } } function getProgressDiameter() { if (lxProgress.lxType === 'circular') { return { 'transform': 'scale(' + parseInt(lxProgress.lxDiameter) / 100 + ')' }; } return; } function init() { lxProgress.lxDiameter = angular.isDefined(lxProgress.lxDiameter) ? lxProgress.lxDiameter : 100; lxProgress.lxColor = angular.isDefined(lxProgress.lxColor) ? lxProgress.lxColor : 'primary'; } } })(); (function() { 'use strict'; angular .module('lumx.radio-button') .directive('lxRadioGroup', lxRadioGroup) .directive('lxRadioButton', lxRadioButton) .directive('lxRadioButtonLabel', lxRadioButtonLabel) .directive('lxRadioButtonHelp', lxRadioButtonHelp); function lxRadioGroup() { return { restrict: 'E', templateUrl: 'radio-group.html', transclude: true, replace: true }; } function lxRadioButton() { return { restrict: 'E', templateUrl: 'radio-button.html', scope: { lxColor: '@?', name: '@', ngChange: '&?', ngDisabled: '=?', ngModel: '=', ngValue: '=?', value: '@?' }, controller: LxRadioButtonController, controllerAs: 'lxRadioButton', bindToController: true, transclude: true, replace: true }; } LxRadioButtonController.$inject = ['$scope', '$timeout', 'LxUtils']; function LxRadioButtonController($scope, $timeout, LxUtils) { var lxRadioButton = this; var radioButtonId; var radioButtonHasChildren; var timer; lxRadioButton.getRadioButtonId = getRadioButtonId; lxRadioButton.getRadioButtonHasChildren = getRadioButtonHasChildren; lxRadioButton.setRadioButtonId = setRadioButtonId; lxRadioButton.setRadioButtonHasChildren = setRadioButtonHasChildren; lxRadioButton.triggerNgChange = triggerNgChange; $scope.$on('$destroy', function() { $timeout.cancel(timer); }); init(); //////////// function getRadioButtonId() { return radioButtonId; } function getRadioButtonHasChildren() { return radioButtonHasChildren; } function init() { setRadioButtonId(LxUtils.generateUUID()); setRadioButtonHasChildren(false); if (angular.isDefined(lxRadioButton.value) && angular.isUndefined(lxRadioButton.ngValue)) { lxRadioButton.ngValue = lxRadioButton.value; } lxRadioButton.lxColor = angular.isUndefined(lxRadioButton.lxColor) ? 'accent' : lxRadioButton.lxColor; } function setRadioButtonId(_radioButtonId) { radioButtonId = _radioButtonId; } function setRadioButtonHasChildren(_radioButtonHasChildren) { radioButtonHasChildren = _radioButtonHasChildren; } function triggerNgChange() { timer = $timeout(lxRadioButton.ngChange); } } function lxRadioButtonLabel() { return { restrict: 'AE', require: ['^lxRadioButton', '^lxRadioButtonLabel'], templateUrl: 'radio-button-label.html', link: link, controller: LxRadioButtonLabelController, controllerAs: 'lxRadioButtonLabel', bindToController: true, transclude: true, replace: true }; function link(scope, element, attrs, ctrls) { ctrls[0].setRadioButtonHasChildren(true); ctrls[1].setRadioButtonId(ctrls[0].getRadioButtonId()); } } function LxRadioButtonLabelController() { var lxRadioButtonLabel = this; var radioButtonId; lxRadioButtonLabel.getRadioButtonId = getRadioButtonId; lxRadioButtonLabel.setRadioButtonId = setRadioButtonId; //////////// function getRadioButtonId() { return radioButtonId; } function setRadioButtonId(_radioButtonId) { radioButtonId = _radioButtonId; } } function lxRadioButtonHelp() { return { restrict: 'AE', require: '^lxRadioButton', templateUrl: 'radio-button-help.html', transclude: true, replace: true }; } })(); (function() { 'use strict'; angular .module('lumx.ripple') .directive('lxRipple', lxRipple); lxRipple.$inject = ['$timeout']; function lxRipple($timeout) { return { restrict: 'A', link: link, }; function link(scope, element, attrs) { var timer; element .css( { position: 'relative', overflow: 'hidden' }) .on('mousedown', function(e) { var ripple; if (element.find('.ripple').length === 0) { ripple = angular.element('<span/>', { class: 'ripple' }); if (attrs.lxRipple) { ripple.addClass('bgc-' + attrs.lxRipple); } element.prepend(ripple); } else { ripple = element.find('.ripple'); } ripple.removeClass('ripple--is-animated'); if (!ripple.height() && !ripple.width()) { var diameter = Math.max(element.outerWidth(), element.outerHeight()); ripple.css( { height: diameter, width: diameter }); } var x = e.pageX - element.offset().left - ripple.width() / 2; var y = e.pageY - element.offset().top - ripple.height() / 2; ripple.css( { top: y + 'px', left: x + 'px' }).addClass('ripple--is-animated'); timer = $timeout(function() { ripple.removeClass('ripple--is-animated'); }, 651); }); scope.$on('$destroy', function() { $timeout.cancel(timer); element.off(); }); } } })(); (function() { 'use strict'; angular .module('lumx.search-filter') .filter('lxSearchHighlight', lxSearchHighlight) .directive('lxSearchFilter', lxSearchFilter); lxSearchHighlight.$inject = ['$sce']; function lxSearchHighlight($sce) { function escapeRegexp(queryToEscape) { return queryToEscape.replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1'); } return function (matchItem, query, icon) { var string = ''; if (icon) { string += '<i class="mdi mdi-' + icon + '"></i>'; } string += query && matchItem ? matchItem.replace(new RegExp(escapeRegexp(query), 'gi'), '<strong>$&</strong>') : matchItem; return $sce.trustAsHtml(string); }; } function lxSearchFilter() { return { restrict: 'E', templateUrl: 'search-filter.html', scope: { autocomplete: '&?lxAutocomplete', closed: '=?lxClosed', color: '@?lxColor', icon: '@?lxIcon', onSelect: '=?lxOnSelect', searchOnFocus: '=?lxSearchOnFocus', theme: '@?lxTheme', width: '@?lxWidth' }, link: link, controller: LxSearchFilterController, controllerAs: 'lxSearchFilter', bindToController: true, replace: true, transclude: true }; function link(scope, element, attrs, ctrl, transclude) { var input; attrs.$observe('lxWidth', function(newWidth) { if (angular.isDefined(scope.lxSearchFilter.closed) && scope.lxSearchFilter.closed) { element.find('.search-filter__container').css('width', newWidth); } }); transclude(function() { input = element.find('input'); ctrl.setInput(input); ctrl.setModel(input.data('$ngModelController')); input.on('focus', ctrl.focusInput); input.on('blur', ctrl.blurInput); input.on('keydown', ctrl.keyEvent); }); scope.$on('$destroy', function() { input.off(); }); } } LxSearchFilterController.$inject = ['$element', '$scope', 'LxDropdownService', 'LxNotificationService', 'LxUtils']; function LxSearchFilterController($element, $scope, LxDropdownService, LxNotificationService, LxUtils) { var lxSearchFilter = this; var debouncedAutocomplete; var input; var itemSelected = false; lxSearchFilter.blurInput = blurInput; lxSearchFilter.clearInput = clearInput; lxSearchFilter.focusInput = focusInput; lxSearchFilter.getClass = getClass; lxSearchFilter.keyEvent = keyEvent; lxSearchFilter.openInput = openInput; lxSearchFilter.selectItem = selectItem; lxSearchFilter.setInput = setInput; lxSearchFilter.setModel = setModel; lxSearchFilter.activeChoiceIndex = -1; lxSearchFilter.color = angular.isDefined(lxSearchFilter.color) ? lxSearchFilter.color : 'black'; lxSearchFilter.dropdownId = LxUtils.generateUUID(); lxSearchFilter.theme = angular.isDefined(lxSearchFilter.theme) ? lxSearchFilter.theme : 'light'; //////////// function blurInput() { if (angular.isDefined(lxSearchFilter.closed) && lxSearchFilter.closed && !input.val()) { $element.velocity( { width: 40 }, { duration: 400, easing: 'easeOutQuint', queue: false }); } if (!input.val()) { lxSearchFilter.modelController.$setViewValue(undefined); } } function clearInput() { lxSearchFilter.modelController.$setViewValue(undefined); lxSearchFilter.modelController.$render(); // Temporarily disabling search on focus since we never want to trigger it when clearing the input. var searchOnFocus = lxSearchFilter.searchOnFocus; lxSearchFilter.searchOnFocus = false; input.focus(); lxSearchFilter.searchOnFocus = searchOnFocus; } function focusInput() { if (!lxSearchFilter.searchOnFocus) { return; } updateAutocomplete(lxSearchFilter.modelController.$viewValue, true); } function getClass() { var searchFilterClass = []; if (angular.isUndefined(lxSearchFilter.closed) || !lxSearchFilter.closed) { searchFilterClass.push('search-filter--opened-mode'); } if (angular.isDefined(lxSearchFilter.closed) && lxSearchFilter.closed) { searchFilterClass.push('search-filter--closed-mode'); } if (input.val()) { searchFilterClass.push('search-filter--has-clear-button'); } if (angular.isDefined(lxSearchFilter.color)) { searchFilterClass.push('search-filter--' + lxSearchFilter.color); } if (angular.isDefined(lxSearchFilter.theme)) { searchFilterClass.push('search-filter--theme-' + lxSearchFilter.theme); } if (angular.isFunction(lxSearchFilter.autocomplete)) { searchFilterClass.push('search-filter--autocomplete'); } if (LxDropdownService.isOpen(lxSearchFilter.dropdownId)) { searchFilterClass.push('search-filter--is-open'); } return searchFilterClass; } function keyEvent(_event) { if (!angular.isFunction(lxSearchFilter.autocomplete)) { return; } if (!LxDropdownService.isOpen(lxSearchFilter.dropdownId)) { lxSearchFilter.activeChoiceIndex = -1; } switch (_event.keyCode) { case 13: keySelect(); if (lxSearchFilter.activeChoiceIndex > -1) { _event.preventDefault(); } break; case 38: keyUp(); _event.preventDefault(); break; case 40: keyDown(); _event.preventDefault(); break; } $scope.$apply(); } function keyDown() { if (lxSearchFilter.autocompleteList.length) { lxSearchFilter.activeChoiceIndex += 1; if (lxSearchFilter.activeChoiceIndex >= lxSearchFilter.autocompleteList.length) { lxSearchFilter.activeChoiceIndex = 0; } } } function keySelect() { if (!lxSearchFilter.autocompleteList || lxSearchFilter.activeChoiceIndex === -1) { return; } selectItem(lxSearchFilter.autocompleteList[lxSearchFilter.activeChoiceIndex]); } function keyUp() { if (lxSearchFilter.autocompleteList.length) { lxSearchFilter.activeChoiceIndex -= 1; if (lxSearchFilter.activeChoiceIndex < 0) { lxSearchFilter.activeChoiceIndex = lxSearchFilter.autocompleteList.length - 1; } } } function onAutocompleteSuccess(autocompleteList) { lxSearchFilter.autocompleteList = autocompleteList; if (lxSearchFilter.autocompleteList.length) { LxDropdownService.open(lxSearchFilter.dropdownId, $element); } else { LxDropdownService.close(lxSearchFilter.dropdownId); } lxSearchFilter.isLoading = false; } function onAutocompleteError(error) { LxNotificationService.error(error); lxSearchFilter.isLoading = false; } function openInput() { if (angular.isDefined(lxSearchFilter.closed) && lxSearchFilter.closed) { $element.velocity( { width: angular.isDefined(lxSearchFilter.width) ? parseInt(lxSearchFilter.width) : 240 }, { duration: 400, easing: 'easeOutQuint', queue: false, complete: function() { input.focus(); } }); } else { input.focus(); } } function selectItem(_item) { itemSelected = true; LxDropdownService.close(lxSearchFilter.dropdownId); lxSearchFilter.modelController.$setViewValue(_item); lxSearchFilter.modelController.$render(); if (angular.isFunction(lxSearchFilter.onSelect)) { lxSearchFilter.onSelect(_item); } } function setInput(_input) { input = _input; } function setModel(_modelController) { lxSearchFilter.modelController = _modelController; if (angular.isFunction(lxSearchFilter.autocomplete) && angular.isFunction(lxSearchFilter.autocomplete())) { debouncedAutocomplete = LxUtils.debounce(function() { lxSearchFilter.isLoading = true; (lxSearchFilter.autocomplete()).apply(this, arguments); }, 500); lxSearchFilter.modelController.$parsers.push(updateAutocomplete); } } function updateAutocomplete(_newValue, _immediate) { if ((_newValue || (angular.isUndefined(_newValue) && lxSearchFilter.searchOnFocus)) && !itemSelected) { if (_immediate) { lxSearchFilter.isLoading = true; (lxSearchFilter.autocomplete())(_newValue, onAutocompleteSuccess, onAutocompleteError); } else { debouncedAutocomplete(_newValue, onAutocompleteSuccess, onAutocompleteError); } } else { debouncedAutocomplete.clear(); LxDropdownService.close(lxSearchFilter.dropdownId); } itemSelected = false; return _newValue; } } })(); (function() { 'use strict'; angular .module('lumx.select') .filter('filterChoices', filterChoices) .directive('lxSelect', lxSelect) .directive('lxSelectSelected', lxSelectSelected) .directive('lxSelectChoices', lxSelectChoices); filterChoices.$inject = ['$filter']; function filterChoices($filter) { return function(choices, externalFilter, textFilter) { if (externalFilter) { return choices; } var toFilter = []; if (!angular.isArray(choices)) { if (angular.isObject(choices)) { for (var idx in choices) { if (angular.isArray(choices[idx])) { toFilter = toFilter.concat(choices[idx]); } } } } else { toFilter = choices; } return $filter('filter')(toFilter, textFilter); }; } function lxSelect() { return { restrict: 'E', templateUrl: 'select.html', scope: { allowClear: '=?lxAllowClear', allowNewValue: '=?lxAllowNewValue', autocomplete: '=?lxAutocomplete', newValueTransform: '=?lxNewValueTransform', choices: '=?lxChoices', choicesCustomStyle: '=?lxChoicesCustomStyle', customStyle: '=?lxCustomStyle', displayFilter: '=?lxDisplayFilter', error: '=?lxError', filter: '&?lxFilter', fixedLabel: '=?lxFixedLabel', helper: '=?lxHelper', helperMessage: '@?lxHelperMessage', label: '@?lxLabel', loading: '=?lxLoading', modelToSelection: '&?lxModelToSelection', multiple: '=?lxMultiple', ngChange: '&?', ngDisabled: '=?', ngModel: '=', selectionToModel: '&?lxSelectionToModel', theme: '@?lxTheme', valid: '=?lxValid', viewMode: '@?lxViewMode' }, link: link, controller: LxSelectController, controllerAs: 'lxSelect', bindToController: true, replace: true, transclude: true }; function link(scope, element, attrs) { var backwardOneWay = ['customStyle']; var backwardTwoWay = ['allowClear', 'choices', 'error', 'loading', 'multiple', 'valid']; angular.forEach(backwardOneWay, function(attribute) { if (angular.isDefined(attrs[attribute])) { attrs.$observe(attribute, function(newValue) { scope.lxSelect[attribute] = newValue; }); } }); angular.forEach(backwardTwoWay, function(attribute) { if (angular.isDefined(attrs[attribute])) { scope.$watch(function() { return scope.$parent.$eval(attrs[attribute]); }, function(newValue) { if (attribute === 'multiple' && angular.isUndefined(newValue)) { scope.lxSelect[attribute] = true; } else { scope.lxSelect[attribute] = newValue; } }); } }); attrs.$observe('placeholder', function(newValue) { scope.lxSelect.label = newValue; }); attrs.$observe('change', function(newValue) { scope.lxSelect.ngChange = function(data) { return scope.$parent.$eval(newValue, data); }; }); attrs.$observe('filter', function(newValue) { scope.lxSelect.filter = function(data) { return scope.$parent.$eval(newValue, data); }; scope.lxSelect.displayFilter = true; }); attrs.$observe('modelToSelection', function(newValue) { scope.lxSelect.modelToSelection = function(data) { return scope.$parent.$eval(newValue, data); }; }); attrs.$observe('selectionToModel', function(newValue) { scope.lxSelect.selectionToModel = function(data) { return scope.$parent.$eval(newValue, data); }; }); } } LxSelectController.$inject = ['$interpolate', '$element', '$filter', '$sce', 'LxDropdownService', 'LxUtils']; function LxSelectController($interpolate, $element, $filter, $sce, LxDropdownService, LxUtils) { var lxSelect = this; var choiceTemplate; var selectedTemplate; lxSelect.displayChoice = displayChoice; lxSelect.displaySelected = displaySelected; lxSelect.displaySubheader = displaySubheader; lxSelect.getFilteredChoices = getFilteredChoices; lxSelect.getSelectedModel = getSelectedModel; lxSelect.isSelected = isSelected; lxSelect.keyEvent = keyEvent; lxSelect.registerChoiceTemplate = registerChoiceTemplate; lxSelect.registerSelectedTemplate = registerSelectedTemplate; lxSelect.select = select; lxSelect.toggleChoice = toggleChoice; lxSelect.unselect = unselect; lxSelect.updateFilter = updateFilter; lxSelect.helperDisplayable = helperDisplayable; lxSelect.activeChoiceIndex = -1; lxSelect.activeSelectedIndex = -1; lxSelect.uuid = LxUtils.generateUUID(); lxSelect.filterModel = undefined; lxSelect.ngModel = angular.isUndefined(lxSelect.ngModel) && lxSelect.multiple ? [] : lxSelect.ngModel; lxSelect.unconvertedModel = lxSelect.multiple ? [] : undefined; lxSelect.viewMode = angular.isUndefined(lxSelect.viewMode) ? 'field' : 'chips'; //////////// function arrayObjectIndexOf(arr, obj) { for (var i = 0; i < arr.length; i++) { if (angular.equals(arr[i], obj)) { return i; } } return -1; } function displayChoice(_choice) { var choiceScope = { $choice: _choice }; return $sce.trustAsHtml($interpolate(choiceTemplate)(choiceScope)); } function displaySelected(_selected) { var selectedScope = {}; if (!angular.isArray(lxSelect.choices)) { var found = false; for (var header in lxSelect.choices) { if (found) { break; } if (lxSelect.choices.hasOwnProperty(header)) { for (var idx = 0, len = lxSelect.choices[header].length; idx < len; idx++) { if (angular.equals(_selected, lxSelect.choices[header][idx])) { selectedScope.$selectedSubheader = header; found = true; break; } } } } } if (angular.isDefined(_selected)) { selectedScope.$selected = _selected; } else { selectedScope.$selected = getSelectedModel(); } return $sce.trustAsHtml($interpolate(selectedTemplate)(selectedScope)); } function displaySubheader(_subheader) { return $sce.trustAsHtml(_subheader); } function getFilteredChoices() { return $filter('filterChoices')(lxSelect.choices, lxSelect.filter, lxSelect.filterModel); } function getSelectedModel() { if (angular.isDefined(lxSelect.modelToSelection) || angular.isDefined(lxSelect.selectionToModel)) { return lxSelect.unconvertedModel; } else { return lxSelect.ngModel; } } function isSelected(_choice) { if (lxSelect.multiple && angular.isDefined(getSelectedModel())) { return arrayObjectIndexOf(getSelectedModel(), _choice) !== -1; } else if (angular.isDefined(getSelectedModel())) { return angular.equals(getSelectedModel(), _choice); } } function keyEvent(_event) { if (_event.keyCode !== 8) { lxSelect.activeSelectedIndex = -1; } if (!LxDropdownService.isOpen('dropdown-' + lxSelect.uuid)) { lxSelect.activeChoiceIndex = -1; } switch (_event.keyCode) { case 8: keyRemove(); break; case 13: keySelect(); _event.preventDefault(); break; case 38: keyUp(); _event.preventDefault(); break; case 40: keyDown(); _event.preventDefault(); break; } } function keyDown() { var filteredChoices = $filter('filterChoices')(lxSelect.choices, lxSelect.filter, lxSelect.filterModel); if (filteredChoices.length) { lxSelect.activeChoiceIndex += 1; if (lxSelect.activeChoiceIndex >= filteredChoices.length) { lxSelect.activeChoiceIndex = 0; } } if (lxSelect.autocomplete) { LxDropdownService.open('dropdown-' + lxSelect.uuid, '#lx-select-selected-wrapper-' + lxSelect.uuid); } } function keyRemove() { if (lxSelect.filterModel || !lxSelect.getSelectedModel().length) { return; } if (lxSelect.activeSelectedIndex === -1) { lxSelect.activeSelectedIndex = lxSelect.getSelectedModel().length - 1; } else { unselect(lxSelect.getSelectedModel()[lxSelect.activeSelectedIndex]); } } function keySelect() { var filteredChoices = $filter('filterChoices')(lxSelect.choices, lxSelect.filter, lxSelect.filterModel); if (filteredChoices.length && filteredChoices[lxSelect.activeChoiceIndex]) { toggleChoice(filteredChoices[lxSelect.activeChoiceIndex]); } else if (lxSelect.filterModel && lxSelect.allowNewValue) { if (angular.isArray(getSelectedModel())) { var value = angular.isFunction(lxSelect.newValueTransform) ? lxSelect.newValueTransform(lxSelect.filterModel) : lxSelect.filterModel; var identical = getSelectedModel().some(function (item) { return angular.equals(item, value); }); if (!identical) { getSelectedModel().push(value); } } lxSelect.filterModel = undefined; LxDropdownService.close('dropdown-' + lxSelect.uuid); } } function keyUp() { var filteredChoices = $filter('filterChoices')(lxSelect.choices, lxSelect.filter, lxSelect.filterModel); if (filteredChoices.length) { lxSelect.activeChoiceIndex -= 1; if (lxSelect.activeChoiceIndex < 0) { lxSelect.activeChoiceIndex = filteredChoices.length - 1; } } if (lxSelect.autocomplete) { LxDropdownService.open('dropdown-' + lxSelect.uuid, '#lx-select-selected-wrapper-' + lxSelect.uuid); } } function registerChoiceTemplate(_choiceTemplate) { choiceTemplate = _choiceTemplate; } function registerSelectedTemplate(_selectedTemplate) { selectedTemplate = _selectedTemplate; } function select(_choice) { if (lxSelect.multiple && angular.isUndefined(lxSelect.ngModel)) { lxSelect.ngModel = []; } if (angular.isDefined(lxSelect.selectionToModel)) { lxSelect.selectionToModel( { data: _choice, callback: function(resp) { if (lxSelect.multiple) { lxSelect.ngModel.push(resp); } else { lxSelect.ngModel = resp; } if (lxSelect.autocomplete) { $element.find('.lx-select-selected__filter').focus(); } } }); } else { if (lxSelect.multiple) { lxSelect.ngModel.push(_choice); } else { lxSelect.ngModel = _choice; } if (lxSelect.autocomplete) { $element.find('.lx-select-selected__filter').focus(); } } } function toggleChoice(_choice, _event) { if (lxSelect.multiple && !lxSelect.autocomplete) { _event.stopPropagation(); } if (lxSelect.multiple && isSelected(_choice)) { unselect(_choice); } else { select(_choice); } if (lxSelect.autocomplete) { lxSelect.activeChoiceIndex = -1; lxSelect.filterModel = undefined; LxDropdownService.close('dropdown-' + lxSelect.uuid); } } function unselect(_choice) { if (angular.isDefined(lxSelect.selectionToModel)) { lxSelect.selectionToModel( { data: _choice, callback: function(resp) { removeElement(lxSelect.ngModel, resp); if (lxSelect.autocomplete) { $element.find('.lx-select-selected__filter').focus(); lxSelect.activeSelectedIndex = -1; } } }); removeElement(lxSelect.unconvertedModel, _choice); } else { removeElement(lxSelect.ngModel, _choice); if (lxSelect.autocomplete) { $element.find('.lx-select-selected__filter').focus(); lxSelect.activeSelectedIndex = -1; } } } function updateFilter() { if (angular.isDefined(lxSelect.filter)) { lxSelect.filter( { newValue: lxSelect.filterModel }); } if (lxSelect.autocomplete) { lxSelect.activeChoiceIndex = -1; if (lxSelect.filterModel) { LxDropdownService.open('dropdown-' + lxSelect.uuid, '#lx-select-selected-wrapper-' + lxSelect.uuid); } else { LxDropdownService.close('dropdown-' + lxSelect.uuid); } } } function helperDisplayable() { // If helper message is not defined, message is not displayed... if (angular.isUndefined(lxSelect.helperMessage)) { return false; } // If helper is defined return it's state. if (angular.isDefined(lxSelect.helper)) { return lxSelect.helper; } // Else check if there's choices. var choices = lxSelect.getFilteredChoices(); if (angular.isArray(choices)) { return !choices.length; } else if (angular.isObject(choices)) { return !Object.keys(choices).length; } return true; } function removeElement(model, element) { var index = -1; for (var i = 0, len = model.length; i < len; i++) { if (angular.equals(element, model[i])) { index = i; break; } } if (index > -1) { model.splice(index, 1); } } } function lxSelectSelected() { return { restrict: 'E', require: ['lxSelectSelected', '^lxSelect'], templateUrl: 'select-selected.html', link: link, controller: LxSelectSelectedController, controllerAs: 'lxSelectSelected', bindToController: true, transclude: true }; function link(scope, element, attrs, ctrls, transclude) { ctrls[0].setParentController(ctrls[1]); transclude(scope, function(clone) { var template = ''; for (var i = 0; i < clone.length; i++) { template += clone[i].data || clone[i].outerHTML || ''; } ctrls[1].registerSelectedTemplate(template); }); } } function LxSelectSelectedController() { var lxSelectSelected = this; lxSelectSelected.clearModel = clearModel; lxSelectSelected.setParentController = setParentController; lxSelectSelected.removeSelected = removeSelected; //////////// function clearModel(_event) { _event.stopPropagation(); lxSelectSelected.parentCtrl.ngModel = undefined; lxSelectSelected.parentCtrl.unconvertedModel = undefined; } function setParentController(_parentCtrl) { lxSelectSelected.parentCtrl = _parentCtrl; } function removeSelected(_selected, _event) { _event.stopPropagation(); lxSelectSelected.parentCtrl.unselect(_selected); } } function lxSelectChoices() { return { restrict: 'E', require: ['lxSelectChoices', '^lxSelect'], templateUrl: 'select-choices.html', link: link, controller: LxSelectChoicesController, controllerAs: 'lxSelectChoices', bindToController: true, transclude: true }; function link(scope, element, attrs, ctrls, transclude) { ctrls[0].setParentController(ctrls[1]); transclude(scope, function(clone) { var template = ''; for (var i = 0; i < clone.length; i++) { template += clone[i].data || clone[i].outerHTML || ''; } ctrls[1].registerChoiceTemplate(template); }); } } LxSelectChoicesController.$inject = ['$scope', '$timeout']; function LxSelectChoicesController($scope, $timeout) { var lxSelectChoices = this; var timer; lxSelectChoices.isArray = isArray; lxSelectChoices.setParentController = setParentController; $scope.$on('$destroy', function() { $timeout.cancel(timer); }); //////////// function isArray() { return angular.isArray(lxSelectChoices.parentCtrl.choices); } function setParentController(_parentCtrl) { lxSelectChoices.parentCtrl = _parentCtrl; $scope.$watch(function() { return lxSelectChoices.parentCtrl.ngModel; }, function(newModel, oldModel) { timer = $timeout(function() { if (newModel !== oldModel && angular.isDefined(lxSelectChoices.parentCtrl.ngChange)) { lxSelectChoices.parentCtrl.ngChange( { newValue: newModel, oldValue: oldModel }); } if (angular.isDefined(lxSelectChoices.parentCtrl.modelToSelection) || angular.isDefined(lxSelectChoices.parentCtrl.selectionToModel)) { toSelection(); } }); }, true); } function toSelection() { if (lxSelectChoices.parentCtrl.multiple) { lxSelectChoices.parentCtrl.unconvertedModel = []; angular.forEach(lxSelectChoices.parentCtrl.ngModel, function(item) { lxSelectChoices.parentCtrl.modelToSelection( { data: item, callback: function(resp) { lxSelectChoices.parentCtrl.unconvertedModel.push(resp); } }); }); } else { lxSelectChoices.parentCtrl.modelToSelection( { data: lxSelectChoices.parentCtrl.ngModel, callback: function(resp) { lxSelectChoices.parentCtrl.unconvertedModel = resp; } }); } } } })(); (function() { 'use strict'; angular .module('lumx.stepper') .directive('lxStepper', lxStepper) .directive('lxStep', lxStep) .directive('lxStepNav', lxStepNav); /* Stepper */ function lxStepper() { return { restrict: 'E', templateUrl: 'stepper.html', scope: { cancel: '&?lxCancel', complete: '&lxComplete', isLinear: '=?lxIsLinear', labels: '=?lxLabels', layout: '@?lxLayout' }, controller: LxStepperController, controllerAs: 'lxStepper', bindToController: true, transclude: true }; } function LxStepperController() { var lxStepper = this; var _classes = []; var _defaultValues = { isLinear: true, labels: { 'back': 'Back', 'cancel': 'Cancel', 'continue': 'Continue', 'optional': 'Optional' }, layout: 'horizontal' }; lxStepper.addStep = addStep; lxStepper.getClasses = getClasses; lxStepper.goToStep = goToStep; lxStepper.isComplete = isComplete; lxStepper.updateStep = updateStep; lxStepper.activeIndex = 0; lxStepper.isLinear = angular.isDefined(lxStepper.isLinear) ? lxStepper.isLinear : _defaultValues.isLinear; lxStepper.labels = angular.isDefined(lxStepper.labels) ? lxStepper.labels : _defaultValues.labels; lxStepper.layout = angular.isDefined(lxStepper.layout) ? lxStepper.layout : _defaultValues.layout; lxStepper.steps = []; //////////// function addStep(step) { lxStepper.steps.push(step); } function getClasses() { _classes.length = 0; _classes.push('lx-stepper--layout-' + lxStepper.layout); if (lxStepper.isLinear) { _classes.push('lx-stepper--is-linear'); } if (lxStepper.steps[lxStepper.activeIndex].feedback) { _classes.push('lx-stepper--step-has-feedback'); } if (lxStepper.steps[lxStepper.activeIndex].isLoading) { _classes.push('lx-stepper--step-is-loading'); } return _classes; } function goToStep(index, bypass) { // Check if the the wanted step previous steps are optionals. If so, check if the step before the last optional step is valid to allow going to the wanted step from the nav (only if linear stepper). var stepBeforeLastOptionalStep; if (!bypass && lxStepper.isLinear) { for (var i = index - 1; i >= 0; i--) { if (angular.isDefined(lxStepper.steps[i]) && !lxStepper.steps[i].isOptional) { stepBeforeLastOptionalStep = lxStepper.steps[i]; break; } } if (angular.isDefined(stepBeforeLastOptionalStep) && stepBeforeLastOptionalStep.isValid === true) { bypass = true; } } // Check if the wanted step previous step is not valid to disallow going to the wanted step from the nav (only if linear stepper). if (!bypass && lxStepper.isLinear && angular.isDefined(lxStepper.steps[index - 1]) && (angular.isUndefined(lxStepper.steps[index - 1].isValid) || lxStepper.steps[index - 1].isValid === false)) { return; } if (index < lxStepper.steps.length) { lxStepper.activeIndex = parseInt(index); } } function isComplete() { var countMandatory = 0; var countValid = 0; for (var i = 0, len = lxStepper.steps.length; i < len; i++) { if (!lxStepper.steps[i].isOptional) { countMandatory++; if (lxStepper.steps[i].isValid === true) { countValid++; } } } if (countValid === countMandatory) { lxStepper.complete(); return true; } } function updateStep(step) { for (var i = 0, len = lxStepper.steps.length; i < len; i++) { if (lxStepper.steps[i].uuid === step.uuid) { lxStepper.steps[i].index = step.index; lxStepper.steps[i].label = step.label; return; } } } } /* Step */ function lxStep() { return { restrict: 'E', require: ['lxStep', '^lxStepper'], templateUrl: 'step.html', scope: { feedback: '@?lxFeedback', isEditable: '=?lxIsEditable', isOptional: '=?lxIsOptional', label: '@lxLabel', submit: '&?lxSubmit', validate: '&?lxValidate' }, link: link, controller: LxStepController, controllerAs: 'lxStep', bindToController: true, replace: true, transclude: true }; function link(scope, element, attrs, ctrls) { ctrls[0].init(ctrls[1], element.index()); attrs.$observe('lxFeedback', function(feedback) { ctrls[0].setFeedback(feedback); }); attrs.$observe('lxLabel', function(label) { ctrls[0].setLabel(label); }); attrs.$observe('lxIsEditable', function(isEditable) { ctrls[0].setIsEditable(isEditable); }); attrs.$observe('lxIsOptional', function(isOptional) { ctrls[0].setIsOptional(isOptional); }); } } LxStepController.$inject = ['$q', 'LxNotificationService', 'LxUtils']; function LxStepController($q, LxNotificationService, LxUtils) { var lxStep = this; var _classes = []; var _nextStepIndex; lxStep.getClasses = getClasses; lxStep.init = init; lxStep.previousStep = previousStep; lxStep.setFeedback = setFeedback; lxStep.setLabel = setLabel; lxStep.setIsEditable = setIsEditable; lxStep.setIsOptional = setIsOptional; lxStep.submitStep = submitStep; lxStep.step = { errorMessage: undefined, feedback: undefined, index: undefined, isEditable: false, isLoading: false, isOptional: false, isValid: undefined, label: undefined, uuid: LxUtils.generateUUID() }; //////////// function getClasses() { _classes.length = 0; if (lxStep.step.index === lxStep.parent.activeIndex) { _classes.push('lx-step--is-active'); } return _classes; } function init(parent, index) { lxStep.parent = parent; lxStep.step.index = index; lxStep.parent.addStep(lxStep.step); } function previousStep() { if (lxStep.step.index > 0) { lxStep.parent.goToStep(lxStep.step.index - 1); } } function setFeedback(feedback) { lxStep.step.feedback = feedback; updateParentStep(); } function setLabel(label) { lxStep.step.label = label; updateParentStep(); } function setIsEditable(isEditable) { lxStep.step.isEditable = isEditable; updateParentStep(); } function setIsOptional(isOptional) { lxStep.step.isOptional = isOptional; updateParentStep(); } function submitStep() { if (lxStep.step.isValid === true && !lxStep.step.isEditable) { lxStep.parent.goToStep(_nextStepIndex, true); return; } var validateFunction = lxStep.validate; var validity = true; if (angular.isFunction(validateFunction)) { validity = validateFunction(); } if (validity === true) { lxStep.step.isLoading = true; updateParentStep(); var submitFunction = lxStep.submit; if (!angular.isFunction(submitFunction)) { submitFunction = function() { return $q(function(resolve) { resolve(); }); }; } var promise = submitFunction(); promise.then(function(nextStepIndex) { lxStep.step.isValid = true; updateParentStep(); var isComplete = lxStep.parent.isComplete(); if (!isComplete) { _nextStepIndex = angular.isDefined(nextStepIndex) && nextStepIndex > lxStep.parent.activeIndex && (!lxStep.parent.isLinear || (lxStep.parent.isLinear && lxStep.parent.steps[nextStepIndex - 1].isOptional)) ? nextStepIndex : lxStep.step.index + 1; lxStep.parent.goToStep(_nextStepIndex, true); } }).catch(function(error) { LxNotificationService.error(error); }).finally(function() { lxStep.step.isLoading = false; updateParentStep(); }); } else { lxStep.step.isValid = false; lxStep.step.errorMessage = validity; updateParentStep(); } } function updateParentStep() { lxStep.parent.updateStep(lxStep.step); } } /* Step nav */ function lxStepNav() { return { restrict: 'E', require: ['lxStepNav', '^lxStepper'], templateUrl: 'step-nav.html', scope: { activeIndex: '@lxActiveIndex', step: '=lxStep' }, link: link, controller: LxStepNavController, controllerAs: 'lxStepNav', bindToController: true, replace: true, transclude: false }; function link(scope, element, attrs, ctrls) { ctrls[0].init(ctrls[1]); } } function LxStepNavController() { var lxStepNav = this; var _classes = []; lxStepNav.getClasses = getClasses; lxStepNav.init = init; //////////// function getClasses() { _classes.length = 0; if (parseInt(lxStepNav.step.index) === parseInt(lxStepNav.activeIndex)) { _classes.push('lx-step-nav--is-active'); } if (lxStepNav.step.isValid === true) { _classes.push('lx-step-nav--is-valid'); } else if (lxStepNav.step.isValid === false) { _classes.push('lx-step-nav--has-error'); } if (lxStepNav.step.isEditable) { _classes.push('lx-step-nav--is-editable'); } if (lxStepNav.step.isOptional) { _classes.push('lx-step-nav--is-optional'); } return _classes; } function init(parent, index) { lxStepNav.parent = parent; } } })(); (function() { 'use strict'; angular .module('lumx.switch') .directive('lxSwitch', lxSwitch) .directive('lxSwitchLabel', lxSwitchLabel) .directive('lxSwitchHelp', lxSwitchHelp); function lxSwitch() { return { restrict: 'E', templateUrl: 'switch.html', scope: { ngModel: '=', name: '@?', ngTrueValue: '@?', ngFalseValue: '@?', ngChange: '&?', ngDisabled: '=?', lxColor: '@?', lxPosition: '@?' }, controller: LxSwitchController, controllerAs: 'lxSwitch', bindToController: true, transclude: true, replace: true }; } LxSwitchController.$inject = ['$scope', '$timeout', 'LxUtils']; function LxSwitchController($scope, $timeout, LxUtils) { var lxSwitch = this; var switchId; var switchHasChildren; var timer; lxSwitch.getSwitchId = getSwitchId; lxSwitch.getSwitchHasChildren = getSwitchHasChildren; lxSwitch.setSwitchId = setSwitchId; lxSwitch.setSwitchHasChildren = setSwitchHasChildren; lxSwitch.triggerNgChange = triggerNgChange; $scope.$on('$destroy', function() { $timeout.cancel(timer); }); init(); //////////// function getSwitchId() { return switchId; } function getSwitchHasChildren() { return switchHasChildren; } function init() { setSwitchId(LxUtils.generateUUID()); setSwitchHasChildren(false); lxSwitch.ngTrueValue = angular.isUndefined(lxSwitch.ngTrueValue) ? true : lxSwitch.ngTrueValue; lxSwitch.ngFalseValue = angular.isUndefined(lxSwitch.ngFalseValue) ? false : lxSwitch.ngFalseValue; lxSwitch.lxColor = angular.isUndefined(lxSwitch.lxColor) ? 'accent' : lxSwitch.lxColor; lxSwitch.lxPosition = angular.isUndefined(lxSwitch.lxPosition) ? 'left' : lxSwitch.lxPosition; } function setSwitchId(_switchId) { switchId = _switchId; } function setSwitchHasChildren(_switchHasChildren) { switchHasChildren = _switchHasChildren; } function triggerNgChange() { timer = $timeout(lxSwitch.ngChange); } } function lxSwitchLabel() { return { restrict: 'AE', require: ['^lxSwitch', '^lxSwitchLabel'], templateUrl: 'switch-label.html', link: link, controller: LxSwitchLabelController, controllerAs: 'lxSwitchLabel', bindToController: true, transclude: true, replace: true }; function link(scope, element, attrs, ctrls) { ctrls[0].setSwitchHasChildren(true); ctrls[1].setSwitchId(ctrls[0].getSwitchId()); } } function LxSwitchLabelController() { var lxSwitchLabel = this; var switchId; lxSwitchLabel.getSwitchId = getSwitchId; lxSwitchLabel.setSwitchId = setSwitchId; //////////// function getSwitchId() { return switchId; } function setSwitchId(_switchId) { switchId = _switchId; } } function lxSwitchHelp() { return { restrict: 'AE', require: '^lxSwitch', templateUrl: 'switch-help.html', transclude: true, replace: true }; } })(); (function() { 'use strict'; angular .module('lumx.tabs') .directive('lxTabs', lxTabs) .directive('lxTab', lxTab) .directive('lxTabsPanes', lxTabsPanes) .directive('lxTabPane', lxTabPane); function lxTabs() { return { restrict: 'E', templateUrl: 'tabs.html', scope: { layout: '@?lxLayout', theme: '@?lxTheme', color: '@?lxColor', indicator: '@?lxIndicator', activeTab: '=?lxActiveTab', panesId: '@?lxPanesId', links: '=?lxLinks' }, controller: LxTabsController, controllerAs: 'lxTabs', bindToController: true, replace: true, transclude: true }; } LxTabsController.$inject = ['LxUtils', '$element', '$scope', '$timeout']; function LxTabsController(LxUtils, $element, $scope, $timeout) { var lxTabs = this; var tabsLength; var timer1; var timer2; var timer3; var timer4; lxTabs.removeTab = removeTab; lxTabs.setActiveTab = setActiveTab; lxTabs.setViewMode = setViewMode; lxTabs.tabIsActive = tabIsActive; lxTabs.updateTabs = updateTabs; lxTabs.activeTab = angular.isDefined(lxTabs.activeTab) ? lxTabs.activeTab : 0; lxTabs.color = angular.isDefined(lxTabs.color) ? lxTabs.color : 'primary'; lxTabs.indicator = angular.isDefined(lxTabs.indicator) ? lxTabs.indicator : 'accent'; lxTabs.layout = angular.isDefined(lxTabs.layout) ? lxTabs.layout : 'full'; lxTabs.tabs = []; lxTabs.theme = angular.isDefined(lxTabs.theme) ? lxTabs.theme : 'light'; lxTabs.viewMode = angular.isDefined(lxTabs.links) ? 'separate' : 'gather'; $scope.$watch(function() { return lxTabs.activeTab; }, function(_newActiveTab, _oldActiveTab) { timer1 = $timeout(function() { setIndicatorPosition(_oldActiveTab); if (lxTabs.viewMode === 'separate') { angular.element('#' + lxTabs.panesId).find('.tabs__pane').hide(); angular.element('#' + lxTabs.panesId).find('.tabs__pane').eq(lxTabs.activeTab).show(); } }); }); $scope.$watch(function() { return lxTabs.links; }, function(_newLinks) { lxTabs.viewMode = angular.isDefined(_newLinks) ? 'separate' : 'gather'; angular.forEach(_newLinks, function(link, index) { var tab = { uuid: (angular.isUndefined(link.uuid) || link.uuid.length === 0) ? LxUtils.generateUUID() : link.uuid, index: index, label: link.label, icon: link.icon, disabled: link.disabled }; updateTabs(tab); }); }); timer2 = $timeout(function() { tabsLength = lxTabs.tabs.length; }); $scope.$on('$destroy', function() { $timeout.cancel(timer1); $timeout.cancel(timer2); $timeout.cancel(timer3); $timeout.cancel(timer4); }); //////////// function removeTab(_tab) { lxTabs.tabs.splice(_tab.index, 1); angular.forEach(lxTabs.tabs, function(tab, index) { tab.index = index; }); if (lxTabs.activeTab === 0) { timer3 = $timeout(function() { setIndicatorPosition(); }); } else { setActiveTab(lxTabs.tabs[0]); } } function setActiveTab(_tab) { if (!_tab.disabled) { lxTabs.activeTab = _tab.index; } } function setIndicatorPosition(_previousActiveTab) { var direction = lxTabs.activeTab > _previousActiveTab ? 'right' : 'left'; var indicator = $element.find('.tabs__indicator'); var activeTab = $element.find('.tabs__link').eq(lxTabs.activeTab); var indicatorLeft = activeTab.position().left; var indicatorRight = $element.outerWidth() - (indicatorLeft + activeTab.outerWidth()); if (angular.isUndefined(_previousActiveTab)) { indicator.css( { left: indicatorLeft, right: indicatorRight }); } else { var animationProperties = { duration: 200, easing: 'easeOutQuint' }; if (direction === 'left') { indicator.velocity( { left: indicatorLeft }, animationProperties); indicator.velocity( { right: indicatorRight }, animationProperties); } else { indicator.velocity( { right: indicatorRight }, animationProperties); indicator.velocity( { left: indicatorLeft }, animationProperties); } } } function setViewMode(_viewMode) { lxTabs.viewMode = _viewMode; } function tabIsActive(_index) { return lxTabs.activeTab === _index; } function updateTabs(_tab) { var newTab = true; angular.forEach(lxTabs.tabs, function(tab) { if (tab.index === _tab.index) { newTab = false; tab.uuid = _tab.uuid; tab.icon = _tab.icon; tab.label = _tab.label; } }); if (newTab) { lxTabs.tabs.push(_tab); if (angular.isDefined(tabsLength)) { timer4 = $timeout(function() { setIndicatorPosition(); }); } } } } function lxTab() { return { restrict: 'E', require: ['lxTab', '^lxTabs'], templateUrl: 'tab.html', scope: { ngDisabled: '=?' }, link: link, controller: LxTabController, controllerAs: 'lxTab', bindToController: true, replace: true, transclude: true }; function link(scope, element, attrs, ctrls) { ctrls[0].init(ctrls[1], element.index()); attrs.$observe('lxLabel', function(_newLabel) { ctrls[0].setLabel(_newLabel); }); attrs.$observe('lxIcon', function(_newIcon) { ctrls[0].setIcon(_newIcon); }); } } LxTabController.$inject = ['$scope', 'LxUtils']; function LxTabController($scope, LxUtils) { var lxTab = this; var parentCtrl; var tab = { uuid: LxUtils.generateUUID(), index: undefined, label: undefined, icon: undefined, disabled: false }; lxTab.init = init; lxTab.setIcon = setIcon; lxTab.setLabel = setLabel; lxTab.tabIsActive = tabIsActive; $scope.$watch(function() { return lxTab.ngDisabled; }, function(_isDisabled) { if (_isDisabled) { tab.disabled = true; } else { tab.disabled = false; } parentCtrl.updateTabs(tab); }); $scope.$on('$destroy', function() { parentCtrl.removeTab(tab); }); //////////// function init(_parentCtrl, _index) { parentCtrl = _parentCtrl; tab.index = _index; parentCtrl.updateTabs(tab); } function setIcon(_icon) { tab.icon = _icon; parentCtrl.updateTabs(tab); } function setLabel(_label) { tab.label = _label; parentCtrl.updateTabs(tab); } function tabIsActive() { return parentCtrl.tabIsActive(tab.index); } } function lxTabsPanes() { return { restrict: 'E', templateUrl: 'tabs-panes.html', scope: true, replace: true, transclude: true }; } function lxTabPane() { return { restrict: 'E', templateUrl: 'tab-pane.html', scope: true, replace: true, transclude: true }; } })(); (function() { 'use strict'; angular .module('lumx.text-field') .directive('lxTextField', lxTextField); lxTextField.$inject = ['$timeout']; function lxTextField($timeout) { return { restrict: 'E', templateUrl: 'text-field.html', scope: { allowClear: '=?lxAllowClear', error: '=?lxError', fixedLabel: '=?lxFixedLabel', focus: '=?lxFocus', icon: '@?lxIcon', label: '@lxLabel', ngDisabled: '=?', theme: '@?lxTheme', valid: '=?lxValid' }, link: link, controller: LxTextFieldController, controllerAs: 'lxTextField', bindToController: true, replace: true, transclude: true }; function link(scope, element, attrs, ctrl, transclude) { var backwardOneWay = ['icon', 'label', 'theme']; var backwardTwoWay = ['error', 'fixedLabel', 'valid']; var input; var timer; angular.forEach(backwardOneWay, function(attribute) { if (angular.isDefined(attrs[attribute])) { attrs.$observe(attribute, function(newValue) { scope.lxTextField[attribute] = newValue; }); } }); angular.forEach(backwardTwoWay, function(attribute) { if (angular.isDefined(attrs[attribute])) { scope.$watch(function() { return scope.$parent.$eval(attrs[attribute]); }, function(newValue) { scope.lxTextField[attribute] = newValue; }); } }); transclude(function() { input = element.find('textarea'); if (input[0]) { input.on('cut paste drop keydown', function() { timer = $timeout(ctrl.updateTextareaHeight); }); } else { input = element.find('input'); } input.addClass('text-field__input'); ctrl.setInput(input); ctrl.setModel(input.data('$ngModelController')); input.on('focus', function() { var phase = scope.$root.$$phase; if (phase === '$apply' || phase === '$digest') { ctrl.focusInput(); } else { scope.$apply(ctrl.focusInput); } }); input.on('blur', ctrl.blurInput); }); scope.$on('$destroy', function() { $timeout.cancel(timer); input.off(); }); } } LxTextFieldController.$inject = ['$scope', '$timeout']; function LxTextFieldController($scope, $timeout) { var lxTextField = this; var input; var modelController; var timer1; var timer2; lxTextField.blurInput = blurInput; lxTextField.clearInput = clearInput; lxTextField.focusInput = focusInput; lxTextField.hasValue = hasValue; lxTextField.setInput = setInput; lxTextField.setModel = setModel; lxTextField.updateTextareaHeight = updateTextareaHeight; $scope.$watch(function() { return modelController.$viewValue; }, function(newValue, oldValue) { if (angular.isDefined(newValue) && newValue) { lxTextField.isActive = true; } else { lxTextField.isActive = false; } }); $scope.$watch(function() { return lxTextField.focus; }, function(newValue, oldValue) { if (angular.isDefined(newValue) && newValue) { $timeout(function() { input.focus(); // Reset the value so we can re-focus the field later on if we want to. lxTextField.focus = false; }); } }); $scope.$on('$destroy', function() { $timeout.cancel(timer1); $timeout.cancel(timer2); }); //////////// function blurInput() { if (!hasValue()) { $scope.$apply(function() { lxTextField.isActive = false; }); } $scope.$apply(function() { lxTextField.isFocus = false; }); } function clearInput(_event) { _event.stopPropagation(); modelController.$setViewValue(undefined); modelController.$render(); } function focusInput() { lxTextField.isActive = true; lxTextField.isFocus = true; } function hasValue() { return angular.isDefined(input.val()) && input.val().length > 0; } function init() { lxTextField.isActive = hasValue(); lxTextField.focus = angular.isDefined(lxTextField.focus) ? lxTextField.focus : false; lxTextField.isFocus = lxTextField.focus; } function setInput(_input) { input = _input; timer1 = $timeout(init); if (input.selector === 'textarea') { timer2 = $timeout(updateTextareaHeight); } } function setModel(_modelControler) { modelController = _modelControler; } function updateTextareaHeight() { var tmpTextArea = angular.element('<textarea class="text-field__input" style="width: ' + input.width() + 'px;">' + input.val() + '</textarea>'); tmpTextArea.appendTo('body'); input.css( { height: tmpTextArea[0].scrollHeight + 'px' }); tmpTextArea.remove(); } } })(); (function() { 'use strict'; angular .module('lumx.tooltip') .directive('lxTooltip', lxTooltip); function lxTooltip() { return { restrict: 'A', scope: { tooltip: '@lxTooltip', position: '@?lxTooltipPosition' }, link: link, controller: LxTooltipController, controllerAs: 'lxTooltip', bindToController: true }; function link(scope, element, attrs, ctrl) { if (angular.isDefined(attrs.lxTooltip)) { attrs.$observe('lxTooltip', function(newValue) { ctrl.updateTooltipText(newValue); }); } if (angular.isDefined(attrs.lxTooltipPosition)) { attrs.$observe('lxTooltipPosition', function(newValue) { scope.lxTooltip.position = newValue; }); } element.on('mouseenter', ctrl.showTooltip); element.on('mouseleave', ctrl.hideTooltip); scope.$on('$destroy', function() { element.off(); }); } } LxTooltipController.$inject = ['$element', '$scope', '$timeout', 'LxDepthService']; function LxTooltipController($element, $scope, $timeout, LxDepthService) { var lxTooltip = this; var timer1; var timer2; var tooltip; var tooltipBackground; var tooltipLabel; lxTooltip.hideTooltip = hideTooltip; lxTooltip.showTooltip = showTooltip; lxTooltip.updateTooltipText = updateTooltipText; lxTooltip.position = angular.isDefined(lxTooltip.position) ? lxTooltip.position : 'top'; $scope.$on('$destroy', function() { if (angular.isDefined(tooltip)) { tooltip.remove(); tooltip = undefined; } $timeout.cancel(timer1); $timeout.cancel(timer2); }); //////////// function hideTooltip() { if (angular.isDefined(tooltip)) { tooltip.removeClass('tooltip--is-active'); timer1 = $timeout(function() { if (angular.isDefined(tooltip)) { tooltip.remove(); tooltip = undefined; } }, 200); } } function setTooltipPosition() { var width = $element.outerWidth(), height = $element.outerHeight(), top = $element.offset().top, left = $element.offset().left; tooltip .append(tooltipBackground) .append(tooltipLabel) .appendTo('body'); if (lxTooltip.position === 'top') { tooltip.css( { left: left - (tooltip.outerWidth() / 2) + (width / 2), top: top - tooltip.outerHeight() }); } else if (lxTooltip.position === 'bottom') { tooltip.css( { left: left - (tooltip.outerWidth() / 2) + (width / 2), top: top + height }); } else if (lxTooltip.position === 'left') { tooltip.css( { left: left - tooltip.outerWidth(), top: top + (height / 2) - (tooltip.outerHeight() / 2) }); } else if (lxTooltip.position === 'right') { tooltip.css( { left: left + width, top: top + (height / 2) - (tooltip.outerHeight() / 2) }); } } function showTooltip() { if (angular.isUndefined(tooltip)) { LxDepthService.register(); tooltip = angular.element('<div/>', { class: 'tooltip tooltip--' + lxTooltip.position }); tooltipBackground = angular.element('<div/>', { class: 'tooltip__background' }); tooltipLabel = angular.element('<span/>', { class: 'tooltip__label', text: lxTooltip.tooltip }); setTooltipPosition(); tooltip .append(tooltipBackground) .append(tooltipLabel) .css('z-index', LxDepthService.getDepth()) .appendTo('body'); timer2 = $timeout(function() { tooltip.addClass('tooltip--is-active'); }); } } function updateTooltipText(_newValue) { if (angular.isDefined(tooltipLabel)) { tooltipLabel.text(_newValue); } } } })(); angular.module("lumx.dropdown").run(['$templateCache', function(a) { a.put('dropdown.html', '<div class="dropdown"\n' + ' ng-class="{ \'dropdown--has-toggle\': lxDropdown.hasToggle,\n' + ' \'dropdown--is-open\': lxDropdown.isOpen }"\n' + ' ng-transclude></div>\n' + ''); a.put('dropdown-toggle.html', '<div class="dropdown-toggle" ng-transclude></div>\n' + ''); a.put('dropdown-menu.html', '<div class="dropdown-menu">\n' + ' <div class="dropdown-menu__content" ng-transclude ng-if="lxDropdownMenu.parentCtrl.isOpen"></div>\n' + '</div>\n' + ''); }]); angular.module("lumx.file-input").run(['$templateCache', function(a) { a.put('file-input.html', '<div class="input-file">\n' + ' <span class="input-file__label">{{ lxFileInput.label }}</span>\n' + ' <span class="input-file__filename">{{ lxFileInput.fileName }}</span>\n' + ' <input type="file" class="input-file__input">\n' + '</div>\n' + ''); }]); angular.module("lumx.text-field").run(['$templateCache', function(a) { a.put('text-field.html', '<div class="text-field"\n' + ' ng-class="{ \'text-field--error\': lxTextField.error,\n' + ' \'text-field--fixed-label\': lxTextField.fixedLabel,\n' + ' \'text-field--has-icon\': lxTextField.icon,\n' + ' \'text-field--has-value\': lxTextField.hasValue(),\n' + ' \'text-field--is-active\': lxTextField.isActive,\n' + ' \'text-field--is-disabled\': lxTextField.ngDisabled,\n' + ' \'text-field--is-focus\': lxTextField.isFocus,\n' + ' \'text-field--theme-light\': !lxTextField.theme || lxTextField.theme === \'light\',\n' + ' \'text-field--theme-dark\': lxTextField.theme === \'dark\',\n' + ' \'text-field--valid\': lxTextField.valid }">\n' + ' <div class="text-field__icon" ng-if="lxTextField.icon">\n' + ' <i class="mdi mdi-{{ lxTextField.icon }}"></i>\n' + ' </div>\n' + '\n' + ' <label class="text-field__label">\n' + ' {{ lxTextField.label }}\n' + ' </label>\n' + '\n' + ' <div ng-transclude></div>\n' + '\n' + ' <span class="text-field__clear" ng-click="lxTextField.clearInput($event)" ng-if="lxTextField.allowClear">\n' + ' <i class="mdi mdi-close-circle"></i>\n' + ' </span>\n' + '</div>\n' + ''); }]); angular.module("lumx.search-filter").run(['$templateCache', function(a) { a.put('search-filter.html', '<div class="search-filter" ng-class="lxSearchFilter.getClass()">\n' + ' <div class="search-filter__container">\n' + ' <div class="search-filter__button">\n' + ' <lx-button type="submit" lx-size="l" lx-color="{{ lxSearchFilter.color }}" lx-type="icon" ng-click="lxSearchFilter.openInput()">\n' + ' <i class="mdi mdi-magnify"></i>\n' + ' </lx-button>\n' + ' </div>\n' + '\n' + ' <div class="search-filter__input" ng-transclude></div>\n' + '\n' + ' <div class="search-filter__clear">\n' + ' <lx-button type="button" lx-size="l" lx-color="{{ lxSearchFilter.color }}" lx-type="icon" ng-click="lxSearchFilter.clearInput()">\n' + ' <i class="mdi mdi-close"></i>\n' + ' </lx-button>\n' + ' </div>\n' + ' </div>\n' + '\n' + ' <div class="search-filter__loader" ng-if="lxSearchFilter.isLoading">\n' + ' <lx-progress lx-type="linear"></lx-progress>\n' + ' </div>\n' + '\n' + ' <lx-dropdown id="{{ lxSearchFilter.dropdownId }}" lx-effect="none" lx-width="100%" ng-if="lxSearchFilter.autocomplete">\n' + ' <lx-dropdown-menu class="search-filter__autocomplete-list">\n' + ' <ul>\n' + ' <li ng-repeat="item in lxSearchFilter.autocompleteList track by $index">\n' + ' <a class="search-filter__autocomplete-item"\n' + ' ng-class="{ \'search-filter__autocomplete-item--is-active\': lxSearchFilter.activeChoiceIndex === $index }"\n' + ' ng-click="lxSearchFilter.selectItem(item)"\n' + ' ng-bind-html="item | lxSearchHighlight:lxSearchFilter.modelController.$viewValue:lxSearchFilter.icon"></a>\n' + ' </li>\n' + ' </ul>\n' + ' </lx-dropdown-menu>\n' + ' </lx-dropdown>\n' + '</div>'); }]); angular.module("lumx.select").run(['$templateCache', function(a) { a.put('select.html', '<div class="lx-select"\n' + ' ng-class="{ \'lx-select--error\': lxSelect.error,\n' + ' \'lx-select--fixed-label\': lxSelect.fixedLabel && lxSelect.viewMode === \'field\',\n' + ' \'lx-select--is-active\': (!lxSelect.multiple && lxSelect.getSelectedModel()) || (lxSelect.multiple && lxSelect.getSelectedModel().length),\n' + ' \'lx-select--is-disabled\': lxSelect.ngDisabled,\n' + ' \'lx-select--is-multiple\': lxSelect.multiple,\n' + ' \'lx-select--is-unique\': !lxSelect.multiple,\n' + ' \'lx-select--theme-light\': !lxSelect.theme || lxSelect.theme === \'light\',\n' + ' \'lx-select--theme-dark\': lxSelect.theme === \'dark\',\n' + ' \'lx-select--valid\': lxSelect.valid,\n' + ' \'lx-select--custom-style\': lxSelect.customStyle,\n' + ' \'lx-select--default-style\': !lxSelect.customStyle,\n' + ' \'lx-select--view-mode-field\': !lxSelect.multiple || (lxSelect.multiple && lxSelect.viewMode === \'field\'),\n' + ' \'lx-select--view-mode-chips\': lxSelect.multiple && lxSelect.viewMode === \'chips\',\n' + ' \'lx-select--autocomplete\': lxSelect.autocomplete }">\n' + ' <span class="lx-select-label" ng-if="!lxSelect.autocomplete">\n' + ' {{ ::lxSelect.label }}\n' + ' </span>\n' + '\n' + ' <lx-dropdown id="dropdown-{{ lxSelect.uuid }}" lx-width="100%" lx-effect="{{ lxSelect.autocomplete ? \'none\' : \'expand\' }}">\n' + ' <ng-transclude></ng-transclude>\n' + ' </lx-dropdown>\n' + '</div>\n' + ''); a.put('select-selected.html', '<div>\n' + ' <lx-dropdown-toggle ng-if="::!lxSelectSelected.parentCtrl.autocomplete">\n' + ' <ng-include src="\'select-selected-content.html\'"></ng-include>\n' + ' </lx-dropdown-toggle>\n' + '\n' + ' <ng-include src="\'select-selected-content.html\'" ng-if="::lxSelectSelected.parentCtrl.autocomplete"></ng-include>\n' + '</div>\n' + ''); a.put('select-selected-content.html', '<div class="lx-select-selected-wrapper" id="lx-select-selected-wrapper-{{ lxSelectSelected.parentCtrl.uuid }}">\n' + ' <div class="lx-select-selected" ng-if="!lxSelectSelected.parentCtrl.multiple && lxSelectSelected.parentCtrl.getSelectedModel()">\n' + ' <span class="lx-select-selected__value"\n' + ' ng-bind-html="lxSelectSelected.parentCtrl.displaySelected()"></span>\n' + '\n' + ' <a class="lx-select-selected__clear"\n' + ' ng-click="lxSelectSelected.clearModel($event)"\n' + ' ng-if="::lxSelectSelected.parentCtrl.allowClear">\n' + ' <i class="mdi mdi-close-circle"></i>\n' + ' </a>\n' + ' </div>\n' + '\n' + ' <div class="lx-select-selected" ng-if="lxSelectSelected.parentCtrl.multiple">\n' + ' <span class="lx-select-selected__tag"\n' + ' ng-class="{ \'lx-select-selected__tag--is-active\': lxSelectSelected.parentCtrl.activeSelectedIndex === $index }"\n' + ' ng-click="lxSelectSelected.removeSelected(selected, $event)"\n' + ' ng-repeat="selected in lxSelectSelected.parentCtrl.getSelectedModel()"\n' + ' ng-bind-html="lxSelectSelected.parentCtrl.displaySelected(selected)"></span>\n' + '\n' + ' <input type="text"\n' + ' placeholder="{{ ::lxSelectSelected.parentCtrl.label }}"\n' + ' class="lx-select-selected__filter"\n' + ' ng-model="lxSelectSelected.parentCtrl.filterModel"\n' + ' ng-change="lxSelectSelected.parentCtrl.updateFilter()"\n' + ' ng-keydown="lxSelectSelected.parentCtrl.keyEvent($event)"\n' + ' ng-if="::lxSelectSelected.parentCtrl.autocomplete && !lxSelectSelected.parentCtrl.ngDisabled">\n' + ' </div>\n' + '</div>'); a.put('select-choices.html', '<lx-dropdown-menu class="lx-select-choices"\n' + ' ng-class="{ \'lx-select-choices--custom-style\': lxSelectChoices.parentCtrl.choicesCustomStyle,\n' + ' \'lx-select-choices--default-style\': !lxSelectChoices.parentCtrl.choicesCustomStyle,\n' + ' \'lx-select-choices--is-multiple\': lxSelectChoices.parentCtrl.multiple,\n' + ' \'lx-select-choices--is-unique\': !lxSelectChoices.parentCtrl.multiple, }">\n' + ' <ul>\n' + ' <li class="lx-select-choices__filter" ng-if="::lxSelectChoices.parentCtrl.displayFilter && !lxSelectChoices.parentCtrl.autocomplete">\n' + ' <lx-search-filter lx-dropdown-filter>\n' + ' <input type="text" ng-model="lxSelectChoices.parentCtrl.filterModel" ng-change="lxSelectChoices.parentCtrl.updateFilter()">\n' + ' </lx-search-filter>\n' + ' </li>\n' + ' \n' + ' <div ng-if="::lxSelectChoices.isArray()">\n' + ' <li class="lx-select-choices__choice"\n' + ' ng-class="{ \'lx-select-choices__choice--is-selected\': lxSelectChoices.parentCtrl.isSelected(choice),\n' + ' \'lx-select-choices__choice--is-focus\': lxSelectChoices.parentCtrl.activeChoiceIndex === $index }"\n' + ' ng-repeat="choice in lxSelectChoices.parentCtrl.choices | filterChoices:lxSelectChoices.parentCtrl.filter:lxSelectChoices.parentCtrl.filterModel"\n' + ' ng-bind-html="::lxSelectChoices.parentCtrl.displayChoice(choice)"\n' + ' ng-click="lxSelectChoices.parentCtrl.toggleChoice(choice, $event)"></li>\n' + ' </div>\n' + '\n' + ' <div ng-if="::!lxSelectChoices.isArray()">\n' + ' <li class="lx-select-choices__subheader"\n' + ' ng-repeat-start="(subheader, children) in lxSelectChoices.parentCtrl.choices"\n' + ' ng-bind-html="::lxSelectChoices.parentCtrl.displaySubheader(subheader)"></li>\n' + '\n' + ' <li class="lx-select-choices__choice"\n' + ' ng-class="{ \'lx-select-choices__choice--is-selected\': lxSelectChoices.parentCtrl.isSelected(choice),\n' + ' \'lx-select-choices__choice--is-focus\': lxSelectChoices.parentCtrl.activeChoiceIndex === $index }"\n' + ' ng-repeat-end\n' + ' ng-repeat="choice in children | filterChoices:lxSelectChoices.parentCtrl.filter:lxSelectChoices.parentCtrl.filterModel"\n' + ' ng-bind-html="::lxSelectChoices.parentCtrl.displayChoice(choice)"\n' + ' ng-click="lxSelectChoices.parentCtrl.toggleChoice(choice, $event)"></li>\n' + ' </div>\n' + '\n' + ' <li class="lx-select-choices__subheader" ng-if="lxSelectChoices.parentCtrl.helperDisplayable()">\n' + ' {{ lxSelectChoices.parentCtrl.helperMessage }}\n' + ' </li>\n' + '\n' + ' <li class="lx-select-choices__loader" ng-if="lxSelectChoices.parentCtrl.loading">\n' + ' <lx-progress lx-type="circular" lx-color="primary" lx-diameter="20"></lx-progress>\n' + ' </li>\n' + ' </ul>\n' + '</lx-dropdown-menu>\n' + ''); }]); angular.module("lumx.tabs").run(['$templateCache', function(a) { a.put('tabs.html', '<div class="tabs tabs--layout-{{ lxTabs.layout }} tabs--theme-{{ lxTabs.theme }} tabs--color-{{ lxTabs.color }} tabs--indicator-{{ lxTabs.indicator }}">\n' + ' <div class="tabs__links">\n' + ' <a class="tabs__link"\n' + ' ng-class="{ \'tabs__link--is-active\': lxTabs.tabIsActive(tab.index),\n' + ' \'tabs__link--is-disabled\': tab.disabled }"\n' + ' ng-repeat="tab in lxTabs.tabs"\n' + ' ng-click="lxTabs.setActiveTab(tab)"\n' + ' lx-ripple>\n' + ' <i class="mdi mdi-{{ tab.icon }}" ng-if="tab.icon"></i>\n' + ' <span ng-if="tab.label">{{ tab.label }}</span>\n' + ' </a>\n' + ' </div>\n' + ' \n' + ' <div class="tabs__panes" ng-if="lxTabs.viewMode === \'gather\'" ng-transclude></div>\n' + ' <div class="tabs__indicator"></div>\n' + '</div>\n' + ''); a.put('tabs-panes.html', '<div class="tabs">\n' + ' <div class="tabs__panes" ng-transclude></div>\n' + '</div>'); a.put('tab.html', '<div class="tabs__pane" ng-class="{ \'tabs__pane--is-disabled\': lxTab.ngDisabled }">\n' + ' <div ng-if="lxTab.tabIsActive()" ng-transclude></div>\n' + '</div>\n' + ''); a.put('tab-pane.html', '<div class="tabs__pane" ng-transclude></div>\n' + ''); }]); angular.module("lumx.date-picker").run(['$templateCache', function(a) { a.put('date-picker.html', '<div class="lx-date">\n' + ' <!-- Date picker input -->\n' + ' <div class="lx-date-input" ng-click="lxDatePicker.openDatePicker()" ng-if="lxDatePicker.hasInput">\n' + ' <ng-transclude></ng-transclude>\n' + ' </div>\n' + ' \n' + ' <!-- Date picker -->\n' + ' <div class="lx-date-picker lx-date-picker--{{ lxDatePicker.color }}">\n' + ' <div ng-if="lxDatePicker.isOpen">\n' + ' <!-- Date picker: header -->\n' + ' <div class="lx-date-picker__header">\n' + ' <a class="lx-date-picker__current-year"\n' + ' ng-class="{ \'lx-date-picker__current-year--is-active\': lxDatePicker.yearSelection }"\n' + ' ng-click="lxDatePicker.displayYearSelection()">\n' + ' {{ lxDatePicker.moment(lxDatePicker.ngModel).format(\'YYYY\') }}\n' + ' </a>\n' + '\n' + ' <a class="lx-date-picker__current-date"\n' + ' ng-class="{ \'lx-date-picker__current-date--is-active\': !lxDatePicker.yearSelection }"\n' + ' ng-click="lxDatePicker.hideYearSelection()">\n' + ' {{ lxDatePicker.getDateFormatted() }}\n' + ' </a>\n' + ' </div>\n' + ' \n' + ' <!-- Date picker: content -->\n' + ' <div class="lx-date-picker__content">\n' + ' <!-- Calendar -->\n' + ' <div class="lx-date-picker__calendar" ng-if="!lxDatePicker.yearSelection">\n' + ' <div class="lx-date-picker__nav">\n' + ' <lx-button lx-size="l" lx-color="black" lx-type="icon" ng-click="lxDatePicker.previousMonth()">\n' + ' <i class="mdi mdi-chevron-left"></i>\n' + ' </lx-button>\n' + '\n' + ' <span>{{ lxDatePicker.ngModelMoment.format(\'MMMM YYYY\') }}</span>\n' + ' \n' + ' <lx-button lx-size="l" lx-color="black" lx-type="icon" ng-click="lxDatePicker.nextMonth()">\n' + ' <i class="mdi mdi-chevron-right"></i>\n' + ' </lx-button>\n' + ' </div>\n' + '\n' + ' <div class="lx-date-picker__days-of-week">\n' + ' <span ng-repeat="day in lxDatePicker.daysOfWeek">{{ day }}</span>\n' + ' </div>\n' + '\n' + ' <div class="lx-date-picker__days">\n' + ' <span class="lx-date-picker__day lx-date-picker__day--is-empty"\n' + ' ng-repeat="x in lxDatePicker.emptyFirstDays">&nbsp;</span>\n' + '\n' + ' <div class="lx-date-picker__day"\n' + ' ng-class="{ \'lx-date-picker__day--is-selected\': day.selected,\n' + ' \'lx-date-picker__day--is-today\': day.today && !day.selected,\n' + ' \'lx-date-picker__day--is-disabled\': day.disabled }"\n' + ' ng-repeat="day in lxDatePicker.days">\n' + ' <a ng-click="lxDatePicker.select(day)">{{ day ? day.format(\'D\') : \'\' }}</a>\n' + ' </div>\n' + '\n' + ' <span class="lx-date-picker__day lx-date-picker__day--is-empty"\n' + ' ng-repeat="x in lxDatePicker.emptyLastDays">&nbsp;</span>\n' + ' </div>\n' + ' </div>\n' + '\n' + ' <!-- Year selection -->\n' + ' <div class="lx-date-picker__year-selector" ng-if="lxDatePicker.yearSelection">\n' + ' <a class="lx-date-picker__year"\n' + ' ng-class="{ \'lx-date-picker__year--is-active\': year == lxDatePicker.moment(lxDatePicker.ngModel).format(\'YYYY\') }"\n' + ' ng-repeat="year in lxDatePicker.years"\n' + ' ng-click="lxDatePicker.selectYear(year)"\n' + ' ng-if="lxDatePicker.yearSelection">\n' + ' {{ year }}\n' + ' </a>\n' + ' </div>\n' + ' </div>\n' + '\n' + ' <!-- Actions -->\n' + ' <div class="lx-date-picker__actions">\n' + ' <lx-button lx-color="{{ lxDatePicker.color }}" lx-type="flat" ng-click="lxDatePicker.closeDatePicker()">\n' + ' Ok\n' + ' </lx-button>\n' + ' </div>\n' + ' </div>\n' + ' </div>\n' + '</div>'); }]); angular.module("lumx.progress").run(['$templateCache', function(a) { a.put('progress.html', '<div class="progress-container progress-container--{{ lxProgress.lxType }} progress-container--{{ lxProgress.lxColor }}"\n' + ' ng-class="{ \'progress-container--determinate\': lxProgress.lxValue,\n' + ' \'progress-container--indeterminate\': !lxProgress.lxValue }">\n' + ' <div class="progress-circular"\n' + ' ng-if="lxProgress.lxType === \'circular\'"\n' + ' ng-style="lxProgress.getProgressDiameter()">\n' + ' <svg class="progress-circular__svg">\n' + ' <circle class="progress-circular__path" cx="50" cy="50" r="20" fill="none" stroke-width="4" stroke-miterlimit="10" ng-style="lxProgress.getCircularProgressValue()">\n' + ' </svg>\n' + ' </div>\n' + '\n' + ' <div class="progress-linear" ng-if="lxProgress.lxType === \'linear\'">\n' + ' <div class="progress-linear__background"></div>\n' + ' <div class="progress-linear__bar progress-linear__bar--first" ng-style="lxProgress.getLinearProgressValue()"></div>\n' + ' <div class="progress-linear__bar progress-linear__bar--second"></div>\n' + ' </div>\n' + '</div>\n' + ''); }]); angular.module("lumx.button").run(['$templateCache', function(a) { a.put('link.html', '<a ng-transclude lx-ripple></a>\n' + ''); a.put('button.html', '<button ng-transclude lx-ripple></button>\n' + ''); }]); angular.module("lumx.checkbox").run(['$templateCache', function(a) { a.put('checkbox.html', '<div class="checkbox checkbox--{{ lxCheckbox.lxColor }}"\n' + ' ng-class="{ \'checkbox--theme-light\': !lxCheckbox.theme || lxCheckbox.theme === \'light\',\n' + ' \'checkbox--theme-dark\': lxCheckbox.theme === \'dark\' }" >\n' + ' <input id="{{ lxCheckbox.getCheckboxId() }}"\n' + ' type="checkbox"\n' + ' class="checkbox__input"\n' + ' name="{{ lxCheckbox.name }}"\n' + ' ng-model="lxCheckbox.ngModel"\n' + ' ng-true-value="{{ lxCheckbox.ngTrueValue }}"\n' + ' ng-false-value="{{ lxCheckbox.ngFalseValue }}"\n' + ' ng-change="lxCheckbox.triggerNgChange()"\n' + ' ng-disabled="lxCheckbox.ngDisabled">\n' + '\n' + ' <label for="{{ lxCheckbox.getCheckboxId() }}" class="checkbox__label" ng-transclude ng-if="!lxCheckbox.getCheckboxHasChildren()"></label>\n' + ' <ng-transclude-replace ng-if="lxCheckbox.getCheckboxHasChildren()"></ng-transclude-replace>\n' + '</div>\n' + ''); a.put('checkbox-label.html', '<label for="{{ lxCheckboxLabel.getCheckboxId() }}" class="checkbox__label" ng-transclude></label>\n' + ''); a.put('checkbox-help.html', '<span class="checkbox__help" ng-transclude></span>\n' + ''); }]); angular.module("lumx.radio-button").run(['$templateCache', function(a) { a.put('radio-group.html', '<div class="radio-group" ng-transclude></div>\n' + ''); a.put('radio-button.html', '<div class="radio-button radio-button--{{ lxRadioButton.lxColor }}">\n' + ' <input id="{{ lxRadioButton.getRadioButtonId() }}"\n' + ' type="radio"\n' + ' class="radio-button__input"\n' + ' name="{{ lxRadioButton.name }}"\n' + ' ng-model="lxRadioButton.ngModel"\n' + ' ng-value="lxRadioButton.ngValue"\n' + ' ng-change="lxRadioButton.triggerNgChange()"\n' + ' ng-disabled="lxRadioButton.ngDisabled">\n' + '\n' + ' <label for="{{ lxRadioButton.getRadioButtonId() }}" class="radio-button__label" ng-transclude ng-if="!lxRadioButton.getRadioButtonHasChildren()"></label>\n' + ' <ng-transclude-replace ng-if="lxRadioButton.getRadioButtonHasChildren()"></ng-transclude-replace>\n' + '</div>\n' + ''); a.put('radio-button-label.html', '<label for="{{ lxRadioButtonLabel.getRadioButtonId() }}" class="radio-button__label" ng-transclude></label>\n' + ''); a.put('radio-button-help.html', '<span class="radio-button__help" ng-transclude></span>\n' + ''); }]); angular.module("lumx.stepper").run(['$templateCache', function(a) { a.put('stepper.html', '<div class="lx-stepper" ng-class="lxStepper.getClasses()">\n' + ' <div class="lx-stepper__header" ng-if="lxStepper.layout === \'horizontal\'">\n' + ' <div class="lx-stepper__nav">\n' + ' <lx-step-nav lx-active-index="{{ lxStepper.activeIndex }}" lx-step="step" ng-repeat="step in lxStepper.steps"></lx-step-nav>\n' + ' </div>\n' + '\n' + ' <div class="lx-stepper__feedback" ng-if="lxStepper.steps[lxStepper.activeIndex].feedback">\n' + ' <span>{{ lxStepper.steps[lxStepper.activeIndex].feedback }}</span>\n' + ' </div>\n' + ' </div>\n' + '\n' + ' <div class="lx-stepper__steps" ng-transclude></div>\n' + '</div>'); a.put('step.html', '<div class="lx-step" ng-class="lxStep.getClasses()">\n' + ' <div class="lx-step__nav" ng-if="lxStep.parent.layout === \'vertical\'">\n' + ' <lx-step-nav lx-active-index="{{ lxStep.parent.activeIndex }}" lx-step="lxStep.step"></lx-step-nav>\n' + ' </div>\n' + '\n' + ' <div class="lx-step__wrapper" ng-if="lxStep.parent.activeIndex === lxStep.step.index">\n' + ' <div class="lx-step__content">\n' + ' <ng-transclude></ng-transclude>\n' + '\n' + ' <div class="lx-step__progress" ng-if="lxStep.step.isLoading">\n' + ' <lx-progress lx-type="circular"></lx-progress>\n' + ' </div>\n' + ' </div>\n' + '\n' + ' <div class="lx-step__actions" ng-if="lxStep.parent.activeIndex === lxStep.step.index">\n' + ' <div class="lx-step__action lx-step__action--continue">\n' + ' <lx-button ng-click="lxStep.submitStep()" ng-disabled="lxStep.isLoading">{{ lxStep.parent.labels.continue }}</lx-button>\n' + ' </div>\n' + '\n' + ' <div class="lx-step__action lx-step__action--cancel" ng-if="lxStep.parent.cancel">\n' + ' <lx-button lx-color="black" lx-type="flat" ng-click="lxStep.parent.cancel()" ng-disabled="lxStep.isLoading">{{ lxStep.parent.labels.cancel }}</lx-button>\n' + ' </div>\n' + '\n' + ' <div class="lx-step__action lx-step__action--back" ng-if="lxStep.parent.isLinear">\n' + ' <lx-button lx-color="black" lx-type="flat" ng-click="lxStep.previousStep()" ng-disabled="lxStep.isLoading || lxStep.step.index === 0">{{ lxStep.parent.labels.back }}</lx-button>\n' + ' </div>\n' + ' </div>\n' + ' </div>\n' + '</div>'); a.put('step-nav.html', '<div class="lx-step-nav" ng-click="lxStepNav.parent.goToStep(lxStepNav.step.index)" ng-class="lxStepNav.getClasses()" lx-ripple>\n' + ' <div class="lx-step-nav__indicator lx-step-nav__indicator--index" ng-if="lxStepNav.step.isValid === undefined">\n' + ' <span>{{ lxStepNav.step.index + 1 }}</span>\n' + ' </div>\n' + '\n' + ' <div class="lx-step-nav__indicator lx-step-nav__indicator--icon" ng-if="lxStepNav.step.isValid === true">\n' + ' <lx-icon lx-id="check" ng-if="!lxStepNav.step.isEditable"></lx-icon>\n' + ' <lx-icon lx-id="pencil" ng-if="lxStepNav.step.isEditable"></lx-icon>\n' + ' </div>\n' + '\n' + ' <div class="lx-step-nav__indicator lx-step-nav__indicator--error" ng-if="lxStepNav.step.isValid === false">\n' + ' <lx-icon lx-id="alert"></lx-icon>\n' + ' </div>\n' + '\n' + ' <div class="lx-step-nav__wrapper">\n' + ' <div class="lx-step-nav__label">\n' + ' <span>{{ lxStepNav.step.label }}</span>\n' + ' </div>\n' + '\n' + ' <div class="lx-step-nav__state">\n' + ' <span ng-if="(lxStepNav.step.isValid === undefined || lxStepNav.step.isValid === true) && lxStepNav.step.isOptional">{{ lxStepNav.parent.labels.optional }}</span>\n' + ' <span ng-if="lxStepNav.step.isValid === false">{{ lxStepNav.step.errorMessage }}</span>\n' + ' </div>\n' + ' </div>\n' + '</div>'); }]); angular.module("lumx.switch").run(['$templateCache', function(a) { a.put('switch.html', '<div class="switch switch--{{ lxSwitch.lxColor }} switch--{{ lxSwitch.lxPosition }}">\n' + ' <input id="{{ lxSwitch.getSwitchId() }}"\n' + ' type="checkbox"\n' + ' class="switch__input"\n' + ' name="{{ lxSwitch.name }}"\n' + ' ng-model="lxSwitch.ngModel"\n' + ' ng-true-value="{{ lxSwitch.ngTrueValue }}"\n' + ' ng-false-value="{{ lxSwitch.ngFalseValue }}"\n' + ' ng-change="lxSwitch.triggerNgChange()"\n' + ' ng-disabled="lxSwitch.ngDisabled">\n' + '\n' + ' <label for="{{ lxSwitch.getSwitchId() }}" class="switch__label" ng-transclude ng-if="!lxSwitch.getSwitchHasChildren()"></label>\n' + ' <ng-transclude-replace ng-if="lxSwitch.getSwitchHasChildren()"></ng-transclude-replace>\n' + '</div>\n' + ''); a.put('switch-label.html', '<label for="{{ lxSwitchLabel.getSwitchId() }}" class="switch__label" ng-transclude></label>\n' + ''); a.put('switch-help.html', '<span class="switch__help" ng-transclude></span>\n' + ''); }]); angular.module("lumx.fab").run(['$templateCache', function(a) { a.put('fab.html', '<div class="fab">\n' + ' <ng-transclude-replace></ng-transclude-replace>\n' + '</div>\n' + ''); a.put('fab-trigger.html', '<div class="fab__primary" ng-transclude></div>\n' + ''); a.put('fab-actions.html', '<div class="fab__actions fab__actions--{{ parentCtrl.lxDirection }}" ng-transclude></div>\n' + ''); }]); angular.module("lumx.icon").run(['$templateCache', function(a) { a.put('icon.html', '<i class="icon mdi" ng-class="lxIcon.getClass()"></i>'); }]); angular.module("lumx.data-table").run(['$templateCache', function(a) { a.put('data-table.html', '<div class="data-table-container">\n' + ' <table class="data-table"\n' + ' ng-class="{ \'data-table--no-border\': !lxDataTable.border,\n' + ' \'data-table--thumbnail\': lxDataTable.thumbnail }">\n' + ' <thead>\n' + ' <tr ng-class="{ \'data-table__selectable-row\': lxDataTable.selectable,\n' + ' \'data-table__selectable-row--is-selected\': lxDataTable.selectable && lxDataTable.allRowsSelected }">\n' + ' <th ng-if="lxDataTable.thumbnail"></th>\n' + ' <th ng-click="lxDataTable.toggleAllSelected()"\n' + ' ng-if="lxDataTable.selectable"></th>\n' + ' <th ng-class=" { \'data-table__sortable-cell\': th.sortable,\n' + ' \'data-table__sortable-cell--asc\': th.sortable && th.sort === \'asc\',\n' + ' \'data-table__sortable-cell--desc\': th.sortable && th.sort === \'desc\' }"\n' + ' ng-click="lxDataTable.sort(th)"\n' + ' ng-repeat="th in lxDataTable.thead track by $index"\n' + ' ng-if="!lxDataTable.thumbnail || (lxDataTable.thumbnail && $index != 0)">\n' + ' <lx-icon lx-id="{{ th.icon }}" ng-if="th.icon"></lx-icon>\n' + ' <span>{{ th.label }}</span>\n' + ' </th>\n' + ' </tr>\n' + ' </thead>\n' + '\n' + ' <tbody>\n' + ' <tr ng-class="{ \'data-table__selectable-row\': lxDataTable.selectable,\n' + ' \'data-table__selectable-row--is-disabled\': lxDataTable.selectable && tr.lxDataTableDisabled,\n' + ' \'data-table__selectable-row--is-selected\': lxDataTable.selectable && tr.lxDataTableSelected }"\n' + ' ng-repeat="tr in lxDataTable.tbody"\n' + ' ng-click="lxDataTable.toggle(tr)">\n' + ' <td ng-if="lxDataTable.thumbnail">\n' + ' <div ng-if="lxDataTable.thead[0].format" ng-bind-html="lxDataTable.$sce.trustAsHtml(lxDataTable.thead[0].format(tr))"></div>\n' + ' </td>\n' + ' <td ng-if="lxDataTable.selectable"></td>\n' + ' <td ng-repeat="th in lxDataTable.thead track by $index"\n' + ' ng-if="!lxDataTable.thumbnail || (lxDataTable.thumbnail && $index != 0)">\n' + ' <span ng-if="!th.format">{{ tr[th.name] }}</span>\n' + ' <div ng-if="th.format" ng-bind-html="lxDataTable.$sce.trustAsHtml(th.format(tr))"></div>\n' + ' </td>\n' + ' </tr>\n' + ' </tbody>\n' + ' </table>\n' + '</div>'); }]);
tholu/cdnjs
ajax/libs/lumx/1.5.14/lumx.js
JavaScript
mit
203,404
// File: chapter14/appUnderTest/app/scripts/app.js angular.module('fifaApp', ['ngRoute']) .config(function($routeProvider) { $routeProvider.when('/', { templateUrl: 'views/team_list.html', controller: 'TeamListCtrl as teamListCtrl' }) .when('/login', { templateUrl: 'views/login.html', }) .when('/team/:code', { templateUrl: 'views/team_details.html', controller:'TeamDetailsCtrl as teamDetailsCtrl', resolve: { auth: ['$q', '$location', 'UserService', function($q, $location, UserService) { return UserService.session().then( function(success) {}, function(err) { $location.path('/login'); return $q.reject(err); }); }] } }); $routeProvider.otherwise({ redirectTo: '/' }); });
dikshay/angularjs-up-and-running
chapter14/appUnderTest/app/scripts/app.js
JavaScript
mit
881
tinymce.PluginManager.add("insertdatetime", function (e) { function t(t, n) { function i(e, t) { if (e = "" + e, e.length < t)for (var n = 0; n < t - e.length; n++)e = "0" + e; return e } return n = n || new Date, t = t.replace("%D", "%m/%d/%Y"), t = t.replace("%r", "%I:%M:%S %p"), t = t.replace("%Y", "" + n.getFullYear()), t = t.replace("%y", "" + n.getYear()), t = t.replace("%m", i(n.getMonth() + 1, 2)), t = t.replace("%d", i(n.getDate(), 2)), t = t.replace("%H", "" + i(n.getHours(), 2)), t = t.replace("%M", "" + i(n.getMinutes(), 2)), t = t.replace("%S", "" + i(n.getSeconds(), 2)), t = t.replace("%I", "" + ((n.getHours() + 11) % 12 + 1)), t = t.replace("%p", "" + (n.getHours() < 12 ? "AM" : "PM")), t = t.replace("%B", "" + e.translate(s[n.getMonth()])), t = t.replace("%b", "" + e.translate(o[n.getMonth()])), t = t.replace("%A", "" + e.translate(r[n.getDay()])), t = t.replace("%a", "" + e.translate(a[n.getDay()])), t = t.replace("%%", "%") } function n(n) { var i = t(n); if (e.settings.insertdatetime_element) { var a; a = /%[HMSIp]/.test(n) ? t("%Y-%m-%dT%H:%M") : t("%Y-%m-%d"), i = '<time datetime="' + a + '">' + i + "</time>"; var r = e.dom.getParent(e.selection.getStart(), "time"); if (r)return e.dom.setOuterHTML(r, i), void 0 } e.insertContent(i) } var i, a = "Sun Mon Tue Wed Thu Fri Sat Sun".split(" "), r = "Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sunday".split(" "), o = "Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split(" "), s = "January February March April May June July August September October November December".split(" "), l = []; e.addCommand("mceInsertDate", function () { n(e.getParam("insertdatetime_dateformat", e.translate("%Y-%m-%d"))) }), e.addCommand("mceInsertTime", function () { n(e.getParam("insertdatetime_timeformat", e.translate("%H:%M:%S"))) }), e.addButton("inserttime", { type: "splitbutton", title: "Insert time", onclick: function () { n(i || "%H:%M:%S") }, menu: l }), tinymce.each(e.settings.insertdatetime_formats || ["%H:%M:%S", "%Y-%m-%d", "%I:%M:%S %p", "%D"], function (e) { l.push({ text: t(e), onclick: function () { i = e, n(e) } }) }), e.addMenuItem("insertdatetime", {icon: "date", text: "Insert date/time", menu: l, context: "insert"}) });
DaveB95/CS3012Website
vendors/tinymce/plugins/insertdatetime/plugin.min.js
JavaScript
gpl-2.0
2,505
/*! * JavaScript for the debug toolbar profiler, enabled through $wgDebugToolbar * and StartProfiler.php. * * @author Erik Bernhardson * @since 1.23 */ ( function ( mw, $ ) { 'use strict'; /** * @singleton * @class mw.Debug.profile */ var profile = mw.Debug.profile = { /** * Object containing data for the debug toolbar * * @property ProfileData */ data: null, /** * @property DOMElement */ container: null, /** * Initializes the profiling pane. */ init: function ( data, width, mergeThresholdPx, dropThresholdPx ) { data = data || mw.config.get( 'debugInfo' ).profile; profile.width = width || $(window).width() - 20; // merge events from same pixel(some events are very granular) mergeThresholdPx = mergeThresholdPx || 2; // only drop events if requested dropThresholdPx = dropThresholdPx || 0; if ( !Array.prototype.map || !Array.prototype.reduce || !Array.prototype.filter ) { profile.container = profile.buildRequiresES5(); } else if ( data.length === 0 ) { profile.container = profile.buildNoData(); } else { // generate a flyout profile.data = new ProfileData( data, profile.width, mergeThresholdPx, dropThresholdPx ); // draw it profile.container = profile.buildSvg( profile.container ); profile.attachFlyout(); } return profile.container; }, buildRequiresES5: function () { return $( '<div>' ) .text( 'An ES5 compatible javascript engine is required for the profile visualization.' ) .get( 0 ); }, buildNoData: function () { return $( '<div>' ).addClass( 'mw-debug-profile-no-data' ) .text( 'No events recorded, ensure profiling is enabled in StartProfiler.php.' ) .get( 0 ); }, /** * Creates DOM nodes appropriately namespaced for SVG. * * @param string tag to create * @return DOMElement */ createSvgElement: document.createElementNS ? document.createElementNS.bind( document, 'http://www.w3.org/2000/svg' ) // throw a error for browsers which does not support document.createElementNS (IE<8) : function () { throw new Error( 'document.createElementNS not supported' ); }, /** * @param DOMElement|undefined */ buildSvg: function ( node ) { var container, group, i, g, timespan = profile.data.timespan, gapPerEvent = 38, space = 10.5, currentHeight = space, totalHeight = 0; profile.ratio = ( profile.width - space * 2 ) / ( timespan.end - timespan.start ); totalHeight += gapPerEvent * profile.data.groups.length; if ( node ) { $( node ).empty(); } else { node = profile.createSvgElement( 'svg' ); node.setAttribute( 'version', '1.2' ); node.setAttribute( 'baseProfile', 'tiny' ); } node.style.height = totalHeight; node.style.width = profile.width; // use a container that can be transformed container = profile.createSvgElement( 'g' ); node.appendChild( container ); for ( i = 0; i < profile.data.groups.length; i++ ) { group = profile.data.groups[i]; g = profile.buildTimeline( group ); g.setAttribute( 'transform', 'translate( 0 ' + currentHeight + ' )' ); container.appendChild( g ); currentHeight += gapPerEvent; } return node; }, /** * @param Object group of periods to transform into graphics */ buildTimeline: function ( group ) { var text, tspan, line, i, sum = group.timespan.sum, ms = ' ~ ' + ( sum < 1 ? sum.toFixed( 2 ) : sum.toFixed( 0 ) ) + ' ms', timeline = profile.createSvgElement( 'g' ); timeline.setAttribute( 'class', 'mw-debug-profile-timeline' ); // draw label text = profile.createSvgElement( 'text' ); text.setAttribute( 'x', profile.xCoord( group.timespan.start ) ); text.setAttribute( 'y', 0 ); text.textContent = group.name; timeline.appendChild( text ); // draw metadata tspan = profile.createSvgElement( 'tspan' ); tspan.textContent = ms; text.appendChild( tspan ); // draw timeline periods for ( i = 0; i < group.periods.length; i++ ) { timeline.appendChild( profile.buildPeriod( group.periods[i] ) ); } // full-width line under each timeline line = profile.createSvgElement( 'line' ); line.setAttribute( 'class', 'mw-debug-profile-underline' ); line.setAttribute( 'x1', 0 ); line.setAttribute( 'y1', 28 ); line.setAttribute( 'x2', profile.width ); line.setAttribute( 'y2', 28 ); timeline.appendChild( line ); return timeline; }, /** * @param Object period to transform into graphics */ buildPeriod: function ( period ) { var node, head = profile.xCoord( period.start ), tail = profile.xCoord( period.end ), g = profile.createSvgElement( 'g' ); g.setAttribute( 'class', 'mw-debug-profile-period' ); $( g ).data( 'period', period ); if ( head + 16 > tail ) { node = profile.createSvgElement( 'rect' ); node.setAttribute( 'x', head ); node.setAttribute( 'y', 8 ); node.setAttribute( 'width', 2 ); node.setAttribute( 'height', 9 ); g.appendChild( node ); node = profile.createSvgElement( 'rect' ); node.setAttribute( 'x', head ); node.setAttribute( 'y', 8 ); node.setAttribute( 'width', ( period.end - period.start ) * profile.ratio || 2 ); node.setAttribute( 'height', 6 ); g.appendChild( node ); } else { node = profile.createSvgElement( 'polygon' ); node.setAttribute( 'points', pointList( [ [ head, 8 ], [ head, 19 ], [ head + 8, 8 ], [ head, 8] ] ) ); g.appendChild( node ); node = profile.createSvgElement( 'polygon' ); node.setAttribute( 'points', pointList( [ [ tail, 8 ], [ tail, 19 ], [ tail - 8, 8 ], [ tail, 8 ] ] ) ); g.appendChild( node ); node = profile.createSvgElement( 'line' ); node.setAttribute( 'x1', head ); node.setAttribute( 'y1', 9 ); node.setAttribute( 'x2', tail ); node.setAttribute( 'y2', 9 ); g.appendChild( node ); } return g; }, /** * @param Object */ buildFlyout: function ( period ) { var contained, sum, ms, mem, i, node = $( '<div>' ); for ( i = 0; i < period.contained.length; i++ ) { contained = period.contained[i]; sum = contained.end - contained.start; ms = '' + ( sum < 1 ? sum.toFixed( 2 ) : sum.toFixed( 0 ) ) + ' ms'; mem = formatBytes( contained.memory ); $( '<div>' ).text( contained.source.name ) .append( $( '<span>' ).text( ' ~ ' + ms + ' / ' + mem ).addClass( 'mw-debug-profile-meta' ) ) .appendTo( node ); } return node; }, /** * Attach a hover flyout to all .mw-debug-profile-period groups. */ attachFlyout: function () { // for some reason addClass and removeClass from jQuery // arn't working on svg elements in chrome <= 33.0 (possibly more) var $container = $( profile.container ), addClass = function ( node, value ) { var current = node.getAttribute( 'class' ), list = current ? current.split( ' ' ) : false, idx = list ? list.indexOf( value ) : -1; if ( idx === -1 ) { node.setAttribute( 'class', current ? ( current + ' ' + value ) : value ); } }, removeClass = function ( node, value ) { var current = node.getAttribute( 'class' ), list = current ? current.split( ' ' ) : false, idx = list ? list.indexOf( value ) : -1; if ( idx !== -1 ) { list.splice( idx, 1 ); node.setAttribute( 'class', list.join( ' ' ) ); } }, // hide all tipsy flyouts hide = function () { $container.find( '.mw-debug-profile-period.tipsy-visible' ) .each( function () { removeClass( this, 'tipsy-visible' ); $( this ).tipsy( 'hide' ); } ); }; $container.find( '.mw-debug-profile-period' ).tipsy( { fade: true, gravity: function () { return $.fn.tipsy.autoNS.call( this ) + $.fn.tipsy.autoWE.call( this ); }, className: 'mw-debug-profile-tipsy', center: false, html: true, trigger: 'manual', title: function () { return profile.buildFlyout( $( this ).data( 'period' ) ).html(); } } ).on( 'mouseenter', function () { hide(); addClass( this, 'tipsy-visible' ); $( this ).tipsy( 'show' ); } ); $container.on( 'mouseleave', function ( event ) { var $from = $( event.relatedTarget ), $to = $( event.target ); // only close the tipsy if we are not if ( $from.closest( '.tipsy' ).length === 0 && $to.closest( '.tipsy' ).length === 0 && $to.get( 0 ).namespaceURI !== 'http://www.w4.org/2000/svg' ) { hide(); } } ).on( 'click', function () { // convenience method for closing hide(); } ); }, /** * @return number the x co-ordinate for the specified timestamp */ xCoord: function ( msTimestamp ) { return ( msTimestamp - profile.data.timespan.start ) * profile.ratio; } }; function ProfileData( data, width, mergeThresholdPx, dropThresholdPx ) { // validate input data this.data = data.map( function ( event ) { event.periods = event.periods.filter( function ( period ) { return period.start && period.end && period.start < period.end // period start must be a reasonable ms timestamp && period.start > 1000000; } ); return event; } ).filter( function ( event ) { return event.name && event.periods.length > 0; } ); // start and end time of the data this.timespan = this.data.reduce( function ( result, event ) { return event.periods.reduce( periodMinMax, result ); }, periodMinMax.initial() ); // transform input data this.groups = this.collate( width, mergeThresholdPx, dropThresholdPx ); return this; } /** * There are too many unique events to display a line for each, * so this does a basic grouping. */ ProfileData.groupOf = function ( label ) { var pos, prefix = 'Profile section ended by close(): '; if ( label.indexOf( prefix ) === 0 ) { label = label.substring( prefix.length ); } pos = [ '::', ':', '-' ].reduce( function ( result, separator ) { var pos = label.indexOf( separator ); if ( pos === -1 ) { return result; } else if ( result === -1 ) { return pos; } else { return Math.min( result, pos ); } }, -1 ); if ( pos === -1 ) { return label; } else { return label.substring( 0, pos ); } }; /** * @return Array list of objects with `name` and `events` keys */ ProfileData.groupEvents = function ( events ) { var group, i, groups = {}; // Group events together for ( i = events.length - 1; i >= 0; i-- ) { group = ProfileData.groupOf( events[i].name ); if ( groups[group] ) { groups[group].push( events[i] ); } else { groups[group] = [events[i]]; } } // Return an array of groups return Object.keys( groups ).map( function ( group ) { return { name: group, events: groups[group] }; } ); }; ProfileData.periodSorter = function ( a, b ) { if ( a.start === b.start ) { return a.end - b.end; } return a.start - b.start; }; ProfileData.genMergePeriodReducer = function ( mergeThresholdMs ) { return function ( result, period ) { if ( result.length === 0 ) { // period is first result return [{ start: period.start, end: period.end, contained: [period] }]; } var last = result[result.length - 1]; if ( period.end < last.end ) { // end is contained within previous result[result.length - 1].contained.push( period ); } else if ( period.start - mergeThresholdMs < last.end ) { // neighbors within merging distance result[result.length - 1].end = period.end; result[result.length - 1].contained.push( period ); } else { // period is next result result.push({ start: period.start, end: period.end, contained: [period] }); } return result; }; }; /** * Collect all periods from the grouped events and apply merge and * drop transformations */ ProfileData.extractPeriods = function ( events, mergeThresholdMs, dropThresholdMs ) { // collect the periods from all events return events.reduce( function ( result, event ) { if ( !event.periods.length ) { return result; } result.push.apply( result, event.periods.map( function ( period ) { // maintain link from period to event period.source = event; return period; } ) ); return result; }, [] ) // sort combined periods .sort( ProfileData.periodSorter ) // Apply merge threshold. Original periods // are maintained in the `contained` property .reduce( ProfileData.genMergePeriodReducer( mergeThresholdMs ), [] ) // Apply drop threshold .filter( function ( period ) { return period.end - period.start > dropThresholdMs; } ); }; /** * runs a callback on all periods in the group. Only valid after * groups.periods[0..n].contained are populated. This runs against * un-transformed data and is better suited to summing or other * stat collection */ ProfileData.reducePeriods = function ( group, callback, result ) { return group.periods.reduce( function ( result, period ) { return period.contained.reduce( callback, result ); }, result ); }; /** * Transforms this.data grouping by labels, merging neighboring * events in the groups, and drops events and groups below the * display threshold. Groups are returned sorted by starting time. */ ProfileData.prototype.collate = function ( width, mergeThresholdPx, dropThresholdPx ) { // ms to pixel ratio var ratio = ( this.timespan.end - this.timespan.start ) / width, // transform thresholds to ms mergeThresholdMs = mergeThresholdPx * ratio, dropThresholdMs = dropThresholdPx * ratio; return ProfileData.groupEvents( this.data ) // generate data about the grouped events .map( function ( group ) { // Cleaned periods from all events group.periods = ProfileData.extractPeriods( group.events, mergeThresholdMs, dropThresholdMs ); // min and max timestamp per group group.timespan = ProfileData.reducePeriods( group, periodMinMax, periodMinMax.initial() ); // ms from first call to end of last call group.timespan.length = group.timespan.end - group.timespan.start; // collect the un-transformed periods group.timespan.sum = ProfileData.reducePeriods( group, function ( result, period ) { result.push( period ); return result; }, [] ) // sort by start time .sort( ProfileData.periodSorter ) // merge overlapping .reduce( ProfileData.genMergePeriodReducer( 0 ), [] ) // sum .reduce( function ( result, period ) { return result + period.end - period.start; }, 0 ); return group; }, this ) // remove groups that have had all their periods filtered .filter( function ( group ) { return group.periods.length > 0; } ) // sort events by first start .sort( function ( a, b ) { return ProfileData.periodSorter( a.timespan, b.timespan ); } ); }; // reducer to find edges of period array function periodMinMax( result, period ) { if ( period.start < result.start ) { result.start = period.start; } if ( period.end > result.end ) { result.end = period.end; } return result; } periodMinMax.initial = function () { return { start: Number.POSITIVE_INFINITY, end: Number.NEGATIVE_INFINITY }; }; function formatBytes( bytes ) { var i, sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']; if ( bytes === 0 ) { return '0 Bytes'; } i = parseInt( Math.floor( Math.log( bytes ) / Math.log( 1024 ) ), 10 ); return Math.round( bytes / Math.pow( 1024, i ), 2 ) + ' ' + sizes[i]; } // turns a 2d array into a point list for svg // polygon points attribute // ex: [[1,2],[3,4],[4,2]] = '1,2 3,4 4,2' function pointList( pairs ) { return pairs.map( function ( pair ) { return pair.join( ',' ); } ).join( ' ' ); } }( mediaWiki, jQuery ) );
kylethayer/bioladder
wiki/resources/src/mediawiki/mediawiki.debug.profile.js
JavaScript
gpl-3.0
15,945
/* * ContextMenu Plugin * * */ (function($) { $.extend(mejs.MepDefaults, contextMenuItems = [ // demo of a fullscreen option { render: function(player) { // check for fullscreen plugin if (typeof player.enterFullScreen == 'undefined') return null; if (player.isFullScreen) { return "Turn off Fullscreen"; } else { return "Go Fullscreen"; } }, click: function(player) { if (player.isFullScreen) { player.exitFullScreen(); } else { player.enterFullScreen(); } } } , // demo of a mute/unmute button { render: function(player) { if (player.media.muted) { return "Unmute"; } else { return "Mute"; } }, click: function(player) { if (player.media.muted) { player.setMuted(false); } else { player.setMuted(true); } } }, // separator { isSeparator: true } , // demo of simple download video { render: function(player) { return "Download Video"; }, click: function(player) { window.location.href = player.media.currentSrc; } } ] ); $.extend(MediaElementPlayer.prototype, { buildcontextmenu: function(player, controls, layers, media) { // create context menu player.contextMenu = $('<div class="mejs-contextmenu"></div>') .appendTo($('body')) .hide(); // create events for showing context menu player.container.bind('contextmenu', function(e) { if (player.isContextMenuEnabled) { e.preventDefault(); player.renderContextMenu(e.clientX-1, e.clientY-1); return false; } }); player.container.bind('click', function() { player.contextMenu.hide(); }); player.contextMenu.bind('mouseleave', function() { //console.log('context hover out'); player.startContextMenuTimer(); }); }, isContextMenuEnabled: true, enableContextMenu: function() { this.isContextMenuEnabled = true; }, disableContextMenu: function() { this.isContextMenuEnabled = false; }, contextMenuTimeout: null, startContextMenuTimer: function() { //console.log('startContextMenuTimer'); var t = this; t.killContextMenuTimer(); t.contextMenuTimer = setTimeout(function() { t.hideContextMenu(); t.killContextMenuTimer(); }, 750); }, killContextMenuTimer: function() { var timer = this.contextMenuTimer; //console.log('killContextMenuTimer', timer); if (timer != null) { clearTimeout(timer); delete timer; timer = null; } }, hideContextMenu: function() { this.contextMenu.hide(); }, renderContextMenu: function(x,y) { // alway re-render the items so that things like "turn fullscreen on" and "turn fullscreen off" are always written correctly var t = this, html = '', items = t.options.contextMenuItems; for (var i=0, il=items.length; i<il; i++) { if (items[i].isSeparator) { html += '<div class="mejs-contextmenu-separator"></div>'; } else { var rendered = items[i].render(t); // render can return null if the item doesn't need to be used at the moment if (rendered != null) { html += '<div class="mejs-contextmenu-item" data-itemindex="' + i + '" id="element-' + (Math.random()*1000000) + '">' + rendered + '</div>'; } } } // position and show the context menu t.contextMenu .empty() .append($(html)) .css({top:y, left:x}) .show(); // bind events t.contextMenu.find('.mejs-contextmenu-item').each(function() { // which one is this? var $dom = $(this), itemIndex = parseInt( $dom.data('itemindex'), 10 ), item = t.options.contextMenuItems[itemIndex]; // bind extra functionality? if (typeof item.show != 'undefined') item.show( $dom , t); // bind click action $dom.click(function() { // perform click action if (typeof item.click != 'undefined') item.click(t); // close t.contextMenu.hide(); }); }); // stop the controls from hiding setTimeout(function() { t.killControlsTimer('rev3'); }, 100); } }); })(mejs.$);
europeana/broken_dont_bother_exhibitions
webtree/themes/main/javascripts/mediaelement-2.7/src/js/mep-feature-contextmenu.js
JavaScript
gpl-3.0
4,424
// Copyright 2009 the Sputnik authors. All rights reserved. /** * The production x >>>= y is the same as x = x >>> y * * @path ch11/11.13/11.13.2/S11.13.2_A4.8_T1.3.js * @description Type(x) and Type(y) vary between primitive string and String object */ //CHECK#1 x = "1"; x >>>= "1"; if (x !== 0) { $ERROR('#1: x = "1"; x >>>= "1"; x === 0. Actual: ' + (x)); } //CHECK#2 x = new String("1"); x >>>= "1"; if (x !== 0) { $ERROR('#2: x = new String("1"); x >>>= "1"; x === 0. Actual: ' + (x)); } //CHECK#3 x = "1"; x >>>= new String("1"); if (x !== 0) { $ERROR('#3: x = "1"; x >>>= new String("1"); x === 0. Actual: ' + (x)); } //CHECK#4 x = new String("1"); x >>>= new String("1"); if (x !== 0) { $ERROR('#4: x = new String("1"); x >>>= new String("1"); x === 0. Actual: ' + (x)); } //CHECK#5 x = "x"; x >>>= "1"; if (x !== 0) { $ERROR('#5: x = "x"; x >>>= "1"; x === 0. Actual: ' + (x)); } //CHECK#6 x = "1"; x >>>= "x"; if (x !== 1) { $ERROR('#6: x = "1"; x >>>= "x"; x === 1. Actual: ' + (x)); }
Oceanswave/NiL.JS
Tests/tests/sputnik/ch11/11.13/11.13.2/S11.13.2_A4.8_T1.3.js
JavaScript
bsd-3-clause
1,023
/// Copyright (c) 2012 Ecma International. All rights reserved. /** * @path ch11/11.4/11.4.1/11.4.1-5-a-27-s.js * @description Strict Mode - TypeError is thrown after deleting a property, calling preventExtensions, and attempting to reassign the property * @onlyStrict */ function testcase() { "use strict"; var a = {x:0, get y() { return 0;}}; delete a.x; Object.preventExtensions(a); try { a.x = 1; return false; } catch (e) { return e instanceof TypeError; } } runTestCase(testcase);
Oceanswave/NiL.JS
Tests/tests/sputnik/ch11/11.4/11.4.1/11.4.1-5-a-27-s.js
JavaScript
bsd-3-clause
587
/*! Select2 4.0.0 | https://github.com/select2/select2/blob/master/LICENSE.md */ (function(){if(jQuery&&jQuery.fn&&jQuery.fn.select2&&jQuery.fn.select2.amd)var e=jQuery.fn.select2.amd;return e.define("select2/i18n/tr",[],function(){return{inputTooLong:function(e){var t=e.input.length-e.maximum,n=t+" karakter daha girmelisiniz";return n},inputTooShort:function(e){var t=e.minimum-e.input.length,n="En az "+t+" karakter daha girmelisiniz";return n},loadingMore:function(){return"Daha fazla…"},maximumSelected:function(e){var t="Sadece "+e.maximum+" seçim yapabilirsiniz";return t},noResults:function(){return"Sonuç bulunamadı"},searching:function(){return"Aranıyor…"}}}),{define:e.define,require:e.require}})();
AndrewListat/paydoc
web/template_admin/plugins/select2/i18n/tr.js
JavaScript
bsd-3-clause
722
/// Copyright (c) 2012 Ecma International. All rights reserved. /** * @path ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-258.js * @description Object.create - 'get' property of one property in 'Properties' is the primitive value null (8.10.5 step 7.b) */ function testcase() { try { Object.create({}, { prop: { get: null } }); return false; } catch (e) { return (e instanceof TypeError); } } runTestCase(testcase);
Oceanswave/NiL.JS
Tests/tests/sputnik/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-258.js
JavaScript
bsd-3-clause
543
module.exports = require('./lib/socket.io');
thetomcraig/redwood
web/node_modules/socket.io/index.js
JavaScript
isc
44
var _complement = require('./internal/_complement'); var _curry2 = require('./internal/_curry2'); var filter = require('./filter'); /** * Similar to `filter`, except that it keeps only values for which the given predicate * function returns falsy. The predicate function is passed one argument: *(value)*. * * Acts as a transducer if a transformer is given in list position. * @see R.transduce * * @func * @memberOf R * @category List * @sig (a -> Boolean) -> [a] -> [a] * @param {Function} fn The function called per iteration. * @param {Array} list The collection to iterate over. * @return {Array} The new filtered array. * @see R.filter * @example * * var isOdd = function(n) { * return n % 2 === 1; * }; * R.reject(isOdd, [1, 2, 3, 4]); //=> [2, 4] */ module.exports = _curry2(function reject(fn, list) { return filter(_complement(fn), list); });
concertcoder/leaky-ionic-app
www/lib/ramda/src/reject.js
JavaScript
mit
899
/************************************************************* * * MathJax/jax/output/HTML-CSS/fonts/Asana-Math/Size1/Regular/Main.js * * Copyright (c) 2013-2014 The MathJax Consortium * * 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. */ MathJax.OutputJax['HTML-CSS'].FONTDATA.FONTS['AsanaMathJax_Size1'] = { directory: 'Size1/Regular', family: 'AsanaMathJax_Size1', testString: '\u0302\u0303\u0305\u0306\u030C\u0332\u0333\u033F\u2016\u2044\u2045\u2046\u20D6\u20D7\u220F', 0x20: [0,0,249,0,0], 0x28: [981,490,399,84,360], 0x29: [981,490,399,40,316], 0x5B: [984,492,350,84,321], 0x5D: [984,492,350,84,321], 0x7B: [981,490,362,84,328], 0x7C: [908,367,241,86,156], 0x7D: [981,490,362,84,328], 0x302: [783,-627,453,0,453], 0x303: [763,-654,700,0,701], 0x305: [587,-542,510,0,511], 0x306: [664,-506,383,0,384], 0x30C: [783,-627,736,0,737], 0x332: [-130,175,510,0,511], 0x333: [-130,283,510,0,511], 0x33F: [695,-542,510,0,511], 0x2016: [908,367,436,86,351], 0x2044: [742,463,382,-69,383], 0x2045: [943,401,353,64,303], 0x2046: [943,401,358,30,269], 0x20D6: [790,-519,807,0,807], 0x20D7: [790,-519,807,0,807], 0x220F: [901,448,1431,78,1355], 0x2210: [901,448,1431,78,1355], 0x2211: [893,446,1224,89,1135], 0x221A: [1280,0,770,63,803], 0x2229: [1039,520,1292,124,1169], 0x222B: [1310,654,1000,54,1001], 0x222C: [1310,654,1659,54,1540], 0x222D: [1310,654,2198,54,2079], 0x222E: [1310,654,1120,54,1001], 0x222F: [1310,654,1659,54,1540], 0x2230: [1310,654,2198,54,2079], 0x2231: [1310,654,1120,54,1001], 0x2232: [1310,654,1146,80,1027], 0x2233: [1310,654,1120,54,1001], 0x22C0: [1040,519,1217,85,1132], 0x22C1: [1040,519,1217,85,1132], 0x22C2: [1039,520,1292,124,1169], 0x22C3: [1039,520,1292,124,1169], 0x2308: [980,490,390,84,346], 0x2309: [980,490,390,84,346], 0x230A: [980,490,390,84,346], 0x230B: [980,490,390,84,346], 0x23B4: [755,-518,977,0,978], 0x23B5: [-238,475,977,0,978], 0x23DC: [821,-545,972,0,973], 0x23DD: [-545,821,972,0,973], 0x23DE: [789,-545,1572,51,1522], 0x23DF: [-545,789,1572,51,1522], 0x23E0: [755,-545,1359,0,1360], 0x23E1: [-545,755,1359,0,1360], 0x27C5: [781,240,450,53,397], 0x27C6: [781,240,450,53,397], 0x27E6: [684,341,502,84,473], 0x27E7: [684,341,502,84,473], 0x27E8: [681,340,422,53,371], 0x27E9: [681,340,422,53,371], 0x27EA: [681,340,605,53,554], 0x27EB: [681,340,605,53,554], 0x29FC: [915,457,518,50,469], 0x29FD: [915,457,518,49,469], 0x2A00: [1100,550,1901,124,1778], 0x2A01: [1100,550,1901,124,1778], 0x2A02: [1100,550,1901,124,1778], 0x2A03: [1039,520,1292,124,1169], 0x2A04: [1039,520,1292,124,1169], 0x2A05: [1024,513,1292,124,1169], 0x2A06: [1024,513,1292,124,1169], 0x2A07: [1039,520,1415,86,1330], 0x2A08: [1039,520,1415,86,1330], 0x2A09: [888,445,1581,124,1459], 0x2A0C: [1310,654,2736,54,2617], 0x2A0D: [1310,654,1120,54,1001], 0x2A0E: [1310,654,1120,54,1001], 0x2A0F: [1310,654,1120,54,1001], 0x2A10: [1310,654,1120,54,1001], 0x2A11: [1310,654,1182,54,1063], 0x2A12: [1310,654,1120,54,1001], 0x2A13: [1310,654,1120,54,1001], 0x2A14: [1310,654,1120,54,1001], 0x2A15: [1310,654,1120,54,1001], 0x2A16: [1310,654,1120,54,1001], 0x2A17: [1310,654,1431,54,1362], 0x2A18: [1310,654,1120,54,1001], 0x2A19: [1310,654,1120,54,1001], 0x2A1A: [1310,654,1120,54,1001], 0x2A1B: [1471,654,1130,54,1011], 0x2A1C: [1471,654,1156,80,1037] }; MathJax.Callback.Queue( ["initFont",MathJax.OutputJax["HTML-CSS"],"AsanaMathJax_Size1"], ["loadComplete",MathJax.Ajax,MathJax.OutputJax["HTML-CSS"].fontDir+"/Size1/Regular/Main.js"] );
uva/mathjax-rails-assets
vendor/assets/javascripts/jax/output/HTML-CSS/fonts/Asana-Math/Size1/Regular/Main.js
JavaScript
mit
4,163
/************************************************************* * * MathJax/jax/output/HTML-CSS/fonts/Neo-Euler/Variants/Regular/Main.js * * Copyright (c) 2013-2014 The MathJax Consortium * * 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. */ MathJax.OutputJax['HTML-CSS'].FONTDATA.FONTS['NeoEulerMathJax_Variants'] = { directory: 'Variants/Regular', family: 'NeoEulerMathJax_Variants', testString: '\u00A0\u2032\u2033\u2034\u2035\u2036\u2037\u2057\uE200\uE201\uE202\uE203\uE204\uE205\uE206', 0x20: [0,0,333,0,0], 0xA0: [0,0,333,0,0], 0x2032: [559,-41,329,48,299], 0x2033: [559,-41,640,48,610], 0x2034: [559,-41,950,48,920], 0x2035: [559,-41,329,48,299], 0x2036: [559,-41,640,48,610], 0x2037: [559,-41,950,48,919], 0x2057: [559,-41,1260,48,1230], 0xE200: [493,13,501,41,456], 0xE201: [469,1,501,46,460], 0xE202: [474,-1,501,59,485], 0xE203: [474,182,501,38,430], 0xE204: [476,192,501,10,482], 0xE205: [458,184,501,47,441], 0xE206: [700,13,501,45,471], 0xE207: [468,181,501,37,498], 0xE208: [706,10,501,40,461], 0xE209: [470,182,501,27,468] }; MathJax.Callback.Queue( ["initFont",MathJax.OutputJax["HTML-CSS"],"NeoEulerMathJax_Variants"], ["loadComplete",MathJax.Ajax,MathJax.OutputJax["HTML-CSS"].fontDir+"/Variants/Regular/Main.js"] );
uva/mathjax-rails-assets
vendor/assets/javascripts/jax/output/HTML-CSS/fonts/Neo-Euler/Variants/Regular/Main.js
JavaScript
mit
1,809
/** * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v9.0.3 * @link http://www.ag-grid.com/ * @license MIT */ "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; Object.defineProperty(exports, "__esModule", { value: true }); var context_1 = require("./context/context"); var LINE_SEPARATOR = '\r\n'; var XmlFactory = (function () { function XmlFactory() { } XmlFactory.prototype.createXml = function (xmlElement, booleanTransformer) { var _this = this; var props = ""; if (xmlElement.properties) { if (xmlElement.properties.prefixedAttributes) { xmlElement.properties.prefixedAttributes.forEach(function (prefixedSet) { Object.keys(prefixedSet.map).forEach(function (key) { props += _this.returnAttributeIfPopulated(prefixedSet.prefix + key, prefixedSet.map[key], booleanTransformer); }); }); } if (xmlElement.properties.rawMap) { Object.keys(xmlElement.properties.rawMap).forEach(function (key) { props += _this.returnAttributeIfPopulated(key, xmlElement.properties.rawMap[key], booleanTransformer); }); } } var result = "<" + xmlElement.name + props; if (!xmlElement.children && !xmlElement.textNode) { return result + "/>" + LINE_SEPARATOR; } if (xmlElement.textNode) { return result + ">" + xmlElement.textNode + "</" + xmlElement.name + ">" + LINE_SEPARATOR; } result += ">" + LINE_SEPARATOR; xmlElement.children.forEach(function (it) { result += _this.createXml(it, booleanTransformer); }); return result + "</" + xmlElement.name + ">" + LINE_SEPARATOR; }; XmlFactory.prototype.returnAttributeIfPopulated = function (key, value, booleanTransformer) { if (!value) { return ""; } var xmlValue = value; if ((typeof (value) === 'boolean')) { if (booleanTransformer) { xmlValue = booleanTransformer(value); } } xmlValue = '"' + xmlValue + '"'; return " " + key + "=" + xmlValue; }; return XmlFactory; }()); XmlFactory = __decorate([ context_1.Bean('xmlFactory') ], XmlFactory); exports.XmlFactory = XmlFactory;
extend1994/cdnjs
ajax/libs/ag-grid/9.0.4/lib/xmlFactory.js
JavaScript
mit
2,992
/** * High performant way to check whether an element with a specific class name is in the given document * Optimized for being heavily executed * Unleashes the power of live node lists * * @param {Object} doc The document object of the context where to check * @param {String} tagName Upper cased tag name * @example * wysihtml5.dom.hasElementWithClassName(document, "foobar"); */ (function(wysihtml5) { var LIVE_CACHE = {}, DOCUMENT_IDENTIFIER = 1; function _getDocumentIdentifier(doc) { return doc._wysihtml5_identifier || (doc._wysihtml5_identifier = DOCUMENT_IDENTIFIER++); } wysihtml5.dom.hasElementWithClassName = function(doc, className) { // getElementsByClassName is not supported by IE<9 // but is sometimes mocked via library code (which then doesn't return live node lists) if (!wysihtml5.browser.supportsNativeGetElementsByClassName()) { return !!doc.querySelector("." + className); } var key = _getDocumentIdentifier(doc) + ":" + className, cacheEntry = LIVE_CACHE[key]; if (!cacheEntry) { cacheEntry = LIVE_CACHE[key] = doc.getElementsByClassName(className); } return cacheEntry.length > 0; }; })(wysihtml5);
StepicOrg/wysihtml5
src/dom/has_element_with_class_name.js
JavaScript
mit
1,231
{ "EL": {"custom":["org.nutz.el.issue279.Uuuid"]} }
lzxz1234/nutz
test/org/nutz/el/issue279/279.js
JavaScript
apache-2.0
51
'use strict'; angular.module('showcase', [ 'showcase.angularWay', 'showcase.angularWay.withOptions', 'showcase.withAjax', 'showcase.withOptions', 'showcase.withPromise', 'showcase.angularWay.dataChange', 'showcase.bindAngularDirective', 'showcase.changeOptions', 'showcase.dataReload.withAjax', 'showcase.dataReload.withPromise', 'showcase.disableDeepWatchers', 'showcase.loadOptionsWithPromise', 'showcase.angularDirectiveInDOM', 'showcase.rerender', 'showcase.rowClickEvent', 'showcase.rowSelect', 'showcase.serverSideProcessing', 'showcase.bootstrapIntegration', 'showcase.overrideBootstrapOptions', 'showcase.withAngularTranslate', 'showcase.withColReorder', 'showcase.withColumnFilter', 'showcase.withLightColumnFilter', 'showcase.withColVis', 'showcase.withResponsive', 'showcase.withScroller', 'showcase.withTableTools', 'showcase.withFixedColumns', 'showcase.withFixedHeader', 'showcase.withButtons', 'showcase.withSelect', 'showcase.dtInstances', 'showcase.usages', 'ui.bootstrap', 'ui.router', 'hljs' ]) .config(sampleConfig) .config(routerConfig) .config(translateConfig) .config(debugDisabled) .run(initDT); backToTop.init({ theme: 'classic', // Available themes: 'classic', 'sky', 'slate' animation: 'fade' // Available animations: 'fade', 'slide' }); function debugDisabled($compileProvider)  { $compileProvider.debugInfoEnabled(false); } function sampleConfig(hljsServiceProvider) { hljsServiceProvider.setOptions({ // replace tab with 4 spaces tabReplace: ' ' }); } function routerConfig($stateProvider, $urlRouterProvider, USAGES) { $urlRouterProvider.otherwise('/welcome'); $stateProvider .state('welcome', { url: '/welcome', templateUrl: 'demo/partials/welcome.html', controller: function($rootScope) { $rootScope.$broadcast('event:changeView', 'welcome'); } }) .state('gettingStarted', { url: '/gettingStarted', templateUrl: 'demo/partials/gettingStarted.html', controller: function($rootScope) { $rootScope.$broadcast('event:changeView', 'gettingStarted'); } }) .state('api', { url: '/api', templateUrl: 'demo/api/api.html', controller: function($rootScope) { $rootScope.$broadcast('event:changeView', 'api'); } }); angular.forEach(USAGES, function(usages, key) { angular.forEach(usages, function(usage) { $stateProvider.state(usage.name, { url: '/' + usage.name, templateUrl: 'demo/' + key + '/' + usage.name + '.html', controller: function($rootScope) { $rootScope.$broadcast('event:changeView', usage.name); }, onExit: usage.onExit }); }); }); } function translateConfig($translateProvider) { $translateProvider.translations('en', { id: 'ID with angular-translate', firstName: 'First name with angular-translate', lastName: 'Last name with angular-translate' }); $translateProvider.translations('fr', { id: 'ID avec angular-translate', firstName: 'Prénom avec angular-translate', lastName: 'Nom avec angular-translate' }); $translateProvider.preferredLanguage('en'); } function initDT(DTDefaultOptions) { DTDefaultOptions.setLoadingTemplate('<img src="/angular-datatables/images/loading.gif" />'); }
Leo-g/Flask-Scaffold
app/templates/static/node_modules/angular-datatables/demo/app.js
JavaScript
mit
3,736
/* * Dynamic To Top Plugin * http://www.mattvarone.com * * By Matt Varone * @sksmatt * */ var mv_dynamic_to_top;(function($,mv_dynamic_to_top){jQuery.fn.DynamicToTop=function(options){var defaults={text:mv_dynamic_to_top.text,min:parseInt(mv_dynamic_to_top.min,10),fade_in:600,fade_out:400,speed:parseInt(mv_dynamic_to_top.speed,10),easing:mv_dynamic_to_top.easing,version:mv_dynamic_to_top.version,id:'dynamic-to-top'},settings=$.extend(defaults,options);if(settings.version===""||settings.version==='0'){settings.text='<span>&nbsp;</span>';} if(!$.isFunction(settings.easing)){settings.easing='linear';} var $toTop=$('<a href=\"#\" id=\"'+settings.id+'\"></a>').html(settings.text);$toTop.hide().appendTo('body').click(function(){$('html, body').stop().animate({scrollTop:0},settings.speed,settings.easing);return false;});$(window).scroll(function(){var sd=jQuery(window).scrollTop();if(typeof document.body.style.maxHeight==="undefined"){$toTop.css({'position':'absolute','top':sd+$(window).height()-mv_dynamic_to_top.margin});} if(sd>settings.min){$toTop.fadeIn(settings.fade_in);}else{$toTop.fadeOut(settings.fade_out);}});};$('body').DynamicToTop();})(jQuery,mv_dynamic_to_top);
richardPZH/wordpress-plus
wp-content/plugins/dynamic-to-top/js/dynamic.to.top.min.js
JavaScript
gpl-2.0
1,192
export default (...modifiers): Array<string> => {};
recipesjs/ingredients
test/fixtures/flow/type-annotations/102/actual.js
JavaScript
mit
52
// Karma configuration // Generated on Sun Apr 14 2013 18:31:17 GMT+0200 (CEST) // base path, that will be used to resolve files and exclude basePath = ''; // list of files / patterns to load in the browser files = [ JASMINE, JASMINE_ADAPTER, 'http://code.angularjs.org/1.1.4/angular.js', 'http://code.angularjs.org/1.1.4/angular-resource.js', 'http://code.angularjs.org/1.1.4/angular-mocks.js', 'http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.4/underscore-min.js', 'src/restangular.js', 'test/*.js' ]; // list of files to exclude exclude = [ ]; // test results reporter to use // possible values: 'dots', 'progress', 'junit' reporters = ['progress']; // web server port port = 9877; // cli runner port runnerPort = 9101; // enable / disable colors in the output (reporters and logs) colors = true; // level of logging // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG logLevel = LOG_INFO; // enable / disable watching file and executing tests whenever any file changes autoWatch = true; // Start these browsers, currently available: // - Chrome // - ChromeCanary // - Firefox // - Opera // - Safari (only Mac) // - PhantomJS // - IE (only Windows) browsers = ['PhantomJS']; // If browser does not capture in given timeout [ms], kill it captureTimeout = 60000; // Continuous Integration mode // if true, it capture browsers, run tests and exit singleRun = false;
kyleiwaniec/yahoo-finance
yahoo-finance/bower_components/angularytics/karma.underscore.conf.js
JavaScript
mit
1,447
(function (_, $, Backbone, Drupal, drupalSettings) { "use strict"; /** * State of an in-place editable entity in the DOM. */ Drupal.edit.EntityModel = Drupal.edit.BaseModel.extend({ defaults: { // The DOM element that represents this entity. It may seem bizarre to // have a DOM element in a Backbone Model, but we need to be able to map // entities in the DOM to EntityModels in memory. el: null, // An entity ID, of the form "<entity type>/<entity ID>", e.g. "node/1". entityID: null, // An entity instance ID. The first intance of a specific entity (i.e. with // a given entity ID) is assigned 0, the second 1, and so on. entityInstanceID: null, // The unique ID of this entity instance on the page, of the form "<entity // type>/<entity ID>[entity instance ID]", e.g. "node/1[0]". id: null, // The label of the entity. label: null, // A Drupal.edit.FieldCollection for all fields of this entity. fields: null, // The attributes below are stateful. The ones above will never change // during the life of a EntityModel instance. // Indicates whether this instance of this entity is currently being // edited in-place. isActive: false, // Whether one or more fields have already been stored in TempStore. inTempStore: false, // Whether one or more fields have already been stored in TempStore *or* // the field that's currently being edited is in the 'changed' or a later // state. In other words, this boolean indicates whether a "Save" button is // necessary or not. isDirty: false, // Whether the request to the server has been made to commit this entity. // Used to prevent multiple such requests. isCommitting: false, // The current processing state of an entity. state: 'closed', // The IDs of the fields whose new values have been stored in TempStore. We // must store this on the EntityModel as well (even though it already is on // the FieldModel) because when a field is rerendered, its FieldModel is // destroyed and this allows us to transition it back to the proper state. fieldsInTempStore: [], // A flag the tells the application that this EntityModel must be reloaded // in order to restore the original values to its fields in the client. reload: false }, /** * @inheritdoc */ initialize: function () { this.set('fields', new Drupal.edit.FieldCollection()); // Respond to entity state changes. this.listenTo(this, 'change:state', this.stateChange); // The state of the entity is largely dependent on the state of its // fields. this.listenTo(this.get('fields'), 'change:state', this.fieldStateChange); // Call Drupal.edit.BaseModel's initialize() method. Drupal.edit.BaseModel.prototype.initialize.call(this); }, /** * Updates FieldModels' states when an EntityModel change occurs. * * @param Drupal.edit.EntityModel entityModel * @param String state * The state of the associated entity. One of Drupal.edit.EntityModel.states. * @param Object options */ stateChange: function (entityModel, state, options) { var to = state; switch (to) { case 'closed': this.set({ 'isActive': false, 'inTempStore': false, 'isDirty': false }); break; case 'launching': break; case 'opening': // Set the fields to candidate state. entityModel.get('fields').each(function (fieldModel) { fieldModel.set('state', 'candidate', options); }); break; case 'opened': // The entity is now ready for editing! this.set('isActive', true); break; case 'committing': // The user indicated they want to save the entity. var fields = this.get('fields'); // For fields that are in an active state, transition them to candidate. fields.chain() .filter(function (fieldModel) { return _.intersection([fieldModel.get('state')], ['active']).length; }) .each(function (fieldModel) { fieldModel.set('state', 'candidate'); }); // For fields that are in a changed state, field values must first be // stored in TempStore. fields.chain() .filter(function (fieldModel) { return _.intersection([fieldModel.get('state')], Drupal.edit.app.changedFieldStates).length; }) .each(function (fieldModel) { fieldModel.set('state', 'saving'); }); break; case 'deactivating': var changedFields = this.get('fields') .filter(function (fieldModel) { return _.intersection([fieldModel.get('state')], ['changed', 'invalid']).length; }); // If the entity contains unconfirmed or unsaved changes, return the // entity to an opened state and ask the user if they would like to save // the changes or discard the changes. // 1. One of the fields is in a changed state. The changed field might // just be a change in the client or it might have been saved to // tempstore. // 2. The saved flag is empty and the confirmed flag is empty. If the // entity has been saved to the server, the fields changed in the // client are irrelevant. If the changes are confirmed, then proceed // to set the fields to candidate state. if ((changedFields.length || this.get('fieldsInTempStore').length) && (!options.saved && !options.confirmed)) { // Cancel deactivation until the user confirms save or discard. this.set('state', 'opened', {confirming: true}); // An action in reaction to state change must be deferred. _.defer(function () { Drupal.edit.app.confirmEntityDeactivation(entityModel); }); } else { var invalidFields = this.get('fields') .filter(function (fieldModel) { return _.intersection([fieldModel.get('state')], ['invalid']).length; }); // Indicate if this EntityModel needs to be reloaded in order to // restore the original values of its fields. entityModel.set('reload', (this.get('fieldsInTempStore').length || invalidFields.length)); // Set all fields to the 'candidate' state. A changed field may have to // go through confirmation first. entityModel.get('fields').each(function (fieldModel) { // If the field is already in the candidate state, trigger a change // event so that the entityModel can move to the next state in // deactivation. if (_.intersection([fieldModel.get('state')], ['candidate', 'highlighted']).length) { fieldModel.trigger('change:state', fieldModel, fieldModel.get('state'), options); } else { fieldModel.set('state', 'candidate', options); } }); } break; case 'closing': // Set all fields to the 'inactive' state. options.reason = 'stop'; this.get('fields').each(function (fieldModel) { fieldModel.set({ 'inTempStore': false, 'state': 'inactive' }, options); }); break; } }, /** * Updates a Field and Entity model's "inTempStore" when appropriate. * * Helper function. * * @param Drupal.edit.EntityModel entityModel * The model of the entity for which a field's state attribute has changed. * @param Drupal.edit.FieldModel fieldModel * The model of the field whose state attribute has changed. * * @see fieldStateChange() */ _updateInTempStoreAttributes: function (entityModel, fieldModel) { var current = fieldModel.get('state'); var previous = fieldModel.previous('state'); var fieldsInTempStore = entityModel.get('fieldsInTempStore'); // If the fieldModel changed to the 'saved' state: remember that this // field was saved to TempStore. if (current === 'saved') { // Mark the entity as saved in TempStore, so that we can pass the // proper "reset TempStore" boolean value when communicating with the // server. entityModel.set('inTempStore', true); // Mark the field as saved in TempStore, so that visual indicators // signifying just that may be rendered. fieldModel.set('inTempStore', true); // Remember that this field is in TempStore, restore when rerendered. fieldsInTempStore.push(fieldModel.get('fieldID')); fieldsInTempStore = _.uniq(fieldsInTempStore); entityModel.set('fieldsInTempStore', fieldsInTempStore); } // If the fieldModel changed to the 'candidate' state from the // 'inactive' state, then this is a field for this entity that got // rerendered. Restore its previous 'inTempStore' attribute value. else if (current === 'candidate' && previous === 'inactive') { fieldModel.set('inTempStore', _.intersection([fieldModel.get('fieldID')], fieldsInTempStore).length > 0); } }, /** * Reacts to state changes in this entity's fields. * * @param Drupal.edit.FieldModel fieldModel * The model of the field whose state attribute changed. * @param String state * The state of the associated field. One of Drupal.edit.FieldModel.states. */ fieldStateChange: function (fieldModel, state) { var entityModel = this; var fieldState = state; // Switch on the entityModel state. // The EntityModel responds to FieldModel state changes as a function of its // state. For example, a field switching back to 'candidate' state when its // entity is in the 'opened' state has no effect on the entity. But that // same switch back to 'candidate' state of a field when the entity is in // the 'committing' state might allow the entity to proceed with the commit // flow. switch (this.get('state')) { case 'closed': case 'launching': // It should be impossible to reach these: fields can't change state // while the entity is closed or still launching. break; case 'opening': // We must change the entity to the 'opened' state, but it must first be // confirmed that all of its fieldModels have transitioned to the // 'candidate' state. // We do this here, because this is called every time a fieldModel // changes state, hence each time this is called, we get closer to the // goal of having all fieldModels in the 'candidate' state. // A state change in reaction to another state change must be deferred. _.defer(function () { entityModel.set('state', 'opened', { 'accept-field-states': Drupal.edit.app.readyFieldStates }); }); break; case 'opened': // Set the isDirty attribute when appropriate so that it is known when // to display the "Save" button in the entity toolbar. // Note that once a field has been changed, there's no way to discard // that change, hence it will have to be saved into TempStore, or the // in-place editing of this field will have to be stopped completely. // In other words: once any field enters the 'changed' field, then for // the remainder of the in-place editing session, the entity is by // definition dirty. if (fieldState === 'changed') { entityModel.set('isDirty', true); } else { this._updateInTempStoreAttributes(entityModel, fieldModel); } break; case 'committing': // If the field save returned a validation error, set the state of the // entity back to 'opened'. if (fieldState === 'invalid') { // A state change in reaction to another state change must be deferred. _.defer(function() { entityModel.set('state', 'opened', { reason: 'invalid' }); }); } else { this._updateInTempStoreAttributes(entityModel, fieldModel); } // Attempt to save the entity. If the entity's fields are not yet all in // a ready state, the save will not be processed. var options = { 'accept-field-states': Drupal.edit.app.readyFieldStates }; if (entityModel.set('isCommitting', true, options)) { entityModel.save({ success: function () { entityModel.set({ 'state': 'deactivating', 'isCommitting' : false }, {'saved': true}); }, error: function () { // Reset the "isCommitting" mutex. entityModel.set('isCommitting', false); // Change the state back to "opened", to allow the user to hit the // "Save" button again. entityModel.set('state', 'opened', { reason: 'networkerror' }); // Show a modal to inform the user of the network error. var message = Drupal.t('Your changes to <q>@entity-title</q> could not be saved, either due to a website problem or a network connection problem.<br>Please try again.', { '@entity-title' : entityModel.get('label') }); Drupal.edit.util.networkErrorModal(Drupal.t('Sorry!'), message); } }); } break; case 'deactivating': // When setting the entity to 'closing', require that all fieldModels // are in either the 'candidate' or 'highlighted' state. // A state change in reaction to another state change must be deferred. _.defer(function() { entityModel.set('state', 'closing', { 'accept-field-states': Drupal.edit.app.readyFieldStates }); }); break; case 'closing': // When setting the entity to 'closed', require that all fieldModels are // in the 'inactive' state. // A state change in reaction to another state change must be deferred. _.defer(function() { entityModel.set('state', 'closed', { 'accept-field-states': ['inactive'] }); }); break; } }, /** * Fires an AJAX request to the REST save URL for an entity. * * @param options * An object of options that contains: * - success: (optional) A function to invoke if the entity is success- * fully saved. */ save: function (options) { var entityModel = this; // @todo Simplify this once https://drupal.org/node/1533366 lands. // @see https://drupal.org/node/2029999. var id = 'edit-save-entity'; // Create a temporary element to be able to use Drupal.ajax. var $el = $('#edit-entity-toolbar').find('.action-save'); // This is the span element inside the button. // Create a Drupal.ajax instance to save the entity. var entitySaverAjax = new Drupal.ajax(id, $el, { url: Drupal.edit.util.buildUrl(entityModel.get('entityID'), drupalSettings.edit.entitySaveURL), event: 'edit-save.edit', progress: { type: 'none' }, error: function () { $el.off('edit-save.edit'); // Let the Drupal.edit.EntityModel Backbone model's error() method // handle errors. options.error.call(entityModel); } }); // Work-around for https://drupal.org/node/2019481 in Drupal 7. entitySaverAjax.commands = {}; // Entity saved successfully. entitySaverAjax.commands.editEntitySaved = function(ajax, response, status) { // Clean up. $(ajax.element).off('edit-save.edit'); // All fields have been moved from TempStore to permanent storage, update // the "inTempStore" attribute on FieldModels, on the EntityModel and // clear EntityModel's "fieldInTempStore" attribute. entityModel.get('fields').each(function (fieldModel) { fieldModel.set('inTempStore', false); }); entityModel.set('inTempStore', false); entityModel.set('fieldsInTempStore', []); // Invoke the optional success callback. if (options.success) { options.success.call(entityModel); } }; // Trigger the AJAX request, which will will return the editEntitySaved AJAX // command to which we then react. $el.trigger('edit-save.edit'); }, /** * {@inheritdoc} * * @param Object attrs * The attributes changes in the save or set call. * @param Object options * An object with the following option: * - String reason (optional): a string that conveys a particular reason * to allow for an exceptional state change. * - Array accept-field-states (optional) An array of strings that * represent field states that the entities must be in to validate. For * example, if accept-field-states is ['candidate', 'highlighted'], then * all the fields of the entity must be in either of these two states * for the save or set call to validate and proceed. */ validate: function (attrs, options) { var acceptedFieldStates = options['accept-field-states'] || []; // Validate state change. var currentState = this.get('state'); var nextState = attrs.state; if (currentState !== nextState) { // Ensure it's a valid state. if (_.indexOf(this.constructor.states, nextState) === -1) { return '"' + nextState + '" is an invalid state'; } // Ensure it's a state change that is allowed. // Check if the acceptStateChange function accepts it. if (!this._acceptStateChange(currentState, nextState, options)) { return 'state change not accepted'; } // If that function accepts it, then ensure all fields are also in an // acceptable state. else if (!this._fieldsHaveAcceptableStates(acceptedFieldStates)) { return 'state change not accepted because fields are not in acceptable state'; } } // Validate setting isCommitting = true. var currentIsCommitting = this.get('isCommitting'); var nextIsCommitting = attrs.isCommitting; if (currentIsCommitting === false && nextIsCommitting === true) { if (!this._fieldsHaveAcceptableStates(acceptedFieldStates)) { return 'isCommitting change not accepted because fields are not in acceptable state'; } } else if (currentIsCommitting === true && nextIsCommitting === true) { return "isCommiting is a mutex, hence only changes are allowed"; } }, // Like @see AppView.acceptEditorStateChange() _acceptStateChange: function (from, to, context) { var accept = true; // In general, enforce the states sequence. Disallow going back from a // "later" state to an "earlier" state, except in explicitly allowed // cases. if (!this.constructor.followsStateSequence(from, to)) { accept = false; // Allow: closing -> closed. // Necessary to stop editing an entity. if (from === 'closing' && to === 'closed') { accept = true; } // Allow: committing -> opened. // Necessary to be able to correct an invalid field, or to hit the "Save" // button again after a server/network error. else if (from === 'committing' && to === 'opened' && context.reason && (context.reason === 'invalid' || context.reason === 'networkerror')) { accept = true; } // Allow: deactivating -> opened. // Necessary to be able to confirm changes with the user. else if (from === 'deactivating' && to === 'opened' && context.confirming) { accept = true; } // Allow: opened -> deactivating. // Necessary to be able to stop editing. else if (from === 'opened' && to === 'deactivating' && context.confirmed) { accept = true; } } return accept; }, /** * @param Array acceptedFieldStates * @see validate() * @return Boolean */ _fieldsHaveAcceptableStates: function (acceptedFieldStates) { var accept = true; // If no acceptable field states are provided, assume all field states are // acceptable. We want to let validation pass as a default and only // check validity on calls to set that explicitly request it. if (acceptedFieldStates.length > 0) { var fieldStates = this.get('fields').pluck('state') || []; // If not all fields are in one of the accepted field states, then we // still can't allow this state change. if (_.difference(fieldStates, acceptedFieldStates).length) { accept = false; } } return accept; }, /** * @inheritdoc */ destroy: function (options) { Drupal.edit.BaseModel.prototype.destroy.call(this, options); this.stopListening(); // Destroy all fields of this entity. this.get('fields').each(function (fieldModel) { fieldModel.destroy(); }); }, /** * {@inheritdoc} */ sync: function () { // We don't use REST updates to sync. return; } }, { /** * A list (sequence) of all possible states an entity can be in during * in-place editing. */ states: [ // Initial state, like field's 'inactive' OR the user has just finished // in-place editing this entity. // - Trigger: none (initial) or EntityModel (finished). // - Expected behavior: (when not initial state): tear down // EntityToolbarView, in-place editors and related views. 'closed', // User has activated in-place editing of this entity. // - Trigger: user. // - Expected behavior: the EntityToolbarView is gets set up, in-place // editors (EditorViews) and related views for this entity's fields are // set up. Upon completion of those, the state is changed to 'opening'. 'launching', // Launching has finished. // - Trigger: application. // - Guarantees: in-place editors ready for use, all entity and field views // have been set up, all fields are in the 'inactive' state. // - Expected behavior: all fields are changed to the 'candidate' state and // once this is completed, the entity state will be changed to 'opened'. 'opening', // Opening has finished. // - Trigger: EntityModel. // - Guarantees: see 'opening', all fields are in the 'candidate' state. // - Expected behavior: the user is able to actually use in-place editing. 'opened', // User has clicked the 'Save' button (and has thus changed at least one // field). // - Trigger: user. // - Guarantees: see 'opened', plus: either a changed field is in TempStore, // or the user has just modified a field without activating (switching to) // another field. // - Expected behavior: 1) if any of the fields are not yet in TempStore, // save them to TempStore, 2) if then any of the fields has the 'invalid' // state, then change the entity state back to 'opened', otherwise: save // the entity by committing it from TempStore into permanent storage. 'committing', // User has clicked the 'Close' button, or has clicked the 'Save' button and // that was successfully completed. // - Trigger: user or EntityModel. // - Guarantees: when having clicked 'Close' hardly any: fields may be in a // variety of states; when having clicked 'Save': all fields are in the // 'candidate' state. // - Expected behavior: transition all fields to the 'candidate' state, // possibly requiring confirmation in the case of having clicked 'Close'. 'deactivating', // Deactivation has been completed. // - Trigger: EntityModel. // - Guarantees: all fields are in the 'candidate' state. // - Expected behavior: change all fields to the 'inactive' state. 'closing' ], /** * Indicates whether the 'from' state comes before the 'to' state. * * @param String from * One of Drupal.edit.EntityModel.states. * @param String to * One of Drupal.edit.EntityModel.states. * @return Boolean */ followsStateSequence: function (from, to) { return _.indexOf(this.states, from) < _.indexOf(this.states, to); } }); Drupal.edit.EntityCollection = Backbone.Collection.extend({ model: Drupal.edit.EntityModel }); }(_, jQuery, Backbone, Drupal, Drupal.settings));
christopherhuntley/daphnedixon
sites/all/modules/edit/js/models/EntityModel.js
JavaScript
gpl-2.0
24,459
/* YUI 3.5.1 (build 22) Copyright 2012 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add('event-valuechange', function(Y) { /** Adds a synthetic `valueChange` event that fires when the `value` property of an `<input>` or `<textarea>` node changes as a result of a keystroke, mouse operation, or input method editor (IME) input event. Usage: YUI().use('event-valuechange', function (Y) { Y.one('#my-input').on('valueChange', function (e) { }); }); @module event-valuechange **/ /** Provides the implementation for the synthetic `valueChange` event. This class isn't meant to be used directly, but is public to make monkeypatching possible. Usage: YUI().use('event-valuechange', function (Y) { Y.one('#my-input').on('valueChange', function (e) { }); }); @class ValueChange @static */ var DATA_KEY = '_valuechange', VALUE = 'value', config, // defined at the end of this file // Just a simple namespace to make methods overridable. VC = { // -- Static Constants ----------------------------------------------------- /** Interval (in milliseconds) at which to poll for changes to the value of an element with one or more `valueChange` subscribers when the user is likely to be interacting with it. @property POLL_INTERVAL @type Number @default 50 @static **/ POLL_INTERVAL: 50, /** Timeout (in milliseconds) after which to stop polling when there hasn't been any new activity (keypresses, mouse clicks, etc.) on an element. @property TIMEOUT @type Number @default 10000 @static **/ TIMEOUT: 10000, // -- Protected Static Methods --------------------------------------------- /** Called at an interval to poll for changes to the value of the specified node. @method _poll @param {Node} node Node to poll. @param {Object} options Options object. @param {EventFacade} [options.e] Event facade of the event that initiated the polling. @protected @static **/ _poll: function (node, options) { var domNode = node._node, // performance cheat; getValue() is a big hit when polling event = options.e, newVal = domNode && domNode.value, vcData = node._data && node._data[DATA_KEY], // another perf cheat facade, prevVal; if (!domNode || !vcData) { VC._stopPolling(node); return; } prevVal = vcData.prevVal; if (newVal !== prevVal) { vcData.prevVal = newVal; facade = { _event : event, currentTarget: (event && event.currentTarget) || node, newVal : newVal, prevVal : prevVal, target : (event && event.target) || node }; Y.Object.each(vcData.notifiers, function (notifier) { notifier.fire(facade); }); VC._refreshTimeout(node); } }, /** Restarts the inactivity timeout for the specified node. @method _refreshTimeout @param {Node} node Node to refresh. @param {SyntheticEvent.Notifier} notifier @protected @static **/ _refreshTimeout: function (node, notifier) { // The node may have been destroyed, so check that it still exists // before trying to get its data. Otherwise an error will occur. if (!node._node) { return; } var vcData = node.getData(DATA_KEY); VC._stopTimeout(node); // avoid dupes // If we don't see any changes within the timeout period (10 seconds by // default), stop polling. vcData.timeout = setTimeout(function () { VC._stopPolling(node, notifier); }, VC.TIMEOUT); }, /** Begins polling for changes to the `value` property of the specified node. If polling is already underway for the specified node, it will not be restarted unless the `force` option is `true` @method _startPolling @param {Node} node Node to watch. @param {SyntheticEvent.Notifier} notifier @param {Object} options Options object. @param {EventFacade} [options.e] Event facade of the event that initiated the polling. @param {Boolean} [options.force=false] If `true`, polling will be restarted even if we're already polling this node. @protected @static **/ _startPolling: function (node, notifier, options) { if (!node.test('input,textarea')) { return; } var vcData = node.getData(DATA_KEY); if (!vcData) { vcData = {prevVal: node.get(VALUE)}; node.setData(DATA_KEY, vcData); } vcData.notifiers || (vcData.notifiers = {}); // Don't bother continuing if we're already polling this node, unless // `options.force` is true. if (vcData.interval) { if (options.force) { VC._stopPolling(node, notifier); // restart polling, but avoid dupe polls } else { vcData.notifiers[Y.stamp(notifier)] = notifier; return; } } // Poll for changes to the node's value. We can't rely on keyboard // events for this, since the value may change due to a mouse-initiated // paste event, an IME input event, or for some other reason that // doesn't trigger a key event. vcData.notifiers[Y.stamp(notifier)] = notifier; vcData.interval = setInterval(function () { VC._poll(node, vcData, options); }, VC.POLL_INTERVAL); VC._refreshTimeout(node, notifier); }, /** Stops polling for changes to the specified node's `value` attribute. @method _stopPolling @param {Node} node Node to stop polling on. @param {SyntheticEvent.Notifier} [notifier] Notifier to remove from the node. If not specified, all notifiers will be removed. @protected @static **/ _stopPolling: function (node, notifier) { // The node may have been destroyed, so check that it still exists // before trying to get its data. Otherwise an error will occur. if (!node._node) { return; } var vcData = node.getData(DATA_KEY) || {}; clearInterval(vcData.interval); delete vcData.interval; VC._stopTimeout(node); if (notifier) { vcData.notifiers && delete vcData.notifiers[Y.stamp(notifier)]; } else { vcData.notifiers = {}; } }, /** Clears the inactivity timeout for the specified node, if any. @method _stopTimeout @param {Node} node @protected @static **/ _stopTimeout: function (node) { var vcData = node.getData(DATA_KEY) || {}; clearTimeout(vcData.timeout); delete vcData.timeout; }, // -- Protected Static Event Handlers -------------------------------------- /** Stops polling when a node's blur event fires. @method _onBlur @param {EventFacade} e @param {SyntheticEvent.Notifier} notifier @protected @static **/ _onBlur: function (e, notifier) { VC._stopPolling(e.currentTarget, notifier); }, /** Resets a node's history and starts polling when a focus event occurs. @method _onFocus @param {EventFacade} e @param {SyntheticEvent.Notifier} notifier @protected @static **/ _onFocus: function (e, notifier) { var node = e.currentTarget, vcData = node.getData(DATA_KEY); if (!vcData) { vcData = {}; node.setData(DATA_KEY, vcData); } vcData.prevVal = node.get(VALUE); VC._startPolling(node, notifier, {e: e}); }, /** Starts polling when a node receives a keyDown event. @method _onKeyDown @param {EventFacade} e @param {SyntheticEvent.Notifier} notifier @protected @static **/ _onKeyDown: function (e, notifier) { VC._startPolling(e.currentTarget, notifier, {e: e}); }, /** Starts polling when an IME-related keyUp event occurs on a node. @method _onKeyUp @param {EventFacade} e @param {SyntheticEvent.Notifier} notifier @protected @static **/ _onKeyUp: function (e, notifier) { // These charCodes indicate that an IME has started. We'll restart // polling and give the IME up to 10 seconds (by default) to finish. if (e.charCode === 229 || e.charCode === 197) { VC._startPolling(e.currentTarget, notifier, { e : e, force: true }); } }, /** Starts polling when a node receives a mouseDown event. @method _onMouseDown @param {EventFacade} e @param {SyntheticEvent.Notifier} notifier @protected @static **/ _onMouseDown: function (e, notifier) { VC._startPolling(e.currentTarget, notifier, {e: e}); }, /** Called when the `valuechange` event receives a new subscriber. @method _onSubscribe @param {Node} node @param {Subscription} sub @param {SyntheticEvent.Notifier} notifier @param {Function|String} [filter] Filter function or selector string. Only provided for delegate subscriptions. @protected @static **/ _onSubscribe: function (node, sub, notifier, filter) { var _valuechange, callbacks, nodes; callbacks = { blur : VC._onBlur, focus : VC._onFocus, keydown : VC._onKeyDown, keyup : VC._onKeyUp, mousedown: VC._onMouseDown }; // Store a utility object on the notifier to hold stuff that needs to be // passed around to trigger event handlers, polling handlers, etc. _valuechange = notifier._valuechange = {}; if (filter) { // If a filter is provided, then this is a delegated subscription. _valuechange.delegated = true; // Add a function to the notifier that we can use to find all // nodes that pass the delegate filter. _valuechange.getNodes = function () { return node.all('input,textarea').filter(filter); }; // Store the initial values for each descendant of the container // node that passes the delegate filter. _valuechange.getNodes().each(function (child) { if (!child.getData(DATA_KEY)) { child.setData(DATA_KEY, {prevVal: child.get(VALUE)}); } }); notifier._handles = Y.delegate(callbacks, node, filter, null, notifier); } else { // This is a normal (non-delegated) event subscription. if (!node.test('input,textarea')) { return; } if (!node.getData(DATA_KEY)) { node.setData(DATA_KEY, {prevVal: node.get(VALUE)}); } notifier._handles = node.on(callbacks, null, null, notifier); } }, /** Called when the `valuechange` event loses a subscriber. @method _onUnsubscribe @param {Node} node @param {Subscription} subscription @param {SyntheticEvent.Notifier} notifier @protected @static **/ _onUnsubscribe: function (node, subscription, notifier) { var _valuechange = notifier._valuechange; notifier._handles && notifier._handles.detach(); if (_valuechange.delegated) { _valuechange.getNodes().each(function (child) { VC._stopPolling(child, notifier); }); } else { VC._stopPolling(node, notifier); } } }; /** Synthetic event that fires when the `value` property of an `<input>` or `<textarea>` node changes as a result of a user-initiated keystroke, mouse operation, or input method editor (IME) input event. Unlike the `onchange` event, this event fires when the value actually changes and not when the element loses focus. This event also reports IME and multi-stroke input more reliably than `oninput` or the various key events across browsers. For performance reasons, only focused nodes are monitored for changes, so programmatic value changes on nodes that don't have focus won't be detected. @example YUI().use('event-valuechange', function (Y) { Y.one('#my-input').on('valueChange', function (e) { }); }); @event valuechange @param {String} prevVal Previous value prior to the latest change. @param {String} newVal New value after the latest change. @for YUI **/ config = { detach: VC._onUnsubscribe, on : VC._onSubscribe, delegate : VC._onSubscribe, detachDelegate: VC._onUnsubscribe, publishConfig: { emitFacade: true } }; Y.Event.define('valuechange', config); Y.Event.define('valueChange', config); // deprecated, but supported for backcompat Y.ValueChange = VC; }, '3.5.1' ,{requires:['event-focus', 'event-synthetic']});
sergiomt/zesped
src/webapp/js/yui/event-valuechange/event-valuechange.js
JavaScript
agpl-3.0
13,297
$(document).delegate('.storage_graph_link', 'click', function(e){ var anchor = this, el = $(anchor), id = el.attr('data-status'); if(e.ctrlKey || e.metaKey){ return true; }else{ e.preventDefault(); } var cell = document.getElementById(id); var text = el.html(); if (text == '[:: show ::]') { anchor.innerHTML = '[:: hide ::]'; if (cell.nodeName == 'IMG') { // <img src='...'/> cell.src=anchor.href; } else { $.ajax({ type: "get", url: anchor.href, success : function(response, textStatus) { cell.style.display = 'block'; cell.parentNode.style.display = 'block'; cell.innerHTML = response; var data = $('#countTrendMeta',cell).text(); graphLineChart($('#countTrend',cell)[0],eval('('+data+')')); data = $('#longTrendMeta',cell).text(); graphLineChart($('#longTrend',cell)[0],eval('('+data+')')); data = $('#avgTrendMeta',cell).text(); graphLineChart($('#avgTrend',cell)[0],eval('('+data+')')); data = $('#errorTrendMeta',cell).text(); graphLineChart($('#errorTrend',cell)[0],eval('('+data+')')); data = $('#piechartMeta',cell).text(); graphPieChart($('#piechart',cell)[0],eval('('+data+')')); } }); } } else { anchor.innerHTML = '[:: show ::]'; cell.style.display = 'none'; cell.parentNode.style.display = 'none'; } })
jialinsun/cat
cat-home/src/main/webapp/js/storage.js
JavaScript
apache-2.0
1,379
description("Test path animation where coordinate modes of start and end differ. You should see PASS messages"); createSVGTestCase(); // Setup test document var path = createSVGElement("path"); path.setAttribute("id", "path"); path.setAttribute("d", "M -30 -30 q 30 0 30 30 t -30 30 Z"); path.setAttribute("fill", "green"); path.setAttribute("onclick", "executeTest()"); path.setAttribute("transform", "translate(50, 50)"); var animate = createSVGElement("animate"); animate.setAttribute("id", "animation"); animate.setAttribute("attributeName", "d"); animate.setAttribute("from", "M -30 -30 q 30 0 30 30 t -30 30 Z"); animate.setAttribute("to", "M -30 -30 Q 30 -30 30 0 T -30 30 Z"); animate.setAttribute("begin", "click"); animate.setAttribute("dur", "4s"); path.appendChild(animate); rootSVGElement.appendChild(path); // Setup animation test function sample1() { // Check initial/end conditions shouldBeEqualToString("path.getAttribute('d')", "M -30 -30 q 30 0 30 30 t -30 30 Z"); } function sample2() { shouldBeEqualToString("path.getAttribute('d')", "M -30 -30 q 37.5 0 37.5 30 t -37.5 30 Z"); } function sample3() { shouldBeEqualToString("path.getAttribute('d')", "M -30 -30 Q 22.5 -30 22.5 0 T -30 30 Z"); } function sample4() { shouldBeEqualToString("path.getAttribute('d')", "M -30 -30 Q 29.9925 -30 29.9925 0 T -30 30 Z"); } function executeTest() { const expectedValues = [ // [animationId, time, sampleCallback] ["animation", 0.0, sample1], ["animation", 1.0, sample2], ["animation", 3.0, sample3], ["animation", 3.999, sample4], ["animation", 4.001, sample1] ]; runAnimationTest(expectedValues); } window.clickX = 40; window.clickY = 70; var successfullyParsed = true;
wuhengzhi/chromium-crosswalk
third_party/WebKit/LayoutTests/svg/animations/script-tests/animate-path-animation-qQ-tT-inverse.js
JavaScript
bsd-3-clause
1,777
var utils = require('./connection_utils'), inherits = require('util').inherits, net = require('net'), EventEmitter = require('events').EventEmitter, inherits = require('util').inherits, MongoReply = require("../responses/mongo_reply").MongoReply, Connection = require("./connection").Connection; var ConnectionPool = exports.ConnectionPool = function(host, port, poolSize, bson, socketOptions) { if(typeof host !== 'string' || typeof port !== 'number') throw "host and port must be specified [" + host + ":" + port + "]"; // Set up event emitter EventEmitter.call(this); // Keep all options for the socket in a specific collection allowing the user to specify the // Wished upon socket connection parameters this.socketOptions = typeof socketOptions === 'object' ? socketOptions : {}; this.socketOptions.host = host; this.socketOptions.port = port; this.bson = bson; // PoolSize is always + 1 for special reserved "measurment" socket (like ping, stats etc) this.poolSize = poolSize; this.minPoolSize = Math.floor(this.poolSize / 2) + 1; // Set default settings for the socket options utils.setIntegerParameter(this.socketOptions, 'timeout', 0); // Delay before writing out the data to the server utils.setBooleanParameter(this.socketOptions, 'noDelay', true); // Delay before writing out the data to the server utils.setIntegerParameter(this.socketOptions, 'keepAlive', 0); // Set the encoding of the data read, default is binary == null utils.setStringParameter(this.socketOptions, 'encoding', null); // Allows you to set a throttling bufferSize if you need to stop overflows utils.setIntegerParameter(this.socketOptions, 'bufferSize', 0); // Internal structures this.openConnections = []; // Assign connection id's this.connectionId = 0; // Current index for selection of pool connection this.currentConnectionIndex = 0; // The pool state this._poolState = 'disconnected'; // timeout control this._timeout = false; } inherits(ConnectionPool, EventEmitter); ConnectionPool.prototype.setMaxBsonSize = function(maxBsonSize) { if(maxBsonSize == null){ maxBsonSize = Connection.DEFAULT_MAX_BSON_SIZE; } for(var i = 0; i < this.openConnections.length; i++) { this.openConnections[i].maxBsonSize = maxBsonSize; } } // Start a function var _connect = function(_self) { return new function() { // Create a new connection instance var connection = new Connection(_self.connectionId++, _self.socketOptions); // Set logger on pool connection.logger = _self.logger; // Connect handler connection.on("connect", function(err, connection) { // Add connection to list of open connections _self.openConnections.push(connection); // If the number of open connections is equal to the poolSize signal ready pool if(_self.openConnections.length === _self.poolSize && _self._poolState !== 'disconnected') { // Set connected _self._poolState = 'connected'; // Emit pool ready _self.emit("poolReady"); } else if(_self.openConnections.length < _self.poolSize) { // We need to open another connection, make sure it's in the next // tick so we don't get a cascade of errors process.nextTick(function() { _connect(_self); }); } }); var numberOfErrors = 0 // Error handler connection.on("error", function(err, connection) { numberOfErrors++; // If we are already disconnected ignore the event if(_self._poolState != 'disconnected' && _self.listeners("error").length > 0) { _self.emit("error", err); } // Set disconnected _self._poolState = 'disconnected'; // Stop _self.stop(); }); // Close handler connection.on("close", function() { // If we are already disconnected ignore the event if(_self._poolState !== 'disconnected' && _self.listeners("close").length > 0) { _self.emit("close"); } // Set disconnected _self._poolState = 'disconnected'; // Stop _self.stop(); }); // Timeout handler connection.on("timeout", function(err, connection) { // If we are already disconnected ignore the event if(_self._poolState !== 'disconnected' && _self.listeners("timeout").length > 0) { _self.emit("timeout", err); } // Set disconnected _self._poolState = 'disconnected'; // Stop _self.stop(); }); // Parse error, needs a complete shutdown of the pool connection.on("parseError", function() { // If we are already disconnected ignore the event if(_self._poolState !== 'disconnected' && _self.listeners("parseError").length > 0) { _self.emit("parseError", new Error("parseError occured")); } _self.stop(); }); connection.on("message", function(message) { _self.emit("message", message); }); // Start connection in the next tick connection.start(); }(); } // Start method, will throw error if no listeners are available // Pass in an instance of the listener that contains the api for // finding callbacks for a given message etc. ConnectionPool.prototype.start = function() { var markerDate = new Date().getTime(); var self = this; if(this.listeners("poolReady").length == 0) { throw "pool must have at least one listener ready that responds to the [poolReady] event"; } // Set pool state to connecting this._poolState = 'connecting'; this._timeout = false; _connect(self); } // Restart a connection pool (on a close the pool might be in a wrong state) ConnectionPool.prototype.restart = function() { // Close all connections this.stop(false); // Now restart the pool this.start(); } // Stop the connections in the pool ConnectionPool.prototype.stop = function(removeListeners) { removeListeners = removeListeners == null ? true : removeListeners; // Set disconnected this._poolState = 'disconnected'; // Clear all listeners if specified if(removeListeners) { this.removeAllEventListeners(); } // Close all connections for(var i = 0; i < this.openConnections.length; i++) { this.openConnections[i].close(); } // Clean up this.openConnections = []; } // Check the status of the connection ConnectionPool.prototype.isConnected = function() { return this._poolState === 'connected'; } // Checkout a connection from the pool for usage, or grab a specific pool instance ConnectionPool.prototype.checkoutConnection = function(id) { var index = (this.currentConnectionIndex++ % (this.openConnections.length)); var connection = this.openConnections[index]; return connection; } ConnectionPool.prototype.getAllConnections = function() { return this.openConnections; } // Remove all non-needed event listeners ConnectionPool.prototype.removeAllEventListeners = function() { this.removeAllListeners("close"); this.removeAllListeners("error"); this.removeAllListeners("timeout"); this.removeAllListeners("connect"); this.removeAllListeners("end"); this.removeAllListeners("parseError"); this.removeAllListeners("message"); this.removeAllListeners("poolReady"); }
cw0100/cwse
nodejs/node_modules/rrestjs/node_modules/mongodb/lib/mongodb/connection/connection_pool.js
JavaScript
gpl-2.0
7,246
define( ({ "collapse": "Spusti traku s alatima editora", "expand": "Proširi traku s alatima editora" }) );
avz-cmf/zaboy-middleware
www/js/dojox/editor/plugins/nls/hr/CollapsibleToolbar.js
JavaScript
gpl-3.0
110