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
/* global test expect */ const ConfigObject = require('../config_object') test('new', () => { const object = new ConfigObject() expect(object).toBeInstanceOf(ConfigObject) expect(object).toBeInstanceOf(Object) }) test('set', () => { const object = new ConfigObject() expect(object.set('key', 'value')).toEqual({ key: 'value' }) }) test('get', () => { const object = new ConfigObject() object.set('key', 'value') object.set('key1', 'value1') expect(object.get('key')).toEqual('value') }) test('delete', () => { const object = new ConfigObject() object.set('key', { key1: 'value' }) expect(object.delete('key.key1')).toEqual({ key: {} }) expect(object.delete('key')).toEqual({}) }) test('toObject', () => { const object = new ConfigObject() object.set('key', 'value') object.set('key1', 'value1') expect(object.toObject()).toEqual({ key: 'value', key1: 'value1' }) }) test('merge', () => { const object = new ConfigObject() object.set('foo', {}) expect(object.merge({ key: 'foo', value: 'bar' })).toEqual( { foo: {}, key: 'foo', value: 'bar' } ) })
jmarkbrooks/shine
vendor/bundle/ruby/2.5.0/gems/webpacker-3.5.2/package/config_types/__tests__/config_object.js
JavaScript
gpl-3.0
1,100
'use strict'; exports.__esModule = true; exports['default'] = mergeMap; var _mergeMapSupport = require('./mergeMap-support'); function mergeMap(project, resultSelector) { var concurrent = arguments.length <= 2 || arguments[2] === undefined ? Number.POSITIVE_INFINITY : arguments[2]; return this.lift(new _mergeMapSupport.MergeMapOperator(project, resultSelector, concurrent)); } module.exports = exports['default'];
NodeVision/NodeVision
node_modules/angular2/node_modules/@reactivex/rxjs/dist/cjs/operators/mergeMap.js
JavaScript
gpl-3.0
428
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"); } } var ObjectRouteHandler = (function () { function ObjectRouteHandler(dbOrSchema, serializerOrRegistry, object) { _classCallCheck(this, ObjectRouteHandler); this.dbOrSchema = dbOrSchema; this.serializerOrRegistry = serializerOrRegistry; this.object = object; } _createClass(ObjectRouteHandler, [{ key: "handle", value: function handle(request) { return this.object; } }]); return ObjectRouteHandler; })(); export default ObjectRouteHandler;
Elektro1776/latestEarthables
core/client/tmp/broccoli_persistent_filterbabel-output_path-mXQppNyR.tmp/modules/ember-cli-mirage/route-handlers/object.js
JavaScript
gpl-3.0
1,209
/* * Don't edit this file by hand! * This file was generated from a npm-package using gulp. * For more information see gulpfile.js in the project root */ define(function (require, exports, module) {"use strict"; var path = require("path"); var util = require("util/util"); var Level = require("./level"); var Handler = require("./handler"); var LogRecord = require("./logrecord"); /** * This class is the equivalent of java.util.logging.Logger * @name Logger * @param {object} [options] * @param {String} [options.name=null] Name to describe this logger * @param {Level} [options.level=Level.SEVERE] Default logging level * * @returns {Logger} * @constructor */ var Logger = function(options) { var self = this; (self.super_ = Logger.super_).call(self); var options = options || {}; this._level = (Level.isValid(options.level))? options.level: Level.SEVERE; this._name = options.name; this._handlers = []; return this; }; util.inherits(Logger, Object); var fillStackInfo = function(/** LogRecord */ record) { var orig = Error.prepareStackTrace; try { var err = new Error(); var caller; Error.prepareStackTrace = function (err, stack) { return stack; }; var parentFrame = err.stack.shift(); var current = parentFrame.getFileName(); while (err.stack.length) { var currentFrame = err.stack.shift(); caller = currentFrame.getFileName(); if(current!==caller) { var info = currentFrame.toString(); record.setSourceFileName(currentFrame.getFileName()); record.setSourceMethodName(currentFrame.getMethodName()); record.setSourceStackFrame(currentFrame); return info; } } } catch (err) {} finally { Error.prepareStackTrace = orig; } return undefined; }; /** * Sets the logging {@link Level} for this {@link Logger} * @param {Level} level Logging level * * @returns {Logger} */ Logger.prototype.setLevel = function(level) { if (!Level.isValid(level)) { return this; } this._level = level; return this; }; /** * Retrieves the logging {@link Level} for this {@link Logger} * @returns {Level} Logging level */ Logger.prototype.getLevel = function() { return this._level; }; /** * Set the name of the logger * @param {string} name Logger name * @returns {Logger} */ Logger.prototype.setName = function(name) { if (!name || typeof "name" !== "string") { return this; } this._name = name; return this; }; /** * Retrieves the name of the logger * @returns {string} Logger name */ Logger.prototype.getName = function() { return this._name; }; /** * Adds a handler to the the logger * @param {Handler} handler The {@link Handler} to add * @returns {Logger} */ Logger.prototype.addHandler = function(handler) { if (!handler || !(handler instanceof Handler)) { return this; } this._handlers.push(handler); return this; }; /** * Removes the specified handler from the logger * @param {Handler} handler The {@link Handler} to remove * @returns {Logger} */ Logger.prototype.removeHandler = function(handler) { if (!handler || !(handler instanceof Handler)) { return this; } var index = this._handlers.indexOf(handler); if (index < 0) { return this; } this._handlers.splice(index,1); return this; }; /** * Retrieves the {@link Handler}s associated with the {@link Logger} * @returns {Array} */ Logger.prototype.getHandlers = function() { return this._handlers; }; /** * Logs the given {@linkcode message} at the specified {@linkcode level} * @param {Level} level Logging level * @param {string} message Message to log * * @returns {Logger} */ Logger.prototype.log = function() {}; /** * Logs the given {@linkcode message}, and error at the specified {@linkcode level} * @param {Level} level Logging level * @param {string} message Message to log * @param {Error} error Error object to log * * @returns {Logger} */ Logger.prototype.log = function() {}; /** * Logs the formatted message ({@linkcode format}), with the given {@linkcode params} * array as input to the {@linkcode format}, at the specified {@linkcode level} * @param {Level} level Logging level * @param {string} format Format to use for the message * @param {...*} params Variable number of parameters as input to the {@linkcode format} * * @returns {Logger} */ /** * Logs the given {@linkcode object}, at the specified {@linkcode level} * @param {Level} level Logging level * @param {object} object Object to log * * @returns {Logger} */ Logger.prototype.log = function() {}; Logger.prototype.log = function() {}; /** * Logs the formatted message ({@linkcode format}), with the given variable {@linkcode params} * as input to the {@linkcode format}, at the specified {@linkcode level} * @param {Level} level Logging level * @param {string} format Format to use for the message * @param {...*} params Variable number of parameters as input to the {@linkcode format} * * @returns {Logger} */ Logger.prototype.log = function() { var args = Array.prototype.splice.call(arguments,0); if (args.length < 2) { return this; } var level = args.shift(); var message = args.shift(); var thrown; var parameters = []; if (util.isError(message) && args.length == 0) { thrown = message; message = ""; } else if (args.length == 1 && util.isError(args[0])) { thrown = args[0]; } else if (args.length == 1 && args[0] instanceof Array) { parameters = args[0]; } else { parameters = args; } if (!Level.isValid(level) || message === undefined) { return this; } var handlers = this.getHandlers(); if (level < this.getLevel()) { return this; } var logRecord = new LogRecord(); logRecord.setLevel(level); logRecord.setLoggerName(this.getName()); logRecord.setMessage(message); logRecord.setMillis(new Date().getTime()); logRecord.setParameters(parameters); logRecord.setThrown(thrown); fillStackInfo(logRecord); handlers.forEach(function(handler) { handler.publish(logRecord); }); return this; }; Logger.prototype._log = function(level, args) { args = Array.prototype.splice.call(args, 0); args.unshift(level); this.log.apply(this, args); return this; }; /** * Logs the given message, at {@linkCode Level.SEVERE} level * @param {string} message Message to log * @returns {Logger} */ Logger.prototype.severe = function() {}; /** * Logs the given formatted message ({@linkcode format}) using the variable {@linkcode params} as input, * at {@linkCode Level.SEVERE} level * @param {string} format Format to use for the message * @param {...*} params Variable number of parameters as input to the {@linkcode format} * @returns {Logger} */ Logger.prototype.severe = function() {}; /** * Logs the given {@linkcode object}, at {@linkCode Level.SEVERE} level * @param {object} object Object to log * * @returns {Logger} */ Logger.prototype.severe = function() {}; /** * Logs the given message, and error at {@linkCode Level.SEVERE} level * @param {string} message Message to log * @param {Error} error Error object to log * @returns {Logger} */ Logger.prototype.severe = function() { return this._log(Level.SEVERE, arguments); }; /** * Logs the given message, at {@linkCode Level.WARNING} level * @param {string} message Message to log * @returns {Logger} */ Logger.prototype.warning = function() {}; /** * Logs the given formatted message ({@linkcode format}) using the variable {@linkcode params} as input, * at {@linkCode Level.WARNING} level * @param {string} format Format to use for the message * @param {...*} params Variable number of parameters as input to the {@linkcode format} * @returns {Logger} */ Logger.prototype.warning = function() {}; /** * Logs the given {@linkcode object}, at {@linkCode Level.WARNING} level * @param {object} object Object to log * * @returns {Logger} */ Logger.prototype.warning = function() {}; /** * Logs the given message, and error at {@linkCode Level.WARNING} level * @param {string} message Message to log * @param {Error} error Error object to log * @returns {Logger} */ Logger.prototype.warning = function() { return this._log(Level.WARNING, arguments); }; /** * Logs the given message, at {@linkCode Level.CONFIG} level * @param {string} message Message to log * @returns {Logger} */ Logger.prototype.config = function() {}; /** * Logs the given formatted message ({@linkcode format}) using the variable {@linkcode params} as input, * at {@link Level.CONFIG} level * @param {string} format Format to use for the message * @param {...*} params Variable number of parameters as input to the {@linkcode format} * @returns {Logger} */ Logger.prototype.config = function() {}; /** * Logs the given {@linkcode object}, at {@linkCode Level.CONFIG} level * @param {object} object Object to log * * @returns {Logger} */ Logger.prototype.config = function() {}; /** * Logs the given message, and error at {@linkCode Level.CONFIG} level * @param {string} message Message to log * @param {Error} error Error object to log * @returns {Logger} */ Logger.prototype.config = function() { return this._log(Level.CONFIG, arguments); }; /** * Logs the given message, at {@linkCode Level.INFO} level * @param {string} message Message to log * @returns {Logger} */ Logger.prototype.info = function() {} /** * Logs the given formatted message ({@linkcode format}) using the variable {@linkcode params} as input, * at {@linkCode Level.INFO} level * @param {string} format Format to use for the message * @param {...*} params Variable number of parameters as input to the {@linkcode format} * @returns {Logger} */ Logger.prototype.info = function() {} /** * Logs the given {@linkcode object}, at {@linkCode Level.INFO} level * @param {object} object Object to log * * @returns {Logger} */ Logger.prototype.info = function() {}; /** * Logs the given message, and error at {@linkCode Level.INFO} level * @param {string} message Message to log * @param {Error} error Error object to log * @returns {Logger} */ Logger.prototype.info = function() { return this._log(Level.INFO, arguments); }; /** * Logs the given message, at {@linkCode Level.FINE} level * @param {string} message Message to log * @returns {Logger} */ Logger.prototype.fine = function() {} /** * Logs the given formatted message ({@linkcode format}) using the variable {@linkcode params} as input, * at {@linkCode Level.FINE} level * @param {string} format Format to use for the message * @param {...*} params Variable number of parameters as input to the {@linkcode format} * @returns {Logger} */ Logger.prototype.fine = function() {} /** * Logs the given {@linkcode object}, at {@linkCode Level.FINE} level * @param {object} object Object to log * * @returns {Logger} */ Logger.prototype.fine = function() {}; /** * Logs the given message, and error at {@linkCode Level.FINE} level * @param {string} message Message to log * @param {Error} error Error object to log * @returns {Logger} */ Logger.prototype.fine = function() { return this._log(Level.FINE, arguments); }; /** * Logs the given message, at {@linkCode Level.FINER} level * @param {string} message Message to log * @returns {Logger} */ Logger.prototype.finer = function() {} /** * Logs the given formatted message ({@linkcode format}) using the variable {@linkcode params} as input, * at {@linkCode Level.FINER} level * @param {string} format Format to use for the message * @param {...*} params Variable number of parameters as input to the {@linkcode format} * @returns {Logger} */ Logger.prototype.finer = function() {} /** * Logs the given {@linkcode object}, at {@linkCode Level.FINER} level * @param {object} object Object to log * * @returns {Logger} */ Logger.prototype.finer = function() {}; /** * Logs the given message, and error at {@linkCode Level.FINER} level * @param {string} message Message to log * @param {Error} error Error object to log * @returns {Logger} */ Logger.prototype.finer = function() { return this._log(Level.FINER, arguments); }; /** * Logs the given message, at {@linkCode Level.FINEST} level * @param {string} message Message to log * @returns {Logger} */ Logger.prototype.finest = function() {}; /** * Logs the given formatted message ({@linkcode format}) using the variable {@linkcode params} as input, * at {@link Level.FINEST} level * @param {string} format Format to use for the message * @param {...*} params Variable number of parameters as input to the {@linkcode format} * @returns {Logger} */ Logger.prototype.finest = function() {}; /** * Logs the given {@linkcode object}, at {@linkCode Level.FINEST} level * @param {object} object Object to log * * @returns {Logger} */ Logger.prototype.finest = function() {}; /** * Logs the given message, and error at {@linkCode Level.FINEST} level * @param {string} message * @param {Error} error Error object to log * @returns {Logger} */ Logger.prototype.finest = function() { return this._log(Level.FINEST, arguments); }; module.exports = Logger; });
mvz/metapolator
app/lib/npm_converted/util-logging/lib/logger.js
JavaScript
gpl-3.0
13,686
// // Run test script in content process instead of chrome (xpcshell's default) // function run_test() { run_test_in_child("../unit/test_dns_cancel.js"); }
Yukarumya/Yukarum-Redfoxes
netwerk/test/unit_ipc/test_dns_cancel_wrap.js
JavaScript
mpl-2.0
159
/** * 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. */ var App = require('app'); require('views/main/admin/highAvailability/resourceManager/step3_view'); describe('App.RMHighAvailabilityWizardStep3View', function () { var view; beforeEach(function() { view = App.RMHighAvailabilityWizardStep3View.create({ controller: Em.Object.create({ content: Em.Object.create(), loadStep: Em.K }) }); }); describe("#didInsertElement()", function () { beforeEach(function () { sinon.spy(view.get('controller'), 'loadStep'); }); afterEach(function () { view.get('controller').loadStep.restore(); }); it("call loadStep", function () { view.didInsertElement(); expect(view.get('controller').loadStep.calledOnce).to.be.true; }); }); });
arenadata/ambari
ambari-web/test/views/main/admin/highAvailability/resourceManager/step3_view_test.js
JavaScript
apache-2.0
1,572
/* -------------------------------------------------------------------------- */ /* Copyright 2002-2016, OpenNebula Project, OpenNebula Systems */ /* */ /* 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. */ /* -------------------------------------------------------------------------- */ define(function(require){ return 'createClusterForm'; });
hsanjuan/one
src/sunstone/public/app/tabs/clusters-tab/form-panels/create/formPanelId.js
JavaScript
apache-2.0
1,276
/** * Copyright 2015 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. */ import { AmpMustache, } from '../amp-mustache'; describe('amp-mustache template', () => { it('should render', () => { const templateElement = document.createElement('template'); templateElement.content.textContent = 'value = {{value}}'; const template = new AmpMustache(templateElement); template.compileCallback(); const result = template.render({value: 'abc'}); expect(result./*OK*/innerHTML).to.equal('value = abc'); }); it('should render {{.}} from string', () => { const templateElement = document.createElement('template'); templateElement.content.textContent = 'value = {{.}}'; const template = new AmpMustache(templateElement); template.compileCallback(); const result = template.render('abc'); expect(result./*OK*/innerHTML).to.equal('value = abc'); }); it('should sanitize output', () => { const templateElement = document.createElement('template'); templateElement./*OK*/innerHTML = 'value = <a href="{{value}}">abc</a>'; const template = new AmpMustache(templateElement); template.compileCallback(); const result = template.render({ value: /*eslint no-script-url: 0*/ 'javascript:alert();', }); expect(result./*OK*/innerHTML).to.equal('value = <a target="_top">abc</a>'); }); it('should sanitize templated tag names', () => { const templateElement = document.createElement('template'); templateElement./*OK*/innerHTML = 'value = <{{value}} href="javascript:alert(0)">abc</{{value}}>'; const template = new AmpMustache(templateElement); template.compileCallback(); const result = template.render({ value: 'a', }); expect(result./*OK*/innerHTML).to.not .equal('<a href="javascript:alert(0)">abc</a>'); expect(result.firstElementChild).to.be.null; }); describe('Sanitizing data- attributes', () => { it('should sanitize templated attribute names', () => { const templateElement = document.createElement('template'); templateElement./*OK*/innerHTML = 'value = <a {{value}}="javascript:alert(0)">abc</a>'; let template = new AmpMustache(templateElement); template.compileCallback(); let result = template.render({ value: 'href', }); expect(result).to.not.equal('<a href="javascript:alert(0)">abc</a>'); expect(result.firstElementChild.getAttribute('href')).to.be.null; templateElement./*OK*/innerHTML = 'value = <p [{{value}}]="javascript:alert()">ALERT</p>'; template = new AmpMustache(templateElement); template.compileCallback(); result = template.render({ value: 'onclick', }); expect(result).to.not .equal('<p [onclick]="javascript:alert()">ALERT</p>'); expect(result.firstElementChild.getAttribute('[onclick]')).to.be.null; expect(result.firstElementChild.getAttribute('onclick')).to.be.null; }); it('should parse data-&style=value output correctly', () => { const templateElement = document.createElement('template'); templateElement./*OK*/innerHTML = 'value = <a href="{{value}}"' + ' data-&style="color:red;">abc</a>'; const template = new AmpMustache(templateElement); template.compileCallback(); const result = template.render({ value: /*eslint no-script-url: 0*/ 'javascript:alert();', }); expect(result./*OK*/innerHTML).to.equal( 'value = <a data-="" target="_top">abc</a>'); }); it('should parse data-&attr=value output correctly', () => { const templateElement = document.createElement('template'); templateElement./*OK*/innerHTML = 'value = <a data-&href="{{value}}">abc</a>'; const template = new AmpMustache(templateElement); template.compileCallback(); const result = template.render({ value: 'https://google.com/', }); expect(result./*OK*/innerHTML).to.equal('value = <a data-=""' + ' href="https://google.com/" target="_top">abc</a>'); }); it('should allow for data-attr=value to output correctly', () => { const templateElement = document.createElement('template'); templateElement./*OK*/innerHTML = 'value = ' + '<a data-my-attr="{{invalidValue}}" data-my-id="{{value}}">abc</a>'; const template = new AmpMustache(templateElement); template.compileCallback(); const result = template.render({ value: 'myid', invalidValue: /*eslint no-script-url: 0*/ 'javascript:alert();', }); expect(result./*OK*/innerHTML).to.equal( 'value = <a data-my-id="myid">abc</a>'); }); }); describe('Rendering Form Fields', () => { it('should allow rendering inputs', () => { const templateElement = document.createElement('template'); templateElement./*OK*/innerHTML = 'value = ' + '<input value="{{value}}" type="text" onchange="{{invalidValue}}">'; const template = new AmpMustache(templateElement); template.compileCallback(); const result = template.render({ value: 'myid', invalidValue: /*eslint no-script-url: 0*/ 'javascript:alert();', }); expect(result./*OK*/innerHTML).to.equal( 'value = <input value="myid" type="text">'); }); it('should allow rendering textarea', () => { const templateElement = document.createElement('template'); templateElement./*OK*/innerHTML = 'value = ' + '<textarea>{{value}}</textarea>'; const template = new AmpMustache(templateElement); template.compileCallback(); const result = template.render({ value: 'Cool story bro.', }); expect(result./*OK*/innerHTML).to.equal( 'value = <textarea>Cool story bro.</textarea>'); }); it('should not allow image/file types rendering', () => { const templateElement = document.createElement('template'); templateElement./*OK*/innerHTML = 'value = ' + '<input value="{{value}}" type="{{type}}">'; const template = new AmpMustache(templateElement); template.compileCallback(); let result = template.render({ value: 'myid', type: 'image', }); expect(result./*OK*/innerHTML).to.equal( 'value = <input value="myid">'); result = template.render({ value: 'myid', type: 'file', }); expect(result./*OK*/innerHTML).to.equal( 'value = <input value="myid">'); result = template.render({ value: 'myid', type: 'text', }); expect(result./*OK*/innerHTML).to.equal( 'value = <input value="myid" type="text">'); result = template.render({ value: 'myid', type: 'button', }); expect(result./*OK*/innerHTML).to.equal( 'value = <input value="myid">'); result = template.render({ value: 'myid', type: 'password', }); expect(result./*OK*/innerHTML).to.equal( 'value = <input value="myid">'); }); it('should sanitize form-related attrs properly', () => { const templateElement = document.createElement('template'); templateElement./*OK*/innerHTML = 'value = ' + '<input value="{{value}}" ' + 'formaction="javascript:javascript:alert(1)" ' + 'formmethod="get" form="form1" formtarget="blank" formnovalidate ' + 'formenctype="">'; const template = new AmpMustache(templateElement); template.compileCallback(); const result = template.render({ value: 'myid', }); expect(result./*OK*/innerHTML).to.equal( 'value = <input value="myid">'); }); it('should not sanitize form tags', () => { const templateElement = document.createElement('template'); templateElement./*OK*/innerHTML = 'value = ' + '<form><input value="{{value}}"></form><input value="hello">'; const template = new AmpMustache(templateElement); template.compileCallback(); const result = template.render({ value: 'myid', }); expect(result./*OK*/innerHTML).to.equal( 'value = <form><input value="myid"></form><input value="hello">'); }); }); describe('Nested templates', () => { it('should not sanitize nested amp-mustache templates', () => { const templateElement = document.createElement('template'); templateElement./*OK*/innerHTML = 'text before a template ' + '<template type="amp-mustache">text inside template</template> ' + 'text after a template'; const template = new AmpMustache(templateElement); template.compileCallback(); const result = template.render({}); expect(result./*OK*/innerHTML).to.equal( 'text before a template ' + '<template type="amp-mustache">text inside template</template> ' + 'text after a template'); }); it('should sanitize nested templates without type="amp-mustache"', () => { const templateElement = document.createElement('template'); templateElement./*OK*/innerHTML = 'text before a template ' + '<template>text inside template</template> ' + 'text after a template'; const template = new AmpMustache(templateElement); template.compileCallback(); const result = template.render({}); expect(result./*OK*/innerHTML).to.equal( 'text before a template text after a template'); }); it('should not render variables inside a nested template', () => { const templateElement = document.createElement('template'); templateElement./*OK*/innerHTML = 'outer: {{outerOnlyValue}} {{mutualValue}} ' + '<template type="amp-mustache">nested: {{nestedOnlyValue}}' + ' {{mutualValue}}</template>'; const template = new AmpMustache(templateElement); template.compileCallback(); const result = template.render({ outerOnlyValue: 'Outer', mutualValue: 'Mutual', nestedOnlyValue: 'Nested', }); expect(result./*OK*/innerHTML).to.equal( 'outer: Outer Mutual ' + '<template type="amp-mustache">nested: {{nestedOnlyValue}}' + ' {{mutualValue}}</template>'); }); it('should compile and render nested templates when invoked', () => { const outerTemplateElement = document.createElement('template'); outerTemplateElement./*OK*/innerHTML = 'outer: {{value}} ' + '<template type="amp-mustache">nested: {{value}}</template>'; const outerTemplate = new AmpMustache(outerTemplateElement); outerTemplate.compileCallback(); const outerResult = outerTemplate.render({ value: 'Outer', }); const nestedTemplateElement = outerResult.querySelector('template'); const nestedTemplate = new AmpMustache(nestedTemplateElement); nestedTemplate.compileCallback(); const nestedResult = nestedTemplate.render({ value: 'Nested', }); expect(nestedResult./*OK*/innerHTML).to.equal('nested: Nested'); }); it('should sanitize the inner template when it gets rendered', () => { const outerTemplateElement = document.createElement('template'); outerTemplateElement./*OK*/innerHTML = 'outer: {{value}} ' + '<template type="amp-mustache">' + '<div onclick="javascript:alert(\'I am evil\')">nested</div>: ' + '{{value}}</template>'; const outerTemplate = new AmpMustache(outerTemplateElement); outerTemplate.compileCallback(); const outerResult = outerTemplate.render({ value: 'Outer', }); const nestedTemplateElement = outerResult.querySelector('template'); const nestedTemplate = new AmpMustache(nestedTemplateElement); nestedTemplate.compileCallback(); const nestedResult = nestedTemplate.render({ value: 'Nested', }); expect(nestedResult./*OK*/innerHTML).to.equal( '<div>nested</div>: Nested'); }); it('should not allow users to pass data having key that starts with ' + '__AMP_NESTED_TEMPLATE_0 when there is a nested template', () => { const templateElement = document.createElement('template'); templateElement./*OK*/innerHTML = 'outer: {{value}} ' + '<template type="amp-mustache">nested: {{value}}</template>'; const template = new AmpMustache(templateElement); template.compileCallback(); const result = template.render({ __AMP_NESTED_TEMPLATE_0: 'MUST NOT RENDER THIS', value: 'Outer', }); expect(result./*OK*/innerHTML).to.equal( 'outer: Outer ' + '<template type="amp-mustache">nested: {{value}}</template>'); }); it('should render user data with a key __AMP_NESTED_TEMPLATE_0 when' + ' there are no nested templates, even though it is not a weird name' + ' for a template variable', () => { const templateElement = document.createElement('template'); templateElement./*OK*/innerHTML = '{{__AMP_NESTED_TEMPLATE_0}}'; const template = new AmpMustache(templateElement); template.compileCallback(); const result = template.render({ __AMP_NESTED_TEMPLATE_0: '123', }); expect(result./*OK*/innerHTML).to.equal('123'); }); }); it('should sanitize triple-mustache', () => { const templateElement = document.createElement('template'); templateElement.content.textContent = 'value = {{{value}}}'; const template = new AmpMustache(templateElement); template.compileCallback(); const result = template.render({value: '<b>abc</b><img><div>def</div>'}); expect(result./*OK*/innerHTML).to.equal('value = <b>abc</b>'); }); it('should unwrap output', () => { const templateElement = document.createElement('template'); templateElement./*OK*/innerHTML = '<a>abc</a>'; const template = new AmpMustache(templateElement); template.compileCallback(); const result = template.render({}); expect(result.tagName).to.equal('A'); expect(result./*OK*/innerHTML).to.equal('abc'); }); });
engtat/amphtml
extensions/amp-mustache/0.1/test/test-amp-mustache.js
JavaScript
apache-2.0
14,835
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ 'use strict'; /** * Display name of operation * */ class OperationDisplay { /** * Create a OperationDisplay. * @member {string} [provider] The resource provider name: * Microsoft.MachineLearningExperimentation * @member {string} [resource] The resource on which the operation is * performed. * @member {string} [operation] The operation that users can perform. * @member {string} [description] The description for the operation. */ constructor() { } /** * Defines the metadata of OperationDisplay * * @returns {object} metadata of OperationDisplay * */ mapper() { return { required: false, serializedName: 'Operation_display', type: { name: 'Composite', className: 'OperationDisplay', modelProperties: { provider: { required: false, serializedName: 'provider', type: { name: 'String' } }, resource: { required: false, serializedName: 'resource', type: { name: 'String' } }, operation: { required: false, serializedName: 'operation', type: { name: 'String' } }, description: { required: false, serializedName: 'description', type: { name: 'String' } } } } }; } } module.exports = OperationDisplay;
xingwu1/azure-sdk-for-node
lib/services/machinelearningservicesManagement/lib/models/operationDisplay.js
JavaScript
apache-2.0
1,865
/** * 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. */ import {RTC_VENDORS} from './callout-vendors.js'; import {tryParseJson} from '../../../src/json'; import {dev, user} from '../../../src/log'; import {Services} from '../../../src/services'; import {isArray, isObject} from '../../../src/types'; import {isSecureUrl} from '../../../src/url'; import {getMode} from '../../../src/mode'; /** @type {string} */ const TAG = 'real-time-config'; /** @type {number} */ const MAX_RTC_CALLOUTS = 5; /** @enum {string} */ export const RTC_ERROR_ENUM = { // Occurs when response is unparseable as JSON MALFORMED_JSON_RESPONSE: 'malformed_json_response', // Occurs when a publisher has specified the same url // or vendor url (after macros are substituted) to call out to more than once. DUPLICATE_URL: 'duplicate_url', // Occurs when a URL fails isSecureUrl check. INSECURE_URL: 'insecure_url', // Occurs when 5 valid callout urls have already been built, and additional // urls are still specified. MAX_CALLOUTS_EXCEEDED: 'max_callouts_exceeded', // Occurs due to XHR failure. NETWORK_FAILURE: 'network_failure', // Occurs when a specified vendor does not exist in RTC_VENDORS. UNKNOWN_VENDOR: 'unknown_vendor', // Occurs when request took longer than timeout TIMEOUT: 'timeout', }; /** * @param {!Array<!Promise<!rtcResponseDef>>} promiseArray * @param {!string} error * @param {!string} callout * @private */ function logAndAddErrorResponse_(promiseArray, error, callout) { dev().warn(TAG, `Dropping RTC Callout to ${callout} due to ${error}`); promiseArray.push(buildErrorResponse_(error, callout)); } /** * @param {!string} error * @param {!string} callout * @param {number=} opt_rtcTime * @return {!Promise<!rtcResponseDef>} * @private */ function buildErrorResponse_(error, callout, opt_rtcTime) { return Promise.resolve(/**@type {rtcResponseDef} */( {error, callout, rtcTime: opt_rtcTime || 0})); } /** * For a given A4A Element, sends out Real Time Config requests to * any urls or vendors specified by the publisher. * @param {!AMP.BaseElement} a4aElement * @param {!Object<string, !../../../src/service/variable-source.SyncResolverDef>} customMacros The ad-network specified macro * substitutions available to use. * @return {Promise<!Array<!rtcResponseDef>>|undefined} * @visibleForTesting */ export function maybeExecuteRealTimeConfig_(a4aElement, customMacros) { const rtcConfig = validateRtcConfig_(a4aElement.element); if (!rtcConfig) { return; } const promiseArray = []; const seenUrls = {}; const rtcStartTime = Date.now(); // For each publisher defined URL, inflate the url using the macros, // and send the RTC request. (rtcConfig['urls'] || []).forEach(url => inflateAndSendRtc_(a4aElement, url, seenUrls, promiseArray, rtcStartTime, customMacros, rtcConfig['timeoutMillis']) ); // For each vendor the publisher has specified, inflate the vendor // url if it exists, and send the RTC request. Object.keys(rtcConfig['vendors'] || []).forEach(vendor => { const vendorObject = RTC_VENDORS[vendor.toLowerCase()]; const url = vendorObject ? vendorObject.url : ''; if (!url) { return logAndAddErrorResponse_(promiseArray, RTC_ERROR_ENUM.UNKNOWN_VENDOR, vendor); } const validVendorMacros = {}; Object.keys(rtcConfig['vendors'][vendor]).forEach(macro => { if (vendorObject.macros && vendorObject.macros.includes(macro)) { validVendorMacros[macro] = rtcConfig['vendors'][vendor][macro]; } else { user().warn(TAG, `Unknown macro: ${macro} for vendor: ${vendor}`); } }); // The ad network defined macros override vendor defined/pub specifed. const macros = Object.assign(validVendorMacros, customMacros); inflateAndSendRtc_(a4aElement, url, seenUrls, promiseArray, rtcStartTime, macros, rtcConfig['timeoutMillis'], vendor.toLowerCase()); }); return Promise.all(promiseArray); } /** * @param {!AMP.BaseElement} a4aElement * @param {!string} url * @param {!Object<string, boolean>} seenUrls * @param {!Array<!Promise<!rtcResponseDef>>} promiseArray * @param {!number} rtcStartTime * @param {!Object<string, !../../../src/service/variable-source.SyncResolverDef>} macros * @param {!number} timeoutMillis * @param {string=} opt_vendor * @private */ function inflateAndSendRtc_(a4aElement, url, seenUrls, promiseArray, rtcStartTime, macros, timeoutMillis, opt_vendor) { const win = a4aElement.win; const ampDoc = a4aElement.getAmpDoc(); if (Object.keys(seenUrls).length == MAX_RTC_CALLOUTS) { return logAndAddErrorResponse_( promiseArray, RTC_ERROR_ENUM.MAX_CALLOUTS_EXCEEDED, opt_vendor || url); } if (macros && Object.keys(macros).length) { const urlReplacements = Services.urlReplacementsForDoc(ampDoc); const whitelist = {}; Object.keys(macros).forEach(key => whitelist[key] = true); url = urlReplacements.expandUrlSync( url, macros, /** opt_collectVars */undefined, whitelist); } if (!isSecureUrl(url) && !(getMode(win).localDev || getMode(win).test)) { return logAndAddErrorResponse_(promiseArray, RTC_ERROR_ENUM.INSECURE_URL, opt_vendor || url); } if (seenUrls[url]) { return logAndAddErrorResponse_(promiseArray, RTC_ERROR_ENUM.DUPLICATE_URL, opt_vendor || url); } seenUrls[url] = true; promiseArray.push(sendRtcCallout_( url, rtcStartTime, win, timeoutMillis, opt_vendor || url)); } /** * @param {!string} url * @param {!number} rtcStartTime * @param {!Window} win * @param {!number} timeoutMillis * @param {!string} callout * @return {!Promise<!rtcResponseDef>} * @private */ function sendRtcCallout_( url, rtcStartTime, win, timeoutMillis, callout) { /** * Note: Timeout is enforced by timerFor, not the value of * rtcTime. There are situations where rtcTime could thus * end up being greater than timeoutMillis. */ return Services.timerFor(win).timeoutPromise( timeoutMillis, Services.xhrFor(win).fetchJson( // NOTE(bradfrizzell): we could include ampCors:false allowing // the request to be cached across sites but for now assume that // is not a required feature. url, {credentials: 'include'}).then(res => { return res.text().then(text => { const rtcTime = Date.now() - rtcStartTime; // An empty text response is allowed, not an error. if (!text) { return {rtcTime, callout}; } const response = tryParseJson(text); return response ? {response, rtcTime, callout} : buildErrorResponse_( RTC_ERROR_ENUM.MALFORMED_JSON_RESPONSE, callout, rtcTime); }); })).catch(error => { return buildErrorResponse_( // The relevant error message for timeout looks like it is // just 'message' but is in fact 'messageXXX' where the // X's are hidden special characters. That's why we use // match here. (error.message && error.message.match(/^timeout/)) ? RTC_ERROR_ENUM.TIMEOUT : RTC_ERROR_ENUM.NETWORK_FAILURE, callout, Date.now() - rtcStartTime); }); } /** * Attempts to parse the publisher-defined RTC config off the amp-ad * element, then validates that the rtcConfig exists, and contains * an entry for either vendor URLs, or publisher-defined URLs. If the * config contains an entry for timeoutMillis, validates that it is a * number, or converts to a number if number-like, otherwise overwrites * with the default. * IMPORTANT: If the rtcConfig is invalid, RTC is aborted, and the ad * request continues without RTC. * @param {!Element} element * @return {?Object} * @visibleForTesting */ export function validateRtcConfig_(element) { const defaultTimeoutMillis = 1000; const unparsedRtcConfig = element.getAttribute('rtc-config'); if (!unparsedRtcConfig) { return null; } const rtcConfig = tryParseJson(unparsedRtcConfig); if (!rtcConfig) { user().warn(TAG, 'Could not parse rtc-config attribute'); return null; } let timeout; try { user().assert(rtcConfig['vendors'] || rtcConfig['urls'], 'RTC Config must specify vendors or urls'); Object.keys(rtcConfig).forEach(key => { switch (key) { case 'vendors': user().assert(isObject(rtcConfig[key]), 'RTC invalid vendors'); break; case 'urls': user().assert(isArray(rtcConfig[key]), 'RTC invalid urls'); break; case 'timeoutMillis': timeout = parseInt(rtcConfig[key], 10); if (isNaN(timeout)) { user().warn(TAG, 'Invalid RTC timeout is NaN, ' + `using default timeout ${defaultTimeoutMillis}ms`); } else if (timeout >= defaultTimeoutMillis || timeout < 0) { timeout = undefined; user().warn(TAG, `Invalid RTC timeout: ${timeout}ms, ` + `using default timeout ${defaultTimeoutMillis}ms`); } break; default: user().warn(TAG, `Unknown RTC Config key: ${key}`); break; } }); if (!Object.keys(rtcConfig['vendors'] || {}).length && !(rtcConfig['urls'] || []).length) { return null; } } catch (unusedErr) { // This error would be due to the asserts above. return null; } rtcConfig['timeoutMillis'] = timeout !== undefined ? timeout : defaultTimeoutMillis; return rtcConfig; } AMP.maybeExecuteRealTimeConfig = maybeExecuteRealTimeConfig_;
gumgum/amphtml
extensions/amp-a4a/0.1/real-time-config-manager.js
JavaScript
apache-2.0
10,381
"use strict"; const color = require('kleur'); const Prompt = require('./prompt'); const _require = require('../util'), style = _require.style, clear = _require.clear; const _require2 = require('sisteransi'), cursor = _require2.cursor, erase = _require2.erase; /** * TogglePrompt Base Element * @param {Object} opts Options * @param {String} opts.message Message * @param {Boolean} [opts.initial=false] Default value * @param {String} [opts.active='no'] Active label * @param {String} [opts.inactive='off'] Inactive label * @param {Stream} [opts.stdin] The Readable stream to listen to * @param {Stream} [opts.stdout] The Writable stream to write readline data to */ class TogglePrompt extends Prompt { constructor(opts = {}) { super(opts); this.msg = opts.message; this.value = !!opts.initial; this.active = opts.active || 'on'; this.inactive = opts.inactive || 'off'; this.initialValue = this.value; this.render(); } reset() { this.value = this.initialValue; this.fire(); this.render(); } exit() { this.abort(); } abort() { this.done = this.aborted = true; this.fire(); this.render(); this.out.write('\n'); this.close(); } submit() { this.done = true; this.aborted = false; this.fire(); this.render(); this.out.write('\n'); this.close(); } deactivate() { if (this.value === false) return this.bell(); this.value = false; this.render(); } activate() { if (this.value === true) return this.bell(); this.value = true; this.render(); } delete() { this.deactivate(); } left() { this.deactivate(); } right() { this.activate(); } down() { this.deactivate(); } up() { this.activate(); } next() { this.value = !this.value; this.fire(); this.render(); } _(c, key) { if (c === ' ') { this.value = !this.value; } else if (c === '1') { this.value = true; } else if (c === '0') { this.value = false; } else return this.bell(); this.render(); } render() { if (this.closed) return; if (this.firstRender) this.out.write(cursor.hide);else this.out.write(clear(this.outputText, this.out.columns)); super.render(); this.outputText = [style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(this.done), this.value ? this.inactive : color.cyan().underline(this.inactive), color.gray('/'), this.value ? color.cyan().underline(this.active) : this.active].join(' '); this.out.write(erase.line + cursor.to(0) + this.outputText); } } module.exports = TogglePrompt;
GoogleCloudPlatform/prometheus-engine
third_party/prometheus_ui/base/web/ui/react-app/node_modules/prompts/dist/elements/toggle.js
JavaScript
apache-2.0
2,677
/** * @ngdoc directive * @name gustav.account.directive:accountBox * @restrict EA * @element ANY * @scope * @description * Displays information about an account. */ angular.module('gustav.account').directive('accountBox', function (Account) { return { templateUrl: 'plugins/account/partials/account.html', restrict: 'EA', scope: { account: '=' }, link: function (scope) { //append only to current accounts if (Account.currentAccounts.filter(function (a) { return a.accountno.iban === scope.account.accountno.iban }).length > 0) { scope.showPlugins = true; } } }; }); /** * @ngdoc directive * @name gustav.account.directive:showPlugins * @restrict EA * @element ANY * @scope * @description * Shows all account context plugins. */ angular.module('gustav.account').directive('accountContext', function ($compile, AccountContext) { return { template: '', restrict: 'EA', scope: { account: '=' }, link: function (scope, element) { var directives = AccountContext.get(); angular.forEach(directives, function (directive) { element.append(directive); }); $compile(element.contents())(scope); } }; }); /** * @ngdoc directive * @name gustav.account.directive:accountIcon * @restrict EA * @element ANY * @scope * @description * Assign account icon class based on account flags */ angular.module('gustav.account').directive('accountIcon', function () { return { template: '', restrict: 'EA', scope: { account: '=accountIcon' }, link: function (scope, element) { var account = scope.account; if (account.flags.indexOf('cardAccount') !== -1) { element.addClass('glyphicon-credit-card'); } else if (account.flags.indexOf('savingsAccount') !== -1) { element.addClass('glyphicon-euro'); } else if (account.flags.indexOf('loanAccount') !== -1) { element.addClass('glyphicon-gift'); } else { element.addClass('glyphicon-user'); } } }; });
amirmamaghani/Gustav
app/plugins/account/scripts/accountDirectives.js
JavaScript
bsd-3-clause
2,332
// Copyright 2022 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. /** @enum {number} */ const SchemeType = { NORMAL: 0, INCREASED_CONTRAST: 1, GRAYSCALE: 2, INVERTED_COLOR: 3, INVERTED_GRAYSCALE: 4, YELLOW_ON_BLACK: 5, }; /** * Class to handle interactions with the chrome.storage API and values that are * stored there. */ class Storage { /** * @param {function()=} opt_callbackForTesting * @private */ constructor(opt_callbackForTesting) { /** @private {boolean} */ this.enabled_ = Storage.ENABLED.defaultValue; /** @private {!SchemeType} */ this.baseScheme_ = Storage.SCHEME.defaultValue; /** @private {!Object<string, !SchemeType>} */ this.siteSchemes_ = Storage.SITE_SCHEMES.defaultValue; this.init_(); } // ======= Public Methods ======= static initialize() { if (!Storage.instance) { Storage.instance = new Storage(); } } /** @return {boolean} */ static get enabled() { return Storage.instance.enabled_; } /** @return {!SchemeType} */ static get baseScheme() { return Storage.instance.baseScheme_; } /** * @param {string} site * @return {!SchemeType} */ static getSiteScheme(site) { const scheme = Storage.instance.siteSchemes_[site]; if (Storage.SCHEME.validate(scheme)) { return scheme; } return Storage.baseScheme; } /** @param {boolean} newValue */ static set enabled(newValue) { Storage.instance.setOrResetValue_(Storage.ENABLED, newValue); Storage.instance.store_(Storage.ENABLED); } /** @param {!SchemeType} newScheme */ static set baseScheme(newScheme) { Storage.instance.setOrResetValue_(Storage.SCHEME, newScheme); Storage.instance.store_(Storage.SCHEME); } /** * @param {string} site * @param {!SchemeType} scheme */ static setSiteScheme(site, scheme) { if (Storage.SCHEME.validate(scheme)) { Storage.instance.siteSchemes_[site] = scheme; } else { Storage.instance.siteSchemes_[site] = Storage.baseScheme; } Storage.instance.store_(Storage.SITE_SCHEMES); } static resetSiteSchemes() { Storage.instance.siteSchemes_ = Storage.SITE_SCHEMES.defaultValue; Storage.instance.store_(Storage.SITE_SCHEMES); } // ======= Private Methods ======= /** * @param {!Storage.Value} container * @param {*} newValue * @private */ setOrResetValue_(container, newValue) { if (newValue === container.get()) { return; } if (container.validate(newValue)) { container.set(newValue); } else { container.reset(); } container.listeners.forEach(listener => listener(newValue)); } /** * @param {function()=} opt_callback * @private */ init_(opt_callback) { chrome.storage.onChanged.addListener(this.onChange_); chrome.storage.local.get(null /* all values */, (results) => { const storedData = Storage.ALL_VALUES.filter(v => results[v.key]); for (const data of storedData) { this.setOrResetValue_(data, results[data.key]); } opt_callback ? opt_callback() : undefined; }); } /** * @param {!Object<string, chrome.storage.StorageChange>} changes * @private */ onChange_(changes) { const changedData = Storage.ALL_VALUES.filter(v => changes[v.key]); for (const data of changedData) { Storage.instance.setOrResetValue_(data, changes[data.key].newValue); } } /** * @param {!Storage.Value} value * @private */ store_(value) { chrome.storage.local.set({ [value.key]: value.get() }); } // ======= Stored Values ======= /** * @typedef {{ * key: string, * defaultValue: *, * validate: function(*): boolean, * get: function: *, * set: function(*), * reset: function(), * listeners: !Array<function(*)> * }} */ static Value; /** @const {!Storage.Value} */ static ENABLED = { key: 'enabled', defaultValue: true, validate: (enabled) => enabled === true || enabled === false, get: () => Storage.instance.enabled_, set: (enabled) => Storage.instance.enabled_ = enabled, reset: () => Storage.instance.enabled_ = Storage.ENABLED.defaultValue, listeners: [], }; /** @const {!Storage.Value} */ static SCHEME = { key: 'scheme', defaultValue: SchemeType.INVERTED_COLOR, validate: (scheme) => Object.values(SchemeType).includes(scheme), get: () => Storage.instance.baseScheme_, set: (scheme) => Storage.instance.baseScheme_ = scheme, reset: () => Storage.instance.baseScheme_ = Storage.SCHEME.defaultValue, listeners: [], }; /** @const {!Storage.Value} */ static SITE_SCHEMES = { key: 'siteschemes', defaultValue: {}, validate: (siteSchemes) => typeof (siteSchemes) === 'object', get: () => Storage.instance.siteSchemes_, set: (siteSchemes) => { for (const site of Object.keys(siteSchemes)) { if (Storage.SCHEME.validate(siteSchemes[site])) { Storage.instance.siteSchemes_[site] = siteSchemes[site]; } } }, reset: () => {} /** Do nothing */, listeners: [], }; /** @const {!Array<!Storage.Value>} */ static ALL_VALUES = [ Storage.ENABLED, Storage.SCHEME, Storage.SITE_SCHEMES ]; }
chromium/chromium
ui/accessibility/extensions/highcontrast/storage.js
JavaScript
bsd-3-clause
5,366
var request = require('supertest'); var app = require(__dirname+'/../../lib/app.js'); var gateway = require(__dirname+'/../../'); describe('delete currency', function(){ it('should return unauthorized without credentials', function(done){ request(app) .delete('/v1/currencies/usd') .expect(401) .end(function(err){ if (err) throw err; done(); }); }); it('should return successfully with credentials', function(done){ request(app) .delete('/v1/currencies/usd') .auth('admin@'+gateway.config.get('DOMAIN'), gateway.config.get('KEY')) .expect(200) .end(function(err){ if (err) throw err; done(); }); }); });
zealord/gatewayd
test/http/remove_currency.js
JavaScript
isc
712
/** * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/> * Build: `lodash modularize modern exports="amd" -o ./modern/` * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE> * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <http://lodash.com/license> */ define(['../internals/baseCreateCallback', '../objects/forOwn', '../objects/isArray', '../objects/isString', '../objects/keys'], function(baseCreateCallback, forOwn, isArray, isString, keys) { /** * This method is like `_.forEach` except that it iterates over elements * of a `collection` from right to left. * * @static * @memberOf _ * @alias eachRight * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function} [callback=identity] The function called per iteration. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Array|Object|string} Returns `collection`. * @example * * _([1, 2, 3]).forEachRight(function(num) { console.log(num); }).join(','); * // => logs each number from right to left and returns '3,2,1' */ function forEachRight(collection, callback, thisArg) { var length = collection ? collection.length : 0; callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3); if (typeof length == 'number') { while (length--) { if (callback(collection[length], length, collection) === false) { break; } } } else { var props = keys(collection); length = props.length; forOwn(collection, function(value, key, collection) { key = props ? props[--length] : --length; return callback(collection[key], key, collection); }); } return collection; } return forEachRight; });
john-bixly/Morsel
app/vendor/lodash-amd/modern/collections/forEachRight.js
JavaScript
mit
1,971
define({ "_widgetLabel": "共有", "selectSocialNetwork": "次のオプションを選択してアプリを共有します:", "email": "電子メール", "facebook": "Facebook", "googlePlus": "Google+", "twitter": "Twitter", "addNew": "新規追加", "socialMediaUrl": "ソーシャル メディアの URL", "uploadIcon": "アイコンのアップロード", "embedAppInWebsite": "Web サイトにアプリを埋め込む" });
cmccullough2/cmv-wab-widgets
wab/2.3/widgets/Share/nls/ja/strings.js
JavaScript
mit
446
import Vue from "vue"; import App from "./App.vue"; Vue.config.productionTip = false; new Vue({ render: h => h(App) }).$mount("#app");
rodet/styleguide
src/main.js
JavaScript
mit
139
// CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function() { var mode = CodeMirror.getMode({indentUnit: 2}, "javascript"); function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); } MT("locals", "[keyword function] [def foo]([def a], [def b]) { [keyword var] [def c] [operator =] [number 10]; [keyword return] [variable-2 a] [operator +] [variable-2 c] [operator +] [variable d]; }"); MT("comma-and-binop", "[keyword function](){ [keyword var] [def x] [operator =] [number 1] [operator +] [number 2], [def y]; }"); MT("destructuring", "([keyword function]([def a], [[[def b], [def c] ]]) {", " [keyword let] {[def d], [property foo]: [def c][operator =][number 10], [def x]} [operator =] [variable foo]([variable-2 a]);", " [[[variable-2 c], [variable y] ]] [operator =] [variable-2 c];", "})();"); MT("destructure_trailing_comma", "[keyword let] {[def a], [def b],} [operator =] [variable foo];", "[keyword let] [def c];"); // Parser still in good state? MT("class_body", "[keyword class] [def Foo] {", " [property constructor]() {}", " [property sayName]() {", " [keyword return] [string-2 `foo${][variable foo][string-2 }oo`];", " }", "}"); MT("class", "[keyword class] [def Point] [keyword extends] [variable SuperThing] {", " [keyword get] [property prop]() { [keyword return] [number 24]; }", " [property constructor]([def x], [def y]) {", " [keyword super]([string 'something']);", " [keyword this].[property x] [operator =] [variable-2 x];", " }", "}"); MT("anonymous_class_expression", "[keyword const] [def Adder] [operator =] [keyword class] [keyword extends] [variable Arithmetic] {", " [property add]([def a], [def b]) {}", "};"); MT("named_class_expression", "[keyword const] [def Subber] [operator =] [keyword class] [def Subtract] {", " [property sub]([def a], [def b]) {}", "};"); MT("class_async_method", "[keyword class] [def Foo] {", " [property sayName1]() {}", " [keyword async] [property sayName2]() {}", "}"); MT("import", "[keyword function] [def foo]() {", " [keyword import] [def $] [keyword from] [string 'jquery'];", " [keyword import] { [def encrypt], [def decrypt] } [keyword from] [string 'crypto'];", "}"); MT("import_trailing_comma", "[keyword import] {[def foo], [def bar],} [keyword from] [string 'baz']") MT("import_dynamic", "[keyword import]([string 'baz']).[property then]") MT("import_dynamic", "[keyword const] [def t] [operator =] [keyword import]([string 'baz']).[property then]") MT("const", "[keyword function] [def f]() {", " [keyword const] [[ [def a], [def b] ]] [operator =] [[ [number 1], [number 2] ]];", "}"); MT("for/of", "[keyword for]([keyword let] [def of] [keyword of] [variable something]) {}"); MT("for await", "[keyword for] [keyword await]([keyword let] [def of] [keyword of] [variable something]) {}"); MT("generator", "[keyword function*] [def repeat]([def n]) {", " [keyword for]([keyword var] [def i] [operator =] [number 0]; [variable-2 i] [operator <] [variable-2 n]; [operator ++][variable-2 i])", " [keyword yield] [variable-2 i];", "}"); MT("let_scoping", "[keyword function] [def scoped]([def n]) {", " { [keyword var] [def i]; } [variable-2 i];", " { [keyword let] [def j]; [variable-2 j]; } [variable j];", " [keyword if] ([atom true]) { [keyword const] [def k]; [variable-2 k]; } [variable k];", "}"); MT("switch_scoping", "[keyword switch] ([variable x]) {", " [keyword default]:", " [keyword let] [def j];", " [keyword return] [variable-2 j]", "}", "[variable j];") MT("leaving_scope", "[keyword function] [def a]() {", " {", " [keyword const] [def x] [operator =] [number 1]", " [keyword if] ([atom true]) {", " [keyword let] [def y] [operator =] [number 2]", " [keyword var] [def z] [operator =] [number 3]", " [variable console].[property log]([variable-2 x], [variable-2 y], [variable-2 z])", " }", " [variable console].[property log]([variable-2 x], [variable y], [variable-2 z])", " }", " [variable console].[property log]([variable x], [variable y], [variable-2 z])", "}") MT("quotedStringAddition", "[keyword let] [def f] [operator =] [variable a] [operator +] [string 'fatarrow'] [operator +] [variable c];"); MT("quotedFatArrow", "[keyword let] [def f] [operator =] [variable a] [operator +] [string '=>'] [operator +] [variable c];"); MT("fatArrow", "[variable array].[property filter]([def a] [operator =>] [variable-2 a] [operator +] [number 1]);", "[variable a];", // No longer in scope "[keyword let] [def f] [operator =] ([[ [def a], [def b] ]], [def c]) [operator =>] [variable-2 a] [operator +] [variable-2 c];", "[variable c];"); MT("spread", "[keyword function] [def f]([def a], [meta ...][def b]) {", " [variable something]([variable-2 a], [meta ...][variable-2 b]);", "}"); MT("quasi", "[variable re][string-2 `fofdlakj${][variable x] [operator +] ([variable re][string-2 `foo`]) [operator +] [number 1][string-2 }fdsa`] [operator +] [number 2]"); MT("quasi_no_function", "[variable x] [operator =] [string-2 `fofdlakj${][variable x] [operator +] [string-2 `foo`] [operator +] [number 1][string-2 }fdsa`] [operator +] [number 2]"); MT("indent_statement", "[keyword var] [def x] [operator =] [number 10]", "[variable x] [operator +=] [variable y] [operator +]", " [atom Infinity]", "[keyword debugger];"); MT("indent_if", "[keyword if] ([number 1])", " [keyword break];", "[keyword else] [keyword if] ([number 2])", " [keyword continue];", "[keyword else]", " [number 10];", "[keyword if] ([number 1]) {", " [keyword break];", "} [keyword else] [keyword if] ([number 2]) {", " [keyword continue];", "} [keyword else] {", " [number 10];", "}"); MT("indent_for", "[keyword for] ([keyword var] [def i] [operator =] [number 0];", " [variable i] [operator <] [number 100];", " [variable i][operator ++])", " [variable doSomething]([variable i]);", "[keyword debugger];"); MT("indent_c_style", "[keyword function] [def foo]()", "{", " [keyword debugger];", "}"); MT("indent_else", "[keyword for] (;;)", " [keyword if] ([variable foo])", " [keyword if] ([variable bar])", " [number 1];", " [keyword else]", " [number 2];", " [keyword else]", " [number 3];"); MT("indent_funarg", "[variable foo]([number 10000],", " [keyword function]([def a]) {", " [keyword debugger];", "};"); MT("indent_below_if", "[keyword for] (;;)", " [keyword if] ([variable foo])", " [number 1];", "[number 2];"); MT("indent_semicolonless_if", "[keyword function] [def foo]() {", " [keyword if] ([variable x])", " [variable foo]()", "}") MT("indent_semicolonless_if_with_statement", "[keyword function] [def foo]() {", " [keyword if] ([variable x])", " [variable foo]()", " [variable bar]()", "}") MT("multilinestring", "[keyword var] [def x] [operator =] [string 'foo\\]", "[string bar'];"); MT("scary_regexp", "[string-2 /foo[[/]]bar/];"); MT("indent_strange_array", "[keyword var] [def x] [operator =] [[", " [number 1],,", " [number 2],", "]];", "[number 10];"); MT("param_default", "[keyword function] [def foo]([def x] [operator =] [string-2 `foo${][number 10][string-2 }bar`]) {", " [keyword return] [variable-2 x];", "}"); MT( "param_destructuring", "[keyword function] [def foo]([def x] [operator =] [string-2 `foo${][number 10][string-2 }bar`]) {", " [keyword return] [variable-2 x];", "}"); MT("new_target", "[keyword function] [def F]([def target]) {", " [keyword if] ([variable-2 target] [operator &&] [keyword new].[keyword target].[property name]) {", " [keyword return] [keyword new]", " .[keyword target];", " }", "}"); MT("async", "[keyword async] [keyword function] [def foo]([def args]) { [keyword return] [atom true]; }"); MT("async_assignment", "[keyword const] [def foo] [operator =] [keyword async] [keyword function] ([def args]) { [keyword return] [atom true]; };"); MT("async_object", "[keyword let] [def obj] [operator =] { [property async]: [atom false] };"); // async be highlighet as keyword and foo as def, but it requires potentially expensive look-ahead. See #4173 MT("async_object_function", "[keyword let] [def obj] [operator =] { [property async] [property foo]([def args]) { [keyword return] [atom true]; } };"); MT("async_object_properties", "[keyword let] [def obj] [operator =] {", " [property prop1]: [keyword async] [keyword function] ([def args]) { [keyword return] [atom true]; },", " [property prop2]: [keyword async] [keyword function] ([def args]) { [keyword return] [atom true]; },", " [property prop3]: [keyword async] [keyword function] [def prop3]([def args]) { [keyword return] [atom true]; },", "};"); MT("async_arrow", "[keyword const] [def foo] [operator =] [keyword async] ([def args]) [operator =>] { [keyword return] [atom true]; };"); MT("async_jquery", "[variable $].[property ajax]({", " [property url]: [variable url],", " [property async]: [atom true],", " [property method]: [string 'GET']", "});"); MT("async_variable", "[keyword const] [def async] [operator =] {[property a]: [number 1]};", "[keyword const] [def foo] [operator =] [string-2 `bar ${][variable async].[property a][string-2 }`];") MT("bigint", "[number 1n] [operator +] [number 0x1afn] [operator +] [number 0o064n] [operator +] [number 0b100n];") MT("async_comment", "[keyword async] [comment /**/] [keyword function] [def foo]([def args]) { [keyword return] [atom true]; }"); MT("indent_switch", "[keyword switch] ([variable x]) {", " [keyword default]:", " [keyword return] [number 2]", "}") MT("regexp_corner_case", "[operator +]{} [operator /] [atom undefined];", "[[[meta ...][string-2 /\\//] ]];", "[keyword void] [string-2 /\\//];", "[keyword do] [string-2 /\\//]; [keyword while] ([number 0]);", "[keyword if] ([number 0]) {} [keyword else] [string-2 /\\//];", "[string-2 `${][variable async][operator ++][string-2 }//`];", "[string-2 `${]{} [operator /] [string-2 /\\//}`];") MT("return_eol", "[keyword return]", "{} [string-2 /5/]") var ts_mode = CodeMirror.getMode({indentUnit: 2}, "application/typescript") function TS(name) { test.mode(name, ts_mode, Array.prototype.slice.call(arguments, 1)) } TS("typescript_extend_type", "[keyword class] [def Foo] [keyword extends] [type Some][operator <][type Type][operator >] {}") TS("typescript_arrow_type", "[keyword let] [def x]: ([variable arg]: [type Type]) [operator =>] [type ReturnType]") TS("typescript_class", "[keyword class] [def Foo] {", " [keyword public] [keyword static] [property main]() {}", " [keyword private] [property _foo]: [type string];", "}") TS("typescript_literal_types", "[keyword import] [keyword *] [keyword as] [def Sequelize] [keyword from] [string 'sequelize'];", "[keyword interface] [def MyAttributes] {", " [property truthy]: [string 'true'] [operator |] [number 1] [operator |] [atom true];", " [property falsy]: [string 'false'] [operator |] [number 0] [operator |] [atom false];", "}", "[keyword interface] [def MyInstance] [keyword extends] [type Sequelize].[type Instance] [operator <] [type MyAttributes] [operator >] {", " [property rawAttributes]: [type MyAttributes];", " [property truthy]: [string 'true'] [operator |] [number 1] [operator |] [atom true];", " [property falsy]: [string 'false'] [operator |] [number 0] [operator |] [atom false];", "}") TS("typescript_extend_operators", "[keyword export] [keyword interface] [def UserModel] [keyword extends]", " [type Sequelize].[type Model] [operator <] [type UserInstance], [type UserAttributes] [operator >] {", " [property findById]: (", " [variable userId]: [type number]", " ) [operator =>] [type Promise] [operator <] [type Array] [operator <] { [property id], [property name] } [operator >>];", " [property updateById]: (", " [variable userId]: [type number],", " [variable isActive]: [type boolean]", " ) [operator =>] [type Promise] [operator <] [type AccountHolderNotificationPreferenceInstance] [operator >];", " }") TS("typescript_interface_with_const", "[keyword const] [def hello]: {", " [property prop1][operator ?]: [type string];", " [property prop2][operator ?]: [type string];", "} [operator =] {};") TS("typescript_double_extend", "[keyword export] [keyword interface] [def UserAttributes] {", " [property id][operator ?]: [type number];", " [property createdAt][operator ?]: [type Date];", "}", "[keyword export] [keyword interface] [def UserInstance] [keyword extends] [type Sequelize].[type Instance][operator <][type UserAttributes][operator >], [type UserAttributes] {", " [property id]: [type number];", " [property createdAt]: [type Date];", "}"); TS("typescript_index_signature", "[keyword interface] [def A] {", " [[ [variable prop]: [type string] ]]: [type any];", " [property prop1]: [type any];", "}"); TS("typescript_generic_class", "[keyword class] [def Foo][operator <][type T][operator >] {", " [property bar]() {}", " [property foo](): [type Foo] {}", "}") TS("typescript_type_when_keyword", "[keyword export] [keyword type] [type AB] [operator =] [type A] [operator |] [type B];", "[keyword type] [type Flags] [operator =] {", " [property p1]: [type string];", " [property p2]: [type boolean];", "};") TS("typescript_type_when_not_keyword", "[keyword class] [def HasType] {", " [property type]: [type string];", " [property constructor]([def type]: [type string]) {", " [keyword this].[property type] [operator =] [variable-2 type];", " }", " [property setType]({ [def type] }: { [property type]: [type string]; }) {", " [keyword this].[property type] [operator =] [variable-2 type];", " }", "}") TS("typescript_function_generics", "[keyword function] [def a]() {}", "[keyword function] [def b][operator <][type IA] [keyword extends] [type object], [type IB] [keyword extends] [type object][operator >]() {}", "[keyword function] [def c]() {}") TS("typescript_complex_return_type", "[keyword function] [def A]() {", " [keyword return] [keyword this].[property property];", "}", "[keyword function] [def B](): [type Promise][operator <]{ [[ [variable key]: [type string] ]]: [type any] } [operator |] [atom null][operator >] {", " [keyword return] [keyword this].[property property];", "}") TS("typescript_complex_type_casting", "[keyword const] [def giftpay] [operator =] [variable config].[property get]([string 'giftpay']) [keyword as] { [[ [variable platformUuid]: [type string] ]]: { [property version]: [type number]; [property apiCode]: [type string]; } };") TS("typescript_keyof", "[keyword function] [def x][operator <][type T] [keyword extends] [keyword keyof] [type X][operator >]([def a]: [type T]) {", " [keyword return]") TS("typescript_new_typeargs", "[keyword let] [def x] [operator =] [keyword new] [variable Map][operator <][type string], [type Date][operator >]([string-2 `foo${][variable bar][string-2 }`])") TS("modifiers", "[keyword class] [def Foo] {", " [keyword public] [keyword abstract] [property bar]() {}", " [property constructor]([keyword readonly] [keyword private] [def x]) {}", "}") TS("arrow prop", "({[property a]: [def p] [operator =>] [variable-2 p]})") TS("generic in function call", "[keyword this].[property a][operator <][type Type][operator >]([variable foo]);", "[keyword this].[property a][operator <][variable Type][operator >][variable foo];") TS("type guard", "[keyword class] [def Appler] {", " [keyword static] [property assertApple]([def fruit]: [type Fruit]): [variable-2 fruit] [keyword is] [type Apple] {", " [keyword if] ([operator !]([variable-2 fruit] [keyword instanceof] [variable Apple]))", " [keyword throw] [keyword new] [variable Error]();", " }", "}") TS("type as variable", "[variable type] [operator =] [variable x] [keyword as] [type Bar];"); TS("enum body", "[keyword export] [keyword const] [keyword enum] [def CodeInspectionResultType] {", " [def ERROR] [operator =] [string 'problem_type_error'],", " [def WARNING] [operator =] [string 'problem_type_warning'],", " [def META],", "}") TS("parenthesized type", "[keyword class] [def Foo] {", " [property x] [operator =] [keyword new] [variable A][operator <][type B], [type string][operator |](() [operator =>] [type void])[operator >]();", " [keyword private] [property bar]();", "}") TS("abstract class", "[keyword export] [keyword abstract] [keyword class] [def Foo] {}") var jsonld_mode = CodeMirror.getMode( {indentUnit: 2}, {name: "javascript", jsonld: true} ); function LD(name) { test.mode(name, jsonld_mode, Array.prototype.slice.call(arguments, 1)); } LD("json_ld_keywords", '{', ' [meta "@context"]: {', ' [meta "@base"]: [string "http://example.com"],', ' [meta "@vocab"]: [string "http://xmlns.com/foaf/0.1/"],', ' [property "likesFlavor"]: {', ' [meta "@container"]: [meta "@list"]', ' [meta "@reverse"]: [string "@beFavoriteOf"]', ' },', ' [property "nick"]: { [meta "@container"]: [meta "@set"] },', ' [property "nick"]: { [meta "@container"]: [meta "@index"] }', ' },', ' [meta "@graph"]: [[ {', ' [meta "@id"]: [string "http://dbpedia.org/resource/John_Lennon"],', ' [property "name"]: [string "John Lennon"],', ' [property "modified"]: {', ' [meta "@value"]: [string "2010-05-29T14:17:39+02:00"],', ' [meta "@type"]: [string "http://www.w3.org/2001/XMLSchema#dateTime"]', ' }', ' } ]]', '}'); LD("json_ld_fake", '{', ' [property "@fake"]: [string "@fake"],', ' [property "@contextual"]: [string "@identifier"],', ' [property "user@domain.com"]: [string "@graphical"],', ' [property "@ID"]: [string "@@ID"]', '}'); })();
gsage/engine
resources/editor/webviews/codemirror/mode/javascript/test.js
JavaScript
mit
19,313
module.exports=['\u2C00','\u2C01','\u2C02','\u2C03','\u2C04','\u2C05','\u2C06','\u2C07','\u2C08','\u2C09','\u2C0A','\u2C0B','\u2C0C','\u2C0D','\u2C0E','\u2C0F','\u2C10','\u2C11','\u2C12','\u2C13','\u2C14','\u2C15','\u2C16','\u2C17','\u2C18','\u2C19','\u2C1A','\u2C1B','\u2C1C','\u2C1D','\u2C1E','\u2C1F','\u2C20','\u2C21','\u2C22','\u2C23','\u2C24','\u2C25','\u2C26','\u2C27','\u2C28','\u2C29','\u2C2A','\u2C2B','\u2C2C','\u2C2D','\u2C2E','\u2C2F','\u2C30','\u2C31','\u2C32','\u2C33','\u2C34','\u2C35','\u2C36','\u2C37','\u2C38','\u2C39','\u2C3A','\u2C3B','\u2C3C','\u2C3D','\u2C3E','\u2C3F','\u2C40','\u2C41','\u2C42','\u2C43','\u2C44','\u2C45','\u2C46','\u2C47','\u2C48','\u2C49','\u2C4A','\u2C4B','\u2C4C','\u2C4D','\u2C4E','\u2C4F','\u2C50','\u2C51','\u2C52','\u2C53','\u2C54','\u2C55','\u2C56','\u2C57','\u2C58','\u2C59','\u2C5A','\u2C5B','\u2C5C','\u2C5D','\u2C5E','\u2C5F']
marclundgren/mithril-fidm-app
node_modules/gulp-jscs/node_modules/jscs/node_modules/unicode-6.3.0/blocks/Glagolitic/symbols.js
JavaScript
mit
880
'use strict'; var AlgoliaSearchCore = require('../../AlgoliaSearchCore.js'); var createAlgoliasearch = require('../createAlgoliasearch.js'); module.exports = createAlgoliasearch(AlgoliaSearchCore, '(lite) ');
shadow000902/blog_source
node_modules/hexo-algoliasearch/node_modules/algoliasearch/src/browser/builds/algoliasearchLite.js
JavaScript
mit
211
var Promise = require('bluebird'), config = require('../config'), crypto = require('crypto'), https = require('https'); module.exports.lookup = function lookup(userData, timeout) { var gravatarUrl = '//www.gravatar.com/avatar/' + crypto.createHash('md5').update(userData.email.toLowerCase().trim()).digest('hex') + '?s=250', image; return new Promise(function gravatarRequest(resolve) { /** * @TODO: * - mock gravatar in test env globally, do not check for test env! * - in test/utils/index.js -> mocks.gravatar.enable(); */ if (config.isPrivacyDisabled('useGravatar') || config.get('env').indexOf('testing') > -1) { return resolve(); } var request, timer, timerEnded = false; request = https.get('https:' + gravatarUrl + '&d=404&r=x', function (response) { clearTimeout(timer); if (response.statusCode !== 404 && !timerEnded) { gravatarUrl += '&d=mm&r=x'; image = gravatarUrl; } resolve({image: image}); }); request.on('error', function () { clearTimeout(timer); // just resolve with no image url if (!timerEnded) { return resolve(); } }); timer = setTimeout(function () { timerEnded = true; request.abort(); return resolve(); }, timeout || 2000); }); };
disordinary/Ghost
core/server/utils/gravatar.js
JavaScript
mit
1,515
var activeRequests = 0; $(function() { $('#change').text('I changed it'); $('#drag').draggable(); $('#drop').droppable({ drop: function(event, ui) { ui.draggable.remove(); $(this).html('Dropped!'); } }); $('#clickable').click(function() { var link = $(this); setTimeout(function() { $(link).after('<a id="has-been-clicked" href="#">Has been clicked</a>'); $(link).after('<input type="submit" value="New Here">'); $(link).after('<input type="text" id="new_field">'); $('#change').remove(); }, 500); return false; }); $('#slow-click').click(function() { var link = $(this); setTimeout(function() { $(link).after('<a id="slow-clicked" href="#">Slow link clicked</a>'); }, 4000); return false; }); $('#waiter').change(function() { activeRequests = 1; setTimeout(function() { activeRequests = 0; }, 500); }); $('#with_focus_event').focus(function() { $('body').append('<p id="focus_event_triggered">Focus Event triggered</p>'); }); $('#with_change_event').change(function() { $('body').append($('<p class="change_event_triggered"></p>').text(this.value)); }); $('#checkbox_with_event').click(function() { $('body').append('<p id="checkbox_event_triggered">Checkbox event triggered</p>'); }); $('#fire_ajax_request').click(function() { $.ajax({url: "/slow_response", context: document.body, success: function() { $('body').append('<p id="ajax_request_done">Ajax request done</p>'); }}); }); $('#reload-link').click(function() { setTimeout(function() { $('#reload-me').replaceWith('<div id="reload-me"><em><a>has been reloaded</a></em></div>'); }, 250) }); $('#reload-list').click(function() { setTimeout(function() { $('#the-list').html('<li>Foo</li><li>Bar</li>'); }, 550) }); $('#change-title').click(function() { setTimeout(function() { $('title').text('changed title') }, 250) }); $('#click-test').on({ dblclick: function() { $(this).after('<a id="has-been-double-clicked" href="#">Has been double clicked</a>'); }, contextmenu: function(e) { e.preventDefault(); $(this).after('<a id="has-been-right-clicked" href="#">Has been right clicked</a>'); } }); $('#open-alert').click(function() { alert('Alert opened'); $(this).attr('opened', 'true'); }); $('#open-delayed-alert').click(function() { var link = this; setTimeout(function() { alert('Delayed alert opened'); $(link).attr('opened', 'true'); }, 250); }); $('#open-slow-alert').click(function() { var link = this; setTimeout(function() { alert('Delayed alert opened'); $(link).attr('opened', 'true'); }, 3000); }); $('#open-confirm').click(function() { if(confirm('Confirm opened')) { $(this).attr('confirmed', 'true'); } else { $(this).attr('confirmed', 'false'); } }); $('#open-prompt').click(function() { var response = prompt('Prompt opened'); if(response === null) { $(this).attr('response', 'dismissed'); } else { $(this).attr('response', response); } }); $('#open-twice').click(function() { if (confirm('Are you sure?')) { if (!confirm('Are you really sure?')) { $(this).attr('confirmed', 'false'); } } }) $('#delayed-page-change').click(function() { setTimeout(function() { window.location.pathname = '/with_html' }, 500) }) $('#with-key-events').keydown(function(e){ $('#key-events-output').append('keydown:'+e.which+' ') }); $('#disable-on-click').click(function(e){ var input = this setTimeout(function() { input.disabled = true; }, 500) }) });
ducktyper/bfnz
vendor/cache/ruby/2.3.0/gems/capybara-2.8.1/lib/capybara/spec/public/test.js
JavaScript
mit
3,770
import { Range } from 'immutable'; export const ADD_HUNDRED_TODOS = 'ADD_HUNDRED_TODOS'; export const ADD_TODO = 'ADD_TODO'; export const CLEAR_ALL_COMPLETED_TODOS = 'CLEAR_ALL_COMPLETED_TODOS'; export const CLEAR_ALL_TODOS = 'CLEAR_ALL_TODOS'; export const DELETE_TODO = 'DELETE_TODO'; export const TOGGLE_TODO_COMPLETED = 'TOGGLE_TODO_COMPLETED'; export function addHundredTodos() { // Note how dependency injection ensures pure action. return ({ getUid, now }) => { const payload = Range(0, 100).map(() => { const id = getUid(); return { createdAt: now(), id, title: `Item #${id}` }; }).toJS(); return { type: ADD_HUNDRED_TODOS, payload }; }; } export function addTodo(title) { return ({ getUid, now }) => ({ type: ADD_TODO, payload: { createdAt: now(), id: getUid(), title: title.trim() } }); } export function clearAllCompletedTodos() { return { type: CLEAR_ALL_COMPLETED_TODOS }; } export function clearAllTodos() { return { type: CLEAR_ALL_TODOS }; } export function deleteTodo(id) { return { type: DELETE_TODO, payload: { id } }; } export function toggleTodoCompleted(todo) { return { type: TOGGLE_TODO_COMPLETED, payload: { todo } }; }
SidhNor/este-cordova-starter-kit
src/common/todos/actions.js
JavaScript
mit
1,302
import _extends from "@babel/runtime/helpers/extends"; import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties"; var _excluded = ["photos", "visibleCount", "size", "layout", "children"]; import { createScopedElement } from "../../lib/jsxRuntime"; import * as React from "react"; import { getClassName } from "../../helpers/getClassName"; import { usePlatform } from "../../hooks/usePlatform"; import { hasReactNode } from "../../lib/utils"; import { classNames } from "../../lib/classNames"; import { useIsomorphicLayoutEffect } from "../../lib/useIsomorphicLayoutEffect"; import Caption from "../Typography/Caption/Caption"; import Subhead from "../Typography/Subhead/Subhead"; import { createMasks } from "./masks"; import { useDOM } from "../../lib/dom"; var UsersStack = function UsersStack(props) { var platform = usePlatform(); var _props$photos = props.photos, photos = _props$photos === void 0 ? [] : _props$photos, _props$visibleCount = props.visibleCount, visibleCount = _props$visibleCount === void 0 ? 0 : _props$visibleCount, size = props.size, layout = props.layout, children = props.children, restProps = _objectWithoutProperties(props, _excluded); var _useDOM = useDOM(), document = _useDOM.document; useIsomorphicLayoutEffect(function () { createMasks(document); }, [document]); var othersCount = Math.max(0, photos.length - visibleCount); var canShowOthers = othersCount > 0 && size === "m"; var photosShown = photos.slice(0, visibleCount); return createScopedElement("div", _extends({}, restProps, { vkuiClass: classNames(getClassName("UsersStack", platform), "UsersStack--size-".concat(size), "UsersStack--l-".concat(layout), { "UsersStack--others": canShowOthers }) }), createScopedElement("div", { vkuiClass: "UsersStack__photos", role: "presentation" }, photosShown.map(function (photo, i) { return createScopedElement("div", { key: i, vkuiClass: "UsersStack__photo", style: { backgroundImage: "url(".concat(photo, ")") } }); }), canShowOthers && createScopedElement(Caption, { weight: "medium", level: "1", vkuiClass: "UsersStack__photo UsersStack__photo--others", "aria-hidden": "true" }, createScopedElement("span", null, "+", othersCount))), hasReactNode(children) && createScopedElement(Subhead, { Component: "span", weight: "regular", vkuiClass: "UsersStack__text" }, children)); }; UsersStack.defaultProps = { photos: [], size: "s", visibleCount: 3, layout: "horizontal" }; // eslint-disable-next-line import/no-default-export export default /*#__PURE__*/React.memo(UsersStack); //# sourceMappingURL=UsersStack.js.map
cdnjs/cdnjs
ajax/libs/vkui/4.27.1/components/UsersStack/UsersStack.js
JavaScript
mit
2,760
;var ls = ls || {}; /** * Опросы */ ls.poll = (function ($) { /** * Голосование в опросе */ this.vote = function(idTopic, idAnswer) { var url = aRouter['ajax']+'vote/question/'; var params = {idTopic: idTopic, idAnswer: idAnswer}; ls.hook.marker('voteBefore'); ls.ajax(url, params, function(result) { if (result.bStateError) { ls.msg.error(null, result.sMsg); } else { ls.msg.notice(null, result.sMsg); var area = $('#topic_question_area_'+idTopic); ls.hook.marker('voteDisplayBefore'); area.html(result.sText); ls.hook.run('ls_pool_vote_after',[idTopic, idAnswer,result],area); } }); }; /** * Добавляет вариант ответа */ this.addAnswer = function() { if($("#question_list li").length == 20) { ls.msg.error(null, ls.lang.get('topic_question_create_answers_error_max')); return false; } var newItem = $("#question_list li:first-child").clone(); newItem.find('a').remove(); var removeAnchor = $('<a href="#"/>').text(ls.lang.get('delete')).click(function(e){ e.preventDefault(); return this.removeAnswer(e.target); }.bind(this)); newItem.appendTo("#question_list").append(removeAnchor); newItem.find('input').val(''); ls.hook.run('ls_pool_add_answer_after',[removeAnchor],newItem); }; /** * Удаляет вариант ответа */ this.removeAnswer = function(obj) { $(obj).parent("li").remove(); return false; }; this.switchResult = function(obj, iTopicId) { if ($('#poll-result-sort-'+iTopicId).css('display') == 'none') { $('#poll-result-original-'+iTopicId).hide(); $('#poll-result-sort-'+iTopicId).show(); $(obj).toggleClass('active'); } else { $('#poll-result-sort-'+iTopicId).hide(); $('#poll-result-original-'+iTopicId).show(); $(obj).toggleClass('active'); } return false; }; return this; }).call(ls.poll || {},jQuery);
ieasyweb/altocms
common/templates/frontend/ls/js/poll.js
JavaScript
gpl-2.0
1,908
( function( mw ) { mediaWiki.messages.set( { "mwe-upwiz-code-unknown": "Unknown language" } ); /** * Utility class which knows about languages, and how to construct HTML to select them * TODO: make this a more common library, used by this and TimedText */ mw.LanguageUpWiz = { defaultCode: 'en', // when we absolutely have no idea what language to preselect initialized: false, UNKNOWN: 'unknown', /** * List of default languages * Make sure you have language templates set up for each of these on your wiki, e.g. {{en}} */ languages: [ { lang: "de", text: "Deutsch" }, { lang: "en", text: "English" }, { lang: "es", text: "Español" }, { lang: "fr", text: "Français" }, { lang: "it", text: "Italiano" }, { lang: "nl", text: "Nederlands" }, { lang: "pl", text: "Polski" }, { lang: "pt", text: "Português" }, { lang: "ru", text: "Русский" }, { lang: "zh", text: "中文" }, { lang: "ja", text: "日本語" } ], /** * cache some useful objects * 1) mostly ready-to-go language HTML menu. When/if we upgrade, make it a jQuery combobox * 2) dict of language code to name -- useful for testing for existence, maybe other things. */ initialize: function() { if ( mw.LanguageUpWiz.initialized ) { return; } // if a language list is defined locally (MediaWiki:LanguageHandler.js), use that list instead if ( typeof LanguageHandler != 'undefined' ) { this.languages = LanguageHandler.languages; } mw.LanguageUpWiz._codes = {}; var select = $j( '<select/>' ); $j.each( mw.LanguageUpWiz.languages, function( i, language ) { // add an option for each language select.append( $j( '<option>' ) .attr( 'value', language.lang ) .append( language.text ) ); // add each language into dictionary mw.LanguageUpWiz._codes[language.lang] = language.text; } ); mw.LanguageUpWiz.$_select = select; mw.LanguageUpWiz.initialized = true; }, /** * Get an HTML select menu of all our languages. * @param name desired name of select element * @param code desired default language code * @return HTML select element configured as desired */ getMenu: function( name, code ) { mw.LanguageUpWiz.initialize(); var $select = mw.LanguageUpWiz.$_select.clone(); $select.attr( 'name', name ); if ( code === mw.LanguageUpWiz.UNKNOWN ) { // n.b. MediaWiki LanguageHandler has ability to add custom label for 'Unknown'; possibly as pseudo-label $select.prepend( $j( '<option>' ).attr( 'value', mw.LanguageUpWiz.UNKNOWN ).append( gM( 'mwe-upwiz-code-unknown' )) ); $select.val( mw.LanguageUpWiz.UNKNOWN ); } else if ( code !== undefined ) { $select.val( mw.LanguageUpWiz.getClosest( code )); } return $select.get( 0 ); }, /** * Figure out the closest language we have to a supplied language code. * It seems that people on Mediawiki set their language code as freetext, and it could be anything, even * variants we don't have a record for, or ones that are not in any ISO standard. * * Logic copied from MediaWiki:LanguageHandler.js * handle null cases, special cases for some Chinese variants * Otherwise, if handed "foo-bar-baz" language, try to match most specific language, * "foo-bar-baz", then "foo-bar", then "foo" * * @param code A string representing a language code, which we may or may not have. * Expected to be separated with dashes as codes from ISO 639, e.g. "zh-tw" for Chinese ( Traditional ) * @return a language code which is close to the supplied parameter, or fall back to mw.LanguageUpWiz.defaultCode */ getClosest: function( code ) { mw.LanguageUpWiz.initialize(); if ( typeof ( code ) != 'string' || code === null || code.length === 0 ) { return mw.LanguageUpWiz.defaultCode; } if ( code == 'nan' || code == 'minnan' ) { return 'zh-min-nan'; } else if ( mw.LanguageUpWiz._codes[code] !== undefined ) { return code; } return mw.LanguageUpWiz.getClosest( code.substring( 0, code.indexOf( '-' )) ); } // enhance a simple text input to be an autocompleting language menu // this will work when/if we move to jQuery 1.4. As of now the autocomplete is too underpowered for our needs without // serious hackery /* $j.fn.languageMenu = function( options ) { var _this = this; _this.autocomplete( null, { minChars: 0, width: 310, selectFirst: true, autoFill: true, mustMatch: true, matchContains: false, highlightItem: true, scroll: true, scrollHeight: 220, formatItem: function( row, i, max, term ) { return row.code + " " + row.code; }, formatMatch: function( row, i, max, term ) { return row.code + " " + row.code; }, formatResult: function( row ) { return row.code; } }, mw.Languages ); // and add a dropdown so we can see the thingy, too return _this; }; */ // XXX the concept of "internal language" exists in UploadForm.js -- seems to be how they handled i18n, with // language codes that has underscores rather than dashes, ( "en_gb" rather than the correct "en-gb" ). // although other info such as Information boxes was recorded correctly. // This is presumed not to apply to the shiny new world of JS2, where i18n is handled in other ways. }; } )( window.mediaWiki );
SuriyaaKudoIsc/wikia-app-test
extensions/UploadWizard/resources/mw.LanguageUpWiz.js
JavaScript
gpl-2.0
5,288
/** * Nanocloud turns any traditional software into a cloud solution, without * changing or redeveloping existing source code. * * Copyright (C) 2016 Nanocloud Software * * This file is part of Nanocloud. * * Nanocloud is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * Nanocloud 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. * * You should have received a copy of the GNU Affero General * Public License * along with this program. If not, see * <http://www.gnu.org/licenses/>. */ import getKeyFromValue from 'nanocloud/utils/get-key-from-value'; import { module, test } from 'qunit'; module('Unit | Utility | get key from value'); var map = { object1: 'value1', object2: 'value2', object3: 'value3', object4: 'value4', }; // Replace this with your real tests. test('it should return the key for a value that exists', function(assert) { let result = getKeyFromValue(map, 'value2'); assert.equal(result, 'object2'); }); test('it should return -1 if value was not found', function(assert) { let result = getKeyFromValue(map, 'value0'); assert.equal(result, -1); });
Gentux/nanocloud
assets/tests/unit/utils/get-key-from-value-test.js
JavaScript
agpl-3.0
1,492
(function (root, factory) { if (typeof define === "function" && define.amd) { define([], factory); } else { root.MessageServer = factory(); } }(this, function() { var CHANNELS = {}; function MessageServer(origins, channel, messageHandlerResolver) { if (!origins || !channel) { throw new Error("MessageServer constructor requires all (\"origins\" and \"channel\") " + "parameters to be set"); } if (CHANNELS[channel]) { throw new Error("Cannot construct MessageServer since channel \"" + channel + "\"already is in use"); } CHANNELS[channel] = true; this._origins = origins || []; this._channel = channel; this._messageHandlerResolver = messageHandlerResolver || this._messageHandlerResolver; this._addEventListener(window, "message", this._receiveMessage); } MessageServer.prototype = { /** * Default implementation that will look for methods in the prototype chain * assuming this class has been extended. * * Note! Could be overridden using the 'messageHandlerResolver' constructor argument. * * @param name {string} The name of the function to invoke * @return Function|null * @private */ _messageHandlerResolver: function(name) { return this[name]; }, _receiveMessage: function(event) { // Do we trust the sender of this message? var allowed = false; for (var i = 0, il = this._origins.length; i < il; i++) { if (event.origin === this._origins[i]) { allowed = true; break; } } if (allowed) { // event.source var data = JSON.parse(event.data); if (data.name && data.channel === this._channel) { var name = data.name; var fn = this._messageHandlerResolver(name); if (typeof fn === "function") { fn(data.value, function(result){ var message = { callback: data.callback, success: true, result: result }; message = JSON.stringify(message); event.source.postMessage(message, event.origin); }, function(code, message){ var messageToPost = { callback: data.callback, failure: true, code: code, message: message }; messageToPost = JSON.stringify(messageToPost); event.source.postMessage(messageToPost, event.origin); }); } else { // The message was not recognized var message = { callback: data.callback, failure: true, code: 1, message: "Message named \"" + name + "\" was not recognized." }; message = JSON.stringify(message); event.source.postMessage(message, event.origin); } } } }, _bind: function(fn) { var args = Array.prototype.slice.call(arguments).slice(2); var me = this; return function() { return fn.apply(me, args.concat(Array.prototype.slice.call(arguments))); }; }, _addEventListener: function(el, event, callback) { if (typeof el.addEventListener === "function") { el.addEventListener(event, this._bind(callback), false); } else { el.attachEvent("on" + event, this._bind(callback)); } } }; return MessageServer; }));
AFaust/Aikau
aikau/src/main/resources/alfresco/integration/MessageServer.js
JavaScript
lgpl-3.0
4,057
/* * Copyright 2012 Amadeus s.a.s. * 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. */ var Aria = require("ariatemplates/Aria"); module.exports = Aria.classDefinition({ $classpath : "test.aria.widgets.wai.input.label.RadioButtonJawsTestCase", $extends : require("./LabelJawsBase"), $prototype : { elementsToTest : "rbWaiEnabledStart" } });
vcarle/ariatemplates
test/aria/widgets/wai/input/label/RadioButtonJawsTestCase.js
JavaScript
apache-2.0
873
var tree = require('../lib/tree'); exports['extend - install new - reduce dep version'] = function (test) { var packages = { 'foo': { versions: { '0.0.1': { config: { name: 'foo', version: '0.0.1', dependencies: {} }, source: 'local' }, '0.0.2': { config: { name: 'foo', version: '0.0.2', dependencies: {} }, source: 'local' }, '0.0.3': { config: { name: 'foo', version: '0.0.3', dependencies: {} }, source: 'repository' } }, current_version: '0.0.3', ranges: {}, sources: [] } }; var bar = { config: { name: 'bar', version: '0.0.1', dependencies: { 'foo': '<= 0.0.2' } }, source: 'local' } var sources = []; tree.extend(bar, sources, packages, function (err, packages) { test.same(packages, { 'foo': { versions: { '0.0.1': { config: { name: 'foo', version: '0.0.1', dependencies: {} }, source: 'local' }, '0.0.2': { config: { name: 'foo', version: '0.0.2', dependencies: {} }, source: 'local' }, '0.0.3': { config: { name: 'foo', version: '0.0.3', dependencies: {} }, source: 'repository' } }, current_version: '0.0.2', ranges: {'bar': '<= 0.0.2'}, sources: [] }, 'bar': { versions: { '0.0.1': { config: { name: 'bar', version: '0.0.1', dependencies: { 'foo': '<= 0.0.2' } }, source: 'local' } }, current_version: '0.0.1', ranges: {}, sources: [] } }); test.done(err); }); }; exports['extend - reinstall existing - increase dep version'] = function (test) { var packages = { 'foo': { versions: { '0.0.1': { config: { name: 'foo', version: '0.0.1', dependencies: {} }, source: 'local' }, '0.0.2': { config: { name: 'foo', version: '0.0.2', dependencies: {} }, source: 'local' }, '0.0.3': { config: { name: 'foo', version: '0.0.3', dependencies: {} }, source: 'repository' } }, current_version: '0.0.2', ranges: {bar: '<= 0.0.2'}, sources: [] }, 'bar': { versions: { '0.0.1': { config: { name: 'bar', version: '0.0.1', dependencies: { 'foo': '<= 0.0.2' } }, source: 'local' } }, current_version: '0.0.1', ranges: {}, sources: [] } }; var bar = { config: { name: 'bar', version: '0.0.2', dependencies: { 'foo': '> 0.0.2' } }, source: 'local' } var sources = []; tree.extend(bar, sources, packages, function (err, packages) { test.same(packages, { 'foo': { versions: { '0.0.1': { config: { name: 'foo', version: '0.0.1', dependencies: {} }, source: 'local' }, '0.0.2': { config: { name: 'foo', version: '0.0.2', dependencies: {} }, source: 'local' }, '0.0.3': { config: { name: 'foo', version: '0.0.3', dependencies: {} }, source: 'repository' } }, current_version: '0.0.3', ranges: {bar: '> 0.0.2'}, sources: [] }, 'bar': { versions: { '0.0.1': { config: { name: 'bar', version: '0.0.1', dependencies: { 'foo': '<= 0.0.2' } }, source: 'local' }, '0.0.2': { config: { name: 'bar', version: '0.0.2', dependencies: { 'foo': '> 0.0.2' } }, source: 'local' } }, current_version: '0.0.2', ranges: {}, sources: [] } }); test.done(err); }); }; exports['extend- install new - missing dep version'] = function (test) { test.expect(1); var packages = { 'foo': { versions: { '0.0.2': { config: { name: 'foo', version: '0.0.2', dependencies: {} }, source: 'local' }, '0.0.3': { config: { name: 'foo', version: '0.0.3', dependencies: {} }, source: 'local' } }, current_version: '0.0.3', ranges: {}, sources: [] } }; var bar = { config: { name: 'bar', version: '0.0.1', dependencies: { 'foo': '< 0.0.2' } }, source: 'local' } var sources = []; tree.extend(bar, sources, packages, function (err, packages) { test.ok( /No matching version for 'foo'/.test(err.message), "No matching version for 'foo'" ); test.done(); }); }; exports['extend - install new - missing dep package'] = function (test) { test.expect(1); var packages = { 'foo': { versions: { '0.0.3': { config: { name: 'foo', version: '0.0.3', dependencies: {} }, source: 'local' } }, current_version: '0.0.3', ranges: {}, sources: [] } }; var bar = { config: { name: 'bar', version: '0.0.1', dependencies: { 'foo': null, 'baz': null } }, source: 'local' } var sources = []; tree.extend(bar, sources, packages, function (err, packages) { test.ok( /No package for 'baz'/.test(err.message), "No package for 'baz'" ); test.done(); }); }; exports['build - fetch from sources'] = function (test) { test.expect(2); var foo = { config: { name: 'foo', version: '0.0.1', dependencies: { 'bar': '>= 0.0.2' } }, source: 'local' }; var sources = [ function (name, callback) { test.equal(name, 'bar'); process.nextTick(function () { callback(null, { '0.0.1': { config: { name: 'bar', version: '0.0.1', dependencies: {} }, source: 'local' }, '0.0.2': { config: { name: 'bar', version: '0.0.2', dependencies: {} }, source: 'local' } }); }) } ]; tree.build(foo, sources, function (err, packages) { delete packages['bar'].ev; test.same(packages, { 'foo': { versions: { '0.0.1': { config: { name: 'foo', version: '0.0.1', dependencies: { 'bar': '>= 0.0.2' } }, source: 'local' } }, ranges: {}, sources: [], current_version: '0.0.1' }, 'bar': { versions: { '0.0.1': { config: { name: 'bar', version: '0.0.1', dependencies: {} }, source: 'local' }, '0.0.2': { config: { name: 'bar', version: '0.0.2', dependencies: {} }, source: 'local' } }, update_in_progress: false, ranges: {'foo': '>= 0.0.2'}, sources: [], current_version: '0.0.2' } }); test.done(err); }); }; exports['build - check multiple sources'] = function (test) { test.expect(4); var source_calls = []; var foo = { config: { name: 'foo', version: '0.0.1', dependencies: { 'bar': '>= 0.0.2' } }, source: 'local' }; var sources = [ function (name, callback) { test.equal(name, 'bar'); source_calls.push('one'); process.nextTick(function () { callback(null, { '0.0.1': { config: { name: 'bar', version: '0.0.1', dependencies: {} }, source: 'local' } }); }) }, function (name, callback) { test.equal(name, 'bar'); source_calls.push('two'); process.nextTick(function () { callback(null, { '0.0.1': { config: { name: 'bar', version: '0.0.1', dependencies: {} }, source: 'repository' }, '0.0.2': { config: { name: 'bar', version: '0.0.2', dependencies: {} }, source: 'repository' } }); }) } ]; tree.build(foo, sources, function (err, packages) { test.same(source_calls, ['one', 'two']); delete packages['bar'].ev; test.same(packages, { 'foo': { versions: { '0.0.1': { config: { name: 'foo', version: '0.0.1', dependencies: { 'bar': '>= 0.0.2' } }, source: 'local' } }, ranges: {}, sources: [], current_version: '0.0.1' }, 'bar': { versions: { '0.0.1': { config: { name: 'bar', version: '0.0.1', dependencies: {} }, source: 'local' }, '0.0.2': { config: { name: 'bar', version: '0.0.2', dependencies: {} }, source: 'repository' } }, ranges: {'foo': '>= 0.0.2'}, sources: [], update_in_progress: false, current_version: '0.0.2' } }); test.done(err); }); }; exports['build - check only as many sources as needed'] = function (test) { test.expect(3); var source_calls = []; var foo = { config: { name: 'foo', version: '0.0.1', dependencies: { 'bar': '>= 0.0.2' } }, source: 'local' }; var sources = [ function (name, callback) { test.equal(name, 'bar'); source_calls.push('one'); process.nextTick(function () { callback(null, { '0.0.1': { config: { name: 'bar', version: '0.0.1', dependencies: {} }, source: 'local' }, '0.0.2': { config: { name: 'bar', version: '0.0.2', dependencies: {} }, source: 'local' } }); }) }, function (name, callback) { test.equal(name, 'bar'); source_calls.push('two'); process.nextTick(function () { callback(null, { '0.0.2': { config: { name: 'bar', version: '0.0.2', dependencies: {} }, souce: 'repository' }, '0.0.3': { config: { name: 'bar', version: '0.0.3', dependencies: {} }, source: 'repository' } }); }) } ]; tree.build(foo, sources, function (err, packages) { test.same(source_calls, ['one']); delete packages['bar'].ev; test.same(packages, { 'foo': { versions: { '0.0.1': { config: { name: 'foo', version: '0.0.1', dependencies: { 'bar': '>= 0.0.2' } }, source: 'local' } }, ranges: {}, sources: [], current_version: '0.0.1' }, 'bar': { versions: { '0.0.1': { config: { name: 'bar', version: '0.0.1', dependencies: {} }, source: 'local' }, '0.0.2': { config: { name: 'bar', version: '0.0.2', dependencies: {} }, source: 'local' } }, ranges: {'foo': '>= 0.0.2'}, sources: [sources[1]], update_in_progress: false, current_version: '0.0.2' } }); test.done(err); }); };
daniel-z/kanso
test/test-lib-tree.js
JavaScript
apache-2.0
16,865
/*! * 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"; const pubsuffix = require("./pubsuffix-psl"); // Gives the permutation of all possible domainMatch()es of a given domain. The // array is in shortest-to-longest order. Handy for indexing. const SPECIAL_USE_DOMAINS = ["local"]; // RFC 6761 function permuteDomain(domain, allowSpecialUseDomain) { let pubSuf = null; if (allowSpecialUseDomain) { const domainParts = domain.split("."); if (SPECIAL_USE_DOMAINS.includes(domainParts[domainParts.length - 1])) { pubSuf = `${domainParts[domainParts.length - 2]}.${ domainParts[domainParts.length - 1] }`; } else { pubSuf = pubsuffix.getPublicSuffix(domain); } } else { pubSuf = pubsuffix.getPublicSuffix(domain); } if (!pubSuf) { return null; } if (pubSuf == domain) { return [domain]; } const prefix = domain.slice(0, -(pubSuf.length + 1)); // ".example.com" const parts = prefix.split(".").reverse(); let cur = pubSuf; const permutations = [cur]; while (parts.length) { cur = `${parts.shift()}.${cur}`; permutations.push(cur); } return permutations; } exports.permuteDomain = permuteDomain;
GoogleCloudPlatform/prometheus-engine
third_party/prometheus_ui/base/web/ui/react-app/node_modules/jsdom/node_modules/tough-cookie/lib/permuteDomain.js
JavaScript
apache-2.0
2,718
export { default } from 'shared/components/schema/input-workload/component';
pengjiang80/ui
lib/shared/app/components/schema/input-workload/component.js
JavaScript
apache-2.0
77
Package.describe({ name: 'rocketchat:message-pin', version: '0.0.1', summary: 'Pin Messages' }); Package.onUse(function(api) { api.versionsFrom('1.0'); api.use([ 'coffeescript', 'underscore', 'less@2.5.0', 'rocketchat:lib' ]); api.addFiles([ 'client/lib/PinnedMessage.coffee', 'client/actionButton.coffee', 'client/pinMessage.coffee', 'client/tabBar.coffee', 'client/views/pinnedMessages.html', 'client/views/pinnedMessages.coffee', 'client/views/stylesheets/messagepin.less', ], 'client'); api.addFiles([ 'server/settings.coffee', 'server/pinMessage.coffee', 'server/publications/pinnedMessages.coffee', 'server/startup/indexes.coffee' ], 'server'); // TAPi18n api.use('templating', 'client'); var _ = Npm.require('underscore'); var fs = Npm.require('fs'); tapi18nFiles = _.compact(_.map(fs.readdirSync('packages/rocketchat-message-pin/i18n'), function(filename) { if (fs.statSync('packages/rocketchat-message-pin/i18n/' + filename).size > 16) { return 'i18n/' + filename; } })); api.use('tap:i18n'); api.addFiles(tapi18nFiles); }); Package.onTest(function(api) { });
TribeMedia/Rocket.Chat
packages/rocketchat-message-pin/package.js
JavaScript
mit
1,131
var assert = require('assert') , EventEmitter = require('events').EventEmitter , fs = require('fs') , sinon = require('sinon') , Twit = require('../lib/twitter') , config1 = require('../config1') , config2 = require('../config2') , helpers = require('./helpers') , util = require('util') , async = require('async') describe('REST API', function () { var twit = null before(function () { twit = new Twit(config1); }) it('GET `account/verify_credentials`', function (done) { twit.get('account/verify_credentials', function (err, reply, response) { checkReply(err, reply) assert.notEqual(reply.followers_count, undefined) assert.notEqual(reply.friends_count, undefined) assert.ok(reply.id_str) checkResponse(response) assert(response.headers['x-rate-limit-limit']) done() }) }) it('GET `account/verify_credentials` using promise API only', function (done) { twit .get('account/verify_credentials', { skip_status: true }) .catch(function (err) { console.log('catch err', err.stack) }) .then(function (result) { checkReply(null, result.data) assert.notEqual(result.data.followers_count, undefined) assert.notEqual(result.data.friends_count, undefined) assert.ok(result.data.id_str) checkResponse(result.resp) assert(result.resp.headers['x-rate-limit-limit']) done() }) }) it('GET `account/verify_credentials` using promise API AND callback API', function (done) { var i = 0; var _checkDataAndResp = function (data, resp) { checkReply(null, data) assert.notEqual(data.followers_count, undefined) assert.notEqual(data.friends_count, undefined) assert.ok(data.id_str) checkResponse(resp) assert(resp.headers['x-rate-limit-limit']) i++; if (i == 2) { done() } } var get = twit.get('account/verify_credentials', function (err, data, resp) { assert(!err, err); _checkDataAndResp(data, resp); }); get.catch(function (err) { console.log('Got error:', err.stack) }); get.then(function (result) { _checkDataAndResp(result.data, result.resp); }); }) it('POST `account/update_profile`', function (done) { twit.post('account/update_profile', function (err, reply, response) { checkReply(err, reply) console.log('\nscreen name:', reply.screen_name) checkResponse(response) done() }) }) it('POST `statuses/update` and POST `statuses/destroy:id`', function (done) { var tweetId = null var params = { status: '@tolga_tezel tweeting using github.com/ttezel/twit. ' + helpers.generateRandomString(7) } twit.post('statuses/update', params, function (err, reply, response) { checkReply(err, reply) console.log('\ntweeted:', reply.text) tweetId = reply.id_str assert(tweetId) checkResponse(response) var deleteParams = { id: tweetId } // Try up to 2 times to delete the tweet. // Even after a 200 response to statuses/update is returned, a delete might 404 so we retry. exports.req_with_retries(twit, 2, 'post', 'statuses/destroy/:id', deleteParams, [404], function (err, body, response) { checkReply(err, body) checkTweet(body) checkResponse(response) done() }) }) }) it('POST `statuses/update` with characters requiring escaping', function (done) { var params = { status: '@tolga_tezel tweeting using github.com/ttezel/twit :) !' + helpers.generateRandomString(15) } twit.post('statuses/update', params, function (err, reply, response) { checkReply(err, reply) console.log('\ntweeted:', reply.text) checkResponse(response) var text = reply.text assert(reply.id_str) twit.post('statuses/destroy/:id', { id: reply.id_str }, function (err, reply, response) { checkReply(err, reply) checkTweet(reply) assert.equal(reply.text, text) checkResponse(response) done() }) }) }) it('POST `statuses/update` with \'Hi!!\' works', function (done) { var params = { status: 'Hi!!' } twit.post('statuses/update', params, function (err, reply, response) { checkReply(err, reply) console.log('\ntweeted:', reply.text) checkResponse(response) var text = reply.text var destroyRoute = 'statuses/destroy/'+reply.id_str twit.post(destroyRoute, function (err, reply, response) { checkReply(err, reply) checkTweet(reply) assert.equal(reply.text, text) checkResponse(response) done() }) }) }) it('GET `statuses/home_timeline`', function (done) { twit.get('statuses/home_timeline', function (err, reply, response) { checkReply(err, reply) checkTweet(reply[0]) checkResponse(response) done() }) }) it('GET `statuses/mentions_timeline`', function (done) { twit.get('statuses/mentions_timeline', function (err, reply, response) { checkReply(err, reply) checkTweet(reply[0]) done() }) }) it('GET `statuses/user_timeline`', function (done) { var params = { screen_name: 'tolga_tezel' } twit.get('statuses/user_timeline', params, function (err, reply, response) { checkReply(err, reply) checkTweet(reply[0]) checkResponse(response) done() }) }) it('GET `search/tweets` { q: "a", since_id: 12345 }', function (done) { var params = { q: 'a', since_id: 12345 } twit.get('search/tweets', params, function (err, reply, response) { checkReply(err, reply) assert.ok(reply.statuses) checkTweet(reply.statuses[0]) checkResponse(response) done() }) }) it('GET `search/tweets` { q: "fun since:2011-11-11" }', function (done) { var params = { q: 'fun since:2011-11-11', count: 100 } twit.get('search/tweets', params, function (err, reply, response) { checkReply(err, reply) assert.ok(reply.statuses) checkTweet(reply.statuses[0]) console.log('\nnumber of fun statuses:', reply.statuses.length) checkResponse(response) done() }) }) it('GET `search/tweets`, using `q` array', function (done) { var params = { q: [ 'banana', 'mango', 'peach' ] } twit.get('search/tweets', params, function (err, reply, response) { checkReply(err, reply) assert.ok(reply.statuses) checkTweet(reply.statuses[0]) checkResponse(response) done() }) }) it('GET `search/tweets` with count set to 100', function (done) { var params = { q: 'happy', count: 100 } twit.get('search/tweets', params, function (err, reply, res) { checkReply(err, reply) console.log('\nnumber of tweets from search:', reply.statuses.length) // twitter won't always send back 100 tweets if we ask for 100, // but make sure it's close to 100 assert(reply.statuses.length > 95) done() }) }) it('GET `search/tweets` with geocode', function (done) { var params = { q: 'apple', geocode: [ '37.781157', '-122.398720', '1mi' ] } twit.get('search/tweets', params, function (err, reply) { checkReply(err, reply) done() }) }) it('GET `direct_messages`', function (done) { twit.get('direct_messages', function (err, reply, response) { checkResponse(response) checkReply(err, reply) assert.ok(Array.isArray(reply)) done() }) }) it('GET `followers/ids`', function (done) { twit.get('followers/ids', function (err, reply, response) { checkReply(err, reply) assert.ok(Array.isArray(reply.ids)) checkResponse(response) done() }) }) it('GET `followers/ids` of screen_name tolga_tezel', function (done) { twit.get('followers/ids', { screen_name: 'tolga_tezel' }, function (err, reply, response) { checkReply(err, reply) assert.ok(Array.isArray(reply.ids)) checkResponse(response) done() }) }) it('POST `statuses/retweet`', function (done) { // search for a tweet to retweet twit.get('search/tweets', { q: 'apple' }, function (err, reply, response) { checkReply(err, reply) assert.ok(reply.statuses) var tweet = reply.statuses[0] checkTweet(tweet) var tweetId = tweet.id_str assert(tweetId) twit.post('statuses/retweet/'+tweetId, function (err, reply, response) { checkReply(err, reply) var retweetId = reply.id_str assert(retweetId) twit.post('statuses/destroy/'+retweetId, function (err, reply, response) { checkReply(err, reply) done() }) }) }) }) // 1.1.8 usage it('POST `statuses/retweet/:id` without `id` in params returns error', function (done) { twit.post('statuses/retweet/:id', function (err, reply, response) { assert(err) assert.equal(err.message, 'Twit: Params object is missing a required parameter for this request: `id`') done() }) }) // 1.1.8 usage it('POST `statuses/retweet/:id`', function (done) { // search for a tweet to retweet twit.get('search/tweets', { q: 'banana' }, function (err, reply, response) { checkReply(err, reply) assert.ok(reply.statuses) var tweet = reply.statuses[0] checkTweet(tweet) var tweetId = tweet.id_str assert(tweetId) twit.post('statuses/retweet/:id', { id: tweetId }, function (err, reply) { checkReply(err, reply) var retweetId = reply.id_str assert(retweetId) twit.post('statuses/destroy/:id', { id: retweetId }, function (err, reply, response) { checkReply(err, reply) done() }) }) }) }) // 1.1.8 usage // skip for now since this API call is having problems on Twitter's side (404) it.skip('GET `users/suggestions/:slug`', function (done) { twit.get('users/suggestions/:slug', { slug: 'funny' }, function (err, reply, res) { checkReply(err, reply) assert.equal(reply.slug, 'funny') done() }) }) // 1.1.8 usage // skip for now since this API call is having problems on Twitter's side (404) it.skip('GET `users/suggestions/:slug/members`', function (done) { twit.get('users/suggestions/:slug/members', { slug: 'funny' }, function (err, reply, res) { checkReply(err, reply) assert(reply[0].id_str) assert(reply[0].screen_name) done() }) }) // 1.1.8 usage it('GET `geo/id/:place_id`', function (done) { var placeId = 'df51dec6f4ee2b2c' twit.get('geo/id/:place_id', { place_id: placeId }, function (err, reply, res) { checkReply(err, reply) assert(reply.country) assert(reply.bounding_box) assert.equal(reply.id, placeId) done() }) }) it('POST `direct_messages/new`', function (done) { var dmId async.series({ postDm: function (next) { var dmParams = { screen_name: 'tolga_tezel', text: 'hey this is a direct message from twit! :) ' + helpers.generateRandomString(15) } // post a direct message from the sender's account twit.post('direct_messages/new', dmParams, function (err, reply) { assert(!err, err) assert(reply) dmId = reply.id_str exports.checkDm(reply) assert.equal(reply.text, dmParams.text) assert(dmId) return next() }) }, deleteDm: function (next) { twit.post('direct_messages/destroy', { id: dmId }, function (err, reply) { assert(!err, err) exports.checkDm(reply) assert.equal(reply.id, dmId) return next() }) } }, done); }) describe('Media Upload', function () { var twit = null before(function () { twit = new Twit(config1) }) it('POST media/upload with png', function (done) { var b64content = fs.readFileSync(__dirname + '/img/cutebird.png', { encoding: 'base64' }) twit.post('media/upload', { media_data: b64content }, function (err, data, response) { assert.equal(response.statusCode, 200) assert(!err, err) exports.checkMediaUpload(data) assert(data.image.image_type == 'image/png' || data.image.image_type == 'image\/png') done() }) }) it('POST media/upload with JPG', function (done) { var b64content = fs.readFileSync(__dirname + '/img/bigbird.jpg', { encoding: 'base64' }) twit.post('media/upload', { media_data: b64content }, function (err, data, response) { assert(!err, err) exports.checkMediaUpload(data) assert.equal(data.image.image_type, 'image/jpeg') done() }) }) it('POST media/upload with static GIF', function (done) { var b64content = fs.readFileSync(__dirname + '/img/twitterbird.gif', { encoding: 'base64' }) twit.post('media/upload', { media_data: b64content }, function (err, data, response) { assert(!err, err) exports.checkMediaUpload(data) assert.equal(data.image.image_type, 'image/gif') done() }) }) it('POST media/upload with animated GIF using `media_data` parameter', function (done) { var b64content = fs.readFileSync(__dirname + '/img/snoopy-animated.gif', { encoding: 'base64' }) twit.post('media/upload', { media_data: b64content }, function (err, data, response) { assert(!err, err) exports.checkMediaUpload(data) var expected_image_types = ['image/gif', 'image/animatedgif'] var image_type = data.image.image_type assert.ok(expected_image_types.indexOf(image_type) !== -1, 'got unexpected image type:' + image_type) done() }) }) it('POST media/upload with animated GIF, then POST a tweet referencing the media', function (done) { var b64content = fs.readFileSync(__dirname + '/img/snoopy-animated.gif', { encoding: 'base64' }); twit.post('media/upload', { media_data: b64content }, function (err, data, response) { assert(!err, err) exports.checkMediaUpload(data) var expected_image_types = ['image/gif', 'image/animatedgif'] var image_type = data.image.image_type assert.ok(expected_image_types.indexOf(image_type) !== -1, 'got unexpected image type:' + image_type) var mediaIdStr = data.media_id_string assert(mediaIdStr) var params = { status: '#nofilter', media_ids: [mediaIdStr] } twit.post('statuses/update', params, function (err, data, response) { assert(!err, err) var tweetIdStr = data.id_str assert(tweetIdStr) exports.req_with_retries(twit, 3, 'post', 'statuses/destroy/:id', { id: tweetIdStr }, [404], function (err, data, response) { checkReply(err, data) done() }) }) }) }) it('POST media/upload with animated GIF using `media` parameter', function (done) { var b64Content = fs.readFileSync(__dirname + '/img/snoopy-animated.gif', { encoding: 'base64' }); twit.post('media/upload', { media: b64Content }, function (err, data, response) { assert(!err, err) exports.checkMediaUpload(data) var expected_image_types = ['image/gif', 'image/animatedgif'] var image_type = data.image.image_type assert.ok(expected_image_types.indexOf(image_type) !== -1, 'got unexpected image type:' + image_type) done() }) }) }) it('POST account/update_profile_image', function (done) { var b64content = fs.readFileSync(__dirname + '/img/snoopy-animated.gif', { encoding: 'base64' }) twit.post('account/update_profile_image', { image: b64content }, function (err, data, response) { assert(!err, err); exports.checkReply(err, data); exports.checkUser(data); done() }) }) it('POST friendships/create', function (done) { var params = { screen_name: 'tolga_tezel', follow: false }; twit.post('friendships/create', params, function (err, data, resp) { assert(!err, err); exports.checkReply(err, data); exports.checkUser(data); done(); }); }) describe('Favorites', function () { it('POST favorites/create and POST favorites/destroy work', function (done) { twit.post('favorites/create', { id: '583531943624597504' }, function (err, data, resp) { assert(!err, err); exports.checkReply(err, data); var tweetIdStr = data.id_str; assert(tweetIdStr); twit.post('favorites/destroy', { id: tweetIdStr }, function (err, data, resp) { assert(!err, err); exports.checkReply(err, data); assert(data.id_str); assert(data.text); done(); }) }) }) }) describe('error handling', function () { describe('handling errors from the twitter api', function () { it('should callback with an Error object with all the info and a response object', function (done) { var twit = new Twit({ consumer_key: 'a', consumer_secret: 'b', access_token: 'c', access_token_secret: 'd' }) twit.get('account/verify_credentials', function (err, reply, res) { assert(err instanceof Error) assert(err.statusCode === 401) assert(err.code > 0) assert(err.message.match(/token/)) assert(err.twitterReply) assert(err.allErrors) assert(res) assert(res.headers) assert.equal(res.statusCode, 401) done() }) }) }) describe('handling other errors', function () { it('should just forward errors raised by underlying request lib', function (done) { var twit = new Twit(config1); var fakeError = new Error('derp') var FakeRequest = function () { EventEmitter.call(this) } util.inherits(FakeRequest, EventEmitter) var stubGet = function () { var fakeRequest = new FakeRequest() process.nextTick(function () { fakeRequest.emit('error', fakeError) }) return fakeRequest } var request = require('request') var stubGet = sinon.stub(request, 'get', stubGet) twit.get('account/verify_credentials', function (err, reply, res) { assert(err === fakeError) // restore request.get stubGet.restore() done() }) }) }) describe('Request timeout', function () { it('set to 1ms should return with a timeout error', function (done) { config1.timeout_ms = 1; var twit = new Twit(config1); twit.get('account/verify_credentials', function (err, reply, res) { assert(err) assert.equal(err.message, 'ETIMEDOUT') delete config1.timeout_ms done() }) }) }) }); }); describe('Twit agent_options config', function () { it('config.trusted_cert_fingerprints works against cert fingerprint for api.twitter.com:443', function (done) { config1.trusted_cert_fingerprints = [ '66:EA:47:62:D9:B1:4F:1A:AE:89:5F:68:BA:6B:8E:BB:F8:1D:BF:8E' ]; var t = new Twit(config1); t.get('account/verify_credentials', function (err, data, resp) { assert(!err, err) assert(data) assert(data.id_str) assert(data.name) assert(data.screen_name) delete config1.trusted_cert_fingerprints done(); }) }) it('config.trusted_cert_fingerprints responds with Error when fingerprint mismatch occurs', function (done) { config1.trusted_cert_fingerprints = [ 'AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA' ]; var t = new Twit(config1); t.get('account/verify_credentials', function (err, data, resp) { assert(err) assert(err.toString().indexOf('Trusted fingerprints are: ' + config1.trusted_cert_fingerprints[0]) !== -1) delete config1.trusted_cert_fingerprints done(); }) }) }) describe('Local time offset compensation', function () { it('Compensates for local time being behind', function (done) { var t1 = Date.now(); var t = new Twit(config2); var stubNow = function () { return 0; } var stubDateNow = sinon.stub(Date, 'now', stubNow); t.get('account/verify_credentials', function (err, data, resp) { assert(err); t.get('account/verify_credentials', function (err, data, resp) { assert(!err, err); exports.checkReply(err, data); exports.checkUser(data); assert(t._twitter_time_minus_local_time_ms > 0) stubDateNow.restore(); done(); }) }) }) }) /** * Basic validation to verify we have no error and reply is an object * * @param {error} err error object (or null) * @param {object} reply reply object received from twitter */ var checkReply = exports.checkReply = function (err, reply) { assert.equal(err, null, 'reply err:'+util.inspect(err, true, 10, true)) assert.equal(typeof reply, 'object') } /** * check the http response object and its headers * @param {object} response http response object */ var checkResponse = exports.checkResponse = function (response) { assert(response) assert(response.headers) assert.equal(response.statusCode, 200) } /** * validate that @tweet is a tweet object * * @param {object} tweet `tweet` object received from twitter */ var checkTweet = exports.checkTweet = function (tweet) { assert.ok(tweet) assert.equal('string', typeof tweet.id_str, 'id_str wasnt string:'+tweet.id_str) assert.equal('string', typeof tweet.text) assert.ok(tweet.user) assert.equal('string', typeof tweet.user.id_str) assert.equal('string', typeof tweet.user.screen_name) } /** * Validate that @dm is a direct message object * * @param {object} dm `direct message` object received from twitter */ exports.checkDm = function checkDm (dm) { assert.ok(dm) assert.equal('string', typeof dm.id_str) assert.equal('string', typeof dm.text) var recipient = dm.recipient assert.ok(recipient) assert.equal('string', typeof recipient.id_str) assert.equal('string', typeof recipient.screen_name) var sender = dm.sender assert.ok(sender) assert.equal('string', typeof sender.id_str) assert.equal('string', typeof sender.screen_name) assert.equal('string', typeof dm.text) } exports.checkMediaUpload = function checkMediaUpload (data) { assert.ok(data) assert.ok(data.image) assert.ok(data.image.w) assert.ok(data.image.h) assert.ok(data.media_id) assert.equal('string', typeof data.media_id_string) assert.ok(data.size) } exports.checkUser = function checkUser (data) { assert.ok(data) assert.ok(data.id_str) assert.ok(data.name) assert.ok(data.screen_name) } exports.assertTweetHasText = function (tweet, text) { assert(tweet.text.toLowerCase().indexOf(text) !== -1, 'expected to find '+text+' in text: '+tweet.text); } exports.req_with_retries = function (twit_instance, num_tries, verb, path, params, status_codes_to_retry, cb) { twit_instance[verb](path, params, function (err, data, response) { if (!num_tries || (status_codes_to_retry.indexOf(response.statusCode) === -1)) { return cb(err, data, response) } exports.req_with_retries(twit_instance, num_tries - 1, verb, path, params, status_codes_to_retry, cb) }) }
PuffyCoffee/tweety
node_modules/twit/tests/rest.js
JavaScript
mit
23,685
export const packageName = "bundle-visualizer"; export const classPrefix = "meteorBundleVisualizer"; export const methodNameStats = `/__meteor__/${packageName}/stats`; export const typeBundle = "bundle"; export const typePackage = "package"; export const typeNodeModules = "node_modules"; function capitalizeFirstLetter(str) { return str.charAt(0).toUpperCase() + str.slice(1); } export function prefixedClass(className) { return `${classPrefix}${capitalizeFirstLetter(className)}`; }
Hansoft/meteor
packages/non-core/bundle-visualizer/common.js
JavaScript
mit
491
(function () { 'use strict'; var controllerId = 'reports.principals.allexpired.controller'; angular .module('app.reports') .controller('ReportsExpired90Controller', ReportsExpired90Controller); ReportsExpired90Controller.$inject = ['$q', 'PrincipalDataService', 'usSpinnerService', 'logger', '$log', '$timeout']; function ReportsExpired90Controller($q, PrincipalDataService, usSpinnerService, logger, $log, $timeout) { var vm = this; vm.principals = []; vm.pageSize = 10; vm.query = ""; vm.currentPage = 1; vm.loading = false; vm.csvExportFileName = "PrincipalsExpiredin90Days"; vm.reportFields = { appId: 'Application ID', displayName: 'Display Name', principalNames: 'Principal Names', replyUrls: 'Reply Url', endDate: 'End Date' }; vm.getPrincipals = getPrincipals; vm.getPrincipalCount = getPrincipalCount; vm.setPageSize = setPageSize; vm.openMenu = openMenu; /*Have to do this for spinner because $broadcast loads first */ $timeout(function () { usSpinnerService.spin('spinner'); }, 100); activate(); function activate() { logger.info('Activating Principals'); vm.loading = true; usSpinnerService.spin('spinner'); getPrincipals(); } function getPrincipals() { $log.info('Info ' + controllerId, 'Entering getPrincipals'); return PrincipalDataService.getExpiredPrincipalsInDays(90) .then(function (data) { vm.principals = data; vm.loading = false; usSpinnerService.stop('spinner'); return vm.principals; }); } function getPrincipalCount() { return vm.principals.length; } function openMenu() { vm.isMenuOpen = !vm.isMenuOpen; } function setPageSize(pageSize) { vm.pageSize = pageSize; } } })();
jansenbe/PnP-Tools
Solutions/Tenant Information Portal/src/TIP.DashBoard/Scripts/app/reports/principals/reports.expired90.controller.js
JavaScript
mit
2,066
var gulp = require('gulp'); var concat = require('gulp-concat'); var uglify = require('gulp-uglify'); var react = require('gulp-react'); gulp.task('build', function() { gulp.src('src/*.jsx') .pipe(react()) .pipe(concat('form-generator.min.js')) .pipe(uglify()) .pipe(gulp.dest('dist')); }); gulp.task('watch', function() { gulp.watch('src/*.jsx', ['build']); }); gulp.task('default', ['watch']);
shaunstanislaus/react-form-generator
gulpfile.js
JavaScript
mit
419
/* * BrainBrowser: Web-based Neurological Visualization Tools * (https://brainbrowser.cbrain.mcgill.ca) * * Copyright (C) 2011 * The Royal Institution for the Advancement of Learning * McGill University * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * 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. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * Author: Tarek Sherif <tsherif@gmail.com> (http://tareksherif.ca/) */ BrainBrowser.VolumeViewer.modules.loading = function(viewer) { "use strict"; var VolumeViewer = BrainBrowser.VolumeViewer; var default_color_map = null; var default_panel_width = 256; var default_panel_height = 256; /** * @doc function * @name viewer.loading:loadVolumes * @param {object} options Description of volumes to load: * * **volumes** {array} An array of volume descriptions. * * **overlay** {boolean|object} Set to true to display an overlay of * the loaded volumes without any interface, or provide and object * containing a description of the template to use for the UI (see below). * * **complete** {function} Callback invoked once all volumes are loaded. * * @description * Initial load of volumes. Usage: * ```js * viewer.loadVolumes({ * volumes: [ * { * type: "minc", * header_url: "volume1.mnc?minc_headers=true", * raw_data_url: "volume1.mnc?raw_data=true", * template: { * element_id: "volume-ui-template", * viewer_insert_class: "volume-viewer-display" * } * }, * { * type: "minc", * header_file: document.getElementById("header-file"), * raw_data_file: document.getElementById("raw-data-file"), * template: { * element_id: "volume-ui-template", * viewer_insert_class: "volume-viewer-display" * } * } * ], * overlay: { * template: { * element_id: "overlay-ui-template", * viewer_insert_class: "overlay-viewer-display" * } * } * }); * ``` * The volume viewer can use the following parameters to describe the volumes to be loaded: * * **type** The type of volume. This should map to one of the volume loaders. * * **template** (optional) Object containing information about the template to use * to produce the UI for each volume. Its properties include **element\_id**, * the id of the element containing the template, and * **viewer\_insert\_class**, the class of the element within the template * in which to insert the volume's display panels. * * Other parameters may be required for given volume types. */ viewer.loadVolumes = function(options) { options = options || {}; var overlay_options = options.overlay && typeof options.overlay === "object" ? options.overlay : {}; var volume_descriptions = options.volumes; var num_descriptions = options.volumes.length; var complete = options.complete; var num_loaded = 0; var i; function loadVolume(i) { setVolume(i, volume_descriptions[i], function() { if (++num_loaded < num_descriptions) { return; } if (options.overlay && num_descriptions > 1) { viewer.createOverlay(overlay_options, function() { if (BrainBrowser.utils.isFunction(complete)) { complete(); } viewer.triggerEvent("volumesloaded"); }); } else { if (BrainBrowser.utils.isFunction(complete)) { complete(); } viewer.triggerEvent("volumesloaded"); } }); } for (i = 0; i < num_descriptions; i++) { loadVolume(i); } }; /** * @doc function * @name viewer.loading:loadVolumeColorMapFromURL * @param {number} vol_id Index of the volume to be updated. * @param {string} url URL of the color map file. * @param {string} cursor_color Color to be used for the cursor. * @param {function} callback Callback to which the color map object will be passed * after loading. * * @description * Load a color map for the specified volume. * ```js * viewer.loadVolumeColorMapFromURL(vol_id, url, "#FF0000", function(volume, color_map) { * // Manipulate volume or color map. * }); * ``` */ viewer.loadVolumeColorMapFromURL = function(vol_id, url, cursor_color, callback) { BrainBrowser.loader.loadColorMapFromURL(url, function(color_map) { setVolumeColorMap(vol_id, color_map, cursor_color, callback); }, { scale: 255 }); }; /** * @doc function * @name viewer.loading:loadDefaultColorMapFromURL * @param {string} url URL of the color map file. * @param {string} cursor_color Color to be used for the cursor. * @param {function} callback Callback to which the color map object will be passed * after loading. * * @description * Load a default color map for the viewer. Used when a given volume * doesn't have its color map set. * ```js * viewer.loadDefaultColorMapFromURL(url, "#FF0000", function(color_map) { * // Manipulate color map. * }); * ``` */ viewer.loadDefaultColorMapFromURL = function(url, cursor_color, callback) { BrainBrowser.loader.loadColorMapFromURL(url, function(color_map) { setDefaultColorMap(color_map, cursor_color, callback); }, { scale: 255 }); }; /** * @doc function * @name viewer.loading:loadVolumeColorMapFromFile * @param {number} vol_id Index of the volume to be updated. * @param {DOMElement} file_input File input element representing the color map file to load. * @param {string} cursor_color Color to be used for the cursor. * @param {function} callback Callback to which the color map object will be passed * after loading. * * @description * Load a color map for the specified volume. * ```js * viewer.loadVolumeColorMapFromFile(vol_id, file_input_element, "#FF0000", function(volume, color_map) { * // Manipulate volume or color map. * }); * ``` */ viewer.loadVolumeColorMapFromFile = function(vol_id, file_input, cursor_color, callback) { BrainBrowser.loader.loadColorMapFromFile(file_input, function(color_map) { setVolumeColorMap(vol_id, color_map, cursor_color, callback); }, { scale: 255 }); }; /** * @doc function * @name viewer.loading:loadDefaultColorMapFromFile * @param {DOMElement} file_input File input element representing the color map file to load. * @param {string} cursor_color Color to be used for the cursor. * @param {function} callback Callback to which the color map object will be passed * after loading. * * @description * Load a default color map for the viewer. Used when a given volume * doesn't have its color map set. * ```js * viewer.loadDefaultColorMapFromFile(file_input_element, "#FF0000", function(color_map) { * // Manipulate color map. * }); * ``` */ viewer.loadDefaultColorMapFromFile = function(file_input, cursor_color, callback) { BrainBrowser.loader.loadColorMapFromFile(file_input, function(color_map) { setDefaultColorMap(color_map, cursor_color, callback); }, { scale: 255 }); }; /** * @doc function * @name viewer.loading:setVolumeColorMap * @param {number} vol_id Index of the volume to be updated. * @param {object} color_map Color map to use for the indicated volume. * * @description * Set the color map for the indicated volume using an actual color map * object. * ```js * viewer.setVolumeColorMap(vol_id, color_map)); * ``` */ viewer.setVolumeColorMap = function(vol_id, color_map) { viewer.volumes[vol_id].color_map = color_map; }; /** * @doc function * @name viewer.loading:loadVolume * @param {object} volume_description Description of the volume to be loaded. * Must contain at least a **type** property that maps to the volume loaders in * **BrainBrowser.volume_loaders.** May contain a **template** property that * indicates the template to be used for the volume's UI. Other properties will be * specific to a particular volume type. * @param {function} callback Callback to which the new volume object will be passed * after loading. * * @description * Load a new volume. * ```js * // Load over the network. * viewer.loadVolume({ * type: "minc", * header_url: "volume1.mnc?minc_headers=true", * raw_data_url: "volume1.mnc?raw_data=true", * template: { * element_id: "volume-ui-template", * viewer_insert_class: "volume-viewer-display" * } * }); * * // Load from local files. * viewer.loadVolume({ * type: "minc", * header_file: document.getElementById("header-file"), * raw_data_file: document.getElementById("raw-data-file"), * template: { * element_id: "volume-ui-template", * viewer_insert_class: "volume-viewer-display" * } * }); * ``` */ viewer.loadVolume = function(volume_description, callback) { setVolume(viewer.volumes.length, volume_description, callback); }; /** * @doc function * @name viewer.loading:clearVolumes * * @description * Clear all loaded volumes. * ```js * viewer.clearVolumes(); * ``` */ viewer.clearVolumes = function() { viewer.volumes.forEach(function(volume) { volume.triggerEvent("eventmodelcleanup"); }); viewer.volumes = []; viewer.containers = []; viewer.active_panel = null; viewer.dom_element.innerHTML = ""; }; /** * @doc function * @name viewer.loading:createOverlay * @param {object} volume_description Will contain at most a **template** * property indicating the template to use for the UI. * @param {function} callback Callback to which the new overlay volume object * will be passed after loading. * * @description * Create an overlay of the currently loaded volumes. * ```js * viewer.createOverlay({ * template: { * element_id: "overlay-ui-template", * viewer_insert_class: "overlay-viewer-display" * } * }); * ``` */ viewer.createOverlay = function(description, callback) { description = description || {}; viewer.loadVolume({ volumes: viewer.volumes, type: "overlay", template: description.template }, callback ); }; /** * @doc function * @name viewer.loading:setDefaultPanelSize * @param {number} width Panel width. * @param {number} height Panel height. * * @description * Set the default size for panel canvases. * ```js * viewer.setDefaultPanelSize(512, 512); * ``` */ viewer.setDefaultPanelSize = function(width, height) { default_panel_width = width; default_panel_height = height; }; viewer.syncPosition = function(panel, volume, axis_name) { var wc = volume.getWorldCoords(); viewer.volumes.forEach(function(synced_volume) { if (synced_volume !== volume) { var synced_panel = synced_volume.display.getPanel(axis_name); synced_panel.volume.setWorldCoords(wc.x, wc.y, wc.z); synced_panel.updated = true; synced_volume.display.forEach(function(panel) { if (panel !== synced_panel) { panel.updateSlice(); } }); } }); }; /////////////////////////// // Private Functions /////////////////////////// // Open volume using appropriate volume loader function openVolume(volume_description, callback){ var loader = VolumeViewer.volume_loaders[volume_description.type]; var error_message; if(loader){ loader(volume_description, callback); } else { error_message = "Unsuported Volume Type"; BrainBrowser.events.triggerEvent("error", { message: error_message }); throw new Error(error_message); } } // Place a volume at a certain position in the volumes array. // This function should be used with care as empty places in the volumes // array will cause problems with rendering. function setVolume(vol_id, volume_description, callback) { openVolume(volume_description, function(volume) { var slices_loaded = 0; var views = volume_description.views || ["xspace","yspace","zspace"]; BrainBrowser.events.addEventModel(volume); volume.addEventListener("eventmodelcleanup", function() { volume.display.triggerEvent("eventmodelcleanup"); }); viewer.volumes[vol_id] = volume; volume.color_map = default_color_map; volume.display = createVolumeDisplay(viewer.dom_element, vol_id, volume_description); volume.propagateEventTo("*", viewer); ["xspace", "yspace", "zspace"].forEach(function(axis) { volume.position[axis] = Math.floor(volume.header[axis].space_length / 2); }); volume.display.forEach(function(panel) { panel.updateSlice(function() { if (++slices_loaded === views.length) { viewer.triggerEvent("volumeloaded", { volume: volume }); if (BrainBrowser.utils.isFunction(callback)) { callback(volume); } } }); }); }); } function setDefaultColorMap(color_map, cursor_color, callback) { color_map.cursor_color = cursor_color; default_color_map = color_map; viewer.volumes.forEach(function(volume) { volume.color_map = volume.color_map || default_color_map; }); if (BrainBrowser.utils.isFunction(callback)) { callback(color_map); } } function setVolumeColorMap(vol_id, color_map, cursor_color, callback) { color_map.cursor_color = cursor_color; viewer.setVolumeColorMap(vol_id, color_map); if (BrainBrowser.utils.isFunction(callback)) { callback(viewer.volumes[vol_id], color_map); } } function getTemplate(dom_element, vol_id, template_id, viewer_insert_class) { var template = document.getElementById(template_id).innerHTML.replace(/\{\{VOLID\}\}/gm, vol_id); var temp = document.createElement("div"); temp.innerHTML = template; var template_elements = temp.childNodes; var viewer_insert = temp.getElementsByClassName(viewer_insert_class)[0]; var i, count; var node; for (i = 0, count = dom_element.childNodes.length; i < count; i++) { node = dom_element.childNodes[i]; if (node.nodeType === 1) { viewer_insert.appendChild(node); i--; count--; } } return template_elements; } // Create canvases and add mouse interface. function createVolumeDisplay(dom_element, vol_id, volume_description) { var container = document.createElement("div"); var volume = viewer.volumes[vol_id]; var display = VolumeViewer.createDisplay(); var template_options = volume_description.template || {}; var views = volume_description.views || ["xspace", "yspace", "zspace"]; var template; display.propagateEventTo("*", volume); container.classList.add("volume-container"); views.forEach(function(axis_name) { var canvas = document.createElement("canvas"); canvas.width = default_panel_width; canvas.height = default_panel_height; canvas.classList.add("slice-display"); canvas.style.backgroundColor = "#000000"; container.appendChild(canvas); display.setPanel( axis_name, VolumeViewer.createPanel({ volume: volume, volume_id: vol_id, axis: axis_name, canvas: canvas, image_center: { x: canvas.width / 2, y: canvas.height / 2 } }) ); }); if (template_options.element_id && template_options.viewer_insert_class) { template = getTemplate(container, vol_id, template_options.element_id, template_options.viewer_insert_class); if (typeof template_options.complete === "function") { template_options.complete(volume, template); } Array.prototype.forEach.call(template, function(node) { if (node.nodeType === 1) { container.appendChild(node); } }); } /////////////////////////////////// // Mouse Events /////////////////////////////////// (function() { var current_target = null; views.forEach(function(axis_name) { var panel = display.getPanel(axis_name); var canvas = panel.canvas; var last_touch_distance = null; function startDrag(pointer, shift_key, ctrl_key) { if (ctrl_key) { viewer.volumes.forEach(function(volume) { volume.display.forEach(function(panel) { panel.anchor = null; }); }); panel.anchor = { x: pointer.x, y: pointer.y }; } if (!shift_key) { panel.updateVolumePosition(pointer.x, pointer.y); volume.display.forEach(function(other_panel) { if (panel !== other_panel) { other_panel.updateSlice(); } }); if (viewer.synced){ viewer.syncPosition(panel, volume, axis_name); } } panel.updated = true; } function drag(pointer, shift_key) { var drag_delta; if(shift_key) { drag_delta = panel.followPointer(pointer); if (viewer.synced){ viewer.volumes.forEach(function(synced_volume, synced_vol_id) { var synced_panel; if (synced_vol_id !== vol_id) { synced_panel = synced_volume.display.getPanel(axis_name); synced_panel.translateImage(drag_delta.dx, drag_delta.dy); } }); } } else { panel.updateVolumePosition(pointer.x, pointer.y); volume.display.forEach(function(other_panel) { if (panel !== other_panel) { other_panel.updateSlice(); } }); if (viewer.synced){ viewer.syncPosition(panel, volume, axis_name); } } panel.updated = true; } function mouseDrag(event) { if(event.target === current_target) { event.preventDefault(); drag(panel.mouse, event.shiftKey); } } function touchDrag(event) { if(event.target === current_target) { event.preventDefault(); drag(panel.touches[0], panel.touches.length === views.length); } } function mouseDragEnd() { document.removeEventListener("mousemove", mouseDrag, false); document.removeEventListener("mouseup", mouseDragEnd, false); viewer.volumes.forEach(function(volume) { volume.display.forEach(function(panel) { panel.anchor = null; }); }); current_target = null; } function touchDragEnd() { document.removeEventListener("touchmove", touchDrag, false); document.removeEventListener("touchend", touchDragEnd, false); viewer.volumes.forEach(function(volume) { volume.display.forEach(function(panel) { panel.anchor = null; }); }); current_target = null; } function touchZoom(event) { var dx = panel.touches[0].x - panel.touches[1].x; var dy = panel.touches[0].y - panel.touches[1].y; var distance = Math.sqrt(dx * dx + dy * dy); var delta; event.preventDefault(); if (last_touch_distance !== null) { delta = distance - last_touch_distance; zoom(delta * 0.2); } last_touch_distance = distance; } function touchZoomEnd() { document.removeEventListener("touchmove", touchZoom, false); document.removeEventListener("touchend", touchZoomEnd, false); last_touch_distance = null; } canvas.addEventListener("mousedown", function(event) { event.preventDefault(); current_target = event.target; if (viewer.active_panel) { viewer.active_panel.updated = true; } viewer.active_panel = panel; document.addEventListener("mousemove", mouseDrag , false); document.addEventListener("mouseup", mouseDragEnd, false); startDrag(panel.mouse, event.shiftKey, event.ctrlKey); }, false); canvas.addEventListener("touchstart", function(event) { event.preventDefault(); current_target = event.target; if (viewer.active_panel) { viewer.active_panel.updated = true; } viewer.active_panel = panel; if (panel.touches.length === 2) { document.removeEventListener("touchmove", touchDrag, false); document.removeEventListener("touchend", touchDragEnd, false); document.addEventListener("touchmove", touchZoom, false); document.addEventListener("touchend", touchZoomEnd, false); } else { document.removeEventListener("touchmove", touchZoom, false); document.removeEventListener("touchend", touchZoomEnd, false); document.addEventListener("touchmove", touchDrag, false); document.addEventListener("touchend", touchDragEnd, false); startDrag(panel.touches[0], panel.touches.length === 3, true); } }, false); function wheelHandler(event) { event.preventDefault(); zoom(Math.max(-1, Math.min(1, (event.wheelDelta || -event.detail)))); } function zoom(delta) { panel.zoom *= (delta < 0) ? 1/1.05 : 1.05; panel.zoom = Math.max(panel.zoom, 0.25); panel.updateVolumePosition(); panel.updateSlice(); if (viewer.synced){ viewer.volumes.forEach(function(synced_volume, synced_vol_id) { var synced_panel = synced_volume.display.getPanel(axis_name); if (synced_vol_id !== vol_id) { synced_panel.zoom = panel.zoom; synced_panel.updateVolumePosition(); synced_panel.updateSlice(); } }); } } canvas.addEventListener("mousewheel", wheelHandler, false); canvas.addEventListener("DOMMouseScroll", wheelHandler, false); // Dammit Firefox }); })(); viewer.containers[vol_id] = container; /* See if a subsequent volume has already been loaded. If so we want * to be sure that this container is inserted before the subsequent * container. This guarantees the ordering of elements. */ var containers = viewer.containers; var next_id; for (next_id = vol_id + 1; next_id < containers.length; next_id++) { if (next_id in containers) { dom_element.insertBefore(container, containers[next_id]); break; } } if (next_id === containers.length) { dom_element.appendChild(container); } viewer.triggerEvent("volumeuiloaded", { container: container, volume: volume, volume_id: vol_id }); return display; } };
codedsk/hubzero-tool-brains
www/assets/brainbrowser-dev/volume-viewer/modules/loading.js
JavaScript
mit
23,878
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _stringify; function _load_stringify() { return _stringify = _interopRequireDefault(require('babel-runtime/core-js/json/stringify')); } var _promise; function _load_promise() { return _promise = _interopRequireDefault(require('babel-runtime/core-js/promise')); } var _toConsumableArray2; function _load_toConsumableArray() { return _toConsumableArray2 = _interopRequireDefault(require('babel-runtime/helpers/toConsumableArray')); } var _asyncToGenerator2; function _load_asyncToGenerator() { return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator')); } var _keys; function _load_keys() { return _keys = _interopRequireDefault(require('babel-runtime/core-js/object/keys')); } var _executeLifecycleScript; function _load_executeLifecycleScript() { return _executeLifecycleScript = require('./util/execute-lifecycle-script.js'); } var _index; function _load_index() { return _index = _interopRequireDefault(require('./util/normalize-manifest/index.js')); } var _errors; function _load_errors() { return _errors = require('./errors.js'); } var _fs; function _load_fs() { return _fs = _interopRequireWildcard(require('./util/fs.js')); } var _constants; function _load_constants() { return _constants = _interopRequireWildcard(require('./constants.js')); } var _packageConstraintResolver; function _load_packageConstraintResolver() { return _packageConstraintResolver = _interopRequireDefault(require('./package-constraint-resolver.js')); } var _requestManager; function _load_requestManager() { return _requestManager = _interopRequireDefault(require('./util/request-manager.js')); } var _index2; function _load_index2() { return _index2 = require('./registries/index.js'); } var _index3; function _load_index3() { return _index3 = require('./reporters/index.js'); } var _map; function _load_map() { return _map = _interopRequireDefault(require('./util/map.js')); } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const detectIndent = require('detect-indent'); const invariant = require('invariant'); const path = require('path'); function sortObject(object) { const sortedObject = {}; (0, (_keys || _load_keys()).default)(object).sort().forEach(item => { sortedObject[item] = object[item]; }); return sortedObject; } class Config { constructor(reporter) { this.constraintResolver = new (_packageConstraintResolver || _load_packageConstraintResolver()).default(this, reporter); this.requestManager = new (_requestManager || _load_requestManager()).default(reporter); this.reporter = reporter; this._init({}); } // // // // // // // // // // // // Whether we should ignore executing lifecycle scripts // // // // /** * Execute a promise produced by factory if it doesn't exist in our cache with * the associated key. */ getCache(key, factory) { const cached = this.cache[key]; if (cached) { return cached; } return this.cache[key] = factory().catch(err => { this.cache[key] = null; throw err; }); } /** * Get a config option from our yarn config. */ getOption(key) { return this.registries.yarn.getOption(key); } /** * Reduce a list of versions to a single one based on an input range. */ resolveConstraints(versions, range) { return this.constraintResolver.reduce(versions, range); } /** * Initialise config. Fetch registry options, find package roots. */ init() { var _arguments = arguments, _this = this; return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { let opts = _arguments.length > 0 && _arguments[0] !== undefined ? _arguments[0] : {}; _this._init(opts); yield (_fs || _load_fs()).mkdirp(_this.globalFolder); yield (_fs || _load_fs()).mkdirp(_this.linkFolder); _this.linkedModules = []; const linkedModules = yield (_fs || _load_fs()).readdir(_this.linkFolder); for (const dir of linkedModules) { const linkedPath = path.join(_this.linkFolder, dir); if (dir[0] === '@') { var _linkedModules; // it's a scope, not a package const scopedLinked = yield (_fs || _load_fs()).readdir(linkedPath); (_linkedModules = _this.linkedModules).push.apply(_linkedModules, (0, (_toConsumableArray2 || _load_toConsumableArray()).default)(scopedLinked.map(function (scopedDir) { return path.join(dir, scopedDir); }))); } else { _this.linkedModules.push(dir); } } for (const key of (0, (_keys || _load_keys()).default)((_index2 || _load_index2()).registries)) { const Registry = (_index2 || _load_index2()).registries[key]; // instantiate registry const registry = new Registry(_this.cwd, _this.registries, _this.requestManager); yield registry.init(); _this.registries[key] = registry; _this.registryFolders.push(registry.folder); const rootModuleFolder = path.join(_this.cwd, registry.folder); if (_this.rootModuleFolders.indexOf(rootModuleFolder) < 0) { _this.rootModuleFolders.push(rootModuleFolder); } } _this.networkConcurrency = opts.networkConcurrency || Number(_this.getOption('network-concurrency')) || (_constants || _load_constants()).NETWORK_CONCURRENCY; _this.requestManager.setOptions({ userAgent: String(_this.getOption('user-agent')), httpProxy: String(opts.httpProxy || _this.getOption('proxy') || ''), httpsProxy: String(opts.httpsProxy || _this.getOption('https-proxy') || ''), strictSSL: Boolean(_this.getOption('strict-ssl')), ca: Array.prototype.concat(opts.ca || _this.getOption('ca') || []).map(String), cafile: String(opts.cafile || _this.getOption('cafile') || ''), cert: String(opts.cert || _this.getOption('cert') || ''), key: String(opts.key || _this.getOption('key') || ''), networkConcurrency: _this.networkConcurrency }); //init & create cacheFolder, tempFolder _this.cacheFolder = String(opts.cacheFolder || _this.getOption('cache-folder') || (_constants || _load_constants()).MODULE_CACHE_DIRECTORY); _this.tempFolder = opts.tempFolder || path.join(_this.cacheFolder, '.tmp'); yield (_fs || _load_fs()).mkdirp(_this.cacheFolder); yield (_fs || _load_fs()).mkdirp(_this.tempFolder); if (opts.production === 'false') { _this.production = false; } else if (_this.getOption('production') || process.env.NODE_ENV === 'production' && process.env.NPM_CONFIG_PRODUCTION !== 'false' && process.env.YARN_PRODUCTION !== 'false') { _this.production = true; } else { _this.production = !!opts.production; } })(); } _init(opts) { this.rootModuleFolders = []; this.registryFolders = []; this.linkedModules = []; this.registries = (0, (_map || _load_map()).default)(); this.cache = (0, (_map || _load_map()).default)(); this.cwd = opts.cwd || this.cwd || process.cwd(); this.looseSemver = opts.looseSemver == undefined ? true : opts.looseSemver; this.commandName = opts.commandName || ''; this.preferOffline = !!opts.preferOffline; this.modulesFolder = opts.modulesFolder; this.globalFolder = opts.globalFolder || (_constants || _load_constants()).GLOBAL_MODULE_DIRECTORY; this.linkFolder = opts.linkFolder || (_constants || _load_constants()).LINK_REGISTRY_DIRECTORY; this.offline = !!opts.offline; this.binLinks = !!opts.binLinks; this.ignorePlatform = !!opts.ignorePlatform; this.ignoreScripts = !!opts.ignoreScripts; this.requestManager.setOptions({ offline: !!opts.offline && !opts.preferOffline, captureHar: !!opts.captureHar }); if (this.modulesFolder) { this.rootModuleFolders.push(this.modulesFolder); } } /** * Generate an absolute module path. */ generateHardModulePath(pkg, ignoreLocation) { invariant(this.cacheFolder, 'No package root'); invariant(pkg, 'Undefined package'); if (pkg.location && !ignoreLocation) { return pkg.location; } let name = pkg.name; let uid = pkg.uid; if (pkg.registry) { name = `${pkg.registry}-${name}`; } const hash = pkg.remote.hash; if (pkg.version && pkg.version !== pkg.uid) { uid = `${pkg.version}-${uid}`; } else if (hash) { uid += `-${hash}`; } return path.join(this.cacheFolder, `${name}-${uid}`); } /** * Execute lifecycle scripts in the specified directory. Ignoring when the --ignore-scripts flag has been * passed. */ executeLifecycleScript(commandName, cwd) { if (this.ignoreScripts) { return (_promise || _load_promise()).default.resolve(); } else { return (0, (_executeLifecycleScript || _load_executeLifecycleScript()).execFromManifest)(this, commandName, cwd || this.cwd); } } /** * Generate an absolute temporary filename location based on the input filename. */ getTemp(filename) { invariant(this.tempFolder, 'No temp folder'); return path.join(this.tempFolder, filename); } /** * Remote packages may be cached in a file system to be available for offline installation. * Second time the same package needs to be installed it will be loaded from there. * Given a package's filename, return a path in the offline mirror location. */ getOfflineMirrorPath(packageFilename) { let mirrorPath; for (const key of ['npm', 'yarn']) { const registry = this.registries[key]; if (registry == null) { continue; } const registryMirrorPath = registry.config['yarn-offline-mirror']; if (registryMirrorPath == null) { continue; } mirrorPath = registryMirrorPath; } if (mirrorPath == null) { return null; } if (packageFilename == null) { return mirrorPath; } return path.join(mirrorPath, path.basename(packageFilename)); } /** * Checker whether the folder input is a valid module folder. We output a yarn metadata * file when we've successfully setup a folder so use this as a marker. */ isValidModuleDest(dest) { return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { if (!(yield (_fs || _load_fs()).exists(dest))) { return false; } if (!(yield (_fs || _load_fs()).exists(path.join(dest, (_constants || _load_constants()).METADATA_FILENAME)))) { return false; } return true; })(); } /** * Read package metadata and normalized package info. */ readPackageMetadata(dir) { var _this2 = this; return this.getCache(`metadata-${dir}`, (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { const metadata = yield _this2.readJson(path.join(dir, (_constants || _load_constants()).METADATA_FILENAME)); const pkg = yield _this2.readManifest(dir, metadata.registry); return { package: pkg, artifacts: metadata.artifacts || [], hash: metadata.hash, remote: metadata.remote, registry: metadata.registry }; })); } /** * Read normalized package info according yarn-metadata.json * throw an error if package.json was not found */ readManifest(dir, priorityRegistry) { var _arguments2 = arguments, _this3 = this; return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { let isRoot = _arguments2.length > 2 && _arguments2[2] !== undefined ? _arguments2[2] : false; const manifest = yield _this3.maybeReadManifest(dir, priorityRegistry, isRoot); if (manifest) { return manifest; } else { throw new (_errors || _load_errors()).MessageError(_this3.reporter.lang('couldntFindPackagejson', dir), 'ENOENT'); } })(); } /** * try get the manifest file by looking * 1. mainfest file in cache * 2. manifest file in registry */ maybeReadManifest(dir, priorityRegistry) { var _this4 = this; let isRoot = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; return this.getCache(`manifest-${dir}`, (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { const metadataLoc = path.join(dir, (_constants || _load_constants()).METADATA_FILENAME); if (!priorityRegistry && (yield (_fs || _load_fs()).exists(metadataLoc))) { var _ref3 = yield _this4.readJson(metadataLoc); priorityRegistry = _ref3.registry; } if (priorityRegistry) { const file = yield _this4.tryManifest(dir, priorityRegistry, isRoot); if (file) { return file; } } for (const registry of (0, (_keys || _load_keys()).default)((_index2 || _load_index2()).registries)) { if (priorityRegistry === registry) { continue; } const file = yield _this4.tryManifest(dir, registry, isRoot); if (file) { return file; } } return null; })); } /** * Read the root manifest. */ readRootManifest() { return this.readManifest(this.cwd, 'npm', true); } /** * Try and find package info with the input directory and registry. */ tryManifest(dir, registry, isRoot) { var _this5 = this; return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { const filename = (_index2 || _load_index2()).registries[registry].filename; const loc = path.join(dir, filename); if (yield (_fs || _load_fs()).exists(loc)) { const data = yield _this5.readJson(loc); data._registry = registry; data._loc = loc; return (0, (_index || _load_index()).default)(data, dir, _this5, isRoot); } else { return null; } })(); } /** * Description */ getFolder(pkg) { let registryName = pkg._registry; if (!registryName) { const ref = pkg._reference; invariant(ref, 'expected reference'); registryName = ref.registry; } return this.registries[registryName].folder; } /** * Get root manifests. */ getRootManifests() { var _this6 = this; return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { const manifests = {}; for (const registryName of (_index2 || _load_index2()).registryNames) { const registry = (_index2 || _load_index2()).registries[registryName]; const jsonLoc = path.join(_this6.cwd, registry.filename); let object = {}; let exists = false; let indent; if (yield (_fs || _load_fs()).exists(jsonLoc)) { exists = true; const info = yield _this6.readJson(jsonLoc, (_fs || _load_fs()).readJsonAndFile); object = info.object; indent = detectIndent(info.content).indent || undefined; } manifests[registryName] = { loc: jsonLoc, object: object, exists: exists, indent: indent }; } return manifests; })(); } /** * Save root manifests. */ saveRootManifests(manifests) { return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { for (const registryName of (_index2 || _load_index2()).registryNames) { var _manifests$registryNa = manifests[registryName]; const loc = _manifests$registryNa.loc, object = _manifests$registryNa.object, exists = _manifests$registryNa.exists, indent = _manifests$registryNa.indent; if (!exists && !(0, (_keys || _load_keys()).default)(object).length) { continue; } for (const field of (_constants || _load_constants()).DEPENDENCY_TYPES) { if (object[field]) { object[field] = sortObject(object[field]); } } yield (_fs || _load_fs()).writeFilePreservingEol(loc, (0, (_stringify || _load_stringify()).default)(object, null, indent || (_constants || _load_constants()).DEFAULT_INDENT) + '\n'); } })(); } /** * Call the passed factory (defaults to fs.readJson) and rethrow a pretty error message if it was the result * of a syntax error. */ readJson(loc) { var _arguments3 = arguments, _this7 = this; return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { let factory = _arguments3.length > 1 && _arguments3[1] !== undefined ? _arguments3[1] : (_fs || _load_fs()).readJson; try { return yield factory(loc); } catch (err) { if (err instanceof SyntaxError) { throw new (_errors || _load_errors()).MessageError(_this7.reporter.lang('jsonError', loc, err.message)); } else { throw err; } } })(); } static create() { var _arguments4 = arguments; return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { let opts = _arguments4.length > 0 && _arguments4[0] !== undefined ? _arguments4[0] : {}; let reporter = _arguments4.length > 1 && _arguments4[1] !== undefined ? _arguments4[1] : new (_index3 || _load_index3()).NoopReporter(); const config = new Config(reporter); yield config.init(opts); return config; })(); } } exports.default = Config;
rafaeltomesouza/frontend-class1
aula2/a9/linkedin/client/.gradle/yarn/node_modules/yarn/lib-legacy/config.js
JavaScript
mit
17,939
export default class DateHelper { // See tests for desired format. static getFormattedDateTime(date) { return `${date.getMonth() + 1}/${date.getDate()} ${date.getHours()}:${this.padLeadingZero(date.getMinutes())}:${this.padLeadingZero(date.getSeconds())}`; } static padLeadingZero(value) { return value > 9 ? value : `0${value}`; } }
afreix/personal-site
src/utils/dateHelper.js
JavaScript
mit
353
/*! UIkit 3.0.0-rc.8 | http://www.getuikit.com | (c) 2014 - 2017 YOOtheme | MIT License */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('uikit-util')) : typeof define === 'function' && define.amd ? define('uikitlightbox_panel', ['uikit-util'], factory) : (global.UIkitLightbox_panel = factory(global.UIkit.util)); }(this, (function (uikitUtil) { 'use strict'; var Animations = { slide: { show: function(dir) { return [ {transform: translate(dir * -100)}, {transform: translate()} ]; }, percent: function(current) { return translated(current); }, translate: function(percent, dir) { return [ {transform: translate(dir * -100 * percent)}, {transform: translate(dir * 100 * (1 - percent))} ]; } } }; function translated(el) { return Math.abs(uikitUtil.css(el, 'transform').split(',')[4] / el.offsetWidth) || 0; } function translate(value, unit) { if ( value === void 0 ) value = 0; if ( unit === void 0 ) unit = '%'; return ("translateX(" + value + (value ? unit : '') + ")"); // currently not translate3d to support IE, translate3d within translate3d does not work while transitioning } function scale3d(value) { return ("scale3d(" + value + ", " + value + ", 1)"); } var Animations$1 = uikitUtil.assign({}, Animations, { fade: { show: function() { return [ {opacity: 0}, {opacity: 1} ]; }, percent: function(current) { return 1 - uikitUtil.css(current, 'opacity'); }, translate: function(percent) { return [ {opacity: 1 - percent}, {opacity: percent} ]; } }, scale: { show: function() { return [ {opacity: 0, transform: scale3d(1 - .2)}, {opacity: 1, transform: scale3d(1)} ]; }, percent: function(current) { return 1 - uikitUtil.css(current, 'opacity'); }, translate: function(percent) { return [ {opacity: 1 - percent, transform: scale3d(1 - .2 * percent)}, {opacity: percent, transform: scale3d(1 - .2 + .2 * percent)} ]; } } }); var Container = { props: { container: Boolean }, data: { container: true }, computed: { container: function(ref) { var container = ref.container; return container === true && this.$container || container && uikitUtil.$(container); } } }; var Class = { connected: function() { uikitUtil.addClass(this.$el, this.$name); } }; var Togglable = { props: { cls: Boolean, animation: 'list', duration: Number, origin: String, transition: String, queued: Boolean }, data: { cls: false, animation: [false], duration: 200, origin: false, transition: 'linear', queued: false, initProps: { overflow: '', height: '', paddingTop: '', paddingBottom: '', marginTop: '', marginBottom: '' }, hideProps: { overflow: 'hidden', height: 0, paddingTop: 0, paddingBottom: 0, marginTop: 0, marginBottom: 0 } }, computed: { hasAnimation: function(ref) { var animation = ref.animation; return !!animation[0]; }, hasTransition: function(ref) { var animation = ref.animation; return this.hasAnimation && animation[0] === true; } }, methods: { toggleElement: function(targets, show, animate) { var this$1 = this; return new uikitUtil.Promise(function (resolve) { targets = uikitUtil.toNodes(targets); var all = function (targets) { return uikitUtil.Promise.all(targets.map(function (el) { return this$1._toggleElement(el, show, animate); })); }; var toggled = targets.filter(function (el) { return this$1.isToggled(el); }); var untoggled = targets.filter(function (el) { return !uikitUtil.includes(toggled, el); }); var p; if (!this$1.queued || !uikitUtil.isUndefined(animate) || !uikitUtil.isUndefined(show) || !this$1.hasAnimation || targets.length < 2) { p = all(untoggled.concat(toggled)); } else { var body = document.body; var scroll = body.scrollTop; var el = toggled[0]; var inProgress = uikitUtil.Animation.inProgress(el) && uikitUtil.hasClass(el, 'uk-animation-leave') || uikitUtil.Transition.inProgress(el) && el.style.height === '0px'; p = all(toggled); if (!inProgress) { p = p.then(function () { var p = all(untoggled); body.scrollTop = scroll; return p; }); } } p.then(resolve, uikitUtil.noop); }); }, toggleNow: function(targets, show) { var this$1 = this; return new uikitUtil.Promise(function (resolve) { return uikitUtil.Promise.all(uikitUtil.toNodes(targets).map(function (el) { return this$1._toggleElement(el, show, false); })).then(resolve, uikitUtil.noop); }); }, isToggled: function(el) { var nodes = uikitUtil.toNodes(el || this.$el); return this.cls ? uikitUtil.hasClass(nodes, this.cls.split(' ')[0]) : !uikitUtil.hasAttr(nodes, 'hidden'); }, updateAria: function(el) { if (this.cls === false) { uikitUtil.attr(el, 'aria-hidden', !this.isToggled(el)); } }, _toggleElement: function(el, show, animate) { var this$1 = this; show = uikitUtil.isBoolean(show) ? show : uikitUtil.Animation.inProgress(el) ? uikitUtil.hasClass(el, 'uk-animation-leave') : uikitUtil.Transition.inProgress(el) ? el.style.height === '0px' : !this.isToggled(el); if (!uikitUtil.trigger(el, ("before" + (show ? 'show' : 'hide')), [this])) { return uikitUtil.Promise.reject(); } var promise = (animate === false || !this.hasAnimation ? this._toggleImmediate : this.hasTransition ? this._toggleHeight : this._toggleAnimation )(el, show); uikitUtil.trigger(el, show ? 'show' : 'hide', [this]); return promise.then(function () { uikitUtil.trigger(el, show ? 'shown' : 'hidden', [this$1]); this$1.$update(el); }); }, _toggle: function(el, toggled) { if (!el) { return; } var changed; if (this.cls) { changed = uikitUtil.includes(this.cls, ' ') || Boolean(toggled) !== uikitUtil.hasClass(el, this.cls); changed && uikitUtil.toggleClass(el, this.cls, uikitUtil.includes(this.cls, ' ') ? undefined : toggled); } else { changed = Boolean(toggled) === uikitUtil.hasAttr(el, 'hidden'); changed && uikitUtil.attr(el, 'hidden', !toggled ? '' : null); } uikitUtil.$$('[autofocus]', el).some(function (el) { return uikitUtil.isVisible(el) && (el.focus() || true); }); this.updateAria(el); changed && this.$update(el); }, _toggleImmediate: function(el, show) { this._toggle(el, show); return uikitUtil.Promise.resolve(); }, _toggleHeight: function(el, show) { var this$1 = this; var inProgress = uikitUtil.Transition.inProgress(el); var inner = el.hasChildNodes ? uikitUtil.toFloat(uikitUtil.css(el.firstElementChild, 'marginTop')) + uikitUtil.toFloat(uikitUtil.css(el.lastElementChild, 'marginBottom')) : 0; var currentHeight = uikitUtil.isVisible(el) ? uikitUtil.height(el) + (inProgress ? 0 : inner) : 0; uikitUtil.Transition.cancel(el); if (!this.isToggled(el)) { this._toggle(el, true); } uikitUtil.height(el, ''); // Update child components first uikitUtil.fastdom.flush(); var endHeight = uikitUtil.height(el) + (inProgress ? 0 : inner); uikitUtil.height(el, currentHeight); return (show ? uikitUtil.Transition.start(el, uikitUtil.assign({}, this.initProps, {overflow: 'hidden', height: endHeight}), Math.round(this.duration * (1 - currentHeight / endHeight)), this.transition) : uikitUtil.Transition.start(el, this.hideProps, Math.round(this.duration * (currentHeight / endHeight)), this.transition).then(function () { return this$1._toggle(el, false); }) ).then(function () { return uikitUtil.css(el, this$1.initProps); }); }, _toggleAnimation: function(el, show) { var this$1 = this; uikitUtil.Animation.cancel(el); if (show) { this._toggle(el, true); return uikitUtil.Animation.in(el, this.animation[0], this.duration, this.origin); } return uikitUtil.Animation.out(el, this.animation[1] || this.animation[0], this.duration, this.origin).then(function () { return this$1._toggle(el, false); }); } } }; var active; var Modal = { mixins: [Class, Container, Togglable], props: { selPanel: String, selClose: String, escClose: Boolean, bgClose: Boolean, stack: Boolean }, data: { cls: 'uk-open', escClose: true, bgClose: true, overlay: true, stack: false }, computed: { panel: function(ref, $el) { var selPanel = ref.selPanel; return uikitUtil.$(selPanel, $el); }, transitionElement: function() { return this.panel; }, transitionDuration: function() { return uikitUtil.toMs(uikitUtil.css(this.transitionElement, 'transitionDuration')); }, bgClose: function(ref) { var bgClose = ref.bgClose; return bgClose && this.panel; } }, events: [ { name: 'click', delegate: function() { return this.selClose; }, handler: function(e) { e.preventDefault(); this.hide(); } }, { name: 'toggle', self: true, handler: function(e) { if (e.defaultPrevented) { return; } e.preventDefault(); this.toggle(); } }, { name: 'beforeshow', self: true, handler: function(e) { var prev = active && active !== this && active; active = this; if (prev) { if (this.stack) { this.prev = prev; } else { prev.hide().then(this.show); e.preventDefault(); return; } } registerEvents(); } }, { name: 'beforehide', self: true, handler: function() { active = active && active !== this && active || this.prev; if (!active) { deregisterEvents(); } } }, { name: 'show', self: true, handler: function() { if (!uikitUtil.hasClass(document.documentElement, this.clsPage)) { this.scrollbarWidth = uikitUtil.width(window) - uikitUtil.width(document); uikitUtil.css(document.body, 'overflowY', this.scrollbarWidth && this.overlay ? 'scroll' : ''); } uikitUtil.addClass(document.documentElement, this.clsPage); } }, { name: 'hidden', self: true, handler: function() { var this$1 = this; var found; var ref = this; var prev = ref.prev; while (prev) { if (prev.clsPage === this$1.clsPage) { found = true; break; } prev = prev.prev; } if (!found) { uikitUtil.removeClass(document.documentElement, this.clsPage); } !this.prev && uikitUtil.css(document.body, 'overflowY', ''); } } ], methods: { toggle: function() { return this.isToggled() ? this.hide() : this.show(); }, show: function() { if (this.isToggled()) { return uikitUtil.Promise.resolve(); } if (this.container && this.$el.parentNode !== this.container) { uikitUtil.append(this.container, this.$el); this._callConnected(); } return this.toggleNow(this.$el, true); }, hide: function() { return this.isToggled() ? this.toggleNow(this.$el, false) : uikitUtil.Promise.resolve(); }, getActive: function() { return active; }, _toggleImmediate: function(el, show) { var this$1 = this; return new uikitUtil.Promise(function (resolve) { return requestAnimationFrame(function () { this$1._toggle(el, show); if (this$1.transitionDuration) { uikitUtil.once(this$1.transitionElement, 'transitionend', resolve, false, function (e) { return e.target === this$1.transitionElement; }); } else { resolve(); } }); } ); } } }; var events; function registerEvents() { if (events) { return; } events = [ uikitUtil.on(document, 'click', function (ref) { var target = ref.target; var defaultPrevented = ref.defaultPrevented; if (active && active.bgClose && !defaultPrevented && (!active.overlay || uikitUtil.within(target, active.$el)) && !uikitUtil.within(target, active.panel)) { active.hide(); } }), uikitUtil.on(document, 'keydown', function (e) { if (e.keyCode === 27 && active && active.escClose) { e.preventDefault(); active.hide(); } }) ]; } function deregisterEvents() { events && events.forEach(function (unbind) { return unbind(); }); events = null; } function Transitioner(prev, next, dir, ref) { var animation = ref.animation; var easing = ref.easing; var percent = animation.percent; var translate = animation.translate; var show = animation.show; if ( show === void 0 ) show = uikitUtil.noop; var props = show(dir); var deferred = new uikitUtil.Deferred(); return { dir: dir, show: function(duration, percent, linear) { var this$1 = this; if ( percent === void 0 ) percent = 0; var timing = linear ? 'linear' : easing; duration -= Math.round(duration * uikitUtil.clamp(percent, -1, 1)); this.translate(percent); triggerUpdate(next, 'itemin', {percent: percent, duration: duration, timing: timing, dir: dir}); triggerUpdate(prev, 'itemout', {percent: 1 - percent, duration: duration, timing: timing, dir: dir}); uikitUtil.Promise.all([ uikitUtil.Transition.start(next, props[1], duration, timing), uikitUtil.Transition.start(prev, props[0], duration, timing) ]).then(function () { this$1.reset(); deferred.resolve(); }, uikitUtil.noop); return deferred.promise; }, stop: function() { return uikitUtil.Transition.stop([next, prev]); }, cancel: function() { uikitUtil.Transition.cancel([next, prev]); }, reset: function() { for (var prop in props[0]) { uikitUtil.css([next, prev], prop, ''); } }, forward: function(duration, percent) { if ( percent === void 0 ) percent = this.percent(); uikitUtil.Transition.cancel([next, prev]); return this.show(duration, percent, true); }, translate: function(percent) { this.reset(); var props = translate(percent, dir); uikitUtil.css(next, props[1]); uikitUtil.css(prev, props[0]); triggerUpdate(next, 'itemtranslatein', {percent: percent, dir: dir}); triggerUpdate(prev, 'itemtranslateout', {percent: 1 - percent, dir: dir}); }, percent: function() { return percent(prev || next, next, dir); }, getDistance: function() { return prev.offsetWidth; } }; } function triggerUpdate(el, type, data) { uikitUtil.trigger(el, uikitUtil.createEvent(type, false, false, data)); } var SliderAutoplay = { props: { autoplay: Boolean, autoplayInterval: Number, pauseOnHover: Boolean }, data: { autoplay: false, autoplayInterval: 7000, pauseOnHover: true }, connected: function() { this.startAutoplay(); }, disconnected: function() { this.stopAutoplay(); }, events: [ { name: 'visibilitychange', el: document, handler: function() { if (document.hidden) { this.stopAutoplay(); } else { this.startAutoplay(); } } }, { name: uikitUtil.pointerDown, handler: 'stopAutoplay' }, { name: 'mouseenter', filter: function() { return this.autoplay; }, handler: function() { this.isHovering = true; } }, { name: 'mouseleave', filter: function() { return this.autoplay; }, handler: function() { this.isHovering = false; } } ], methods: { startAutoplay: function() { var this$1 = this; this.stopAutoplay(); if (this.autoplay) { this.interval = setInterval( function () { return !(this$1.isHovering && this$1.pauseOnHover) && !this$1.stack.length && this$1.show('next'); }, this.autoplayInterval ); } }, stopAutoplay: function() { if (this.interval) { clearInterval(this.interval); } } } }; var SliderDrag = { data: { threshold: 10, preventCatch: false }, init: function() { var this$1 = this; ['start', 'move', 'end'].forEach(function (key) { var fn = this$1[key]; this$1[key] = function (e) { var pos = uikitUtil.getPos(e).x * (uikitUtil.isRtl ? -1 : 1); this$1.prevPos = pos !== this$1.pos ? this$1.pos : this$1.prevPos; this$1.pos = pos; fn(e); }; }); }, events: [ { name: uikitUtil.pointerDown, delegate: function() { return this.slidesSelector; }, handler: function(e) { if (!uikitUtil.isTouch(e) && hasTextNodesOnly(e.target) || e.button > 0 || this.length < 2 || this.preventCatch ) { return; } this.start(e); } }, { name: 'dragstart', handler: function(e) { e.preventDefault(); } } ], methods: { start: function() { this.drag = this.pos; if (this._transitioner) { this.percent = this._transitioner.percent(); this.drag += this._transitioner.getDistance() * this.percent * this.dir; this._transitioner.translate(this.percent); this._transitioner.cancel(); this.dragging = true; this.stack = []; } else { this.prevIndex = this.index; } this.unbindMove = uikitUtil.on(document, uikitUtil.pointerMove, this.move, {capture: true, passive: false}); uikitUtil.on(window, 'scroll', this.unbindMove); uikitUtil.on(document, uikitUtil.pointerUp, this.end, true); }, move: function(e) { var this$1 = this; var distance = this.pos - this.drag; if (distance === 0 || this.prevPos === this.pos || !this.dragging && Math.abs(distance) < this.threshold) { return; } e.cancelable && e.preventDefault(); this.dragging = true; this.dir = (distance < 0 ? 1 : -1); var ref = this; var slides = ref.slides; var ref$1 = this; var prevIndex = ref$1.prevIndex; var dis = Math.abs(distance); var nextIndex = this.getIndex(prevIndex + this.dir, prevIndex); var width = this._getDistance(prevIndex, nextIndex) || slides[prevIndex].offsetWidth; while (nextIndex !== prevIndex && dis > width) { this$1.drag -= width * this$1.dir; prevIndex = nextIndex; dis -= width; nextIndex = this$1.getIndex(prevIndex + this$1.dir, prevIndex); width = this$1._getDistance(prevIndex, nextIndex) || slides[prevIndex].offsetWidth; } this.percent = dis / width; var prev = slides[prevIndex]; var next = slides[nextIndex]; var changed = this.index !== nextIndex; var edge = prevIndex === nextIndex; var itemShown; [this.index, this.prevIndex].filter(function (i) { return !uikitUtil.includes([nextIndex, prevIndex], i); }).forEach(function (i) { uikitUtil.trigger(slides[i], 'itemhidden', [this$1]); if (edge) { itemShown = true; this$1.prevIndex = prevIndex; } }); if (this.index === prevIndex && this.prevIndex !== prevIndex || itemShown) { uikitUtil.trigger(slides[this.index], 'itemshown', [this]); } if (changed) { this.prevIndex = prevIndex; this.index = nextIndex; !edge && uikitUtil.trigger(prev, 'beforeitemhide', [this]); uikitUtil.trigger(next, 'beforeitemshow', [this]); } this._transitioner = this._translate(Math.abs(this.percent), prev, !edge && next); if (changed) { !edge && uikitUtil.trigger(prev, 'itemhide', [this]); uikitUtil.trigger(next, 'itemshow', [this]); } }, end: function() { uikitUtil.off(window, 'scroll', this.unbindMove); this.unbindMove(); uikitUtil.off(document, uikitUtil.pointerUp, this.end, true); if (this.dragging) { this.dragging = null; if (this.index === this.prevIndex) { this.percent = 1 - this.percent; this.dir *= -1; this._show(false, this.index, true); this._transitioner = null; } else { var dirChange = (uikitUtil.isRtl ? this.dir * (uikitUtil.isRtl ? 1 : -1) : this.dir) < 0 === this.prevPos > this.pos; this.index = dirChange ? this.index : this.prevIndex; if (dirChange) { this.percent = 1 - this.percent; } this.show(this.dir > 0 && !dirChange || this.dir < 0 && dirChange ? 'next' : 'previous', true); } uikitUtil.preventClick(); } this.drag = this.percent = null; } } }; function hasTextNodesOnly(el) { return !el.children.length && el.childNodes.length; } var SliderNav = { data: { selNav: false }, computed: { nav: function(ref, $el) { var selNav = ref.selNav; return uikitUtil.$(selNav, $el); }, navItemSelector: function(ref) { var attrItem = ref.attrItem; return ("[" + attrItem + "],[data-" + attrItem + "]"); }, navItems: function(_, $el) { return uikitUtil.$$(this.navItemSelector, $el); } }, update: [ { write: function() { var this$1 = this; if (this.nav && this.length !== this.nav.children.length) { uikitUtil.html(this.nav, this.slides.map(function (_, i) { return ("<li " + (this$1.attrItem) + "=\"" + i + "\"><a href=\"#\"></a></li>"); }).join('')); } uikitUtil.toggleClass(uikitUtil.$$(this.navItemSelector, this.$el).concat(this.nav), 'uk-hidden', !this.maxIndex); this.updateNav(); }, events: ['load', 'resize'] } ], events: [ { name: 'click', delegate: function() { return this.navItemSelector; }, handler: function(e) { e.preventDefault(); e.current.blur(); this.show(uikitUtil.data(e.current, this.attrItem)); } }, { name: 'itemshow', handler: 'updateNav' } ], methods: { updateNav: function() { var this$1 = this; var i = this.getValidIndex(); this.navItems.forEach(function (el) { var cmd = uikitUtil.data(el, this$1.attrItem); uikitUtil.toggleClass(el, this$1.clsActive, uikitUtil.toNumber(cmd) === i); uikitUtil.toggleClass(el, 'uk-invisible', this$1.finite && (cmd === 'previous' && i === 0 || cmd === 'next' && i >= this$1.maxIndex)); }); } } }; var Slider = { attrs: true, mixins: [SliderAutoplay, SliderDrag, SliderNav], props: { clsActivated: Boolean, easing: String, index: Number, finite: Boolean, velocity: Number }, data: function () { return ({ easing: 'ease', finite: false, velocity: 1, index: 0, stack: [], percent: 0, clsActive: 'uk-active', clsActivated: false, Transitioner: false, transitionOptions: {} }); }, computed: { duration: function(ref, $el) { var velocity = ref.velocity; return speedUp($el.offsetWidth / velocity); }, length: function() { return this.slides.length; }, list: function(ref, $el) { var selList = ref.selList; return uikitUtil.$(selList, $el); }, maxIndex: function() { return this.length - 1; }, slidesSelector: function(ref) { var selList = ref.selList; return (selList + " > *"); }, slides: function() { return uikitUtil.toNodes(this.list.children); } }, events: { itemshown: function() { this.$update(this.list); } }, methods: { show: function(index, force) { var this$1 = this; if ( force === void 0 ) force = false; if (this.dragging || !this.length) { return; } var ref = this; var stack = ref.stack; var queueIndex = force ? 0 : stack.length; var reset = function () { stack.splice(queueIndex, 1); if (stack.length) { this$1.show(stack.shift(), true); } }; stack[force ? 'unshift' : 'push'](index); if (!force && stack.length > 1) { if (stack.length === 2) { this._transitioner.forward(Math.min(this.duration, 200)); } return; } var prevIndex = this.index; var prev = uikitUtil.hasClass(this.slides, this.clsActive) && this.slides[prevIndex]; var nextIndex = this.getIndex(index, this.index); var next = this.slides[nextIndex]; if (prev === next) { reset(); return; } this.dir = getDirection(index, prevIndex); this.prevIndex = prevIndex; this.index = nextIndex; prev && uikitUtil.trigger(prev, 'beforeitemhide', [this]); if (!uikitUtil.trigger(next, 'beforeitemshow', [this, prev])) { this.index = this.prevIndex; reset(); return; } var promise = this._show(prev, next, force).then(function () { prev && uikitUtil.trigger(prev, 'itemhidden', [this$1]); uikitUtil.trigger(next, 'itemshown', [this$1]); return new uikitUtil.Promise(function (resolve) { uikitUtil.fastdom.write(function () { stack.shift(); if (stack.length) { this$1.show(stack.shift(), true); } else { this$1._transitioner = null; } resolve(); }); }); }); prev && uikitUtil.trigger(prev, 'itemhide', [this]); uikitUtil.trigger(next, 'itemshow', [this]); return promise; }, getIndex: function(index, prev) { if ( index === void 0 ) index = this.index; if ( prev === void 0 ) prev = this.index; return uikitUtil.clamp(uikitUtil.getIndex(index, this.slides, prev, this.finite), 0, this.maxIndex); }, getValidIndex: function(index, prevIndex) { if ( index === void 0 ) index = this.index; if ( prevIndex === void 0 ) prevIndex = this.prevIndex; return this.getIndex(index, prevIndex); }, _show: function(prev, next, force) { this._transitioner = this._getTransitioner( prev, next, this.dir, uikitUtil.assign({ easing: force ? next.offsetWidth < 600 ? 'cubic-bezier(0.25, 0.46, 0.45, 0.94)' /* easeOutQuad */ : 'cubic-bezier(0.165, 0.84, 0.44, 1)' /* easeOutQuart */ : this.easing }, this.transitionOptions) ); if (!force && !prev) { this._transitioner.translate(1); return uikitUtil.Promise.resolve(); } var ref = this.stack; var length = ref.length; return this._transitioner[length > 1 ? 'forward' : 'show'](length > 1 ? Math.min(this.duration, 75 + 75 / (length - 1)) : this.duration, this.percent); }, _getDistance: function(prev, next) { return new this._getTransitioner(prev, prev !== next && next).getDistance(); }, _translate: function(percent, prev, next) { if ( prev === void 0 ) prev = this.prevIndex; if ( next === void 0 ) next = this.index; var transitioner = this._getTransitioner(prev !== next ? prev : false, next); transitioner.translate(percent); return transitioner; }, _getTransitioner: function(prev, next, dir, options) { if ( prev === void 0 ) prev = this.prevIndex; if ( next === void 0 ) next = this.index; if ( dir === void 0 ) dir = this.dir || 1; if ( options === void 0 ) options = this.transitionOptions; return new this.Transitioner( uikitUtil.isNumber(prev) ? this.slides[prev] : prev, uikitUtil.isNumber(next) ? this.slides[next] : next, dir * (uikitUtil.isRtl ? -1 : 1), options ); } } }; function getDirection(index, prevIndex) { return index === 'next' ? 1 : index === 'previous' ? -1 : index < prevIndex ? -1 : 1; } function speedUp(x) { return .5 * x + 300; // parabola through (400,500; 600,600; 1800,1200) } var Slideshow = { mixins: [Slider], props: { animation: String }, data: { animation: 'slide', clsActivated: 'uk-transition-active', Animations: Animations, Transitioner: Transitioner }, computed: { animation: function(ref) { var animation = ref.animation; var Animations$$1 = ref.Animations; return uikitUtil.assign(animation in Animations$$1 ? Animations$$1[animation] : Animations$$1.slide, {name: animation}); }, transitionOptions: function() { return {animation: this.animation}; } }, events: { 'itemshow itemhide itemshown itemhidden': function(ref) { var target = ref.target; this.$update(target); }, itemshow: function() { uikitUtil.isNumber(this.prevIndex) && uikitUtil.fastdom.flush(); // iOS 10+ will honor the video.play only if called from a gesture handler }, beforeitemshow: function(ref) { var target = ref.target; uikitUtil.addClass(target, this.clsActive); }, itemshown: function(ref) { var target = ref.target; uikitUtil.addClass(target, this.clsActivated); }, itemhidden: function(ref) { var target = ref.target; uikitUtil.removeClass(target, this.clsActive, this.clsActivated); } } }; var Component = { mixins: [Container, Modal, Togglable, Slideshow], functional: true, props: { delayControls: Number, preload: Number, videoAutoplay: Boolean, template: String }, data: function () { return ({ preload: 1, videoAutoplay: false, delayControls: 3000, items: [], cls: 'uk-open', clsPage: 'uk-lightbox-page', selList: '.uk-lightbox-items', attrItem: 'uk-lightbox-item', selClose: '.uk-close-large', pauseOnHover: false, velocity: 2, Animations: Animations$1, template: "<div class=\"uk-lightbox uk-overflow-hidden\"> <ul class=\"uk-lightbox-items\"></ul> <div class=\"uk-lightbox-toolbar uk-position-top uk-text-right uk-transition-slide-top uk-transition-opaque\"> <button class=\"uk-lightbox-toolbar-icon uk-close-large\" type=\"button\" uk-close></button> </div> <a class=\"uk-lightbox-button uk-position-center-left uk-position-medium uk-transition-fade\" href=\"#\" uk-slidenav-previous uk-lightbox-item=\"previous\"></a> <a class=\"uk-lightbox-button uk-position-center-right uk-position-medium uk-transition-fade\" href=\"#\" uk-slidenav-next uk-lightbox-item=\"next\"></a> <div class=\"uk-lightbox-toolbar uk-lightbox-caption uk-position-bottom uk-text-center uk-transition-slide-bottom uk-transition-opaque\"></div> </div>" }); }, created: function() { var this$1 = this; this.$mount(uikitUtil.append(this.container, this.template)); this.caption = uikitUtil.$('.uk-lightbox-caption', this.$el); this.items.forEach(function () { return uikitUtil.append(this$1.list, '<li></li>'); }); }, events: [ { name: (uikitUtil.pointerMove + " " + uikitUtil.pointerDown + " keydown"), handler: 'showControls' }, { name: 'click', self: true, delegate: function() { return this.slidesSelector; }, handler: function(e) { e.preventDefault(); this.hide(); } }, { name: 'shown', self: true, handler: 'showControls' }, { name: 'hide', self: true, handler: function() { this.hideControls(); uikitUtil.removeClass(this.slides, this.clsActive); uikitUtil.Transition.stop(this.slides); } }, { name: 'keyup', el: document, handler: function(e) { if (!this.isToggled(this.$el)) { return; } switch (e.keyCode) { case 37: this.show('previous'); break; case 39: this.show('next'); break; } } }, { name: 'beforeitemshow', handler: function(e) { if (this.isToggled()) { return; } this.preventCatch = true; e.preventDefault(); this.toggleNow(this.$el, true); this.animation = Animations$1['scale']; uikitUtil.removeClass(e.target, this.clsActive); this.stack.splice(1, 0, this.index); } }, { name: 'itemshow', handler: function(ref) { var this$1 = this; var target = ref.target; var i = uikitUtil.index(target); var ref$1 = this.getItem(i); var caption = ref$1.caption; uikitUtil.css(this.caption, 'display', caption ? '' : 'none'); uikitUtil.html(this.caption, caption); for (var j = 0; j <= this.preload; j++) { this$1.loadItem(this$1.getIndex(i + j)); this$1.loadItem(this$1.getIndex(i - j)); } } }, { name: 'itemshown', handler: function() { this.preventCatch = false; } }, { name: 'itemload', handler: function(_, item) { var this$1 = this; var source = item.source; var type = item.type; var alt = item.alt; this.setItem(item, '<span uk-spinner></span>'); if (!source) { return; } var matches; // Image if (type === 'image' || source.match(/\.(jp(e)?g|png|gif|svg)($|\?)/i)) { uikitUtil.getImage(source).then( function (img) { return this$1.setItem(item, ("<img width=\"" + (img.width) + "\" height=\"" + (img.height) + "\" src=\"" + source + "\" alt=\"" + (alt ? alt : '') + "\">")); }, function () { return this$1.setError(item); } ); // Video } else if (type === 'video' || source.match(/\.(mp4|webm|ogv)($|\?)/i)) { var video = uikitUtil.$(("<video controls playsinline" + (item.poster ? (" poster=\"" + (item.poster) + "\"") : '') + " uk-video=\"" + (this.videoAutoplay) + "\"></video>")); uikitUtil.attr(video, 'src', source); uikitUtil.on(video, 'error', function () { return this$1.setError(item); }); uikitUtil.on(video, 'loadedmetadata', function () { uikitUtil.attr(video, {width: video.videoWidth, height: video.videoHeight}); this$1.setItem(item, video); }); // Iframe } else if (type === 'iframe' || source.match(/\.(html|php)($|\?)/i)) { this.setItem(item, ("<iframe class=\"uk-lightbox-iframe\" src=\"" + source + "\" frameborder=\"0\" allowfullscreen></iframe>")); // YouTube } else if ((matches = source.match(/\/\/.*?youtube(-nocookie)?\.[a-z]+\/watch\?v=([^&\s]+)/) || source.match(/()youtu\.be\/(.*)/))) { var id = matches[2]; var setIframe = function (width, height) { if ( width === void 0 ) width = 640; if ( height === void 0 ) height = 450; return this$1.setItem(item, getIframe(("https://www.youtube" + (matches[1] || '') + ".com/embed/" + id), width, height, this$1.videoAutoplay)); }; uikitUtil.getImage(("https://img.youtube.com/vi/" + id + "/maxresdefault.jpg")).then( function (ref) { var width = ref.width; var height = ref.height; // YouTube default 404 thumb, fall back to low resolution if (width === 120 && height === 90) { uikitUtil.getImage(("https://img.youtube.com/vi/" + id + "/0.jpg")).then( function (ref) { var width = ref.width; var height = ref.height; return setIframe(width, height); }, setIframe ); } else { setIframe(width, height); } }, setIframe ); // Vimeo } else if ((matches = source.match(/(\/\/.*?)vimeo\.[a-z]+\/([0-9]+).*?/))) { uikitUtil.ajax(("https://vimeo.com/api/oembed.json?maxwidth=1920&url=" + (encodeURI(source))), {responseType: 'json', withCredentials: false}) .then( function (ref) { var ref_response = ref.response; var height = ref_response.height; var width = ref_response.width; return this$1.setItem(item, getIframe(("https://player.vimeo.com/video/" + (matches[2])), width, height, this$1.videoAutoplay)); }, function () { return this$1.setError(item); } ); } } } ], methods: { loadItem: function(index) { if ( index === void 0 ) index = this.index; var item = this.getItem(index); if (item.content) { return; } uikitUtil.trigger(this.$el, 'itemload', [item]); }, getItem: function(index) { if ( index === void 0 ) index = this.index; return this.items[index] || {}; }, setItem: function(item, content) { uikitUtil.assign(item, {content: content}); var el = uikitUtil.html(this.slides[this.items.indexOf(item)], content); uikitUtil.trigger(this.$el, 'itemloaded', [this, el]); this.$update(el); }, setError: function(item) { this.setItem(item, '<span uk-icon="icon: bolt; ratio: 2"></span>'); }, showControls: function() { clearTimeout(this.controlsTimer); this.controlsTimer = setTimeout(this.hideControls, this.delayControls); uikitUtil.addClass(this.$el, 'uk-active', 'uk-transition-active'); }, hideControls: function() { uikitUtil.removeClass(this.$el, 'uk-active', 'uk-transition-active'); } } }; function getIframe(src, width, height, autoplay) { return ("<iframe src=\"" + src + "\" width=\"" + width + "\" height=\"" + height + "\" style=\"max-width: 100%; box-sizing: border-box;\" frameborder=\"0\" allowfullscreen uk-video=\"autoplay: " + autoplay + "\" uk-responsive></iframe>"); } /* global UIkit, 'lightboxPanel' */ if (typeof window !== 'undefined' && window.UIkit) { window.UIkit.component('lightboxPanel', Component); } return Component; })));
extend1994/cdnjs
ajax/libs/uikit/3.0.0-rc.8/js/components/lightbox-panel.js
JavaScript
mit
51,570
require('colors'); var moment = require('moment'); module.exports = function() { function _log(text) { var timeStamp = moment().format('D/M/YY HH:mm:ss'); console.log('[bower] '.green, timeStamp.cyan, ' ', text); } function _error(text, exception) { _log(text.red); console.log(exception); } function _logHelp() { console.log([ ' _ _ _', ' _ __ _ _(_)_ ____ _| |_ ___ ___| |__ _____ __ _____ _ _', ' | \'_ \\ \'_| \\ V / _` | _/ -_)___| \'_ \\/ _ \\ V V / -_) \'_|', ' | .__/_| |_|\\_/\\__,_|\\__\\___| |_.__/\\___/\\_/\\_/\\___|_|', ' |_|', 'usage: private-bower [options]', '', 'options:', ' --h --help Print this list and exit.', ' --config Path to the config file (Must be a valid json)' ].join('\n')); } return { log: _log, error: _error, logHelp: _logHelp }; }();
migros/private-bower
lib/infrastructure/logger.js
JavaScript
mit
1,050
/** * @license Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.html or http://ckeditor.com/license */ (function() { function addCombo( editor, comboName, styleType, lang, entries, defaultLabel, styleDefinition, order ) { var config = editor.config; // Gets the list of fonts from the settings. var names = entries.split( ';' ), values = []; // Create style objects for all fonts. var styles = {}; for ( var i = 0; i < names.length; i++ ) { var parts = names[ i ]; if ( parts ) { parts = parts.split( '/' ); var vars = {}, name = names[ i ] = parts[ 0 ]; vars[ styleType ] = values[ i ] = parts[ 1 ] || name; styles[ name ] = new CKEDITOR.style( styleDefinition, vars ); styles[ name ]._.definition.name = name; } else names.splice( i--, 1 ); } editor.ui.addRichCombo( comboName, { label: lang.label, title: lang.panelTitle, toolbar: 'styles,' + order, panel: { css: [ CKEDITOR.skin.getPath( 'editor' ) ].concat( config.contentsCss ), multiSelect: false, attributes: { 'aria-label': lang.panelTitle } }, init: function() { this.startGroup( lang.panelTitle ); for ( var i = 0; i < names.length; i++ ) { var name = names[ i ]; // Add the tag entry to the panel list. this.add( name, styles[ name ].buildPreview(), name ); } }, onClick: function( value ) { editor.focus(); editor.fire( 'saveSnapshot' ); var style = styles[ value ]; editor[ this.getValue() == value ? 'removeStyle' : 'applyStyle' ]( style ); editor.fire( 'saveSnapshot' ); }, onRender: function() { editor.on( 'selectionChange', function( ev ) { var currentValue = this.getValue(); var elementPath = ev.data.path, elements = elementPath.elements; // For each element into the elements path. for ( var i = 0, element; i < elements.length; i++ ) { element = elements[ i ]; // Check if the element is removable by any of // the styles. for ( var value in styles ) { if ( styles[ value ].checkElementMatch( element, true ) ) { if ( value != currentValue ) this.setValue( value ); return; } } } // If no styles match, just empty it. this.setValue( '', defaultLabel ); }, this ); } }); } CKEDITOR.plugins.add( 'font', { requires: 'richcombo', lang: 'af,ar,bg,bn,bs,ca,cs,cy,da,de,el,en-au,en-ca,en-gb,en,eo,es,et,eu,fa,fi,fo,fr-ca,fr,gl,gu,he,hi,hr,hu,is,it,ja,ka,km,ko,ku,lt,lv,mk,mn,ms,nb,nl,no,pl,pt-br,pt,ro,ru,sk,sl,sr-latn,sr,sv,th,tr,ug,uk,vi,zh-cn,zh', // %REMOVE_LINE_CORE% init: function( editor ) { var config = editor.config; addCombo( editor, 'Font', 'family', editor.lang.font, config.font_names, config.font_defaultLabel, config.font_style, 30 ); addCombo( editor, 'FontSize', 'size', editor.lang.font.fontSize, config.fontSize_sizes, config.fontSize_defaultLabel, config.fontSize_style, 40 ); } }); })(); /** * The list of fonts names to be displayed in the Font combo in the toolbar. * Entries are separated by semi-colons (`';'`), while it's possible to have more * than one font for each entry, in the HTML way (separated by comma). * * A display name may be optionally defined by prefixing the entries with the * name and the slash character. For example, `'Arial/Arial, Helvetica, sans-serif'` * will be displayed as `'Arial'` in the list, but will be outputted as * `'Arial, Helvetica, sans-serif'`. * * config.font_names = * 'Arial/Arial, Helvetica, sans-serif;' + * 'Times New Roman/Times New Roman, Times, serif;' + * 'Verdana'; * * config.font_names = 'Arial;Times New Roman;Verdana'; * * @cfg {String} [font_names=see source] * @member CKEDITOR.config */ CKEDITOR.config.font_names = 'Arial/Arial, Helvetica, sans-serif;' + 'Comic Sans MS/Comic Sans MS, cursive;' + 'Courier New/Courier New, Courier, monospace;' + 'Georgia/Georgia, serif;' + 'Lucida Sans Unicode/Lucida Sans Unicode, Lucida Grande, sans-serif;' + 'Tahoma/Tahoma, Geneva, sans-serif;' + 'Times New Roman/Times New Roman, Times, serif;' + 'Trebuchet MS/Trebuchet MS, Helvetica, sans-serif;' + 'Verdana/Verdana, Geneva, sans-serif'; /** * The text to be displayed in the Font combo is none of the available values * matches the current cursor position or text selection. * * // If the default site font is Arial, we may making it more explicit to the end user. * config.font_defaultLabel = 'Arial'; * * @cfg {String} [font_defaultLabel=''] * @member CKEDITOR.config */ CKEDITOR.config.font_defaultLabel = ''; /** * The style definition to be used to apply the font in the text. * * // This is actually the default value for it. * config.font_style = { * element: 'span', * styles: { 'font-family': '#(family)' }, * overrides: [ { element: 'font', attributes: { 'face': null } } ] * }; * * @cfg {Object} [font_style=see example] * @member CKEDITOR.config */ CKEDITOR.config.font_style = { element: 'span', styles: { 'font-family': '#(family)' }, overrides: [ { element: 'font', attributes: { 'face': null } }] }; /** * The list of fonts size to be displayed in the Font Size combo in the * toolbar. Entries are separated by semi-colons (`';'`). * * Any kind of "CSS like" size can be used, like `'12px'`, `'2.3em'`, `'130%'`, * `'larger'` or `'x-small'`. * * A display name may be optionally defined by prefixing the entries with the * name and the slash character. For example, `'Bigger Font/14px'` will be * displayed as `'Bigger Font'` in the list, but will be outputted as `'14px'`. * * config.fontSize_sizes = '16/16px;24/24px;48/48px;'; * * config.fontSize_sizes = '12px;2.3em;130%;larger;x-small'; * * config.fontSize_sizes = '12 Pixels/12px;Big/2.3em;30 Percent More/130%;Bigger/larger;Very Small/x-small'; * * @cfg {String} [fontSize_sizes=see source] * @member CKEDITOR.config */ CKEDITOR.config.fontSize_sizes = '8/8px;9/9px;10/10px;11/11px;12/12px;14/14px;16/16px;18/18px;20/20px;22/22px;24/24px;26/26px;28/28px;36/36px;48/48px;72/72px'; /** * The text to be displayed in the Font Size combo is none of the available * values matches the current cursor position or text selection. * * // If the default site font size is 12px, we may making it more explicit to the end user. * config.fontSize_defaultLabel = '12px'; * * @cfg {String} [fontSize_defaultLabel=''] * @member CKEDITOR.config */ CKEDITOR.config.fontSize_defaultLabel = ''; /** * The style definition to be used to apply the font size in the text. * * // This is actually the default value for it. * config.fontSize_style = { * element: 'span', * styles: { 'font-size': '#(size)' }, * overrides: [ { element :'font', attributes: { 'size': null } } ] * }; * * @cfg {Object} [fontSize_style=see example] * @member CKEDITOR.config */ CKEDITOR.config.fontSize_style = { element: 'span', styles: { 'font-size': '#(size)' }, overrides: [ { element: 'font', attributes: { 'size': null } }] };
bkahlert/com.bkahlert.nebula
src/com/bkahlert/nebula/widgets/composer/html/plugins/font/plugin.js
JavaScript
mit
7,353
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.is = is; // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is function is(x, y) { return x === y && ( // -0 is not +0 x !== 0 || 1 / x === 1 / y) || // both NaN x !== x && y !== y; } //# sourceMappingURL=is.js.map
cdnjs/cdnjs
ajax/libs/vkui/4.27.2/cjs/lib/is.js
JavaScript
mit
349
import React from 'react'; import PropTypes from 'prop-types'; const Select = ({ placeholder, onChange, options, disabled, value, }) => { const renderOptions = arr => arr.map(({ name, id }) => ( <option key={id} value={id}> {name} </option> )); return ( <select disabled={disabled} className="form-control" value={value} onChange={onChange} > <option value="" disabled >{placeholder}</option> {renderOptions(options)} </select> ); }; export default Select; Select.propTypes = { onChange: PropTypes.func.isRequired, options: PropTypes.arrayOf(PropTypes.object).isRequired, disabled: PropTypes.bool, placeholder: PropTypes.string.isRequired, value: PropTypes.string, }; Select.defaultProps = { disabled: false, value: '', };
mccun934/katello
webpack/move_to_pf/Select/Select.js
JavaScript
gpl-2.0
826
tinyMCE.addI18n('sl.modxlink',{ link_desc:"Insert/edit link" });
svyatoslavteterin/belton.by
core/packages/tinymce-4.3.3-pl/modPlugin/46c188883a90c37d912c8b5f16d2bdbd/0/tinymce/jscripts/tiny_mce/plugins/modxlink/langs/sl.js
JavaScript
gpl-2.0
68
/* * Kendo UI Web v2013.3.1119 (http://kendoui.com) * Copyright 2013 Telerik AD. All rights reserved. * * Kendo UI Web commercial licenses may be obtained at * https://www.kendoui.com/purchase/license-agreement/kendo-ui-web-commercial.aspx * If you do not own a commercial license, this file shall be governed by the * GNU General Public License (GPL) version 3. * For GPL requirements, please review: http://www.gnu.org/copyleft/gpl.html */ (function( window, undefined ) { kendo.cultures["qut-GT"] = { name: "qut-GT", numberFormat: { pattern: ["-n"], decimals: 2, ",": ",", ".": ".", groupSize: [3], percent: { pattern: ["-n %","n %"], decimals: 2, ",": ",", ".": ".", groupSize: [3], symbol: "%" }, currency: { pattern: ["($n)","$n"], decimals: 2, ",": ",", ".": ".", groupSize: [3], symbol: "Q" } }, calendars: { standard: { days: { names: ["juq\u0027ij","kaq\u0027ij","oxq\u0027ij","kajq\u0027ij","joq\u0027ij","waqq\u0027ij","wuqq\u0027ij"], namesAbbr: ["juq","kaq","oxq","kajq","joq","waqq","wuqq"], namesShort: ["ju","ka","ox","ka","jo","wa","wu"] }, months: { names: ["nab\u0027e ik\u0027","ukab\u0027 ik\u0027","rox ik\u0027","ukaj ik\u0027","uro\u0027 ik\u0027","uwaq ik\u0027","uwuq ik\u0027","uwajxaq ik\u0027","ub\u0027elej ik\u0027","ulaj ik\u0027","ujulaj ik\u0027","ukab\u0027laj ik\u0027",""], namesAbbr: ["nab\u0027e","ukab","rox","ukaj","uro","uwaq","uwuq","uwajxaq","ub\u0027elej","ulaj","ujulaj","ukab\u0027laj",""] }, AM: ["a.m.","a.m.","A.M."], PM: ["p.m.","p.m.","P.M."], patterns: { d: "dd/MM/yyyy", D: "dddd, dd' de 'MMMM' de 'yyyy", F: "dddd, dd' de 'MMMM' de 'yyyy hh:mm:ss tt", g: "dd/MM/yyyy hh:mm tt", G: "dd/MM/yyyy hh:mm:ss tt", m: "dd MMMM", M: "dd MMMM", s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss", t: "hh:mm tt", T: "hh:mm:ss tt", u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'", y: "MMMM' de 'yyyy", Y: "MMMM' de 'yyyy" }, "/": "/", ":": ":", firstDay: 0 } } } })(this);
hschaen/teamcalbaseball
wp-content/themes/teamcalbaseball/src/js/cultures/kendo.culture.qut-GT.js
JavaScript
gpl-2.0
2,800
/* Distributed under both the W3C Test Suite License [1] and the W3C 3-clause BSD License [2]. To contribute to a W3C Test Suite, see the policies and contribution forms [3]. [1] http://www.w3.org/Consortium/Legal/2008/04-testsuite-license [2] http://www.w3.org/Consortium/Legal/2008/03-bsd-license [3] http://www.w3.org/2004/10/27-testcases */ 'use strict'; const MS_PER_SEC = 1000; // The recommended minimum precision to use for time values[1]. // // [1] https://drafts.csswg.org/web-animations/#precision-of-time-values const TIME_PRECISION = 0.0005; // ms // Allow implementations to substitute an alternative method for comparing // times based on their precision requirements. if (!window.assert_times_equal) { window.assert_times_equal = (actual, expected, description) => { assert_approx_equals(actual, expected, TIME_PRECISION * 2, description); }; } // Allow implementations to substitute an alternative method for comparing // a time value based on its precision requirements with a fixed value. if (!window.assert_time_equals_literal) { window.assert_time_equals_literal = (actual, expected, description) => { if (Math.abs(expected) === Infinity) { assert_equals(actual, expected, description); } else { assert_approx_equals(actual, expected, TIME_PRECISION, description); } } } // creates div element, appends it to the document body and // removes the created element during test cleanup function createDiv(test, doc) { return createElement(test, 'div', doc); } // creates element of given tagName, appends it to the document body and // removes the created element during test cleanup // if tagName is null or undefined, returns div element function createElement(test, tagName, doc) { if (!doc) { doc = document; } const element = doc.createElement(tagName || 'div'); doc.body.appendChild(element); test.add_cleanup(() => { element.remove(); }); return element; } // Creates a style element with the specified rules, appends it to the document // head and removes the created element during test cleanup. // |rules| is an object. For example: // { '@keyframes anim': '' , // '.className': 'animation: anim 100s;' }; // or // { '.className1::before': 'content: ""; width: 0px; transition: all 10s;', // '.className2::before': 'width: 100px;' }; // The object property name could be a keyframes name, or a selector. // The object property value is declarations which are property:value pairs // split by a space. function createStyle(test, rules, doc) { if (!doc) { doc = document; } const extraStyle = doc.createElement('style'); doc.head.appendChild(extraStyle); if (rules) { const sheet = extraStyle.sheet; for (const selector in rules) { sheet.insertRule(`${selector}{${rules[selector]}}`, sheet.cssRules.length); } } test.add_cleanup(() => { extraStyle.remove(); }); } // Create a pseudo element function getPseudoElement(test, type) { createStyle(test, { '@keyframes anim': '', [`.pseudo::${type}`]: 'animation: anim 10s; ' + 'content: \'\';' }); const div = createDiv(test); div.classList.add('pseudo'); const anims = document.getAnimations(); assert_true(anims.length >= 1); const anim = anims[anims.length - 1]; anim.cancel(); return anim.effect.target; } // Cubic bezier with control points (0, 0), (x1, y1), (x2, y2), and (1, 1). function cubicBezier(x1, y1, x2, y2) { const xForT = t => { const omt = 1-t; return 3 * omt * omt * t * x1 + 3 * omt * t * t * x2 + t * t * t; }; const yForT = t => { const omt = 1-t; return 3 * omt * omt * t * y1 + 3 * omt * t * t * y2 + t * t * t; }; const tForX = x => { // Binary subdivision. let mint = 0, maxt = 1; for (let i = 0; i < 30; ++i) { const guesst = (mint + maxt) / 2; const guessx = xForT(guesst); if (x < guessx) { maxt = guesst; } else { mint = guesst; } } return (mint + maxt) / 2; }; return x => { if (x == 0) { return 0; } if (x == 1) { return 1; } return yForT(tForX(x)); }; } function stepEnd(nsteps) { return x => Math.floor(x * nsteps) / nsteps; } function stepStart(nsteps) { return x => { const result = Math.floor(x * nsteps + 1.0) / nsteps; return (result > 1.0) ? 1.0 : result; }; } function framesTiming(nframes) { return x => { const result = Math.floor(x * nframes) / (nframes - 1); return (result > 1.0 && x <= 1.0) ? 1.0 : result; }; } function waitForAnimationFrames(frameCount) { return new Promise(resolve => { function handleFrame() { if (--frameCount <= 0) { resolve(); } else { window.requestAnimationFrame(handleFrame); // wait another frame } } window.requestAnimationFrame(handleFrame); }); } // Continually calls requestAnimationFrame until |minDelay| has elapsed // as recorded using document.timeline.currentTime (i.e. frame time not // wall-clock time). function waitForAnimationFramesWithDelay(minDelay) { const startTime = document.timeline.currentTime; return new Promise(resolve => { (function handleFrame() { if (document.timeline.currentTime - startTime >= minDelay) { resolve(); } else { window.requestAnimationFrame(handleFrame); } }()); }); } // Waits for a requestAnimationFrame callback in the next refresh driver tick. function waitForNextFrame() { const timeAtStart = document.timeline.currentTime; return new Promise(resolve => { window.requestAnimationFrame(() => { if (timeAtStart === document.timeline.currentTime) { window.requestAnimationFrame(resolve); } else { resolve(); } }); }); } // Returns 'matrix()' or 'matrix3d()' function string generated from an array. function createMatrixFromArray(array) { return (array.length == 16 ? 'matrix3d' : 'matrix') + `(${array.join()})`; } // Returns 'matrix3d()' function string equivalent to // 'rotate3d(x, y, z, radian)'. function rotate3dToMatrix3d(x, y, z, radian) { return createMatrixFromArray(rotate3dToMatrix(x, y, z, radian)); } // Returns an array of the 4x4 matrix equivalent to 'rotate3d(x, y, z, radian)'. // https://drafts.csswg.org/css-transforms-2/#Rotate3dDefined function rotate3dToMatrix(x, y, z, radian) { const sc = Math.sin(radian / 2) * Math.cos(radian / 2); const sq = Math.sin(radian / 2) * Math.sin(radian / 2); // Normalize the vector. const length = Math.sqrt(x*x + y*y + z*z); x /= length; y /= length; z /= length; return [ 1 - 2 * (y*y + z*z) * sq, 2 * (x * y * sq + z * sc), 2 * (x * z * sq - y * sc), 0, 2 * (x * y * sq - z * sc), 1 - 2 * (x*x + z*z) * sq, 2 * (y * z * sq + x * sc), 0, 2 * (x * z * sq + y * sc), 2 * (y * z * sq - x * sc), 1 - 2 * (x*x + y*y) * sq, 0, 0, 0, 0, 1 ]; } // Compare matrix string like 'matrix(1, 0, 0, 1, 100, 0)' with tolerances. function assert_matrix_equals(actual, expected, description) { const matrixRegExp = /^matrix(?:3d)*\((.+)\)/; assert_regexp_match(actual, matrixRegExp, 'Actual value is not a matrix') assert_regexp_match(expected, matrixRegExp, 'Expected value is not a matrix'); const actualMatrixArray = actual.match(matrixRegExp)[1].split(',').map(Number); const expectedMatrixArray = expected.match(matrixRegExp)[1].split(',').map(Number); assert_equals(actualMatrixArray.length, expectedMatrixArray.length, `dimension of the matrix: ${description}`); for (let i = 0; i < actualMatrixArray.length; i++) { assert_approx_equals(actualMatrixArray[i], expectedMatrixArray[i], 0.0001, `expected ${expected} but got ${actual}: ${description}`); } } // Compare rotate3d vector like '0 1 0 45deg' with tolerances. function assert_rotate3d_equals(actual, expected, description) { const rotationRegExp =/^((([+-]?\d+(\.+\d+)?\s){3})?\d+(\.+\d+)?)deg/; assert_regexp_match(actual, rotationRegExp, 'Actual value is not a rotate3d vector') assert_regexp_match(expected, rotationRegExp, 'Expected value is not a rotate3d vector'); const actualRotationVector = actual.match(rotationRegExp)[1].split(' ').map(Number); const expectedRotationVector = expected.match(rotationRegExp)[1].split(' ').map(Number); assert_equals(actualRotationVector.length, expectedRotationVector.length, `dimension of the matrix: ${description}`); for (let i = 0; i < actualRotationVector.length; i++) { assert_approx_equals(actualRotationVector[i], expectedRotationVector[i], 0.0001, `expected ${expected} but got ${actual}: ${description}`); } }
danlrobertson/servo
tests/wpt/web-platform-tests/web-animations/testcommon.js
JavaScript
mpl-2.0
8,786
/** * @file list_gallery.js * @brief List-type image gallery * @author NHN (developers@xpressengine.com) **/ (function($){ var listShow = xe.createPlugin('list', { API_SHOW_LIST : function(sender, params) { var srl = params[0], imgs, $zone, i, c, im, scale, w1, w2, h1, h2; imgs = this.cast('GET_IMAGES', [srl]); if(!imgs.length) return; $zone = $('#zone_list_gallery_'+srl).empty(); width = $zone.innerWidth(); for(i=0,c=imgs.length; i < c; i++) { im = imgs[i]; w1 = im.$obj.prop('width'); h1 = im.$obj.prop('height'); if (w1 == 0){ w1 = im.$obj.attr('width'); } if(h1 ==0){ h1 = im.$obj.attr('height'); } if(w1 > width - 25) { w2 = width - 25; scale = w2 / w1; h2 = Math.floor(h1 * scale); w1 = w2; h1 = h2; im.$obj.attr('rel', 'xe_gallery'); } $zone.append(im.$obj); im.$obj.css({width:w1+'px', height:h1, margin:'0 10px', display:'block'}); } } }); var gallery = xe.getApp('Gallery')[0]; if(gallery) gallery.registerPlugin(new listShow); })(jQuery);
daolcms/xdt-ex-core
modules/editor/components/image_gallery/tpl/list_gallery.js
JavaScript
lgpl-2.1
1,049
/*! * Ext JS Library 3.2.1 * Copyright(c) 2006-2010 Ext JS, Inc. * licensing@extjs.com * http://www.extjs.com/license */ Ext.onReady(function(){ // The action var action = new Ext.Action({ text: 'Action 1', handler: function(){ Ext.example.msg('Click','You clicked on "Action 1".'); }, iconCls: 'blist' }); var panel = new Ext.Panel({ title: 'Actions', width:600, height:300, bodyStyle: 'padding:10px;', // lazy inline style tbar: [ action, { // <-- Add the action directly to a toolbar text: 'Action Menu', menu: [action] // <-- Add the action directly to a menu } ], items: [ new Ext.Button(action) // <-- Add the action as a button ], renderTo: Ext.getBody() }); var tb = panel.getTopToolbar(); // Buttons added to the toolbar of the Panel above // to test/demo doing group operations with an action tb.add('->', { text: 'Disable', handler: function(){ action.setDisabled(!action.isDisabled()); this.setText(action.isDisabled() ? 'Enable' : 'Disable'); } }, { text: 'Change Text', handler: function(){ Ext.Msg.prompt('Enter Text', 'Enter new text for Action 1:', function(btn, text){ if(btn == 'ok' && text){ action.setText(text); action.setHandler(function(){ Ext.example.msg('Click','You clicked on "'+text+'".'); }); } }); } }, { text: 'Change Icon', handler: function(){ action.setIconClass(action.getIconClass() == 'blist' ? 'bmenu' : 'blist'); } }); tb.doLayout(); });
DeepLit/WHG
root/static/js/ext/examples/menu/actions.js
JavaScript
apache-2.0
1,908
/* * 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. */ gadgets.i18n = gadgets.i18n || {}; gadgets.i18n.DateTimeConstants = { ERAS:["\u043c.\u044d.\u04e9","\u043c.\u044d."], ERANAMES:["\u043c\u0430\u043d\u0430\u0439 \u044d\u0440\u0438\u043d\u0438\u0439 \u04e9\u043c\u043d\u04e9\u0445","\u043c\u0430\u043d\u0430\u0439 \u044d\u0440\u0438\u043d\u0438\u0439"], NARROWMONTHS:["1","2","3","4","5","6","7","8","9","10","11","12"], MONTHS:["\u0425\u0443\u043b\u0433\u0430\u043d\u0430","\u04ae\u0445\u044d\u0440","\u0411\u0430\u0440","\u0422\u0443\u0443\u043b\u0430\u0439","\u041b\u0443\u0443","\u041c\u043e\u0433\u043e\u0439","\u041c\u043e\u0440\u044c","\u0425\u043e\u043d\u044c","\u0411\u0438\u0447","\u0422\u0430\u0445\u0438\u0430","\u041d\u043e\u0445\u043e\u0439","\u0413\u0430\u0445\u0430\u0439"], SHORTMONTHS:["\u0445\u0443\u043b","\u04af\u0445\u044d","\u0431\u0430\u0440","\u0442\u0443\u0443","\u043b\u0443\u0443","\u043c\u043e\u0433","\u043c\u043e\u0440","\u0445\u043e\u043d","\u0431\u0438\u0447","\u0442\u0430\u0445","\u043d\u043e\u0445","\u0433\u0430\u0445"], WEEKDAYS:["\u043d\u044f\u043c","\u0434\u0430\u0432\u0430\u0430","\u043c\u044f\u0433\u043c\u0430\u0440","\u043b\u0445\u0430\u0433\u0432\u0430","\u043f\u04af\u0440\u044d\u0432","\u0431\u0430\u0430\u0441\u0430\u043d","\u0431\u044f\u043c\u0431\u0430"], SHORTWEEKDAYS:["\u041d\u044f","\u0414\u0430","\u041c\u044f","\u041b\u0445","\u041f\u04af","\u0411\u0430","\u0411\u044f"], NARROWWEEKDAYS:["1","2","3","4","5","6","7"], SHORTQUARTERS:["1/4","2/4","3/4","4/4"], QUARTERS:["\u0434\u04e9\u0440\u04e9\u0432\u043d\u0438\u0439 \u043d\u044d\u0433","\u0434\u04e9\u0440\u04e9\u0432\u043d\u0438\u0439 \u0445\u043e\u0451\u0440","\u0434\u04e9\u0440\u04e9\u0432\u043d\u0438\u0439 \u0433\u0443\u0440\u0430\u0432","\u0434\u04e9\u0440\u04e9\u0432\u043d\u0438\u0439 \u0434\u04e9\u0440\u04e9\u0432"], AMPMS:["AM","PM"], DATEFORMATS:["EEEE, y MMMM dd","y MMMM d","y MMM d","yy/MM/dd"], TIMEFORMATS:["HH:mm:ss zzzz","HH:mm:ss z","HH:mm:ss","HH:mm"], FIRSTDAYOFWEEK: 6, WEEKENDRANGE: [5, 6], FIRSTWEEKCUTOFFDAY: 2 }; gadgets.i18n.DateTimeConstants.STANDALONENARROWMONTHS = gadgets.i18n.DateTimeConstants.NARROWMONTHS; gadgets.i18n.DateTimeConstants.STANDALONEMONTHS = gadgets.i18n.DateTimeConstants.MONTHS; gadgets.i18n.DateTimeConstants.STANDALONESHORTMONTHS = gadgets.i18n.DateTimeConstants.SHORTMONTHS; gadgets.i18n.DateTimeConstants.STANDALONEWEEKDAYS = gadgets.i18n.DateTimeConstants.WEEKDAYS; gadgets.i18n.DateTimeConstants.STANDALONESHORTWEEKDAYS = gadgets.i18n.DateTimeConstants.SHORTWEEKDAYS; gadgets.i18n.DateTimeConstants.STANDALONENARROWWEEKDAYS = gadgets.i18n.DateTimeConstants.NARROWWEEKDAYS;
vohtaski/moodle-shindig
features/src/main/javascript/features/i18n/data/DateTimeConstants__mn_Mong_CN.js
JavaScript
apache-2.0
3,426
// Copyright (c) 2012 Ecma International. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- es5id: 15.2.3.10-3-2 description: > Object.preventExtensions - indexed properties cannot be added into the returned object includes: [propertyHelper.js] ---*/ var obj = {}; assert(Object.isExtensible(obj)); Object.preventExtensions(obj); assert(!Object.isExtensible(obj)); verifyNotWritable(obj, "0", "nocheck"); assert(!obj.hasOwnProperty("0"));
sebastienros/jint
Jint.Tests.Test262/test/built-ins/Object/preventExtensions/15.2.3.10-3-2.js
JavaScript
bsd-2-clause
501
/** * Uploader.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 */ /** * Upload blobs or blob infos to the specified URL or handler. * * @private * @class tinymce.file.Uploader * @example * var uploader = new Uploader({ * url: '/upload.php', * basePath: '/base/path', * credentials: true, * handler: function(data, success, failure) { * ... * } * }); * * uploader.upload(blobInfos).then(function(result) { * ... * }); */ define("tinymce/file/Uploader", [ "tinymce/util/Promise", "tinymce/util/Tools", "tinymce/util/Fun" ], function(Promise, Tools, Fun) { return function(uploadStatus, settings) { var pendingPromises = {}; function filename(blobInfo) { var ext, extensions; extensions = { 'image/jpeg': 'jpg', 'image/jpg': 'jpg', 'image/gif': 'gif', 'image/png': 'png' }; ext = extensions[blobInfo.blob().type.toLowerCase()] || 'dat'; return blobInfo.filename() + '.' + ext; } function pathJoin(path1, path2) { if (path1) { return path1.replace(/\/$/, '') + '/' + path2.replace(/^\//, ''); } return path2; } function blobInfoToData(blobInfo) { return { id: blobInfo.id, blob: blobInfo.blob, base64: blobInfo.base64, filename: Fun.constant(filename(blobInfo)) }; } function defaultHandler(blobInfo, success, failure, progress) { var xhr, formData; xhr = new XMLHttpRequest(); xhr.open('POST', settings.url); xhr.withCredentials = settings.credentials; xhr.upload.onprogress = function(e) { progress(e.loaded / e.total * 100); }; xhr.onerror = function() { failure("Image upload failed due to a XHR Transport error. Code: " + xhr.status); }; xhr.onload = function() { var json; if (xhr.status != 200) { failure("HTTP Error: " + xhr.status); return; } json = JSON.parse(xhr.responseText); if (!json || typeof json.location != "string") { failure("Invalid JSON: " + xhr.responseText); return; } success(pathJoin(settings.basePath, json.location)); }; formData = new FormData(); formData.append('file', blobInfo.blob(), blobInfo.filename()); xhr.send(formData); } function noUpload() { return new Promise(function(resolve) { resolve([]); }); } function handlerSuccess(blobInfo, url) { return { url: url, blobInfo: blobInfo, status: true }; } function handlerFailure(blobInfo, error) { return { url: '', blobInfo: blobInfo, status: false, error: error }; } function resolvePending(blobUri, result) { Tools.each(pendingPromises[blobUri], function(resolve) { resolve(result); }); delete pendingPromises[blobUri]; } function uploadBlobInfo(blobInfo, handler, openNotification) { uploadStatus.markPending(blobInfo.blobUri()); return new Promise(function(resolve) { var notification, progress; var noop = function() { }; try { var closeNotification = function() { if (notification) { notification.close(); progress = noop; // Once it's closed it's closed } }; var success = function(url) { closeNotification(); uploadStatus.markUploaded(blobInfo.blobUri(), url); resolvePending(blobInfo.blobUri(), handlerSuccess(blobInfo, url)); resolve(handlerSuccess(blobInfo, url)); }; var failure = function(error) { closeNotification(); uploadStatus.removeFailed(blobInfo.blobUri()); resolvePending(blobInfo.blobUri(), handlerFailure(blobInfo, error)); resolve(handlerFailure(blobInfo, error)); }; progress = function(percent) { if (percent < 0 || percent > 100) { return; } if (!notification) { notification = openNotification(); } notification.progressBar.value(percent); }; handler(blobInfoToData(blobInfo), success, failure, progress); } catch (ex) { resolve(handlerFailure(blobInfo, ex.message)); } }); } function isDefaultHandler(handler) { return handler === defaultHandler; } function pendingUploadBlobInfo(blobInfo) { var blobUri = blobInfo.blobUri(); return new Promise(function(resolve) { pendingPromises[blobUri] = pendingPromises[blobUri] || []; pendingPromises[blobUri].push(resolve); }); } function uploadBlobs(blobInfos, openNotification) { blobInfos = Tools.grep(blobInfos, function(blobInfo) { return !uploadStatus.isUploaded(blobInfo.blobUri()); }); return Promise.all(Tools.map(blobInfos, function(blobInfo) { return uploadStatus.isPending(blobInfo.blobUri()) ? pendingUploadBlobInfo(blobInfo) : uploadBlobInfo(blobInfo, settings.handler, openNotification); })); } function upload(blobInfos, openNotification) { return (!settings.url && isDefaultHandler(settings.handler)) ? noUpload() : uploadBlobs(blobInfos, openNotification); } settings = Tools.extend({ credentials: false, // We are adding a notify argument to this (at the moment, until it doesn't work) handler: defaultHandler }, settings); return { upload: upload }; }; });
oncebuilder/OnceBuilder
libs/tinymce/js/tinymce/classes/file/Uploader.js
JavaScript
mit
5,322
require('traceur'); var System = require('../dist/es6-module-loader.src'); System.parser = 'traceur'; module.exports = { Loader: global.LoaderPolyfill, System: System };
AbdulBasitBashir/learn-angular2
step9_gulp_router/node_modules/es6-module-loader/lib/index-traceur.js
JavaScript
mit
177
import 'ember-material-lite/extensions/tooltip'; export function initialize(/* container, application */) { // application.inject('route', 'foo', 'service:foo'); } export default { name: 'material-lite-extensions', initialize };
leoeuclids/ember-material-lite
addon/initializers/material-lite-extensions.js
JavaScript
mit
237
/* BulagaJS - v1.0.0 - 2017-02-23 * https://github.com/juvarabrera/bulagajs * * Copyright (c) 2017 Juvar Abrera; * Licensed under the MIT license */ "use strict"; $.fn.bulaga = function(options) { function Bulaga(el, options) { var obj = this; this.el = el; if(options == undefined) options = {}; this.options = options; var done = false; var DEFAULT_OPTIONS = { "animation": "SLIDE_UP", "duration": 500, "position": .25, "callback": false, "bounce": false, "distance": 100, "base": false, "repeat": false }; this.ready = function() { this.el.css("opacity", "0"); for(var i in DEFAULT_OPTIONS) { if(!this.options.hasOwnProperty(i)) this.options[i] = DEFAULT_OPTIONS[i]; } if(!this.animate.hasOwnProperty(this.options.animation)) this.options.animation = DEFAULT_OPTIONS.animation; $(window).scroll(function() { obj.checkScroll(); }).scroll(); }; this.checkScroll = function() { var oP = this.el.offset().top, sH = $(window).outerHeight(), pos = $(window).scrollTop(); if(pos >= oP - sH + parseInt(sH * parseFloat(this.options.position)) && !done) { done = true; this.animate[this.options.animation](); } if(pos + sH < oP && this.options.repeat) { done = false; this.el.css("opacity", "0"); } }; this.callback = function() { if(this.options.callback) this.options.callback(); }; this.animate = { "FADE_IN": function() { obj.el.animate({"opacity": "1"}, parseInt(obj.options.duration), obj.callback()); }, "SLIDE_RIGHT": function() { obj.slide("right"); }, "SLIDE_LEFT": function() { obj.slide("left"); }, "SLIDE_UP": function() { obj.slide("top"); }, "SLIDE_DOWN": function() { obj.slide("bottom"); } }; this.slide = function(direction) { var css = {}; if(obj.el.css("position") == "relative" || obj.el.css("position") == "static") css["position"] = "relative"; else if(obj.options.base) direction = obj.options.base; var original = (obj.el.css(direction) == "auto") ? 0 : parseFloat(obj.el.css(direction).slice(0, -2)); css[direction] = (obj.options.distance+parseFloat(original))+"px"; obj.el.css(css); css = {"opacity": "1"}; css[direction] = original-((obj.options.bounce) ? 20 : 0)+"px"; obj.el.animate(css, obj.options.duration, function() { if(obj.options.bounce) { css = {}; css[direction] = original+"px"; obj.el.animate(css, obj.options.duration); } }); }; this.ready(); } var b = new Bulaga($(this), options); return this; };
gdgphilippines/boomerang
public/assets/scripts/bulaga-1.0.0.js
JavaScript
mit
2,620
(function(hello) { hello.init({ windows: { name: 'Windows live', // REF: http://msdn.microsoft.com/en-us/library/hh243641.aspx oauth: { version: 2, auth: 'https://login.live.com/oauth20_authorize.srf', grant: 'https://login.live.com/oauth20_token.srf' }, // Refresh the access_token once expired refresh: true, logout: function() { return 'http://login.live.com/oauth20_logout.srf?ts=' + (new Date()).getTime(); }, // Authorization scopes scope: { basic: 'wl.signin,wl.basic', email: 'wl.emails', birthday: 'wl.birthday', events: 'wl.calendars', photos: 'wl.photos', videos: 'wl.photos', friends: 'wl.contacts_emails', files: 'wl.skydrive', publish: 'wl.share', publish_files: 'wl.skydrive_update', create_event: 'wl.calendars_update,wl.events_create', offline_access: 'wl.offline_access' }, // API base URL base: 'https://apis.live.net/v5.0/', // Map GET requests get: { // Friends me: 'me', 'me/friends': 'me/friends', 'me/following': 'me/contacts', 'me/followers': 'me/friends', 'me/contacts': 'me/contacts', 'me/albums': 'me/albums', // Include the data[id] in the path 'me/album': '@{id}/files', 'me/photo': '@{id}', // Files 'me/files': '@{parent|me/skydrive}/files', 'me/folders': '@{id|me/skydrive}/files', 'me/folder': '@{id|me/skydrive}/files' }, // Map POST requests post: { 'me/albums': 'me/albums', 'me/album': '@{id}/files/', 'me/folders': '@{id|me/skydrive/}', 'me/files': '@{parent|me/skydrive}/files' }, // Map DELETE requests del: { // Include the data[id] in the path 'me/album': '@{id}', 'me/photo': '@{id}', 'me/folder': '@{id}', 'me/files': '@{id}' }, wrap: { me: formatUser, 'me/friends': formatFriends, 'me/contacts': formatFriends, 'me/followers': formatFriends, 'me/following': formatFriends, 'me/albums': formatAlbums, 'me/photos': formatDefault, 'default': formatDefault }, xhr: function(p) { if (p.method !== 'get' && p.method !== 'delete' && !hello.utils.hasBinary(p.data)) { // Does this have a data-uri to upload as a file? if (typeof (p.data.file) === 'string') { p.data.file = hello.utils.toBlob(p.data.file); } else { p.data = JSON.stringify(p.data); p.headers = { 'Content-Type': 'application/json' }; } } return true; }, jsonp: function(p) { if (p.method !== 'get' && !hello.utils.hasBinary(p.data)) { p.data.method = p.method; p.method = 'get'; } } } }); function formatDefault(o) { if ('data' in o) { o.data.forEach(function(d) { if (d.picture) { d.thumbnail = d.picture; } if (d.images) { d.pictures = d.images .map(formatImage) .sort(function(a, b) { return a.width - b.width; }); } }); } return o; } function formatImage(image) { return { width: image.width, height: image.height, source: image.source }; } function formatAlbums(o) { if ('data' in o) { o.data.forEach(function(d) { d.photos = d.files = 'https://apis.live.net/v5.0/' + d.id + '/photos'; }); } return o; } function formatUser(o, headers, req) { if (o.id) { var token = req.query.access_token; if (o.emails) { o.email = o.emails.preferred; } // If this is not an non-network friend if (o.is_friend !== false) { // Use the id of the user_id if available var id = (o.user_id || o.id); o.thumbnail = o.picture = 'https://apis.live.net/v5.0/' + id + '/picture?access_token=' + token; } } return o; } function formatFriends(o, headers, req) { if ('data' in o) { o.data.forEach(function(d) { formatUser(d, headers, req); }); } return o; } })(hello);
arunreddy143/helloJs
src/modules/windows.js
JavaScript
mit
3,904
/* MIT https://github.com/kenwheeler/cash */ (function(){ 'use strict';var e=document,g=window,h=Array.prototype,l=h.filter,m=h.indexOf,aa=h.map,p=h.push,q=h.reverse,r=h.slice,ba=/^#[\w-]*$/,ca=/^\.[\w-]*$/,da=/<.+>/,ea=/^\w+$/;function t(a,b){void 0===b&&(b=e);return ca.test(a)?b.getElementsByClassName(a.slice(1)):ea.test(a)?b.getElementsByTagName(a):b.querySelectorAll(a)} function u(a,b){if(a){if(a.__cash)return a;var c=a;if(v(a)){if(c=ba.test(a)?e.getElementById(a.slice(1)):da.test(a)?w(a):t(a,b),!c)return}else if(x(a))return this.ready(a);if(c.nodeType||c===g)c=[c];this.length=c.length;a=0;for(b=this.length;a<b;a++)this[a]=c[a]}}function y(a,b){return new u(a,b)}var z=y.fn=y.prototype=u.prototype={constructor:y,__cash:!0,length:0,splice:h.splice};z.get=function(a){return void 0===a?r.call(this):this[0>a?a+this.length:a]};z.eq=function(a){return y(this.get(a))}; z.first=function(){return this.eq(0)};z.last=function(){return this.eq(-1)};z.map=function(a){return y(aa.call(this,function(b,c){return a.call(b,c,b)}))};z.slice=function(){return y(r.apply(this,arguments))};var fa=/(?:^\w|[A-Z]|\b\w)/g,ha=/[\s-_]+/g;function A(a){return a.replace(fa,function(a,c){return a[c?"toUpperCase":"toLowerCase"]()}).replace(ha,"")}y.camelCase=A;function B(a,b){for(var c=0,d=a.length;c<d&&!1!==b.call(a[c],a[c],c,a);c++);}y.each=B; z.each=function(a){B(this,function(b,c){return a.call(b,c,b)});return this};z.removeProp=function(a){return this.each(function(b,c){delete c[a]})};g.cash=g.$=y;y.extend=z.extend=function(a){void 0===a&&(a=this);for(var b=arguments,c=b.length,d=2>c?0:1;d<c;d++)for(var f in b[d])a[f]=b[d][f];return a};var C=1;y.guid=C;function D(a,b){var c=a&&(a.matches||a.webkitMatchesSelector||a.mozMatchesSelector||a.msMatchesSelector||a.oMatchesSelector);return!!c&&c.call(a,b)}y.matches=D; function x(a){return"function"===typeof a}y.isFunction=x;function v(a){return"string"===typeof a}y.isString=v;function E(a){return!isNaN(parseFloat(a))&&isFinite(a)}y.isNumeric=E;var F=Array.isArray;y.isArray=F;z.prop=function(a,b){if(a){if(v(a))return 2>arguments.length?this[0]&&this[0][a]:this.each(function(c,f){f[a]=b});for(var c in a)this.prop(c,a[c]);return this}};function H(a){return v(a)?function(b,c){return D(c,a)}:a.__cash?function(b,c){return a.is(c)}:function(a,c,d){return c===d}} z.filter=function(a){if(!a)return y();var b=x(a)?a:H(a);return y(l.call(this,function(c,d){return b.call(c,d,c,a)}))};var ia=/\S+/g;function I(a){return v(a)?a.match(ia)||[]:[]}z.hasClass=function(a){var b=I(a),c=!1;b.length&&this.each(function(a,f){c=f.classList.contains(b[0]);return!c});return c};z.removeAttr=function(a){var b=I(a);return b.length?this.each(function(a,d){B(b,function(a){d.removeAttribute(a)})}):this}; z.attr=function(a,b){if(a){if(v(a)){if(2>arguments.length){if(!this[0])return;var c=this[0].getAttribute(a);return null===c?void 0:c}return null===b?this.removeAttr(a):this.each(function(c,f){f.setAttribute(a,b)})}for(c in a)this.attr(c,a[c]);return this}};z.toggleClass=function(a,b){var c=I(a),d=void 0!==b;return c.length?this.each(function(a,k){B(c,function(a){d?b?k.classList.add(a):k.classList.remove(a):k.classList.toggle(a)})}):this};z.addClass=function(a){return this.toggleClass(a,!0)}; z.removeClass=function(a){return arguments.length?this.toggleClass(a,!1):this.attr("class","")};var J;function w(a){if(!J){J=e.implementation.createHTMLDocument("");var b=J.createElement("base");b.href=e.location.href;J.head.appendChild(b)}v(a)||(a="");J.body.innerHTML=a;return r.call(J.body.childNodes)}y.parseHTML=w;function K(a){return a.filter(function(a,c,d){return d.indexOf(a)===c})}y.unique=K;z.add=function(a,b){return y(K(this.get().concat(y(a,b).get())))}; function L(a,b,c){if(1===a.nodeType)return a=g.getComputedStyle(a,null),b?c?a.getPropertyValue(b):a[b]:a}function M(a,b){return parseInt(L(a,b),10)||0}var N=/^--/,O={},ja=e.createElement("div").style,ka=["webkit","moz","ms","o"];function P(a,b){void 0===b&&(b=N.test(a));if(b)return a;if(!O[a]){b=A(a);var c=""+b.charAt(0).toUpperCase()+b.slice(1);b=(b+" "+ka.join(c+" ")+c).split(" ");B(b,function(b){if(b in ja)return O[a]=b,!1})}return O[a]}y.prefixedProp=P; var la={animationIterationCount:!0,columnCount:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0};function Q(a,b,c){void 0===c&&(c=N.test(a));return c||la[a]||!E(b)?b:b+"px"}z.css=function(a,b){if(v(a)){var c=N.test(a);a=P(a,c);if(2>arguments.length)return this[0]&&L(this[0],a,c);if(!a)return this;b=Q(a,b,c);return this.each(function(d,k){1===k.nodeType&&(c?k.style.setProperty(a,b):k.style[a]=b)})}for(var d in a)this.css(d,a[d]);return this}; var ma=/^data-(.*)/;y.hasData=function(a){return"__cashData"in a};function R(a){return a.__cashData=a.__cashData||{}}function S(a,b){var c=R(a);if(b){if(!(b in c)&&(a=a.dataset?a.dataset[b]||a.dataset[A(b)]:y(a).attr("data-"+b),void 0!==a)){try{a=JSON.parse(a)}catch(d){}c[b]=a}return c[b]}return c} z.data=function(a,b){var c=this;if(!a){if(!this[0])return;B(this[0].attributes,function(a){(a=a.name.match(ma))&&c.data(a[1])});return S(this[0])}if(v(a))return void 0===b?this[0]&&S(this[0],a):this.each(function(c,d){R(d)[a]=b});for(var d in a)this.data(d,a[d]);return this};z.removeData=function(a){return this.each(function(b,c){void 0===a?delete c.__cashData:delete R(c)[a]})}; function T(a,b){return M(a,"border"+(b?"Left":"Top")+"Width")+M(a,"padding"+(b?"Left":"Top"))+M(a,"padding"+(b?"Right":"Bottom"))+M(a,"border"+(b?"Right":"Bottom")+"Width")}B(["Width","Height"],function(a){z["inner"+a]=function(){return this[0]&&this[0]["client"+a]}}); B(["width","height"],function(a,b){z[a]=function(c){if(!this[0])return void 0===c?void 0:this;if(!arguments.length)return this[0].getBoundingClientRect()[a]-T(this[0],!b);c=parseInt(c,10);return this.each(function(d,f){1===f.nodeType&&(d=L(f,"boxSizing"),f.style[a]=Q(a,c+("border-box"===d?T(f,!b):0)))})}});B(["Width","Height"],function(a,b){z["outer"+a]=function(c){if(this[0])return this[0]["offset"+a]+(c?M(this[0],"margin"+(b?"Top":"Left"))+M(this[0],"margin"+(b?"Bottom":"Right")):0)}}); function U(a,b){for(var c=0,d=b.length;c<d;c++)if(0>a.indexOf(b[c]))return!1;return!0}function na(a,b,c){B(a[c],function(a){b.removeEventListener(c,a[1])});delete a[c]}function oa(a,b,c,d){d.guid=d.guid||C++;var f=a.__cashEvents=a.__cashEvents||{};f[b]=f[b]||[];f[b].push([c,d]);a.addEventListener(b,d)}function V(a){a=a.split(".");return[a[0],a.slice(1).sort()]} function W(a,b,c,d){var f=a.__cashEvents=a.__cashEvents||{};if(b){var k=f[b];k&&(d&&(d.guid=d.guid||C++),f[b]=k.filter(function(f){var k=f[0];f=f[1];if(d&&f.guid!==d.guid||!U(k,c))return!0;a.removeEventListener(b,f)}))}else if(c&&c.length)for(b in f)W(a,b,c,d);else for(b in f)na(f,a,b)}z.off=function(a,b){var c=this;void 0===a?this.each(function(a,b){return W(b)}):B(I(a),function(a){a=V(a);var d=a[0],k=a[1];c.each(function(a,c){return W(c,d,k,b)})});return this}; z.on=function(a,b,c,d){var f=this;if(!v(a)){for(var k in a)this.on(k,b,a[k]);return this}x(b)&&(c=b,b=!1);B(I(a),function(a){a=V(a);var k=a[0],G=a[1];f.each(function(a,f){a=function pa(a){if(!a.namespace||U(G,a.namespace.split("."))){var n=f;if(b)for(n=a.target;!D(n,b);){if(n===f)return;n=n.parentNode;if(!n)return}a.namespace=a.namespace||"";n=c.call(n,a,a.data);d&&W(f,k,G,pa);!1===n&&(a.preventDefault(),a.stopPropagation())}};a.guid=c.guid=c.guid||C++;oa(f,k,G,a)})});return this}; z.one=function(a,b,c){return this.on(a,b,c,!0)};z.ready=function(a){function b(){return a(y)}"loading"!==e.readyState?setTimeout(b):e.addEventListener("DOMContentLoaded",b);return this};z.trigger=function(a,b){var c=a;if(v(a)){var d=V(a);a=d[0];d=d[1];c=e.createEvent("HTMLEvents");c.initEvent(a,!0,!0);c.namespace=d.join(".")}c.data=b;return this.each(function(a,b){b.dispatchEvent(c)})}; function qa(a){var b=[];B(a.options,function(a){!a.selected||a.disabled||a.parentNode.disabled||b.push(a.value)});return b}var ra=/select-one/i,sa=/select-multiple/i;function X(a){var b=a.type;return ra.test(b)?0>a.selectedIndex?null:a.options[a.selectedIndex].value:sa.test(b)?qa(a):a.value}var ta=/%20/g,ua=/file|reset|submit|button|image/i,va=/radio|checkbox/i; z.serialize=function(){var a="";this.each(function(b,c){B(c.elements||[c],function(b){if(!b.disabled&&b.name&&"FIELDSET"!==b.tagName&&!ua.test(b.type)&&(!va.test(b.type)||b.checked)){var c=X(b);void 0!==c&&(c=F(c)?c:[c],B(c,function(c){var d=a;c="&"+encodeURIComponent(b.name)+"="+encodeURIComponent(c).replace(ta,"+");a=d+c}))}})});return a.substr(1)};z.val=function(a){return void 0===a?this[0]&&X(this[0]):this.each(function(b,c){c.value=a})};z.clone=function(){return this.map(function(a,b){return b.cloneNode(!0)})}; z.detach=function(){return this.each(function(a,b){b.parentNode&&b.parentNode.removeChild(b)})};function Y(a,b,c){var d=v(b);!d&&b.length?B(b,function(b){return Y(a,b,c)}):B(a,d?function(a){a.insertAdjacentHTML(c?"afterbegin":"beforeend",b)}:function(a,d){d=d?b.cloneNode(!0):b;c?a.insertBefore(d,a.childNodes[0]):a.appendChild(d)})}z.append=function(){var a=this;B(arguments,function(b){Y(a,b)});return this};z.appendTo=function(a){Y(y(a),this);return this}; z.html=function(a){if(void 0===a)return this[0]&&this[0].innerHTML;var b=a.nodeType?a[0].outerHTML:a;return this.each(function(a,d){d.innerHTML=b})};z.empty=function(){return this.html("")};z.insertAfter=function(a){var b=this;y(a).each(function(a,d){var c=d.parentNode;b.each(function(b,f){c.insertBefore(a?f.cloneNode(!0):f,d.nextSibling)})});return this};z.after=function(){var a=this;B(q.apply(arguments),function(b){q.apply(y(b).slice()).insertAfter(a)});return this}; z.insertBefore=function(a){var b=this;y(a).each(function(a,d){var c=d.parentNode;b.each(function(b,f){c.insertBefore(a?f.cloneNode(!0):f,d)})});return this};z.before=function(){var a=this;B(arguments,function(b){y(b).insertBefore(a)});return this};z.prepend=function(){var a=this;B(arguments,function(b){Y(a,b,!0)});return this};z.prependTo=function(a){Y(y(a),q.apply(this.slice()),!0);return this};z.remove=function(){return this.detach().off()}; z.replaceWith=function(a){var b=this;return this.each(function(c,d){if(c=d.parentNode){var f=y(a);if(!f[0])return b.remove(),!1;c.replaceChild(f[0],d);y(f[0]).after(f.slice(1))}})};z.replaceAll=function(a){y(a).replaceWith(this);return this};z.text=function(a){return void 0===a?this[0]?this[0].textContent:"":this.each(function(b,c){c.textContent=a})};var Z=e.documentElement; z.offset=function(){var a=this[0];if(a)return a=a.getBoundingClientRect(),{top:a.top+g.pageYOffset-Z.clientTop,left:a.left+g.pageXOffset-Z.clientLeft}};z.offsetParent=function(){return y(this[0]&&this[0].offsetParent)};z.position=function(){var a=this[0];if(a)return{left:a.offsetLeft,top:a.offsetTop}};z.children=function(a){var b=[];this.each(function(a,d){p.apply(b,d.children)});b=y(K(b));return a?b.filter(function(b,d){return D(d,a)}):b}; z.find=function(a){for(var b=[],c=0,d=this.length;c<d;c++){var f=t(a,this[c]);f.length&&p.apply(b,f)}return y(b.length&&K(b))};z.has=function(a){var b=v(a)?function(b,d){return!!t(a,d).length}:function(b,d){return d.contains(a)};return this.filter(b)};z.is=function(a){if(!a||!this[0])return!1;var b=H(a),c=!1;this.each(function(d,f){c=b(d,f,a);return!c});return c};z.next=function(){return y(this[0]&&this[0].nextElementSibling)}; z.not=function(a){if(!a||!this[0])return this;var b=H(a);return this.filter(function(c,d){return!b(c,d,a)})};z.parent=function(){var a=[];this.each(function(b,c){c&&c.parentNode&&a.push(c.parentNode)});return y(K(a))};z.index=function(a){var b=a?y(a)[0]:this[0];a=a?this:y(b).parent().children();return m.call(a,b)};z.closest=function(a){return a&&this[0]?this.is(a)?this.filter(a):this.parent().closest(a):y()}; z.parents=function(a){var b=[],c;this.each(function(d,f){for(c=f;c&&c.parentNode&&c!==e.body.parentNode;)c=c.parentNode,(!a||a&&D(c,a))&&b.push(c)});return y(K(b))};z.prev=function(){return y(this[0]&&this[0].previousElementSibling)};z.siblings=function(){var a=this[0];return this.parent().children().filter(function(b,c){return c!==a})}; })();
jonobr1/cdnjs
ajax/libs/cash/2.2.1/cash.min.js
JavaScript
mit
12,108
/* 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/. */ define([ 'chai', 'sinon', 'jquery', 'models/auth_brokers/iframe', 'models/reliers/relier', 'lib/promise', 'lib/channels/null', 'lib/session', '../../../mocks/window' ], function (chai, sinon, $, IframeAuthenticationBroker, Relier, p, NullChannel, Session, WindowMock) { 'use strict'; var assert = chai.assert; describe('models/auth_brokers/iframe', function () { var broker; var windowMock; var relierMock; var channelMock; beforeEach(function () { windowMock = new WindowMock(); relierMock = new Relier(); channelMock = new NullChannel(); sinon.spy(channelMock, 'send'); broker = new IframeAuthenticationBroker({ window: windowMock, relier: relierMock, channel: channelMock, session: Session }); }); afterEach(function () { if ($.getJSON.restore) { $.getJSON.restore(); } }); describe('sendOAuthResultToRelier', function () { it('sends an `oauth_complete` message', function () { sinon.stub(broker, 'send', function () { return p(); }); return broker.sendOAuthResultToRelier({ email: 'testuser@testuesr.com' }) .then(function () { assert.isTrue(broker.send.calledWith('oauth_complete')); }); }); }); describe('getChannel', function () { it('gets an IframeChannel', function () { var channel = broker.getChannel(); assert.ok(channel); }); }); describe('canCancel', function () { it('returns true', function () { assert.isTrue(broker.canCancel()); }); }); describe('cancel', function () { it('sends the `oauth_cancel` message over the channel', function () { return broker.cancel() .then(function () { assert.isTrue(channelMock.send.calledWith('oauth_cancel')); }); }); }); describe('afterLoaded', function () { it('sends a `loaded` message', function () { return broker.afterLoaded() .then(function () { assert.isTrue(channelMock.send.calledWith('loaded')); }); }); }); }); });
riadhchtara/fxa-password-manager
app/tests/spec/models/auth_brokers/iframe.js
JavaScript
mpl-2.0
2,421
var b = new ArrayBuffer(4); var dv = new DataView(b); dv.setInt32(0, 42); var w = wrap(dv); assertEq(DataView.prototype.getInt32.call(w, 0), 42);
michath/ConMonkey
js/src/jit-test/tests/basic/testBug761439.js
JavaScript
mpl-2.0
146
/* -*- 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/. */ //----------------------------------------------------------------------------- var BUGNUMBER = 444979; var summary = 'switch -0 is same as switch 0'; var actual = ''; var expect = ''; //----------------------------------------------------------------------------- test(); //----------------------------------------------------------------------------- function test() { enterFunc ('test'); printBugNumber(BUGNUMBER); printStatus (summary); expect = 'y==0'; actual = ''; var shortSwitch = 'var y=-0;switch (y){case 0: actual="y==0"; break; default: actual="y!=0";}'; eval(shortSwitch); reportCompare(expect, actual, summary + ': shortSwitch'); actual = ''; var longSwitch = 'var y=-0;var t=0;switch(y){case -1:'; for (var i = 0; i < 64000; i++) { longSwitch += ' t++;'; } longSwitch += ' break; case 0: actual = "y==0"; break; default: actual = "y!=0";}'; eval(longSwitch); reportCompare(expect, actual, summary + ': longSwitch'); exitFunc ('test'); }
JasonGross/mozjs
js/src/tests/ecma_3/Statements/regress-444979.js
JavaScript
mpl-2.0
1,286
/* Any copyright is dedicated to the Public Domain. * http://creativecommons.org/licenses/publicdomain/ */ // To JSON.stringify, symbols are the same as undefined. var symbols = [ Symbol(), Symbol.for("ponies"), Symbol.iterator ]; for (var sym of symbols) { assertEq(JSON.stringify(sym), undefined); assertEq(JSON.stringify([sym]), "[null]"); // JSON.stringify skips symbol-valued properties! assertEq(JSON.stringify({x: sym}), '{}'); // However such properties are passed to the replacerFunction if any. var replacer = function (key, val) { assertEq(typeof this, "object"); if (typeof val === "symbol") { assertEq(val, sym); return "ding"; } return val; }; assertEq(JSON.stringify(sym, replacer), '"ding"'); assertEq(JSON.stringify({x: sym}, replacer), '{"x":"ding"}'); } if (typeof reportCompare === 'function') reportCompare(0, 0, 'ok');
cstipkovic/spidermonkey-research
js/src/tests/ecma_6/Symbol/json-stringify-values.js
JavaScript
mpl-2.0
956
/* -*- 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/. */ /** File Name: 15.6.4-2.js ECMA Section: 15.6.4 Properties of the Boolean Prototype Object Description: The Boolean prototype object is itself a Boolean object (its [[Class]] is "Boolean") whose value is false. The value of the internal [[Prototype]] property of the Boolean prototype object is the Object prototype object (15.2.3.1). Author: christine@netscape.com Date: 30 september 1997 */ var VERSION = "ECMA_2" startTest(); var SECTION = "15.6.4-2"; writeHeaderToLog( SECTION + " Properties of the Boolean Prototype Object"); new TestCase( SECTION, "Boolean.prototype.__proto__", Object.prototype, Boolean.prototype.__proto__ ); test();
michath/ConMonkey
js/src/tests/ecma/extensions/15.6.4-2.js
JavaScript
mpl-2.0
1,028
var searchData= [ ['debug',['debug',['../class_q_rspec.html#a2e597199e2a6a4e04ba44a1ec1a8f7be',1,'QRspec']]] ];
Darkflib/php-qrcode
docs/html/search/functions_64.js
JavaScript
lgpl-3.0
114
export * from './actions'; export * from './actionTypes'; export * from './constants'; export * from './functions';
gpolitis/jitsi-meet
react/features/base/settings/index.js
JavaScript
apache-2.0
116
/*! * Module dependencies. */ var utils = require('./utils'); var EventEmitter = require('events').EventEmitter; var driver = global.MONGOOSE_DRIVER_PATH || './drivers/node-mongodb-native'; var Schema = require('./schema'); var Collection = require(driver + '/collection'); var STATES = require('./connectionstate'); var MongooseError = require('./error'); var muri = require('muri'); var PromiseProvider = require('./promise_provider'); /*! * Protocol prefix regexp. * * @api private */ var rgxProtocol = /^(?:.)+:\/\//; /*! * A list of authentication mechanisms that don't require a password for authentication. * This is used by the authMechanismDoesNotRequirePassword method. * * @api private */ var authMechanismsWhichDontRequirePassword = [ 'MONGODB-X509' ]; /** * Connection constructor * * For practical reasons, a Connection equals a Db. * * @param {Mongoose} base a mongoose instance * @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter * @event `connecting`: Emitted when `connection.{open,openSet}()` is executed on this connection. * @event `connected`: Emitted when this connection successfully connects to the db. May be emitted _multiple_ times in `reconnected` scenarios. * @event `open`: Emitted after we `connected` and `onOpen` is executed on all of this connections models. * @event `disconnecting`: Emitted when `connection.close()` was executed. * @event `disconnected`: Emitted after getting disconnected from the db. * @event `close`: Emitted after we `disconnected` and `onClose` executed on all of this connections models. * @event `reconnected`: Emitted after we `connected` and subsequently `disconnected`, followed by successfully another successfull connection. * @event `error`: Emitted when an error occurs on this connection. * @event `fullsetup`: Emitted in a replica-set scenario, when primary and at least one seconaries specified in the connection string are connected. * @event `all`: Emitted in a replica-set scenario, when all nodes specified in the connection string are connected. * @api public */ function Connection(base) { this.base = base; this.collections = {}; this.models = {}; this.config = {autoIndex: true}; this.replica = false; this.hosts = null; this.host = null; this.port = null; this.user = null; this.pass = null; this.name = null; this.options = null; this.otherDbs = []; this._readyState = STATES.disconnected; this._closeCalled = false; this._hasOpened = false; } /*! * Inherit from EventEmitter */ Connection.prototype.__proto__ = EventEmitter.prototype; /** * Connection ready state * * - 0 = disconnected * - 1 = connected * - 2 = connecting * - 3 = disconnecting * * Each state change emits its associated event name. * * ####Example * * conn.on('connected', callback); * conn.on('disconnected', callback); * * @property readyState * @api public */ Object.defineProperty(Connection.prototype, 'readyState', { get: function() { return this._readyState; }, set: function(val) { if (!(val in STATES)) { throw new Error('Invalid connection state: ' + val); } if (this._readyState !== val) { this._readyState = val; // loop over the otherDbs on this connection and change their state for (var i = 0; i < this.otherDbs.length; i++) { this.otherDbs[i].readyState = val; } if (STATES.connected === val) { this._hasOpened = true; } this.emit(STATES[val]); } } }); /** * A hash of the collections associated with this connection * * @property collections */ Connection.prototype.collections; /** * The mongodb.Db instance, set when the connection is opened * * @property db */ Connection.prototype.db; /** * A hash of the global options that are associated with this connection * * @property config */ Connection.prototype.config; /** * Opens the connection to MongoDB. * * `options` is a hash with the following possible properties: * * config - passed to the connection config instance * db - passed to the connection db instance * server - passed to the connection server instance(s) * replset - passed to the connection ReplSet instance * user - username for authentication * pass - password for authentication * auth - options for authentication (see http://mongodb.github.com/node-mongodb-native/api-generated/db.html#authenticate) * * ####Notes: * * Mongoose forces the db option `forceServerObjectId` false and cannot be overridden. * Mongoose defaults the server `auto_reconnect` options to true which can be overridden. * See the node-mongodb-native driver instance for options that it understands. * * _Options passed take precedence over options included in connection strings._ * * @param {String} connection_string mongodb://uri or the host to which you are connecting * @param {String} [database] database name * @param {Number} [port] database port * @param {Object} [options] options * @param {Function} [callback] * @see node-mongodb-native https://github.com/mongodb/node-mongodb-native * @see http://mongodb.github.com/node-mongodb-native/api-generated/db.html#authenticate * @api public */ Connection.prototype.open = function(host, database, port, options, callback) { var parsed; var Promise = PromiseProvider.get(); if (typeof database === 'string') { switch (arguments.length) { case 2: port = 27017; break; case 3: switch (typeof port) { case 'function': callback = port; port = 27017; break; case 'object': options = port; port = 27017; break; } break; case 4: if (typeof options === 'function') { callback = options; options = {}; } } } else { switch (typeof database) { case 'function': callback = database; database = undefined; break; case 'object': options = database; database = undefined; callback = port; break; } if (!rgxProtocol.test(host)) { host = 'mongodb://' + host; } try { parsed = muri(host); } catch (err) { this.error(err, callback); return new Promise.ES6(function(resolve, reject) { reject(err); }); } database = parsed.db; host = parsed.hosts[0].host || parsed.hosts[0].ipc; port = parsed.hosts[0].port || 27017; } this.options = this.parseOptions(options, parsed && parsed.options); // make sure we can open if (STATES.disconnected !== this.readyState) { var err = new Error('Trying to open unclosed connection.'); err.state = this.readyState; this.error(err, callback); return new Promise.ES6(function(resolve, reject) { reject(err); }); } if (!host) { this.error(new Error('Missing hostname.'), callback); return new Promise.ES6(function(resolve, reject) { reject(err); }); } if (!database) { this.error(new Error('Missing database name.'), callback); return new Promise.ES6(function(resolve, reject) { reject(err); }); } // authentication if (this.optionsProvideAuthenticationData(options)) { this.user = options.user; this.pass = options.pass; } else if (parsed && parsed.auth) { this.user = parsed.auth.user; this.pass = parsed.auth.pass; // Check hostname for user/pass } else if (/@/.test(host) && /:/.test(host.split('@')[0])) { host = host.split('@'); var auth = host.shift().split(':'); host = host.pop(); this.user = auth[0]; this.pass = auth[1]; } else { this.user = this.pass = undefined; } // global configuration options if (options && options.config) { this.config.autoIndex = options.config.autoIndex !== false; } this.name = database; this.host = host; this.port = port; var _this = this; var promise = new Promise.ES6(function(resolve, reject) { _this._open(true, function(error) { callback && callback(error); if (error) { // Error can be on same tick re: christkv/mongodb-core#157 setImmediate(function() { reject(error); if (!callback && !promise.$hasHandler) { _this.emit('error', error); } }); return; } resolve(); }); }); return promise; }; /** * Helper for `dropDatabase()`. * * @param {Function} callback * @return {Promise} * @api public */ Connection.prototype.dropDatabase = function(callback) { var Promise = PromiseProvider.get(); var _this = this; var promise = new Promise.ES6(function(resolve, reject) { if (_this.readyState !== STATES.connected) { _this.on('open', function() { _this.db.dropDatabase(function(error) { if (error) { reject(error); } else { resolve(); } }); }); } else { _this.db.dropDatabase(function(error) { if (error) { reject(error); } else { resolve(); } }); } }); if (callback) { promise.then(function() { callback(); }, callback); } return promise; }; /** * Opens the connection to a replica set. * * ####Example: * * var db = mongoose.createConnection(); * db.openSet("mongodb://user:pwd@localhost:27020,localhost:27021,localhost:27012/mydb"); * * The database name and/or auth need only be included in one URI. * The `options` is a hash which is passed to the internal driver connection object. * * Valid `options` * * db - passed to the connection db instance * server - passed to the connection server instance(s) * replset - passed to the connection ReplSetServer instance * user - username for authentication * pass - password for authentication * auth - options for authentication (see http://mongodb.github.com/node-mongodb-native/api-generated/db.html#authenticate) * mongos - Boolean - if true, enables High Availability support for mongos * * _Options passed take precedence over options included in connection strings._ * * ####Notes: * * _If connecting to multiple mongos servers, set the `mongos` option to true._ * * conn.open('mongodb://mongosA:27501,mongosB:27501', { mongos: true }, cb); * * Mongoose forces the db option `forceServerObjectId` false and cannot be overridden. * Mongoose defaults the server `auto_reconnect` options to true which can be overridden. * See the node-mongodb-native driver instance for options that it understands. * * _Options passed take precedence over options included in connection strings._ * * @param {String} uris MongoDB connection string * @param {String} [database] database name if not included in `uris` * @param {Object} [options] passed to the internal driver * @param {Function} [callback] * @see node-mongodb-native https://github.com/mongodb/node-mongodb-native * @see http://mongodb.github.com/node-mongodb-native/api-generated/db.html#authenticate * @api public */ Connection.prototype.openSet = function(uris, database, options, callback) { if (!rgxProtocol.test(uris)) { uris = 'mongodb://' + uris; } var Promise = PromiseProvider.get(); switch (arguments.length) { case 3: switch (typeof database) { case 'string': this.name = database; break; case 'object': callback = options; options = database; database = null; break; } if (typeof options === 'function') { callback = options; options = {}; } break; case 2: switch (typeof database) { case 'string': this.name = database; break; case 'function': callback = database; database = null; break; case 'object': options = database; database = null; break; } } if (typeof database === 'string') { this.name = database; } var parsed; try { parsed = muri(uris); } catch (err) { this.error(err, callback); return new Promise.ES6(function(resolve, reject) { reject(err); }); } if (!this.name) { this.name = parsed.db; } this.hosts = parsed.hosts; this.options = this.parseOptions(options, parsed && parsed.options); this.replica = true; if (!this.name) { var err = new Error('No database name provided for replica set'); this.error(err, callback); return new Promise.ES6(function(resolve, reject) { reject(err); }); } // authentication if (this.optionsProvideAuthenticationData(options)) { this.user = options.user; this.pass = options.pass; } else if (parsed && parsed.auth) { this.user = parsed.auth.user; this.pass = parsed.auth.pass; } else { this.user = this.pass = undefined; } // global configuration options if (options && options.config) { this.config.autoIndex = options.config.autoIndex !== false; } var _this = this; var emitted = false; var promise = new Promise.ES6(function(resolve, reject) { _this._open(true, function(error) { callback && callback(error); if (error) { reject(error); if (!callback && !promise.$hasHandler && !emitted) { emitted = true; _this.emit('error', error); } return; } resolve(); }); }); return promise; }; /** * error * * Graceful error handling, passes error to callback * if available, else emits error on the connection. * * @param {Error} err * @param {Function} callback optional * @api private */ Connection.prototype.error = function(err, callback) { if (callback) { return callback(err); } this.emit('error', err); }; /** * Handles opening the connection with the appropriate method based on connection type. * * @param {Function} callback * @api private */ Connection.prototype._open = function(emit, callback) { this.readyState = STATES.connecting; this._closeCalled = false; var _this = this; var method = this.replica ? 'doOpenSet' : 'doOpen'; // open connection this[method](function(err) { if (err) { _this.readyState = STATES.disconnected; if (_this._hasOpened) { if (callback) { callback(err); } } else { _this.error(err, emit && callback); } return; } _this.onOpen(callback); }); }; /** * Called when the connection is opened * * @api private */ Connection.prototype.onOpen = function(callback) { var _this = this; function open(err, isAuth) { if (err) { _this.readyState = isAuth ? STATES.unauthorized : STATES.disconnected; _this.error(err, callback); return; } _this.readyState = STATES.connected; // avoid having the collection subscribe to our event emitter // to prevent 0.3 warning for (var i in _this.collections) { if (utils.object.hasOwnProperty(_this.collections, i)) { _this.collections[i].onOpen(); } } callback && callback(); _this.emit('open'); } // re-authenticate if we're not already connected #3871 if (this._readyState !== STATES.connected && this.shouldAuthenticate()) { _this.db.authenticate(_this.user, _this.pass, _this.options.auth, function(err) { open(err, true); }); } else { open(); } }; /** * Closes the connection * * @param {Function} [callback] optional * @return {Connection} self * @api public */ Connection.prototype.close = function(callback) { var _this = this; var Promise = PromiseProvider.get(); return new Promise.ES6(function(resolve, reject) { _this._close(function(error) { callback && callback(error); if (error) { reject(error); return; } resolve(); }); }); }; /** * Handles closing the connection * * @param {Function} callback * @api private */ Connection.prototype._close = function(callback) { var _this = this; this._closeCalled = true; switch (this.readyState) { case 0: // disconnected callback && callback(); break; case 1: // connected case 4: // unauthorized this.readyState = STATES.disconnecting; this.doClose(function(err) { if (err) { _this.error(err, callback); } else { _this.onClose(); callback && callback(); } }); break; case 2: // connecting this.once('open', function() { _this.close(callback); }); break; case 3: // disconnecting if (!callback) { break; } this.once('close', function() { callback(); }); break; } return this; }; /** * Called when the connection closes * * @api private */ Connection.prototype.onClose = function() { this.readyState = STATES.disconnected; // avoid having the collection subscribe to our event emitter // to prevent 0.3 warning for (var i in this.collections) { if (utils.object.hasOwnProperty(this.collections, i)) { this.collections[i].onClose(); } } this.emit('close'); }; /** * Retrieves a collection, creating it if not cached. * * Not typically needed by applications. Just talk to your collection through your model. * * @param {String} name of the collection * @param {Object} [options] optional collection options * @return {Collection} collection instance * @api public */ Connection.prototype.collection = function(name, options) { if (!(name in this.collections)) { this.collections[name] = new Collection(name, this, options); } return this.collections[name]; }; /** * Defines or retrieves a model. * * var mongoose = require('mongoose'); * var db = mongoose.createConnection(..); * db.model('Venue', new Schema(..)); * var Ticket = db.model('Ticket', new Schema(..)); * var Venue = db.model('Venue'); * * _When no `collection` argument is passed, Mongoose produces a collection name by passing the model `name` to the [utils.toCollectionName](#utils_exports.toCollectionName) method. This method pluralizes the name. If you don't like this behavior, either pass a collection name or set your schemas collection name option._ * * ####Example: * * var schema = new Schema({ name: String }, { collection: 'actor' }); * * // or * * schema.set('collection', 'actor'); * * // or * * var collectionName = 'actor' * var M = conn.model('Actor', schema, collectionName) * * @param {String} name the model name * @param {Schema} [schema] a schema. necessary when defining a model * @param {String} [collection] name of mongodb collection (optional) if not given it will be induced from model name * @see Mongoose#model #index_Mongoose-model * @return {Model} The compiled model * @api public */ Connection.prototype.model = function(name, schema, collection) { // collection name discovery if (typeof schema === 'string') { collection = schema; schema = false; } if (utils.isObject(schema) && !schema.instanceOfSchema) { schema = new Schema(schema); } if (schema && !schema.instanceOfSchema) { throw new Error('The 2nd parameter to `mongoose.model()` should be a ' + 'schema or a POJO'); } if (this.models[name] && !collection) { // model exists but we are not subclassing with custom collection if (schema && schema.instanceOfSchema && schema !== this.models[name].schema) { throw new MongooseError.OverwriteModelError(name); } return this.models[name]; } var opts = {cache: false, connection: this}; var model; if (schema && schema.instanceOfSchema) { // compile a model model = this.base.model(name, schema, collection, opts); // only the first model with this name is cached to allow // for one-offs with custom collection names etc. if (!this.models[name]) { this.models[name] = model; } model.init(); return model; } if (this.models[name] && collection) { // subclassing current model with alternate collection model = this.models[name]; schema = model.prototype.schema; var sub = model.__subclass(this, schema, collection); // do not cache the sub model return sub; } // lookup model in mongoose module model = this.base.models[name]; if (!model) { throw new MongooseError.MissingSchemaError(name); } if (this === model.prototype.db && (!collection || collection === model.collection.name)) { // model already uses this connection. // only the first model with this name is cached to allow // for one-offs with custom collection names etc. if (!this.models[name]) { this.models[name] = model; } return model; } this.models[name] = model.__subclass(this, schema, collection); return this.models[name]; }; /** * Returns an array of model names created on this connection. * @api public * @return {Array} */ Connection.prototype.modelNames = function() { return Object.keys(this.models); }; /** * @brief Returns if the connection requires authentication after it is opened. Generally if a * username and password are both provided than authentication is needed, but in some cases a * password is not required. * @api private * @return {Boolean} true if the connection should be authenticated after it is opened, otherwise false. */ Connection.prototype.shouldAuthenticate = function() { return (this.user !== null && this.user !== void 0) && ((this.pass !== null || this.pass !== void 0) || this.authMechanismDoesNotRequirePassword()); }; /** * @brief Returns a boolean value that specifies if the current authentication mechanism needs a * password to authenticate according to the auth objects passed into the open/openSet methods. * @api private * @return {Boolean} true if the authentication mechanism specified in the options object requires * a password, otherwise false. */ Connection.prototype.authMechanismDoesNotRequirePassword = function() { if (this.options && this.options.auth) { return authMechanismsWhichDontRequirePassword.indexOf(this.options.auth.authMechanism) >= 0; } return true; }; /** * @brief Returns a boolean value that specifies if the provided objects object provides enough * data to authenticate with. Generally this is true if the username and password are both specified * but in some authentication methods, a password is not required for authentication so only a username * is required. * @param {Object} [options] the options object passed into the open/openSet methods. * @api private * @return {Boolean} true if the provided options object provides enough data to authenticate with, * otherwise false. */ Connection.prototype.optionsProvideAuthenticationData = function(options) { return (options) && (options.user) && ((options.pass) || this.authMechanismDoesNotRequirePassword()); }; /*! * Module exports. */ Connection.STATES = STATES; module.exports = Connection;
jiaomuhub/active
webapp/node_modules/mongoose/lib/connection.js
JavaScript
apache-2.0
23,296
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const fs = require("fs-extra"); const path = require("path"); const webpack = require("webpack"); const app_utils_1 = require("../utilities/app-utils"); const webpack_config_1 = require("../models/webpack-config"); const utils_1 = require("../models/webpack-configs/utils"); const config_1 = require("../models/config"); const stats_1 = require("../utilities/stats"); const Task = require('../ember-cli/lib/models/task'); const SilentError = require('silent-error'); exports.default = Task.extend({ run: function (runTaskOptions) { const config = config_1.CliConfig.fromProject().config; const app = app_utils_1.getAppFromConfig(runTaskOptions.app); const outputPath = runTaskOptions.outputPath || app.outDir; if (this.project.root === path.resolve(outputPath)) { throw new SilentError('Output path MUST not be project root directory!'); } if (config.project && config.project.ejected) { throw new SilentError('An ejected project cannot use the build command anymore.'); } if (runTaskOptions.deleteOutputPath) { fs.removeSync(path.resolve(this.project.root, outputPath)); } const webpackConfig = new webpack_config_1.NgCliWebpackConfig(runTaskOptions, app).buildConfig(); const webpackCompiler = webpack(webpackConfig); const statsConfig = utils_1.getWebpackStatsConfig(runTaskOptions.verbose); return new Promise((resolve, reject) => { const callback = (err, stats) => { if (err) { return reject(err); } const json = stats.toJson('verbose'); if (runTaskOptions.verbose) { this.ui.writeLine(stats.toString(statsConfig)); } else { this.ui.writeLine(stats_1.statsToString(json, statsConfig)); } if (stats.hasWarnings()) { this.ui.writeLine(stats_1.statsWarningsToString(json, statsConfig)); } if (stats.hasErrors()) { this.ui.writeError(stats_1.statsErrorsToString(json, statsConfig)); } if (runTaskOptions.watch) { return; } else if (runTaskOptions.statsJson) { fs.writeFileSync(path.resolve(this.project.root, outputPath, 'stats.json'), JSON.stringify(stats.toJson(), null, 2)); } if (stats.hasErrors()) { reject(); } else { resolve(); } }; if (runTaskOptions.watch) { webpackCompiler.watch({ poll: runTaskOptions.poll }, callback); } else { webpackCompiler.run(callback); } }) .catch((err) => { if (err) { this.ui.writeError('\nAn error occured during the build:\n' + ((err && err.stack) || err)); } throw err; }); } }); //# sourceMappingURL=/users/hansl/sources/hansl/angular-cli/tasks/build.js.map
tongpa/pypollmanage
pypollmanage/public/javascript/node_modules/@angular/cli/tasks/build.js
JavaScript
apache-2.0
3,293
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import { stringify } from '../facade/lang'; /** * A parameter metadata that specifies a dependency. * * ### Example ([live demo](http://plnkr.co/edit/6uHYJK?p=preview)) * * ```typescript * class Engine {} * * @Injectable() * class Car { * engine; * constructor(@Inject("MyEngine") engine:Engine) { * this.engine = engine; * } * } * * var injector = Injector.resolveAndCreate([ * {provide: "MyEngine", useClass: Engine}, * Car * ]); * * expect(injector.get(Car).engine instanceof Engine).toBe(true); * ``` * * When `@Inject()` is not present, {@link Injector} will use the type annotation of the parameter. * * ### Example * * ```typescript * class Engine {} * * @Injectable() * class Car { * constructor(public engine: Engine) {} //same as constructor(@Inject(Engine) engine:Engine) * } * * var injector = Injector.resolveAndCreate([Engine, Car]); * expect(injector.get(Car).engine instanceof Engine).toBe(true); * ``` * @stable */ export var InjectMetadata = (function () { function InjectMetadata(token) { this.token = token; } InjectMetadata.prototype.toString = function () { return "@Inject(" + stringify(this.token) + ")"; }; return InjectMetadata; }()); /** * A parameter metadata that marks a dependency as optional. {@link Injector} provides `null` if * the dependency is not found. * * ### Example ([live demo](http://plnkr.co/edit/AsryOm?p=preview)) * * ```typescript * class Engine {} * * @Injectable() * class Car { * engine; * constructor(@Optional() engine:Engine) { * this.engine = engine; * } * } * * var injector = Injector.resolveAndCreate([Car]); * expect(injector.get(Car).engine).toBeNull(); * ``` * @stable */ export var OptionalMetadata = (function () { function OptionalMetadata() { } OptionalMetadata.prototype.toString = function () { return "@Optional()"; }; return OptionalMetadata; }()); /** * `DependencyMetadata` is used by the framework to extend DI. * This is internal to Angular and should not be used directly. * @stable */ export var DependencyMetadata = (function () { function DependencyMetadata() { } Object.defineProperty(DependencyMetadata.prototype, "token", { get: function () { return null; }, enumerable: true, configurable: true }); return DependencyMetadata; }()); /** * A marker metadata that marks a class as available to {@link Injector} for creation. * * ### Example ([live demo](http://plnkr.co/edit/Wk4DMQ?p=preview)) * * ```typescript * @Injectable() * class UsefulService {} * * @Injectable() * class NeedsService { * constructor(public service:UsefulService) {} * } * * var injector = Injector.resolveAndCreate([NeedsService, UsefulService]); * expect(injector.get(NeedsService).service instanceof UsefulService).toBe(true); * ``` * {@link Injector} will throw {@link NoAnnotationError} when trying to instantiate a class that * does not have `@Injectable` marker, as shown in the example below. * * ```typescript * class UsefulService {} * * class NeedsService { * constructor(public service:UsefulService) {} * } * * var injector = Injector.resolveAndCreate([NeedsService, UsefulService]); * expect(() => injector.get(NeedsService)).toThrowError(); * ``` * @stable */ export var InjectableMetadata = (function () { function InjectableMetadata() { } return InjectableMetadata; }()); /** * Specifies that an {@link Injector} should retrieve a dependency only from itself. * * ### Example ([live demo](http://plnkr.co/edit/NeagAg?p=preview)) * * ```typescript * class Dependency { * } * * @Injectable() * class NeedsDependency { * dependency; * constructor(@Self() dependency:Dependency) { * this.dependency = dependency; * } * } * * var inj = Injector.resolveAndCreate([Dependency, NeedsDependency]); * var nd = inj.get(NeedsDependency); * * expect(nd.dependency instanceof Dependency).toBe(true); * * var inj = Injector.resolveAndCreate([Dependency]); * var child = inj.resolveAndCreateChild([NeedsDependency]); * expect(() => child.get(NeedsDependency)).toThrowError(); * ``` * @stable */ export var SelfMetadata = (function () { function SelfMetadata() { } SelfMetadata.prototype.toString = function () { return "@Self()"; }; return SelfMetadata; }()); /** * Specifies that the dependency resolution should start from the parent injector. * * ### Example ([live demo](http://plnkr.co/edit/Wchdzb?p=preview)) * * ```typescript * class Dependency { * } * * @Injectable() * class NeedsDependency { * dependency; * constructor(@SkipSelf() dependency:Dependency) { * this.dependency = dependency; * } * } * * var parent = Injector.resolveAndCreate([Dependency]); * var child = parent.resolveAndCreateChild([NeedsDependency]); * expect(child.get(NeedsDependency).dependency instanceof Depedency).toBe(true); * * var inj = Injector.resolveAndCreate([Dependency, NeedsDependency]); * expect(() => inj.get(NeedsDependency)).toThrowError(); * ``` * @stable */ export var SkipSelfMetadata = (function () { function SkipSelfMetadata() { } SkipSelfMetadata.prototype.toString = function () { return "@SkipSelf()"; }; return SkipSelfMetadata; }()); /** * Specifies that an injector should retrieve a dependency from any injector until reaching the * closest host. * * In Angular, a component element is automatically declared as a host for all the injectors in * its view. * * ### Example ([live demo](http://plnkr.co/edit/GX79pV?p=preview)) * * In the following example `App` contains `ParentCmp`, which contains `ChildDirective`. * So `ParentCmp` is the host of `ChildDirective`. * * `ChildDirective` depends on two services: `HostService` and `OtherService`. * `HostService` is defined at `ParentCmp`, and `OtherService` is defined at `App`. * *```typescript * class OtherService {} * class HostService {} * * @Directive({ * selector: 'child-directive' * }) * class ChildDirective { * constructor(@Optional() @Host() os:OtherService, @Optional() @Host() hs:HostService){ * console.log("os is null", os); * console.log("hs is NOT null", hs); * } * } * * @Component({ * selector: 'parent-cmp', * providers: [HostService], * template: ` * Dir: <child-directive></child-directive> * `, * directives: [ChildDirective] * }) * class ParentCmp { * } * * @Component({ * selector: 'app', * providers: [OtherService], * template: ` * Parent: <parent-cmp></parent-cmp> * `, * directives: [ParentCmp] * }) * class App { * } *``` * @stable */ export var HostMetadata = (function () { function HostMetadata() { } HostMetadata.prototype.toString = function () { return "@Host()"; }; return HostMetadata; }()); //# sourceMappingURL=metadata.js.map
psumkin/northshore
ui/node_modules/@angular/core/src/di/metadata.js
JavaScript
apache-2.0
7,116
/* * 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. */ const merge = require('webpack-merge'); const commonCfg = require('./webpack.common'); module.exports = merge(commonCfg, { mode: 'development', cache: true, node: { fs: 'empty', child_process: 'empty' }, // Entry points. entry: null, // Output system. output: null, optimization: { splitChunks: { chunks: 'async' } }, module: { exprContextCritical: false, rules: [ {test: /\.s?css$/, use: ['ignore-loader']} ] } });
ilantukh/ignite
modules/web-console/frontend/webpack/webpack.test.js
JavaScript
apache-2.0
1,351
/*! * jquery.fancytree.edit.js * * Make node titles editable. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/) * * Copyright (c) 2014, Martin Wendt (http://wwWendt.de) * * Released under the MIT license * https://github.com/mar10/fancytree/wiki/LicenseInfo * * @version @VERSION * @date @DATE */ ;(function($, window, document, undefined) { "use strict"; /******************************************************************************* * Private functions and variables */ var isMac = /Mac/.test(navigator.platform), escapeHtml = $.ui.fancytree.escapeHtml, unescapeHtml = $.ui.fancytree.unescapeHtml; // modifiers = {shift: "shiftKey", ctrl: "ctrlKey", alt: "altKey", meta: "metaKey"}, // specialKeys = { // 8: "backspace", 9: "tab", 10: "return", 13: "return", 16: "shift", 17: "ctrl", 18: "alt", 19: "pause", // 20: "capslock", 27: "esc", 32: "space", 33: "pageup", 34: "pagedown", 35: "end", 36: "home", // 37: "left", 38: "up", 39: "right", 40: "down", 45: "insert", 46: "del", // 96: "0", 97: "1", 98: "2", 99: "3", 100: "4", 101: "5", 102: "6", 103: "7", // 104: "8", 105: "9", 106: "*", 107: "+", 109: "-", 110: ".", 111 : "/", // 112: "f1", 113: "f2", 114: "f3", 115: "f4", 116: "f5", 117: "f6", 118: "f7", 119: "f8", // 120: "f9", 121: "f10", 122: "f11", 123: "f12", 144: "numlock", 145: "scroll", 186: ";", 191: "/", // 220: "\\", 222: "'", 224: "meta" // }, // shiftNums = { // "`": "~", "1": "!", "2": "@", "3": "#", "4": "$", "5": "%", "6": "^", "7": "&", // "8": "*", "9": "(", "0": ")", "-": "_", "=": "+", ";": ": ", "'": "\"", ",": "<", // ".": ">", "/": "?", "\\": "|" // }; // $.ui.fancytree.isKeydownEvent = function(e, code){ // var i, part, partmap, partlist = code.split("+"), len = parts.length; // var c = String.fromCharCode(e.which).toLowerCase(); // for( i = 0; i < len; i++ ) { // } // alert (parts.unshift()); // alert (parts.unshift()); // alert (parts.unshift()); // }; /** * [ext-edit] Start inline editing of current node title. * * @alias FancytreeNode#editStart * @requires Fancytree */ $.ui.fancytree._FancytreeNodeClass.prototype.editStart = function(){ var $input, node = this, tree = this.tree, local = tree.ext.edit, prevTitle = node.title, instOpts = tree.options.edit, $title = $(".fancytree-title", node.span), eventData = {node: node, tree: tree, options: tree.options}; if( instOpts.beforeEdit.call(node, {type: "beforeEdit"}, eventData) === false){ return false; } // beforeEdit may want to modify the title before editing prevTitle = node.title; node.debug("editStart"); // Disable standard Fancytree mouse- and key handling tree.widget._unbind(); // #116: ext-dnd prevents the blur event, so we have to catch outer clicks $(document).on("mousedown.fancytree-edit", function(event){ if( ! $(event.target).hasClass("fancytree-edit-input") ){ node.editEnd(true, event); } }); // Replace node with <input> $input = $("<input />", { "class": "fancytree-edit-input", value: unescapeHtml(prevTitle) }); if ( instOpts.adjustWidthOfs != null ) { $input.width($title.width() + instOpts.adjustWidthOfs); } if ( instOpts.inputCss != null ) { $input.css(instOpts.inputCss); } eventData.input = $input; $title.html($input); $.ui.fancytree.assert(!local.currentNode, "recursive edit"); local.currentNode = this; // Focus <input> and bind keyboard handler $input .focus() .change(function(event){ $input.addClass("fancytree-edit-dirty"); }).keydown(function(event){ switch( event.which ) { case $.ui.keyCode.ESCAPE: node.editEnd(false, event); break; case $.ui.keyCode.ENTER: node.editEnd(true, event); return false; // so we don't start editmode on Mac } event.stopPropagation(); }).blur(function(event){ return node.editEnd(true, event); }); instOpts.edit.call(node, {type: "edit"}, eventData); }; /** * [ext-edit] Stop inline editing. * @param {Boolean} [applyChanges=false] * @alias FancytreeNode#editEnd * @requires jquery.fancytree.edit.js */ $.ui.fancytree._FancytreeNodeClass.prototype.editEnd = function(applyChanges, _event){ var node = this, tree = this.tree, local = tree.ext.edit, instOpts = tree.options.edit, $title = $(".fancytree-title", node.span), $input = $title.find("input.fancytree-edit-input"), newVal = $input.val(), dirty = $input.hasClass("fancytree-edit-dirty"), doSave = (applyChanges || (dirty && applyChanges !== false)) && (newVal !== node.title), eventData = { node: node, tree: tree, options: tree.options, originalEvent: _event, dirty: dirty, save: doSave, input: $input, value: newVal }; if( instOpts.beforeClose.call(node, {type: "beforeClose"}, eventData) === false){ return false; } if( doSave && instOpts.save.call(node, {type: "save"}, eventData) === false){ return false; } $input .removeClass("fancytree-edit-dirty") .unbind(); // Unbind outer-click handler $(document).off(".fancytree-edit"); if( doSave ) { node.setTitle( escapeHtml(newVal) ); }else{ node.renderTitle(); } // Re-enable mouse and keyboard handling tree.widget._bind(); local.currentNode = null; node.setFocus(); // Set keyboard focus, even if setFocus() claims 'nothing to do' $(tree.$container).focus(); eventData.input = null; instOpts.close.call(node, {type: "close"}, eventData); return true; }; $.ui.fancytree._FancytreeNodeClass.prototype.startEdit = function(){ this.warn("FancytreeNode.startEdit() is deprecated since 2014-01-04. Use .editStart() instead."); return this.editStart.apply(this, arguments); }; $.ui.fancytree._FancytreeNodeClass.prototype.endEdit = function(){ this.warn("FancytreeNode.endEdit() is deprecated since 2014-01-04. Use .editEnd() instead."); return this.editEnd.apply(this, arguments); }; ///** // * Create a new child or sibling node. // * // * @param {String} [mode] 'before', 'after', or 'child' // * @lends FancytreeNode.prototype // * @requires jquery.fancytree.edit.js // */ //$.ui.fancytree._FancytreeNodeClass.prototype.editCreateNode = function(mode){ // var newNode, // node = this, // tree = this.tree, // local = tree.ext.edit, // instOpts = tree.options.edit, // $title = $(".fancytree-title", node.span), // $input = $title.find("input.fancytree-edit-input"), // newVal = $input.val(), // dirty = $input.hasClass("fancytree-edit-dirty"), // doSave = (applyChanges || (dirty && applyChanges !== false)) && (newVal !== node.title), // eventData = { // node: node, tree: tree, options: tree.options, originalEvent: _event, // dirty: dirty, // save: doSave, // input: $input, // value: newVal // }; // // node.debug("editCreate"); // // if( instOpts.beforeEdit.call(node, {type: "beforeCreateNode"}, eventData) === false){ // return false; // } // newNode = this.addNode({title: "Neuer Knoten"}, mode); // // newNode.editStart(); //}; /** * [ext-edit] Check if any node in this tree in edit mode. * * @returns {FancytreeNode | null} * @alias Fancytree#isEditing * @requires jquery.fancytree.edit.js */ $.ui.fancytree._FancytreeClass.prototype.isEditing = function(){ return this.ext.edit.currentNode; }; /** * [ext-edit] Check if this node is in edit mode. * @returns {Boolean} true if node is currently beeing edited * @alias FancytreeNode#isEditing * @requires jquery.fancytree.edit.js */ $.ui.fancytree._FancytreeNodeClass.prototype.isEditing = function(){ return this.tree.ext.edit.currentNode === this; }; /******************************************************************************* * Extension code */ $.ui.fancytree.registerExtension({ name: "edit", version: "0.1.0", // Default options for this extension. options: { adjustWidthOfs: 4, // null: don't adjust input size to content inputCss: {minWidth: "3em"}, triggerCancel: ["esc", "tab", "click"], // triggerStart: ["f2", "dblclick", "shift+click", "mac+enter"], triggerStart: ["f2", "shift+click", "mac+enter"], beforeClose: $.noop, // Return false to prevent cancel/save (data.input is available) beforeEdit: $.noop, // Return false to prevent edit mode close: $.noop, // Editor was removed edit: $.noop, // Editor was opened (available as data.input) // keypress: $.noop, // Not yet implemented save: $.noop // Save data.input.val() or return false to keep editor open }, // Local attributes currentNode: null, treeInit: function(ctx){ this._super(ctx); this.$container.addClass("fancytree-ext-edit"); }, nodeClick: function(ctx) { if( $.inArray("shift+click", ctx.options.edit.triggerStart) >= 0 ){ if( ctx.originalEvent.shiftKey ){ ctx.node.editStart(); return false; } } return this._super(ctx); }, nodeDblclick: function(ctx) { if( $.inArray("dblclick", ctx.options.edit.triggerStart) >= 0 ){ ctx.node.editStart(); return false; } return this._super(ctx); }, nodeKeydown: function(ctx) { switch( ctx.originalEvent.which ) { case 113: // [F2] if( $.inArray("f2", ctx.options.edit.triggerStart) >= 0 ){ ctx.node.editStart(); return false; } break; case $.ui.keyCode.ENTER: if( $.inArray("mac+enter", ctx.options.edit.triggerStart) >= 0 && isMac ){ ctx.node.editStart(); return false; } break; } return this._super(ctx); } }); }(jQuery, window, document));
shpark76/WhereHows
wherehows-web/public/legacy-app/vendors/fancytree/src/jquery.fancytree.edit.js
JavaScript
apache-2.0
9,398
// Copyright 2016 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. // Flags: --allow-natives-syntax --opt --no-always-opt var global = {} var fish = [ {'name': 'foo'}, {'name': 'bar'}, ]; for (var i = 0; i < fish.length; i++) { global[fish[i].name] = 1; } function load() { var sum = 0; for (var i = 0; i < fish.length; i++) { var name = fish[i].name; sum += global[name]; } return sum; } %PrepareFunctionForOptimization(load); load(); load(); %OptimizeFunctionOnNextCall(load); load(); assertOptimized(load); function store() { for (var i = 0; i < fish.length; i++) { var name = fish[i].name; global[name] = 1; } } %PrepareFunctionForOptimization(store); store(); store(); %OptimizeFunctionOnNextCall(store); store(); assertOptimized(store); // Regression test for KeyedStoreIC bug: would use PROPERTY mode erroneously. function store_element(obj, key) { obj[key] = 0; } var o1 = new Array(3); var o2 = new Array(3); o2.o2 = "o2"; var o3 = new Array(3); o3.o3 = "o3"; var o4 = new Array(3); o4.o4 = "o4"; var o5 = new Array(3); o5.o5 = "o5"; // Make the KeyedStoreIC megamorphic. store_element(o1, 0); // Premonomorphic store_element(o1, 0); // Monomorphic store_element(o2, 0); // 2-way polymorphic. store_element(o3, 0); // 3-way polymorphic. store_element(o4, 0); // 4-way polymorphic. store_element(o5, 0); // Megamorphic. function inferrable_store(key) { store_element(o5, key); } %PrepareFunctionForOptimization(inferrable_store); inferrable_store(0); inferrable_store(0); %OptimizeFunctionOnNextCall(inferrable_store); inferrable_store(0); assertOptimized(inferrable_store); // If |inferrable_store| emitted a generic keyed store, it won't deopt upon // seeing a property name key. It should have inferred a receiver map and // emitted an elements store, however. inferrable_store("deopt"); // TurboFan is not sophisticated enough to use key type provided by ICs. if (!isTurboFanned(inferrable_store)) { assertUnoptimized(inferrable_store); }
youtube/cobalt
third_party/v8/test/mjsunit/regress/regress-crbug-594183.js
JavaScript
bsd-3-clause
2,111
this.L = this.L || {}; this.L.Control = this.L.Control || {}; this.L.Control.Geocoder = (function (L) { 'use strict'; L = L && L.hasOwnProperty('default') ? L['default'] : L; var lastCallbackId = 0; // Adapted from handlebars.js // https://github.com/wycats/handlebars.js/ var badChars = /[&<>"'`]/g; var possible = /[&<>"'`]/; var escape = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#x27;', '`': '&#x60;' }; function escapeChar(chr) { return escape[chr]; } function htmlEscape(string) { if (string == null) { return ''; } else if (!string) { return string + ''; } // Force a string conversion as this will be done by the append regardless and // the regex test will do this transparently behind the scenes, causing issues if // an object's to string has escaped characters in it. string = '' + string; if (!possible.test(string)) { return string; } return string.replace(badChars, escapeChar); } function jsonp(url, params, callback, context, jsonpParam) { var callbackId = '_l_geocoder_' + lastCallbackId++; params[jsonpParam || 'callback'] = callbackId; window[callbackId] = L.Util.bind(callback, context); var script = document.createElement('script'); script.type = 'text/javascript'; script.src = url + L.Util.getParamString(params); script.id = callbackId; document.getElementsByTagName('head')[0].appendChild(script); } function getJSON(url, params, callback) { var xmlHttp = new XMLHttpRequest(); xmlHttp.onreadystatechange = function() { if (xmlHttp.readyState !== 4) { return; } if (xmlHttp.status !== 200 && xmlHttp.status !== 304) { callback(''); return; } callback(JSON.parse(xmlHttp.response)); }; xmlHttp.open('GET', url + L.Util.getParamString(params), true); xmlHttp.setRequestHeader('Accept', 'application/json'); xmlHttp.send(null); } function template(str, data) { return str.replace(/\{ *([\w_]+) *\}/g, function(str, key) { var value = data[key]; if (value === undefined) { value = ''; } else if (typeof value === 'function') { value = value(data); } return htmlEscape(value); }); } var Nominatim = { class: L.Class.extend({ options: { serviceUrl: 'https://nominatim.openstreetmap.org/', geocodingQueryParams: {}, reverseQueryParams: {}, htmlTemplate: function(r) { var a = r.address, parts = []; if (a.road || a.building) { parts.push('{building} {road} {house_number}'); } if (a.city || a.town || a.village || a.hamlet) { parts.push( '<span class="' + (parts.length > 0 ? 'leaflet-control-geocoder-address-detail' : '') + '">{postcode} {city} {town} {village} {hamlet}</span>' ); } if (a.state || a.country) { parts.push( '<span class="' + (parts.length > 0 ? 'leaflet-control-geocoder-address-context' : '') + '">{state} {country}</span>' ); } return template(parts.join('<br/>'), a, true); } }, initialize: function(options) { L.Util.setOptions(this, options); }, geocode: function(query, cb, context) { getJSON( this.options.serviceUrl + 'search', L.extend( { q: query, limit: 5, format: 'json', addressdetails: 1 }, this.options.geocodingQueryParams ), L.bind(function(data) { var results = []; for (var i = data.length - 1; i >= 0; i--) { var bbox = data[i].boundingbox; for (var j = 0; j < 4; j++) bbox[j] = parseFloat(bbox[j]); results[i] = { icon: data[i].icon, name: data[i].display_name, html: this.options.htmlTemplate ? this.options.htmlTemplate(data[i]) : undefined, bbox: L.latLngBounds([bbox[0], bbox[2]], [bbox[1], bbox[3]]), center: L.latLng(data[i].lat, data[i].lon), properties: data[i] }; } cb.call(context, results); }, this) ); }, reverse: function(location, scale, cb, context) { getJSON( this.options.serviceUrl + 'reverse', L.extend( { lat: location.lat, lon: location.lng, zoom: Math.round(Math.log(scale / 256) / Math.log(2)), addressdetails: 1, format: 'json' }, this.options.reverseQueryParams ), L.bind(function(data) { var result = [], loc; if (data && data.lat && data.lon) { loc = L.latLng(data.lat, data.lon); result.push({ name: data.display_name, html: this.options.htmlTemplate ? this.options.htmlTemplate(data) : undefined, center: loc, bounds: L.latLngBounds(loc, loc), properties: data }); } cb.call(context, result); }, this) ); } }), factory: function(options) { return new L.Control.Geocoder.Nominatim(options); } }; var Control = { class: L.Control.extend({ options: { showResultIcons: false, collapsed: true, expand: 'touch', // options: touch, click, anythingelse position: 'topright', placeholder: 'Search...', errorMessage: 'Nothing found.', suggestMinLength: 3, suggestTimeout: 250, defaultMarkGeocode: true }, includes: L.Evented.prototype || L.Mixin.Events, initialize: function(options) { L.Util.setOptions(this, options); if (!this.options.geocoder) { this.options.geocoder = new Nominatim.class(); } this._requestCount = 0; }, onAdd: function(map) { var className = 'leaflet-control-geocoder', container = L.DomUtil.create('div', className + ' leaflet-bar'), icon = L.DomUtil.create('button', className + '-icon', container), form = (this._form = L.DomUtil.create('div', className + '-form', container)), input; this._map = map; this._container = container; icon.innerHTML = '&nbsp;'; icon.type = 'button'; input = this._input = L.DomUtil.create('input', '', form); input.type = 'text'; input.placeholder = this.options.placeholder; this._errorElement = L.DomUtil.create('div', className + '-form-no-error', container); this._errorElement.innerHTML = this.options.errorMessage; this._alts = L.DomUtil.create( 'ul', className + '-alternatives leaflet-control-geocoder-alternatives-minimized', container ); L.DomEvent.disableClickPropagation(this._alts); L.DomEvent.addListener(input, 'keydown', this._keydown, this); if (this.options.geocoder.suggest) { L.DomEvent.addListener(input, 'input', this._change, this); } L.DomEvent.addListener( input, 'blur', function() { if (this.options.collapsed && !this._preventBlurCollapse) { this._collapse(); } this._preventBlurCollapse = false; }, this ); if (this.options.collapsed) { if (this.options.expand === 'click') { L.DomEvent.addListener( container, 'click', function(e) { if (e.button === 0 && e.detail !== 2) { this._toggle(); } }, this ); } else if (L.Browser.touch && this.options.expand === 'touch') { L.DomEvent.addListener( container, 'touchstart mousedown', function(e) { this._toggle(); e.preventDefault(); // mobile: clicking focuses the icon, so UI expands and immediately collapses e.stopPropagation(); }, this ); } else { L.DomEvent.addListener(container, 'mouseover', this._expand, this); L.DomEvent.addListener(container, 'mouseout', this._collapse, this); this._map.on('movestart', this._collapse, this); } } else { this._expand(); if (L.Browser.touch) { L.DomEvent.addListener( container, 'touchstart', function() { this._geocode(); }, this ); } else { L.DomEvent.addListener( container, 'click', function() { this._geocode(); }, this ); } } if (this.options.defaultMarkGeocode) { this.on('markgeocode', this.markGeocode, this); } this.on( 'startgeocode', function() { L.DomUtil.addClass(this._container, 'leaflet-control-geocoder-throbber'); }, this ); this.on( 'finishgeocode', function() { L.DomUtil.removeClass(this._container, 'leaflet-control-geocoder-throbber'); }, this ); L.DomEvent.disableClickPropagation(container); return container; }, _geocodeResult: function(results, suggest) { if (!suggest && results.length === 1) { this._geocodeResultSelected(results[0]); } else if (results.length > 0) { this._alts.innerHTML = ''; this._results = results; L.DomUtil.removeClass(this._alts, 'leaflet-control-geocoder-alternatives-minimized'); for (var i = 0; i < results.length; i++) { this._alts.appendChild(this._createAlt(results[i], i)); } } else { L.DomUtil.addClass(this._errorElement, 'leaflet-control-geocoder-error'); } }, markGeocode: function(result) { result = result.geocode || result; this._map.fitBounds(result.bbox); if (this._geocodeMarker) { this._map.removeLayer(this._geocodeMarker); } this._geocodeMarker = new L.Marker(result.center) .bindPopup(result.html || result.name) .addTo(this._map) .openPopup(); return this; }, _geocode: function(suggest) { var requestCount = ++this._requestCount, mode = suggest ? 'suggest' : 'geocode', eventData = { input: this._input.value }; this._lastGeocode = this._input.value; if (!suggest) { this._clearResults(); } this.fire('start' + mode, eventData); this.options.geocoder[mode]( this._input.value, function(results) { if (requestCount === this._requestCount) { eventData.results = results; this.fire('finish' + mode, eventData); this._geocodeResult(results, suggest); } }, this ); }, _geocodeResultSelected: function(result) { this.fire('markgeocode', { geocode: result }); }, _toggle: function() { if (L.DomUtil.hasClass(this._container, 'leaflet-control-geocoder-expanded')) { this._collapse(); } else { this._expand(); } }, _expand: function() { L.DomUtil.addClass(this._container, 'leaflet-control-geocoder-expanded'); this._input.select(); this.fire('expand'); }, _collapse: function() { L.DomUtil.removeClass(this._container, 'leaflet-control-geocoder-expanded'); L.DomUtil.addClass(this._alts, 'leaflet-control-geocoder-alternatives-minimized'); L.DomUtil.removeClass(this._errorElement, 'leaflet-control-geocoder-error'); this._input.blur(); // mobile: keyboard shouldn't stay expanded this.fire('collapse'); }, _clearResults: function() { L.DomUtil.addClass(this._alts, 'leaflet-control-geocoder-alternatives-minimized'); this._selection = null; L.DomUtil.removeClass(this._errorElement, 'leaflet-control-geocoder-error'); }, _createAlt: function(result, index) { var li = L.DomUtil.create('li', ''), a = L.DomUtil.create('a', '', li), icon = this.options.showResultIcons && result.icon ? L.DomUtil.create('img', '', a) : null, text = result.html ? undefined : document.createTextNode(result.name), mouseDownHandler = function mouseDownHandler(e) { // In some browsers, a click will fire on the map if the control is // collapsed directly after mousedown. To work around this, we // wait until the click is completed, and _then_ collapse the // control. Messy, but this is the workaround I could come up with // for #142. this._preventBlurCollapse = true; L.DomEvent.stop(e); this._geocodeResultSelected(result); L.DomEvent.on( li, 'click', function() { if (this.options.collapsed) { this._collapse(); } else { this._clearResults(); } }, this ); }; if (icon) { icon.src = result.icon; } li.setAttribute('data-result-index', index); if (result.html) { a.innerHTML = a.innerHTML + result.html; } else { a.appendChild(text); } // Use mousedown and not click, since click will fire _after_ blur, // causing the control to have collapsed and removed the items // before the click can fire. L.DomEvent.addListener(li, 'mousedown touchstart', mouseDownHandler, this); return li; }, _keydown: function(e) { var _this = this, select = function select(dir) { if (_this._selection) { L.DomUtil.removeClass(_this._selection, 'leaflet-control-geocoder-selected'); _this._selection = _this._selection[dir > 0 ? 'nextSibling' : 'previousSibling']; } if (!_this._selection) { _this._selection = _this._alts[dir > 0 ? 'firstChild' : 'lastChild']; } if (_this._selection) { L.DomUtil.addClass(_this._selection, 'leaflet-control-geocoder-selected'); } }; switch (e.keyCode) { // Escape case 27: if (this.options.collapsed) { this._collapse(); } break; // Up case 38: select(-1); break; // Up case 40: select(1); break; // Enter case 13: if (this._selection) { var index = parseInt(this._selection.getAttribute('data-result-index'), 10); this._geocodeResultSelected(this._results[index]); this._clearResults(); } else { this._geocode(); } break; } }, _change: function() { var v = this._input.value; if (v !== this._lastGeocode) { clearTimeout(this._suggestTimeout); if (v.length >= this.options.suggestMinLength) { this._suggestTimeout = setTimeout( L.bind(function() { this._geocode(true); }, this), this.options.suggestTimeout ); } else { this._clearResults(); } } } }), factory: function(options) { return new L.Control.Geocoder(options); } }; var Bing = { class: L.Class.extend({ initialize: function(key) { this.key = key; }, geocode: function(query, cb, context) { jsonp( 'https://dev.virtualearth.net/REST/v1/Locations', { query: query, key: this.key }, function(data) { var results = []; if (data.resourceSets.length > 0) { for (var i = data.resourceSets[0].resources.length - 1; i >= 0; i--) { var resource = data.resourceSets[0].resources[i], bbox = resource.bbox; results[i] = { name: resource.name, bbox: L.latLngBounds([bbox[0], bbox[1]], [bbox[2], bbox[3]]), center: L.latLng(resource.point.coordinates) }; } } cb.call(context, results); }, this, 'jsonp' ); }, reverse: function(location, scale, cb, context) { jsonp( '//dev.virtualearth.net/REST/v1/Locations/' + location.lat + ',' + location.lng, { key: this.key }, function(data) { var results = []; for (var i = data.resourceSets[0].resources.length - 1; i >= 0; i--) { var resource = data.resourceSets[0].resources[i], bbox = resource.bbox; results[i] = { name: resource.name, bbox: L.latLngBounds([bbox[0], bbox[1]], [bbox[2], bbox[3]]), center: L.latLng(resource.point.coordinates) }; } cb.call(context, results); }, this, 'jsonp' ); } }), factory: function(key) { return new L.Control.Geocoder.Bing(key); } }; var MapQuest = { class: L.Class.extend({ options: { serviceUrl: 'https://www.mapquestapi.com/geocoding/v1' }, initialize: function(key, options) { // MapQuest seems to provide URI encoded API keys, // so to avoid encoding them twice, we decode them here this._key = decodeURIComponent(key); L.Util.setOptions(this, options); }, _formatName: function() { var r = [], i; for (i = 0; i < arguments.length; i++) { if (arguments[i]) { r.push(arguments[i]); } } return r.join(', '); }, geocode: function(query, cb, context) { getJSON( this.options.serviceUrl + '/address', { key: this._key, location: query, limit: 5, outFormat: 'json' }, L.bind(function(data) { var results = [], loc, latLng; if (data.results && data.results[0].locations) { for (var i = data.results[0].locations.length - 1; i >= 0; i--) { loc = data.results[0].locations[i]; latLng = L.latLng(loc.latLng); results[i] = { name: this._formatName(loc.street, loc.adminArea4, loc.adminArea3, loc.adminArea1), bbox: L.latLngBounds(latLng, latLng), center: latLng }; } } cb.call(context, results); }, this) ); }, reverse: function(location, scale, cb, context) { getJSON( this.options.serviceUrl + '/reverse', { key: this._key, location: location.lat + ',' + location.lng, outputFormat: 'json' }, L.bind(function(data) { var results = [], loc, latLng; if (data.results && data.results[0].locations) { for (var i = data.results[0].locations.length - 1; i >= 0; i--) { loc = data.results[0].locations[i]; latLng = L.latLng(loc.latLng); results[i] = { name: this._formatName(loc.street, loc.adminArea4, loc.adminArea3, loc.adminArea1), bbox: L.latLngBounds(latLng, latLng), center: latLng }; } } cb.call(context, results); }, this) ); } }), factory: function(key, options) { return new L.Control.Geocoder.MapQuest(key, options); } }; var Mapbox = { class: L.Class.extend({ options: { serviceUrl: 'https://api.tiles.mapbox.com/v4/geocode/mapbox.places-v1/', geocodingQueryParams: {}, reverseQueryParams: {} }, initialize: function(accessToken, options) { L.setOptions(this, options); this.options.geocodingQueryParams.access_token = accessToken; this.options.reverseQueryParams.access_token = accessToken; }, geocode: function(query, cb, context) { var params = this.options.geocodingQueryParams; if ( typeof params.proximity !== 'undefined' && params.proximity.hasOwnProperty('lat') && params.proximity.hasOwnProperty('lng') ) { params.proximity = params.proximity.lng + ',' + params.proximity.lat; } getJSON(this.options.serviceUrl + encodeURIComponent(query) + '.json', params, function( data ) { var results = [], loc, latLng, latLngBounds; if (data.features && data.features.length) { for (var i = 0; i <= data.features.length - 1; i++) { loc = data.features[i]; latLng = L.latLng(loc.center.reverse()); if (loc.hasOwnProperty('bbox')) { latLngBounds = L.latLngBounds( L.latLng(loc.bbox.slice(0, 2).reverse()), L.latLng(loc.bbox.slice(2, 4).reverse()) ); } else { latLngBounds = L.latLngBounds(latLng, latLng); } results[i] = { name: loc.place_name, bbox: latLngBounds, center: latLng }; } } cb.call(context, results); }); }, suggest: function(query, cb, context) { return this.geocode(query, cb, context); }, reverse: function(location, scale, cb, context) { getJSON( this.options.serviceUrl + encodeURIComponent(location.lng) + ',' + encodeURIComponent(location.lat) + '.json', this.options.reverseQueryParams, function(data) { var results = [], loc, latLng, latLngBounds; if (data.features && data.features.length) { for (var i = 0; i <= data.features.length - 1; i++) { loc = data.features[i]; latLng = L.latLng(loc.center.reverse()); if (loc.hasOwnProperty('bbox')) { latLngBounds = L.latLngBounds( L.latLng(loc.bbox.slice(0, 2).reverse()), L.latLng(loc.bbox.slice(2, 4).reverse()) ); } else { latLngBounds = L.latLngBounds(latLng, latLng); } results[i] = { name: loc.place_name, bbox: latLngBounds, center: latLng }; } } cb.call(context, results); } ); } }), factory: function(accessToken, options) { return new L.Control.Geocoder.Mapbox(accessToken, options); } }; var What3Words = { class: L.Class.extend({ options: { serviceUrl: 'https://api.what3words.com/v2/' }, initialize: function(accessToken) { this._accessToken = accessToken; }, geocode: function(query, cb, context) { //get three words and make a dot based string getJSON( this.options.serviceUrl + 'forward', { key: this._accessToken, addr: query.split(/\s+/).join('.') }, function(data) { var results = [], latLng, latLngBounds; if (data.hasOwnProperty('geometry')) { latLng = L.latLng(data.geometry['lat'], data.geometry['lng']); latLngBounds = L.latLngBounds(latLng, latLng); results[0] = { name: data.words, bbox: latLngBounds, center: latLng }; } cb.call(context, results); } ); }, suggest: function(query, cb, context) { return this.geocode(query, cb, context); }, reverse: function(location, scale, cb, context) { getJSON( this.options.serviceUrl + 'reverse', { key: this._accessToken, coords: [location.lat, location.lng].join(',') }, function(data) { var results = [], latLng, latLngBounds; if (data.status.status == 200) { latLng = L.latLng(data.geometry['lat'], data.geometry['lng']); latLngBounds = L.latLngBounds(latLng, latLng); results[0] = { name: data.words, bbox: latLngBounds, center: latLng }; } cb.call(context, results); } ); } }), factory: function(accessToken) { return new L.Control.Geocoder.What3Words(accessToken); } }; var Google = { class: L.Class.extend({ options: { serviceUrl: 'https://maps.googleapis.com/maps/api/geocode/json', geocodingQueryParams: {}, reverseQueryParams: {} }, initialize: function(key, options) { this._key = key; L.setOptions(this, options); // Backwards compatibility this.options.serviceUrl = this.options.service_url || this.options.serviceUrl; }, geocode: function(query, cb, context) { var params = { address: query }; if (this._key && this._key.length) { params.key = this._key; } params = L.Util.extend(params, this.options.geocodingQueryParams); getJSON(this.options.serviceUrl, params, function(data) { var results = [], loc, latLng, latLngBounds; if (data.results && data.results.length) { for (var i = 0; i <= data.results.length - 1; i++) { loc = data.results[i]; latLng = L.latLng(loc.geometry.location); latLngBounds = L.latLngBounds( L.latLng(loc.geometry.viewport.northeast), L.latLng(loc.geometry.viewport.southwest) ); results[i] = { name: loc.formatted_address, bbox: latLngBounds, center: latLng, properties: loc.address_components }; } } cb.call(context, results); }); }, reverse: function(location, scale, cb, context) { var params = { latlng: encodeURIComponent(location.lat) + ',' + encodeURIComponent(location.lng) }; params = L.Util.extend(params, this.options.reverseQueryParams); if (this._key && this._key.length) { params.key = this._key; } getJSON(this.options.serviceUrl, params, function(data) { var results = [], loc, latLng, latLngBounds; if (data.results && data.results.length) { for (var i = 0; i <= data.results.length - 1; i++) { loc = data.results[i]; latLng = L.latLng(loc.geometry.location); latLngBounds = L.latLngBounds( L.latLng(loc.geometry.viewport.northeast), L.latLng(loc.geometry.viewport.southwest) ); results[i] = { name: loc.formatted_address, bbox: latLngBounds, center: latLng, properties: loc.address_components }; } } cb.call(context, results); }); } }), factory: function(key, options) { return new L.Control.Geocoder.Google(key, options); } }; var Photon = { class: L.Class.extend({ options: { serviceUrl: 'https://photon.komoot.de/api/', reverseUrl: 'https://photon.komoot.de/reverse/', nameProperties: ['name', 'street', 'suburb', 'hamlet', 'town', 'city', 'state', 'country'] }, initialize: function(options) { L.setOptions(this, options); }, geocode: function(query, cb, context) { var params = L.extend( { q: query }, this.options.geocodingQueryParams ); getJSON( this.options.serviceUrl, params, L.bind(function(data) { cb.call(context, this._decodeFeatures(data)); }, this) ); }, suggest: function(query, cb, context) { return this.geocode(query, cb, context); }, reverse: function(latLng, scale, cb, context) { var params = L.extend( { lat: latLng.lat, lon: latLng.lng }, this.options.reverseQueryParams ); getJSON( this.options.reverseUrl, params, L.bind(function(data) { cb.call(context, this._decodeFeatures(data)); }, this) ); }, _decodeFeatures: function(data) { var results = [], i, f, c, latLng, extent, bbox; if (data && data.features) { for (i = 0; i < data.features.length; i++) { f = data.features[i]; c = f.geometry.coordinates; latLng = L.latLng(c[1], c[0]); extent = f.properties.extent; if (extent) { bbox = L.latLngBounds([extent[1], extent[0]], [extent[3], extent[2]]); } else { bbox = L.latLngBounds(latLng, latLng); } results.push({ name: this._deocodeFeatureName(f), html: this.options.htmlTemplate ? this.options.htmlTemplate(f) : undefined, center: latLng, bbox: bbox, properties: f.properties }); } } return results; }, _deocodeFeatureName: function(f) { var j, name; for (j = 0; !name && j < this.options.nameProperties.length; j++) { name = f.properties[this.options.nameProperties[j]]; } return name; } }), factory: function(options) { return new L.Control.Geocoder.Photon(options); } }; var Mapzen = { class: L.Class.extend({ options: { serviceUrl: 'https://search.mapzen.com/v1', geocodingQueryParams: {}, reverseQueryParams: {} }, initialize: function(apiKey, options) { L.Util.setOptions(this, options); this._apiKey = apiKey; this._lastSuggest = 0; }, geocode: function(query, cb, context) { var _this = this; getJSON( this.options.serviceUrl + '/search', L.extend( { api_key: this._apiKey, text: query }, this.options.geocodingQueryParams ), function(data) { cb.call(context, _this._parseResults(data, 'bbox')); } ); }, suggest: function(query, cb, context) { var _this = this; getJSON( this.options.serviceUrl + '/autocomplete', L.extend( { api_key: this._apiKey, text: query }, this.options.geocodingQueryParams ), L.bind(function(data) { if (data.geocoding.timestamp > this._lastSuggest) { this._lastSuggest = data.geocoding.timestamp; cb.call(context, _this._parseResults(data, 'bbox')); } }, this) ); }, reverse: function(location, scale, cb, context) { var _this = this; getJSON( this.options.serviceUrl + '/reverse', L.extend( { api_key: this._apiKey, 'point.lat': location.lat, 'point.lon': location.lng }, this.options.reverseQueryParams ), function(data) { cb.call(context, _this._parseResults(data, 'bounds')); } ); }, _parseResults: function(data, bboxname) { var results = []; L.geoJson(data, { pointToLayer: function(feature, latlng) { return L.circleMarker(latlng); }, onEachFeature: function(feature, layer) { var result = {}, bbox, center; if (layer.getBounds) { bbox = layer.getBounds(); center = bbox.getCenter(); } else { center = layer.getLatLng(); bbox = L.latLngBounds(center, center); } result.name = layer.feature.properties.label; result.center = center; result[bboxname] = bbox; result.properties = layer.feature.properties; results.push(result); } }); return results; } }), factory: function(apiKey, options) { return new L.Control.Geocoder.Mapzen(apiKey, options); } }; var ArcGis = { class: L.Class.extend({ options: { service_url: 'http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer' }, initialize: function(accessToken, options) { L.setOptions(this, options); this._accessToken = accessToken; }, geocode: function(query, cb, context) { var params = { SingleLine: query, outFields: 'Addr_Type', forStorage: false, maxLocations: 10, f: 'json' }; if (this._key && this._key.length) { params.token = this._key; } getJSON(this.options.service_url + '/findAddressCandidates', params, function(data) { var results = [], loc, latLng, latLngBounds; if (data.candidates && data.candidates.length) { for (var i = 0; i <= data.candidates.length - 1; i++) { loc = data.candidates[i]; latLng = L.latLng(loc.location.y, loc.location.x); latLngBounds = L.latLngBounds( L.latLng(loc.extent.ymax, loc.extent.xmax), L.latLng(loc.extent.ymin, loc.extent.xmin) ); results[i] = { name: loc.address, bbox: latLngBounds, center: latLng }; } } cb.call(context, results); }); }, suggest: function(query, cb, context) { return this.geocode(query, cb, context); }, reverse: function(location, scale, cb, context) { var params = { location: encodeURIComponent(location.lng) + ',' + encodeURIComponent(location.lat), distance: 100, f: 'json' }; getJSON(this.options.service_url + '/reverseGeocode', params, function(data) { var result = [], loc; if (data && !data.error) { loc = L.latLng(data.location.y, data.location.x); result.push({ name: data.address.Match_addr, center: loc, bounds: L.latLngBounds(loc, loc) }); } cb.call(context, result); }); } }), factory: function(accessToken, options) { return new L.Control.Geocoder.ArcGis(accessToken, options); } }; var HERE = { class: L.Class.extend({ options: { geocodeUrl: 'http://geocoder.api.here.com/6.2/geocode.json', reverseGeocodeUrl: 'http://reverse.geocoder.api.here.com/6.2/reversegeocode.json', app_id: '<insert your app_id here>', app_code: '<insert your app_code here>', geocodingQueryParams: {}, reverseQueryParams: {} }, initialize: function(options) { L.setOptions(this, options); }, geocode: function(query, cb, context) { var params = { searchtext: query, gen: 9, app_id: this.options.app_id, app_code: this.options.app_code, jsonattributes: 1 }; params = L.Util.extend(params, this.options.geocodingQueryParams); this.getJSON(this.options.geocodeUrl, params, cb, context); }, reverse: function(location, scale, cb, context) { var params = { prox: encodeURIComponent(location.lat) + ',' + encodeURIComponent(location.lng), mode: 'retrieveAddresses', app_id: this.options.app_id, app_code: this.options.app_code, gen: 9, jsonattributes: 1 }; params = L.Util.extend(params, this.options.reverseQueryParams); this.getJSON(this.options.reverseGeocodeUrl, params, cb, context); }, getJSON: function(url, params, cb, context) { getJSON(url, params, function(data) { var results = [], loc, latLng, latLngBounds; if (data.response.view && data.response.view.length) { for (var i = 0; i <= data.response.view[0].result.length - 1; i++) { loc = data.response.view[0].result[i].location; latLng = L.latLng(loc.displayPosition.latitude, loc.displayPosition.longitude); latLngBounds = L.latLngBounds( L.latLng(loc.mapView.topLeft.latitude, loc.mapView.topLeft.longitude), L.latLng(loc.mapView.bottomRight.latitude, loc.mapView.bottomRight.longitude) ); results[i] = { name: loc.address.label, bbox: latLngBounds, center: latLng }; } } cb.call(context, results); }); } }), factory: function(options) { return new L.Control.Geocoder.HERE(options); } }; var Geocoder = L.Util.extend(Control.class, { Nominatim: Nominatim.class, nominatim: Nominatim.factory, Bing: Bing.class, bing: Bing.factory, MapQuest: MapQuest.class, mapQuest: MapQuest.factory, Mapbox: Mapbox.class, mapbox: Mapbox.factory, What3Words: What3Words.class, what3words: What3Words.factory, Google: Google.class, google: Google.factory, Photon: Photon.class, photon: Photon.factory, Mapzen: Mapzen.class, mapzen: Mapzen.factory, ArcGis: ArcGis.class, arcgis: ArcGis.factory, HERE: HERE.class, here: HERE.factory }); L.Util.extend(L.Control, { Geocoder: Geocoder, geocoder: Control.factory }); return Geocoder; }(L)); //# sourceMappingURL=Control.Geocoder.js.map
ThomasDaheim/GPXEditor
src/main/resources/leaflet/geocoder/Control.Geocoder.js
JavaScript
bsd-3-clause
37,785
/* The contents of this file are subject to the Netscape Public License * Version 1.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.mozilla.org/NPL/ * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * The Original Code is Mozilla Communicator client code, released March * 31, 1998. * * The Initial Developer of the Original Code is Netscape Communications * Corporation. Portions created by Netscape are Copyright (C) 1998 * Netscape Communications Corporation. All Rights Reserved. * */ /** File Name: 15.5.4.9-1.js ECMA Section: 15.5.4.9 String.prototype.substring( start ) Description: 15.5.4.9 String.prototype.substring(start) Returns a substring of the result of converting this object to a string, starting from character position start and running to the end of the string. The result is a string value, not a String object. If the argument is NaN or negative, it is replaced with zero; if the argument is larger than the length of the string, it is replaced with the length of the string. When the substring method is called with one argument start, the following steps are taken: 1.Call ToString, giving it the this value as its argument. 2.Call ToInteger(start). 3.Compute the number of characters in Result(1). 4.Compute min(max(Result(2), 0), Result(3)). 5.Return a string whose length is the difference between Result(3) and Result(4), containing characters from Result(1), namely the characters with indices Result(4) through Result(3)1, in ascending order. Author: christine@netscape.com Date: 12 november 1997 */ var SECTION = "15.5.4.9-1"; var VERSION = "ECMA_1"; startTest(); var TITLE = "String.prototype.substring( start )"; writeHeaderToLog( SECTION + " "+ TITLE); var testcases = getTestCases(); test(); function getTestCases() { var array = new Array(); var item = 0; array[item++] = new TestCase( SECTION, "String.prototype.substring.length", 2, String.prototype.substring.length ); array[item++] = new TestCase( SECTION, "delete String.prototype.substring.length", false, delete String.prototype.substring.length ); array[item++] = new TestCase( SECTION, "delete String.prototype.substring.length; String.prototype.substring.length", 2, eval("delete String.prototype.substring.length; String.prototype.substring.length") ); // test cases for when substring is called with no arguments. // this is a string object array[item++] = new TestCase( SECTION, "var s = new String('this is a string object'); typeof s.substring()", "string", eval("var s = new String('this is a string object'); typeof s.substring()") ); array[item++] = new TestCase( SECTION, "var s = new String(''); s.substring()", "", eval("var s = new String(''); s.substring()") ); array[item++] = new TestCase( SECTION, "var s = new String('this is a string object'); s.substring()", "this is a string object", eval("var s = new String('this is a string object'); s.substring()") ); array[item++] = new TestCase( SECTION, "var s = new String('this is a string object'); s.substring(NaN)", "this is a string object", eval("var s = new String('this is a string object'); s.substring(NaN)") ); array[item++] = new TestCase( SECTION, "var s = new String('this is a string object'); s.substring(-0.01)", "this is a string object", eval("var s = new String('this is a string object'); s.substring(-0.01)") ); array[item++] = new TestCase( SECTION, "var s = new String('this is a string object'); s.substring(s.length)", "", eval("var s = new String('this is a string object'); s.substring(s.length)") ); array[item++] = new TestCase( SECTION, "var s = new String('this is a string object'); s.substring(s.length+1)", "", eval("var s = new String('this is a string object'); s.substring(s.length+1)") ); array[item++] = new TestCase( SECTION, "var s = new String('this is a string object'); s.substring(Infinity)", "", eval("var s = new String('this is a string object'); s.substring(Infinity)") ); array[item++] = new TestCase( SECTION, "var s = new String('this is a string object'); s.substring(-Infinity)", "this is a string object", eval("var s = new String('this is a string object'); s.substring(-Infinity)") ); // this is not a String object, start is not an integer array[item++] = new TestCase( SECTION, "var s = new Array(1,2,3,4,5); s.substring = String.prototype.substring; s.substring()", "1,2,3,4,5", eval("var s = new Array(1,2,3,4,5); s.substring = String.prototype.substring; s.substring()") ); array[item++] = new TestCase( SECTION, "var s = new Array(1,2,3,4,5); s.substring = String.prototype.substring; s.substring(true)", ",2,3,4,5", eval("var s = new Array(1,2,3,4,5); s.substring = String.prototype.substring; s.substring(true)") ); array[item++] = new TestCase( SECTION, "var s = new Array(1,2,3,4,5); s.substring = String.prototype.substring; s.substring('4')", "3,4,5", eval("var s = new Array(1,2,3,4,5); s.substring = String.prototype.substring; s.substring('4')") ); array[item++] = new TestCase( SECTION, "var s = new Array(); s.substring = String.prototype.substring; s.substring('4')", "", eval("var s = new Array(); s.substring = String.prototype.substring; s.substring('4')") ); // this is an object object array[item++] = new TestCase( SECTION, "var obj = new Object(); obj.substring = String.prototype.substring; obj.substring(8)", "Object]", eval("var obj = new Object(); obj.substring = String.prototype.substring; obj.substring(8)") ); // this is a function object array[item++] = new TestCase( SECTION, "var obj = new Function(); obj.substring = String.prototype.substring; obj.toString = Object.prototype.toString; obj.substring(8)", "Function]", eval("var obj = new Function(); obj.substring = String.prototype.substring; obj.toString = Object.prototype.toString; obj.substring(8)") ); // this is a number object array[item++] = new TestCase( SECTION, "var obj = new Number(NaN); obj.substring = String.prototype.substring; obj.substring(false)", "NaN", eval("var obj = new Number(NaN); obj.substring = String.prototype.substring; obj.substring(false)") ); // this is the Math object array[item++] = new TestCase( SECTION, "var obj = Math; obj.substring = String.prototype.substring; obj.substring(Math.PI)", "ject Math]", eval("var obj = Math; obj.substring = String.prototype.substring; obj.substring(Math.PI)") ); // this is a Boolean object array[item++] = new TestCase( SECTION, "var obj = new Boolean(); obj.substring = String.prototype.substring; obj.substring(new Array())", "false", eval("var obj = new Boolean(); obj.substring = String.prototype.substring; obj.substring(new Array())") ); // this is a user defined object array[item++] = new TestCase( SECTION, "var obj = new MyObject( null ); obj.substring(0)", "null", eval( "var obj = new MyObject( null ); obj.substring(0)") ); return array; } function test() { for ( tc=0; tc < testcases.length; tc++ ) { testcases[tc].passed = writeTestCaseResult( testcases[tc].expect, testcases[tc].actual, testcases[tc].description +" = "+ testcases[tc].actual ); testcases[tc].reason += ( testcases[tc].passed ) ? "" : "wrong value "; } stopTest(); return ( testcases ); } function MyObject( value ) { this.value = value; this.substring = String.prototype.substring; this.toString = new Function ( "return this.value+''" ); }
frivoal/presto-testo
core/standards/scripts/jstest-futhark/es-regression/imported-netscape/ecma/String/15.5.4.9-1.js
JavaScript
bsd-3-clause
10,111
var getSchema = require('../../../server/data/meta/schema'), should = require('should'); describe('getSchema', function () { it('should return post schema if context starts with post', function () { var metadata = { blog: { title: 'Blog Title', logo: 'http://mysite.com/author/image/url/logo.jpg' }, authorImage: 'http://mysite.com/author/image/url/me.jpg', authorFacebook: 'testuser', creatorTwitter: '@testuser', authorUrl: 'http://mysite.com/author/me/', metaTitle: 'Post Title', url: 'http://mysite.com/post/my-post-slug/', publishedDate: '2015-12-25T05:35:01.234Z', modifiedDate: '2016-01-21T22:13:05.412Z', coverImage: 'http://mysite.com/content/image/mypostcoverimage.jpg', keywords: ['one', 'two', 'tag'], metaDescription: 'Post meta description' }, data = { context: ['post'], post: { author: { name: 'Post Author', website: 'http://myblogsite.com/', bio: 'My author bio.', facebook: 'testuser', twitter: '@testuser' } } }, schema = getSchema(metadata, data); should.deepEqual(schema, { '@context': 'https://schema.org', '@type': 'Article', author: { '@type': 'Person', description: 'My author bio.', image: 'http://mysite.com/author/image/url/me.jpg', name: 'Post Author', sameAs: [ 'http://myblogsite.com/', 'https://www.facebook.com/testuser', 'https://twitter.com/testuser' ], url: 'http://mysite.com/author/me/' }, dateModified: '2016-01-21T22:13:05.412Z', datePublished: '2015-12-25T05:35:01.234Z', description: 'Post meta description', headline: 'Post Title', image: 'http://mysite.com/content/image/mypostcoverimage.jpg', keywords: 'one, two, tag', publisher: { '@type': 'Organization', name: 'Blog Title', logo: 'http://mysite.com/author/image/url/logo.jpg' }, url: 'http://mysite.com/post/my-post-slug/' }); }); it('should return post schema removing null or undefined values', function () { var metadata = { blog: { title: 'Blog Title' }, authorImage: null, authorFacebook: undefined, creatorTwitter: undefined, authorUrl: 'http://mysite.com/author/me/', metaTitle: 'Post Title', url: 'http://mysite.com/post/my-post-slug/', publishedDate: '2015-12-25T05:35:01.234Z', modifiedDate: '2016-01-21T22:13:05.412Z', coverImage: undefined, keywords: [], metaDescription: 'Post meta description' }, data = { context: ['post'], post: { author: { name: 'Post Author', website: undefined, bio: null, facebook: null, twitter: null } } }, schema = getSchema(metadata, data); should.deepEqual(schema, { '@context': 'https://schema.org', '@type': 'Article', author: { '@type': 'Person', name: 'Post Author', sameAs: [], url: 'http://mysite.com/author/me/' }, dateModified: '2016-01-21T22:13:05.412Z', datePublished: '2015-12-25T05:35:01.234Z', description: 'Post meta description', headline: 'Post Title', publisher: { '@type': 'Organization', name: 'Blog Title', logo: null }, url: 'http://mysite.com/post/my-post-slug/' }); }); it('should return home schema if context starts with home', function () { var metadata = { blog: { title: 'Blog Title' }, url: 'http://mysite.com/post/my-post-slug/', coverImage: 'http://mysite.com/content/image/mypostcoverimage.jpg', metaDescription: 'This is the theme description' }, data = { context: ['home'] }, schema = getSchema(metadata, data); should.deepEqual(schema, { '@context': 'https://schema.org', '@type': 'Website', description: 'This is the theme description', image: 'http://mysite.com/content/image/mypostcoverimage.jpg', publisher: 'Blog Title', url: 'http://mysite.com/post/my-post-slug/' }); }); it('should return tag schema if context starts with tag', function () { var metadata = { blog: { title: 'Blog Title' }, url: 'http://mysite.com/post/my-post-slug/', coverImage: 'http://mysite.com/content/image/mypostcoverimage.jpg', metaDescription: 'This is the tag description!' }, data = { context: ['tag'], tag: { name: 'Great Tag' } }, schema = getSchema(metadata, data); should.deepEqual(schema, { '@context': 'https://schema.org', '@type': 'Series', description: 'This is the tag description!', image: 'http://mysite.com/content/image/mypostcoverimage.jpg', name: 'Great Tag', publisher: 'Blog Title', url: 'http://mysite.com/post/my-post-slug/' }); }); it('should return author schema if context starts with author', function () { var metadata = { blog: { title: 'Blog Title' }, authorImage: 'http://mysite.com/author/image/url/me.jpg', authorUrl: 'http://mysite.com/author/me/', metaDescription: 'This is the author description!' }, data = { context: ['author'], author: { name: 'Author Name', website: 'http://myblogsite.com/', twitter: '@testuser' } }, schema = getSchema(metadata, data); should.deepEqual(schema, { '@context': 'https://schema.org', '@type': 'Person', description: 'This is the author description!', name: 'Author Name', sameAs: [ 'http://myblogsite.com/', 'https://twitter.com/testuser' ], url: 'http://mysite.com/author/me/' }); }); it('should return null if not a supported type', function () { var metadata = {}, data = {}, schema = getSchema(metadata, data); should.deepEqual(schema, null); }); });
NovaDevelopGroup/Academy
core/test/unit/metadata/schema_spec.js
JavaScript
mit
7,260
// This service worker is required to expose an exported Godot project as a // Progressive Web App. It provides an offline fallback page telling the user // that they need an Internet connection to run the project if desired. // Incrementing CACHE_VERSION will kick off the install event and force // previously cached resources to be updated from the network. const CACHE_VERSION = "@GODOT_VERSION@"; const CACHE_NAME = "@GODOT_NAME@-cache"; const OFFLINE_URL = "@GODOT_OFFLINE_PAGE@"; // Files that will be cached on load. const CACHED_FILES = @GODOT_CACHE@; // Files that we might not want the user to preload, and will only be cached on first load. const CACHABLE_FILES = @GODOT_OPT_CACHE@; const FULL_CACHE = CACHED_FILES.concat(CACHABLE_FILES); self.addEventListener("install", (event) => { event.waitUntil(async function () { const cache = await caches.open(CACHE_NAME); // Clear old cache (including optionals). await Promise.all(FULL_CACHE.map(path => cache.delete(path))); // Insert new one. const done = await cache.addAll(CACHED_FILES); return done; }()); }); self.addEventListener("activate", (event) => { event.waitUntil(async function () { if ("navigationPreload" in self.registration) { await self.registration.navigationPreload.enable(); } }()); // Tell the active service worker to take control of the page immediately. self.clients.claim(); }); self.addEventListener("fetch", (event) => { const isNavigate = event.request.mode === "navigate"; const url = event.request.url || ""; const referrer = event.request.referrer || ""; const base = referrer.slice(0, referrer.lastIndexOf("/") + 1); const local = url.startsWith(base) ? url.replace(base, "") : ""; const isCachable = FULL_CACHE.some(v => v === local) || (base === referrer && base.endsWith(CACHED_FILES[0])); if (isNavigate || isCachable) { event.respondWith(async function () { try { // Use the preloaded response, if it's there let request = event.request.clone(); let response = await event.preloadResponse; if (!response) { // Or, go over network. response = await fetch(event.request); } if (isCachable) { // Update the cache const cache = await caches.open(CACHE_NAME); cache.put(request, response.clone()); } return response; } catch (error) { const cache = await caches.open(CACHE_NAME); if (event.request.mode === "navigate") { // Check if we have full cache. const cached = await Promise.all(FULL_CACHE.map(name => cache.match(name))); const missing = cached.some(v => v === undefined); const cachedResponse = missing ? await caches.match(OFFLINE_URL) : await caches.match(CACHED_FILES[0]); return cachedResponse; } const cachedResponse = await caches.match(event.request); return cachedResponse; } }()); } });
honix/godot
misc/dist/html/service-worker.js
JavaScript
mit
2,848
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _actionTypes = require('./actionTypes'); var _deleteInWithCleanUp = require('./deleteInWithCleanUp'); var _deleteInWithCleanUp2 = _interopRequireDefault(_deleteInWithCleanUp); var _plain = require('./structure/plain'); var _plain2 = _interopRequireDefault(_plain); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } var isReduxFormAction = function isReduxFormAction(action) { return action && action.type && action.type.length > _actionTypes.prefix.length && action.type.substring(0, _actionTypes.prefix.length) === _actionTypes.prefix; }; var createReducer = function createReducer(structure) { var _behaviors; var deepEqual = structure.deepEqual, empty = structure.empty, getIn = structure.getIn, setIn = structure.setIn, deleteIn = structure.deleteIn, fromJS = structure.fromJS, keys = structure.keys, size = structure.size, splice = structure.splice; var deleteInWithCleanUp = (0, _deleteInWithCleanUp2.default)(structure); var doSplice = function doSplice(state, key, field, index, removeNum, value, force) { var existing = getIn(state, key + '.' + field); return existing || force ? setIn(state, key + '.' + field, splice(existing, index, removeNum, value)) : state; }; var doPlainSplice = function doPlainSplice(state, key, field, index, removeNum, value, force) { var slice = getIn(state, key); var existing = _plain2.default.getIn(slice, field); return existing || force ? setIn(state, key, _plain2.default.setIn(slice, field, _plain2.default.splice(existing, index, removeNum, value))) : state; }; var rootKeys = ['values', 'fields', 'submitErrors', 'asyncErrors']; var arraySplice = function arraySplice(state, field, index, removeNum, value) { var result = state; var nonValuesValue = value != null ? empty : undefined; result = doSplice(result, 'values', field, index, removeNum, value, true); result = doSplice(result, 'fields', field, index, removeNum, nonValuesValue); result = doPlainSplice(result, 'syncErrors', field, index, removeNum, undefined); result = doPlainSplice(result, 'syncWarnings', field, index, removeNum, undefined); result = doSplice(result, 'submitErrors', field, index, removeNum, undefined); result = doSplice(result, 'asyncErrors', field, index, removeNum, undefined); return result; }; var behaviors = (_behaviors = {}, _defineProperty(_behaviors, _actionTypes.ARRAY_INSERT, function (state, _ref) { var _ref$meta = _ref.meta, field = _ref$meta.field, index = _ref$meta.index, payload = _ref.payload; return arraySplice(state, field, index, 0, payload); }), _defineProperty(_behaviors, _actionTypes.ARRAY_MOVE, function (state, _ref2) { var _ref2$meta = _ref2.meta, field = _ref2$meta.field, from = _ref2$meta.from, to = _ref2$meta.to; var array = getIn(state, 'values.' + field); var length = array ? size(array) : 0; var result = state; if (length) { rootKeys.forEach(function (key) { var path = key + '.' + field; if (getIn(result, path)) { var value = getIn(result, path + '[' + from + ']'); result = setIn(result, path, splice(getIn(result, path), from, 1)); // remove result = setIn(result, path, splice(getIn(result, path), to, 0, value)); // insert } }); } return result; }), _defineProperty(_behaviors, _actionTypes.ARRAY_POP, function (state, _ref3) { var field = _ref3.meta.field; var array = getIn(state, 'values.' + field); var length = array ? size(array) : 0; return length ? arraySplice(state, field, length - 1, 1) : state; }), _defineProperty(_behaviors, _actionTypes.ARRAY_PUSH, function (state, _ref4) { var field = _ref4.meta.field, payload = _ref4.payload; var array = getIn(state, 'values.' + field); var length = array ? size(array) : 0; return arraySplice(state, field, length, 0, payload); }), _defineProperty(_behaviors, _actionTypes.ARRAY_REMOVE, function (state, _ref5) { var _ref5$meta = _ref5.meta, field = _ref5$meta.field, index = _ref5$meta.index; return arraySplice(state, field, index, 1); }), _defineProperty(_behaviors, _actionTypes.ARRAY_REMOVE_ALL, function (state, _ref6) { var field = _ref6.meta.field; var array = getIn(state, 'values.' + field); var length = array ? size(array) : 0; return length ? arraySplice(state, field, 0, length) : state; }), _defineProperty(_behaviors, _actionTypes.ARRAY_SHIFT, function (state, _ref7) { var field = _ref7.meta.field; return arraySplice(state, field, 0, 1); }), _defineProperty(_behaviors, _actionTypes.ARRAY_SPLICE, function (state, _ref8) { var _ref8$meta = _ref8.meta, field = _ref8$meta.field, index = _ref8$meta.index, removeNum = _ref8$meta.removeNum, payload = _ref8.payload; return arraySplice(state, field, index, removeNum, payload); }), _defineProperty(_behaviors, _actionTypes.ARRAY_SWAP, function (state, _ref9) { var _ref9$meta = _ref9.meta, field = _ref9$meta.field, indexA = _ref9$meta.indexA, indexB = _ref9$meta.indexB; var result = state; rootKeys.forEach(function (key) { var valueA = getIn(result, key + '.' + field + '[' + indexA + ']'); var valueB = getIn(result, key + '.' + field + '[' + indexB + ']'); if (valueA !== undefined || valueB !== undefined) { result = setIn(result, key + '.' + field + '[' + indexA + ']', valueB); result = setIn(result, key + '.' + field + '[' + indexB + ']', valueA); } }); return result; }), _defineProperty(_behaviors, _actionTypes.ARRAY_UNSHIFT, function (state, _ref10) { var field = _ref10.meta.field, payload = _ref10.payload; return arraySplice(state, field, 0, 0, payload); }), _defineProperty(_behaviors, _actionTypes.AUTOFILL, function (state, _ref11) { var field = _ref11.meta.field, payload = _ref11.payload; var result = state; result = deleteInWithCleanUp(result, 'asyncErrors.' + field); result = deleteInWithCleanUp(result, 'submitErrors.' + field); result = setIn(result, 'fields.' + field + '.autofilled', true); result = setIn(result, 'values.' + field, payload); return result; }), _defineProperty(_behaviors, _actionTypes.BLUR, function (state, _ref12) { var _ref12$meta = _ref12.meta, field = _ref12$meta.field, touch = _ref12$meta.touch, payload = _ref12.payload; var result = state; var initial = getIn(result, 'initial.' + field); if (initial === undefined && payload === '') { result = deleteInWithCleanUp(result, 'values.' + field); } else if (payload !== undefined) { result = setIn(result, 'values.' + field, payload); } if (field === getIn(result, 'active')) { result = deleteIn(result, 'active'); } result = deleteIn(result, 'fields.' + field + '.active'); if (touch) { result = setIn(result, 'fields.' + field + '.touched', true); result = setIn(result, 'anyTouched', true); } return result; }), _defineProperty(_behaviors, _actionTypes.CHANGE, function (state, _ref13) { var _ref13$meta = _ref13.meta, field = _ref13$meta.field, touch = _ref13$meta.touch, persistentSubmitErrors = _ref13$meta.persistentSubmitErrors, payload = _ref13.payload; var result = state; var initial = getIn(result, 'initial.' + field); if (initial === undefined && payload === '') { result = deleteInWithCleanUp(result, 'values.' + field); } else if (payload !== undefined) { result = setIn(result, 'values.' + field, payload); } result = deleteInWithCleanUp(result, 'asyncErrors.' + field); if (!persistentSubmitErrors) { result = deleteInWithCleanUp(result, 'submitErrors.' + field); } result = deleteInWithCleanUp(result, 'fields.' + field + '.autofilled'); if (touch) { result = setIn(result, 'fields.' + field + '.touched', true); result = setIn(result, 'anyTouched', true); } return result; }), _defineProperty(_behaviors, _actionTypes.CLEAR_SUBMIT, function (state) { return deleteIn(state, 'triggerSubmit'); }), _defineProperty(_behaviors, _actionTypes.CLEAR_SUBMIT_ERRORS, function (state) { return deleteInWithCleanUp(state, 'submitErrors'); }), _defineProperty(_behaviors, _actionTypes.CLEAR_ASYNC_ERROR, function (state, _ref14) { var field = _ref14.meta.field; return deleteIn(state, 'asyncErrors.' + field); }), _defineProperty(_behaviors, _actionTypes.FOCUS, function (state, _ref15) { var field = _ref15.meta.field; var result = state; var previouslyActive = getIn(state, 'active'); result = deleteIn(result, 'fields.' + previouslyActive + '.active'); result = setIn(result, 'fields.' + field + '.visited', true); result = setIn(result, 'fields.' + field + '.active', true); result = setIn(result, 'active', field); return result; }), _defineProperty(_behaviors, _actionTypes.INITIALIZE, function (state, _ref16) { var payload = _ref16.payload, _ref16$meta = _ref16.meta, keepDirty = _ref16$meta.keepDirty, keepSubmitSucceeded = _ref16$meta.keepSubmitSucceeded; var mapData = fromJS(payload); var result = empty; // clean all field state // persist old warnings, they will get recalculated if the new form values are different from the old values var warning = getIn(state, 'warning'); if (warning) { result = setIn(result, 'warning', warning); } var syncWarnings = getIn(state, 'syncWarnings'); if (syncWarnings) { result = setIn(result, 'syncWarnings', syncWarnings); } // persist old errors, they will get recalculated if the new form values are different from the old values var error = getIn(state, 'error'); if (error) { result = setIn(result, 'error', error); } var syncErrors = getIn(state, 'syncErrors'); if (syncErrors) { result = setIn(result, 'syncErrors', syncErrors); } var registeredFields = getIn(state, 'registeredFields'); if (registeredFields) { result = setIn(result, 'registeredFields', registeredFields); } var newValues = mapData; if (keepDirty && registeredFields) { // // Keep the value of dirty fields while updating the value of // pristine fields. This way, apps can reinitialize forms while // avoiding stomping on user edits. // // Note 1: The initialize action replaces all initial values // regardless of keepDirty. // // Note 2: When a field is dirty, keepDirty is enabled, and the field // value is the same as the new initial value for the field, the // initialize action causes the field to become pristine. That effect // is what we want. // var previousValues = getIn(state, 'values'); var previousInitialValues = getIn(state, 'initial'); keys(registeredFields).forEach(function (name) { var previousInitialValue = getIn(previousInitialValues, name); var previousValue = getIn(previousValues, name); if (!deepEqual(previousValue, previousInitialValue)) { // This field was dirty. Restore the dirty value. newValues = setIn(newValues, name, previousValue); } }); } if (keepSubmitSucceeded && getIn(state, 'submitSucceeded')) { result = setIn(result, 'submitSucceeded', true); } result = setIn(result, 'values', newValues); result = setIn(result, 'initial', mapData); return result; }), _defineProperty(_behaviors, _actionTypes.REGISTER_FIELD, function (state, _ref17) { var _ref17$payload = _ref17.payload, name = _ref17$payload.name, type = _ref17$payload.type; var key = 'registeredFields[\'' + name + '\']'; var field = getIn(state, key); if (field) { var count = getIn(field, 'count') + 1; field = setIn(field, 'count', count); } else { field = fromJS({ name: name, type: type, count: 1 }); } return setIn(state, key, field); }), _defineProperty(_behaviors, _actionTypes.RESET, function (state) { var result = empty; var registeredFields = getIn(state, 'registeredFields'); if (registeredFields) { result = setIn(result, 'registeredFields', registeredFields); } var values = getIn(state, 'initial'); if (values) { result = setIn(result, 'values', values); result = setIn(result, 'initial', values); } return result; }), _defineProperty(_behaviors, _actionTypes.SUBMIT, function (state) { return setIn(state, 'triggerSubmit', true); }), _defineProperty(_behaviors, _actionTypes.START_ASYNC_VALIDATION, function (state, _ref18) { var field = _ref18.meta.field; return setIn(state, 'asyncValidating', field || true); }), _defineProperty(_behaviors, _actionTypes.START_SUBMIT, function (state) { return setIn(state, 'submitting', true); }), _defineProperty(_behaviors, _actionTypes.STOP_ASYNC_VALIDATION, function (state, _ref19) { var payload = _ref19.payload; var result = state; result = deleteIn(result, 'asyncValidating'); if (payload && Object.keys(payload).length) { var _error = payload._error, fieldErrors = _objectWithoutProperties(payload, ['_error']); if (_error) { result = setIn(result, 'error', _error); } if (Object.keys(fieldErrors).length) { result = setIn(result, 'asyncErrors', fromJS(fieldErrors)); } else { result = deleteIn(result, 'asyncErrors'); } } else { result = deleteIn(result, 'error'); result = deleteIn(result, 'asyncErrors'); } return result; }), _defineProperty(_behaviors, _actionTypes.STOP_SUBMIT, function (state, _ref20) { var payload = _ref20.payload; var result = state; result = deleteIn(result, 'submitting'); result = deleteIn(result, 'submitFailed'); result = deleteIn(result, 'submitSucceeded'); if (payload && Object.keys(payload).length) { var _error = payload._error, fieldErrors = _objectWithoutProperties(payload, ['_error']); if (_error) { result = setIn(result, 'error', _error); } else { result = deleteIn(result, 'error'); } if (Object.keys(fieldErrors).length) { result = setIn(result, 'submitErrors', fromJS(fieldErrors)); } else { result = deleteIn(result, 'submitErrors'); } result = setIn(result, 'submitFailed', true); } else { result = setIn(result, 'submitSucceeded', true); result = deleteIn(result, 'error'); result = deleteIn(result, 'submitErrors'); } return result; }), _defineProperty(_behaviors, _actionTypes.SET_SUBMIT_FAILED, function (state, _ref21) { var fields = _ref21.meta.fields; var result = state; result = setIn(result, 'submitFailed', true); result = deleteIn(result, 'submitSucceeded'); result = deleteIn(result, 'submitting'); fields.forEach(function (field) { return result = setIn(result, 'fields.' + field + '.touched', true); }); if (fields.length) { result = setIn(result, 'anyTouched', true); } return result; }), _defineProperty(_behaviors, _actionTypes.SET_SUBMIT_SUCCEEDED, function (state) { var result = state; result = deleteIn(result, 'submitFailed'); result = setIn(result, 'submitSucceeded', true); return result; }), _defineProperty(_behaviors, _actionTypes.TOUCH, function (state, _ref22) { var fields = _ref22.meta.fields; var result = state; fields.forEach(function (field) { return result = setIn(result, 'fields.' + field + '.touched', true); }); result = setIn(result, 'anyTouched', true); return result; }), _defineProperty(_behaviors, _actionTypes.UNREGISTER_FIELD, function (state, _ref23) { var _ref23$payload = _ref23.payload, name = _ref23$payload.name, destroyOnUnmount = _ref23$payload.destroyOnUnmount; var result = state; var key = 'registeredFields[\'' + name + '\']'; var field = getIn(result, key); if (!field) { return result; } var count = getIn(field, 'count') - 1; if (count <= 0 && destroyOnUnmount) { result = deleteIn(result, key); if (deepEqual(getIn(result, 'registeredFields'), empty)) { result = deleteIn(result, 'registeredFields'); } } else { field = setIn(field, 'count', count); result = setIn(result, key, field); } return result; }), _defineProperty(_behaviors, _actionTypes.UNTOUCH, function (state, _ref24) { var fields = _ref24.meta.fields; var result = state; fields.forEach(function (field) { return result = deleteIn(result, 'fields.' + field + '.touched'); }); var anyTouched = keys(getIn(result, 'registeredFields')).some(function (key) { return getIn(result, 'fields.' + key + '.touched'); }); result = anyTouched ? setIn(result, 'anyTouched', true) : deleteIn(result, 'anyTouched'); return result; }), _defineProperty(_behaviors, _actionTypes.UPDATE_SYNC_ERRORS, function (state, _ref25) { var _ref25$payload = _ref25.payload, syncErrors = _ref25$payload.syncErrors, error = _ref25$payload.error; var result = state; if (error) { result = setIn(result, 'error', error); result = setIn(result, 'syncError', true); } else { result = deleteIn(result, 'error'); result = deleteIn(result, 'syncError'); } if (Object.keys(syncErrors).length) { result = setIn(result, 'syncErrors', syncErrors); } else { result = deleteIn(result, 'syncErrors'); } return result; }), _defineProperty(_behaviors, _actionTypes.UPDATE_SYNC_WARNINGS, function (state, _ref26) { var _ref26$payload = _ref26.payload, syncWarnings = _ref26$payload.syncWarnings, warning = _ref26$payload.warning; var result = state; if (warning) { result = setIn(result, 'warning', warning); } else { result = deleteIn(result, 'warning'); } if (Object.keys(syncWarnings).length) { result = setIn(result, 'syncWarnings', syncWarnings); } else { result = deleteIn(result, 'syncWarnings'); } return result; }), _behaviors); var reducer = function reducer() { var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : empty; var action = arguments[1]; var behavior = behaviors[action.type]; return behavior ? behavior(state, action) : state; }; var byForm = function byForm(reducer) { return function () { var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : empty; var action = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var form = action && action.meta && action.meta.form; if (!form || !isReduxFormAction(action)) { return state; } if (action.type === _actionTypes.DESTROY) { return action.meta.form.reduce(function (result, form) { return deleteInWithCleanUp(result, form); }, state); } var formState = getIn(state, form); var result = reducer(formState, action); return result === formState ? state : setIn(state, form, result); }; }; /** * Adds additional functionality to the reducer */ function decorate(target) { target.plugin = function plugin(reducers) { var _this = this; // use 'function' keyword to enable 'this' return decorate(function () { var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : empty; var action = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; return Object.keys(reducers).reduce(function (accumulator, key) { var previousState = getIn(accumulator, key); var nextState = reducers[key](previousState, action, getIn(state, key)); return nextState === previousState ? accumulator : setIn(accumulator, key, nextState); }, _this(state, action)); }); }; return target; } return decorate(byForm(reducer)); }; exports.default = createReducer;
Akkuma/npm-cache-benchmark
pnpm-offline/.pnpm-store-offline/1/registry.npmjs.org/redux-form/6.6.3/lib/reducer.js
JavaScript
mit
20,975
module.exports={title:"Tidal",hex:"000000",source:"https://tidal.com",svg:'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Tidal icon</title><path d="M12.012 3.992L8.008 7.996 4.004 3.992 0 7.996 4.004 12l4.004-4.004L12.012 12l-4.004 4.004 4.004 4.004 4.004-4.004L12.012 12l4.004-4.004-4.004-4.004zM16.042 7.996l3.979-3.979L24 7.996l-3.979 3.979z"/></svg>'};
cdnjs/cdnjs
ajax/libs/simple-icons/1.9.28/tidal.min.js
JavaScript
mit
388
/* * Copyright (c) 2008-2014 The Open Source Geospatial Foundation * * Published under the BSD license. * See https://github.com/geoext/geoext2/blob/master/license.txt for the full * text of the license. */ /* * @requires GeoExt/data/reader/CswRecords.js */ /** * The model for the structure returned by CS-W GetRecords. * * @class GeoExt.data.CswRecordsModel */ Ext.define('GeoExt.data.CswRecordsModel',{ extend: 'Ext.data.Model', requires: [ 'Ext.data.proxy.Memory', 'GeoExt.data.reader.CswRecords' ], alias: 'model.gx_cswrecords', fields: [ {name: "title"}, {name: "subject"}, {name: "URI"}, {name: "bounds"}, {name: "projection", type: "string"} ], proxy: { type: 'memory', reader: { type: 'gx_cswrecords' } } });
henriquespedro/Autarquia-Livre
vendor/geoext2/src/GeoExt/data/CswRecordsModel.js
JavaScript
gpl-2.0
856
({ showTarget : function(component) { var evt = $A.get('e.ui:popupTargetToggle'); evt.setParams({ component : component, show : true }); evt.fire(); }, hideTarget : function(component) { var evt = $A.get('e.ui:popupTargetToggle'); evt.setParams({ component : component, show : false }); evt.fire(); } })
lcnbala/aura
aura-components/src/test/components/uitest/popupTestTriggerElement/popupTestTriggerElementController.js
JavaScript
apache-2.0
337
/** * Copyright 2015 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. */ import { isLoaded, listen, listenOnce, listenOncePromise, loadPromise, } from '../../src/event-helper'; import {Observable} from '../../src/observable'; import * as sinon from 'sinon'; describe('EventHelper', () => { function getEvent(name, target) { const event = document.createEvent('Event'); event.initEvent(name, true, true); event.testTarget = target; return event; } let sandbox; let clock; let element; let loadObservable; let errorObservable; beforeEach(() => { sandbox = sinon.sandbox.create(); clock = sandbox.useFakeTimers(); loadObservable = new Observable(); errorObservable = new Observable(); element = { tagName: 'TEST', complete: false, readyState: '', addEventListener: function(type, callback) { if (type == 'load') { loadObservable.add(callback); } else if (type == 'error') { errorObservable.add(callback); } else { expect(type).to.equal('load or error'); } }, removeEventListener: function(type, callback) { if (type == 'load') { loadObservable.remove(callback); } else if (type == 'error') { errorObservable.remove(callback); } else { expect(type).to.equal('load or error'); } }, }; }); afterEach(() => { // Very important that all listeners are removed. expect(loadObservable.getHandlerCount()).to.equal(0); expect(errorObservable.getHandlerCount()).to.equal(0); sandbox.restore(); }); it('listen', () => { const event = getEvent('load', element); let c = 0; const handler = e => { c++; expect(e).to.equal(event); }; const unlisten = listen(element, 'load', handler); // Not fired yet. expect(c).to.equal(0); // Fired once. loadObservable.fire(event); expect(c).to.equal(1); // Fired second time. loadObservable.fire(event); expect(c).to.equal(2); unlisten(); loadObservable.fire(event); expect(c).to.equal(2); }); it('listenOnce', () => { const event = getEvent('load', element); let c = 0; const handler = e => { c++; expect(e).to.equal(event); }; listenOnce(element, 'load', handler); // Not fired yet. expect(c).to.equal(0); // Fired once. loadObservable.fire(event); expect(c).to.equal(1); // Fired second time: no longer listening. loadObservable.fire(event); expect(c).to.equal(1); }); it('listenOnce - cancel', () => { const event = getEvent('load', element); let c = 0; const handler = e => { c++; expect(e).to.equal(event); }; const unlisten = listenOnce(element, 'load', handler); // Not fired yet. expect(c).to.equal(0); // Cancel. unlisten(); // Fired once: no longer listening. loadObservable.fire(event); expect(c).to.equal(0); }); it('listenOncePromise - load event', () => { const event = getEvent('load', element); const promise = listenOncePromise(element, 'load').then(result => { expect(result).to.equal(event); }); loadObservable.fire(event); return promise; }); it('listenOncePromise - with time limit', () => { const event = getEvent('load', element); const promise = expect(listenOncePromise(element, 'load', false, 100)) .to.eventually.become(event); clock.tick(99); loadObservable.fire(event); return promise; }); it('listenOncePromise - timeout', () => { const promise = expect(listenOncePromise(element, 'load', false, 100)) .to.eventually.be.rejectedWith('timeout'); clock.tick(101); return promise; }); it('isLoaded for complete property', () => { expect(isLoaded(element)).to.equal(false); element.complete = true; expect(isLoaded(element)).to.equal(true); }); it('isLoaded for readyState property', () => { expect(isLoaded(element)).to.equal(false); element.readyState = 'complete'; expect(isLoaded(element)).to.equal(true); }); it('isLoaded for Window', () => { expect(isLoaded(window)).to.equal(true); const win = { document: { readyState: 'interactive', }, }; expect(isLoaded(win)).to.equal(false); win.document.readyState = 'complete'; expect(isLoaded(win)).to.equal(true); }); it('loadPromise - already complete', () => { element.complete = true; return loadPromise(element).then(result => { expect(result).to.equal(element); }); }); it('loadPromise - already readyState == complete', () => { element.readyState = 'complete'; return loadPromise(element).then(result => { expect(result).to.equal(element); }); }); it('loadPromise - load event', () => { const promise = loadPromise(element).then(result => { expect(result).to.equal(element); }); loadObservable.fire(getEvent('load', element)); return promise; }); it('loadPromise - error event', () => { const promise = loadPromise(element).then(result => { assert.fail('must never be here: ' + result); }).then(() => { throw new Error('Should not be reached.'); }, reason => { expect(reason.message).to.include('Failed to load'); }); errorObservable.fire(getEvent('error', element)); return promise; }); });
DistroScale/amphtml
test/functional/test-event-helper.js
JavaScript
apache-2.0
6,023
import {getNextArrow, getPrevArrow, getSlide} from './helpers'; /** The total number of slides in the carousel */ const SLIDE_COUNT = 7; describes.endtoend( 'amp-base-carousel - arrows with custom arrows', { version: '0.1', fixture: 'amp-base-carousel/custom-arrows.amp.html', experiments: [ 'amp-base-carousel', 'layers', 'amp-lightbox-gallery-base-carousel', ], //TODO(spaharmi): fails on shadow demo environments: ['single', 'viewer-demo'], }, async function (env) { let controller; let prevArrow; let nextArrow; beforeEach(async () => { controller = env.controller; nextArrow = await getNextArrow(controller); prevArrow = await getPrevArrow(controller); }); it('should go to the next slide', async () => { const secondSlide = await getSlide(controller, 1); await controller.click(nextArrow); await expect(controller.getElementRect(secondSlide)).to.include({ 'x': 0, }); }); it('should go to the previous slide', async () => { const lastSlide = await getSlide(controller, SLIDE_COUNT - 1); await controller.click(prevArrow); await expect(controller.getElementRect(lastSlide)).to.include({ 'x': 0, }); }); } );
alanorozco/amphtml
extensions/amp-base-carousel/0.1/test-e2e/test-arrows.js
JavaScript
apache-2.0
1,291
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("react"), require("react-dom")); else if(typeof define === 'function' && define.amd) define(["react", "react-dom"], factory); else if(typeof exports === 'object') exports["Slider"] = factory(require("react"), require("react-dom")); else root["Slider"] = factory(root["React"], root["ReactDOM"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_2__, __WEBPACK_EXTERNAL_MODULE_6__) { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; module.exports = __webpack_require__(1); /***/ }), /* 1 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _innerSlider = __webpack_require__(3); var _objectAssign = __webpack_require__(7); var _objectAssign2 = _interopRequireDefault(_objectAssign); var _json2mq = __webpack_require__(21); var _json2mq2 = _interopRequireDefault(_json2mq); var _defaultProps = __webpack_require__(10); var _defaultProps2 = _interopRequireDefault(_defaultProps); var _canUseDom = __webpack_require__(23); var _canUseDom2 = _interopRequireDefault(_canUseDom); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var enquire = _canUseDom2.default && __webpack_require__(24); var Slider = function (_React$Component) { _inherits(Slider, _React$Component); function Slider(props) { _classCallCheck(this, Slider); var _this = _possibleConstructorReturn(this, _React$Component.call(this, props)); _this.state = { breakpoint: null }; _this._responsiveMediaHandlers = []; _this.innerSliderRefHandler = _this.innerSliderRefHandler.bind(_this); return _this; } Slider.prototype.innerSliderRefHandler = function innerSliderRefHandler(ref) { this.innerSlider = ref; }; Slider.prototype.media = function media(query, handler) { // javascript handler for css media query enquire.register(query, handler); this._responsiveMediaHandlers.push({ query: query, handler: handler }); }; Slider.prototype.componentWillMount = function componentWillMount() { var _this2 = this; if (this.props.responsive) { var breakpoints = this.props.responsive.map(function (breakpt) { return breakpt.breakpoint; }); // sort them in increasing order of their numerical value breakpoints.sort(function (x, y) { return x - y; }); breakpoints.forEach(function (breakpoint, index) { // media query for each breakpoint var bQuery; if (index === 0) { bQuery = (0, _json2mq2.default)({ minWidth: 0, maxWidth: breakpoint }); } else { bQuery = (0, _json2mq2.default)({ minWidth: breakpoints[index - 1], maxWidth: breakpoint }); } // when not using server side rendering _canUseDom2.default && _this2.media(bQuery, function () { _this2.setState({ breakpoint: breakpoint }); }); }); // Register media query for full screen. Need to support resize from small to large // convert javascript object to media query string var query = (0, _json2mq2.default)({ minWidth: breakpoints.slice(-1)[0] }); _canUseDom2.default && this.media(query, function () { _this2.setState({ breakpoint: null }); }); } }; Slider.prototype.componentWillUnmount = function componentWillUnmount() { this._responsiveMediaHandlers.forEach(function (obj) { enquire.unregister(obj.query, obj.handler); }); }; Slider.prototype.slickPrev = function slickPrev() { this.innerSlider.slickPrev(); }; Slider.prototype.slickNext = function slickNext() { this.innerSlider.slickNext(); }; Slider.prototype.slickGoTo = function slickGoTo(slide) { this.innerSlider.slickGoTo(slide); }; Slider.prototype.slickPause = function slickPause() { this.innerSlider.pause(); }; Slider.prototype.slickPlay = function slickPlay() { this.innerSlider.autoPlay(); }; Slider.prototype.render = function render() { var _this3 = this; var settings; var newProps; if (this.state.breakpoint) { // never executes in the first render // so defaultProps should be already there in this.props newProps = this.props.responsive.filter(function (resp) { return resp.breakpoint === _this3.state.breakpoint; }); settings = newProps[0].settings === 'unslick' ? 'unslick' : (0, _objectAssign2.default)({}, _defaultProps2.default, this.props, newProps[0].settings); } else { settings = (0, _objectAssign2.default)({}, _defaultProps2.default, this.props); } // force scrolling by one if centerMode is on if (settings.centerMode) { if (settings.slidesToScroll > 1 && (undefined) !== 'production') { console.warn('slidesToScroll should be equal to 1 in centerMode, you are using ' + settings.slidesToScroll); } settings.slidesToScroll = 1; } // force showing one slide and scrolling by one if the fade mode is on if (settings.fade) { if (settings.slidesToShow > 1 && (undefined) !== 'production') { console.warn('slidesToShow should be equal to 1 when fade is true, you\'re using ' + settings.slidesToShow); } if (settings.slidesToScroll > 1 && (undefined) !== 'production') { console.warn('slidesToScroll should be equal to 1 when fade is true, you\'re using ' + settings.slidesToScroll); } settings.slidesToShow = 1; settings.slidesToScroll = 1; } // makes sure that children is an array, even when there is only 1 child var children = _react2.default.Children.toArray(this.props.children); // Children may contain false or null, so we should filter them // children may also contain string filled with spaces (in certain cases where we use jsx strings) children = children.filter(function (child) { if (typeof child === 'string') { return !!child.trim(); } return !!child; }); if (settings === 'unslick') { // if 'unslick' responsive breakpoint setting used, just return the <Slider> tag nested HTML return _react2.default.createElement( 'div', { className: this.props.className + ' unslicked' }, children ); } else { return _react2.default.createElement( _innerSlider.InnerSlider, _extends({ ref: this.innerSliderRefHandler }, settings), children ); } }; return Slider; }(_react2.default.Component); exports.default = Slider; /***/ }), /* 2 */ /***/ (function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_2__; /***/ }), /* 3 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.InnerSlider = undefined; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _eventHandlers = __webpack_require__(4); var _eventHandlers2 = _interopRequireDefault(_eventHandlers); var _helpers = __webpack_require__(8); var _helpers2 = _interopRequireDefault(_helpers); var _initialState = __webpack_require__(9); var _initialState2 = _interopRequireDefault(_initialState); var _defaultProps = __webpack_require__(10); var _defaultProps2 = _interopRequireDefault(_defaultProps); var _createReactClass = __webpack_require__(11); var _createReactClass2 = _interopRequireDefault(_createReactClass); var _classnames = __webpack_require__(17); var _classnames2 = _interopRequireDefault(_classnames); var _objectAssign = __webpack_require__(7); var _objectAssign2 = _interopRequireDefault(_objectAssign); var _track = __webpack_require__(18); var _dots = __webpack_require__(19); var _arrows = __webpack_require__(20); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var InnerSlider = exports.InnerSlider = (0, _createReactClass2.default)({ displayName: 'InnerSlider', mixins: [_helpers2.default, _eventHandlers2.default], list: null, // wraps the track track: null, // component that rolls out like a film listRefHandler: function listRefHandler(ref) { this.list = ref; }, trackRefHandler: function trackRefHandler(ref) { this.track = ref; }, getInitialState: function getInitialState() { return _extends({}, _initialState2.default, { currentSlide: this.props.initialSlide }); }, componentWillMount: function componentWillMount() { if (this.props.init) { this.props.init(); } this.setState({ mounted: true }); var lazyLoadedList = []; // number of slides shown in the active frame var slidesToShow = this.props.slidesToShow; var childrenLen = _react2.default.Children.count(this.props.children); var currentSlide = this.state.currentSlide; for (var i = 0; i < childrenLen; i++) { // if currentSlide is the lastSlide of current frame and // rest of the active slides are on the left of currentSlide // then the following might cause a problem if (i >= currentSlide && i < currentSlide + slidesToShow) { lazyLoadedList.push(i); } } if (this.props.centerMode === true) { // add slides to show on the left in case of centerMode with lazyLoad var additionalCount = Math.floor(slidesToShow / 2); if (parseInt(this.props.centerPadding) > 0) { additionalCount += 1; } var additionalNum = currentSlide; while (additionalCount--) { lazyLoadedList.push((--additionalNum + childrenLen) % childrenLen); } } if (this.props.lazyLoad && this.state.lazyLoadedList.length === 0) { this.setState({ lazyLoadedList: lazyLoadedList }); } }, componentDidMount: function componentDidMount() { // Hack for autoplay -- Inspect Later this.initialize(this.props); this.adaptHeight(); // To support server-side rendering if (!window) { return; } if (window.addEventListener) { window.addEventListener('resize', this.onWindowResized); } else { window.attachEvent('onresize', this.onWindowResized); } }, componentWillUnmount: function componentWillUnmount() { if (this.animationEndCallback) { clearTimeout(this.animationEndCallback); } if (window.addEventListener) { window.removeEventListener('resize', this.onWindowResized); } else { window.detachEvent('onresize', this.onWindowResized); } if (this.state.autoPlayTimer) { clearInterval(this.state.autoPlayTimer); } }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { if (this.props.slickGoTo != nextProps.slickGoTo) { if ((undefined) !== 'production') { console.warn('react-slick deprecation warning: slickGoTo prop is deprecated and it will be removed in next release. Use slickGoTo method instead'); } this.changeSlide({ message: 'index', index: nextProps.slickGoTo, currentSlide: this.state.currentSlide }); } else if (this.state.currentSlide >= nextProps.children.length) { this.update(nextProps); this.changeSlide({ message: 'index', index: nextProps.children.length - nextProps.slidesToShow, currentSlide: this.state.currentSlide }); } else { this.update(nextProps); } }, componentDidUpdate: function componentDidUpdate() { if (this.props.lazyLoad && this.props.centerMode) { var childrenLen = _react2.default.Children.count(this.props.children); var additionalCount = Math.floor(this.props.slidesToShow / 2); if (parseInt(this.props.centerPadding) > 0) additionalCount++; var leftMostSlide = (this.state.currentSlide - additionalCount + childrenLen) % childrenLen; var rightMostSlide = (this.state.currentSlide + additionalCount) % childrenLen; if (!this.state.lazyLoadedList.includes(leftMostSlide)) { this.setState({ lazyLoadedList: this.state.lazyLoadedList + [leftMostSlide] }); } if (!this.state.lazyLoadedList.includes(rightMostSlide)) { this.setState({ lazyLoadedList: this.state.lazyLoadedList + [rightMostSlide] }); } } this.adaptHeight(); }, onWindowResized: function onWindowResized() { this.update(this.props); // animating state should be cleared while resizing, otherwise autoplay stops working this.setState({ animating: false }); clearTimeout(this.animationEndCallback); delete this.animationEndCallback; }, slickPrev: function slickPrev() { this.changeSlide({ message: 'previous' }); }, slickNext: function slickNext() { this.changeSlide({ message: 'next' }); }, slickGoTo: function slickGoTo(slide) { slide = Number(slide); !isNaN(slide) && this.changeSlide({ message: 'index', index: slide, currentSlide: this.state.currentSlide }); }, render: function render() { var className = (0, _classnames2.default)('slick-initialized', 'slick-slider', this.props.className, { 'slick-vertical': this.props.vertical }); var trackProps = { fade: this.props.fade, cssEase: this.props.cssEase, speed: this.props.speed, infinite: this.props.infinite, centerMode: this.props.centerMode, focusOnSelect: this.props.focusOnSelect ? this.selectHandler : null, currentSlide: this.state.currentSlide, lazyLoad: this.props.lazyLoad, lazyLoadedList: this.state.lazyLoadedList, rtl: this.props.rtl, slideWidth: this.state.slideWidth, slideHeight: this.state.slideHeight, listHeight: this.state.listHeight, vertical: this.props.vertical, slidesToShow: this.props.slidesToShow, slidesToScroll: this.props.slidesToScroll, slideCount: this.state.slideCount, trackStyle: this.state.trackStyle, variableWidth: this.props.variableWidth }; var dots; if (this.props.dots === true && this.state.slideCount >= this.props.slidesToShow) { var dotProps = { dotsClass: this.props.dotsClass, slideCount: this.state.slideCount, slidesToShow: this.props.slidesToShow, currentSlide: this.state.currentSlide, slidesToScroll: this.props.slidesToScroll, clickHandler: this.changeSlide, children: this.props.children, customPaging: this.props.customPaging, infinite: this.props.infinite }; dots = _react2.default.createElement(_dots.Dots, dotProps); } var prevArrow, nextArrow; var arrowProps = { infinite: this.props.infinite, centerMode: this.props.centerMode, currentSlide: this.state.currentSlide, slideCount: this.state.slideCount, slidesToShow: this.props.slidesToShow, prevArrow: this.props.prevArrow, nextArrow: this.props.nextArrow, clickHandler: this.changeSlide }; if (this.props.arrows) { prevArrow = _react2.default.createElement(_arrows.PrevArrow, arrowProps); nextArrow = _react2.default.createElement(_arrows.NextArrow, arrowProps); } var verticalHeightStyle = null; if (this.props.vertical) { verticalHeightStyle = { height: this.state.listHeight }; } var centerPaddingStyle = null; if (this.props.vertical === false) { if (this.props.centerMode === true) { centerPaddingStyle = { padding: '0px ' + this.props.centerPadding }; } } else { if (this.props.centerMode === true) { centerPaddingStyle = { padding: this.props.centerPadding + ' 0px' }; } } var listStyle = (0, _objectAssign2.default)({}, verticalHeightStyle, centerPaddingStyle); return _react2.default.createElement( 'div', { className: className, onMouseEnter: this.onInnerSliderEnter, onMouseLeave: this.onInnerSliderLeave, onMouseOver: this.onInnerSliderOver }, prevArrow, _react2.default.createElement( 'div', { ref: this.listRefHandler, className: 'slick-list', style: listStyle, onMouseDown: this.swipeStart, onMouseMove: this.state.dragging ? this.swipeMove : null, onMouseUp: this.swipeEnd, onMouseLeave: this.state.dragging ? this.swipeEnd : null, onTouchStart: this.swipeStart, onTouchMove: this.state.dragging ? this.swipeMove : null, onTouchEnd: this.swipeEnd, onTouchCancel: this.state.dragging ? this.swipeEnd : null, onKeyDown: this.props.accessibility ? this.keyHandler : null }, _react2.default.createElement( _track.Track, _extends({ ref: this.trackRefHandler }, trackProps), this.props.children ) ), nextArrow, dots ); } }); /***/ }), /* 4 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _trackHelper = __webpack_require__(5); var _helpers = __webpack_require__(8); var _helpers2 = _interopRequireDefault(_helpers); var _objectAssign = __webpack_require__(7); var _objectAssign2 = _interopRequireDefault(_objectAssign); var _reactDom = __webpack_require__(6); var _reactDom2 = _interopRequireDefault(_reactDom); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var EventHandlers = { // Event handler for previous and next // gets called if slide is changed via arrows or dots but not swiping/dragging changeSlide: function changeSlide(options) { var indexOffset, previousInt, slideOffset, unevenOffset, targetSlide; var _props = this.props, slidesToScroll = _props.slidesToScroll, slidesToShow = _props.slidesToShow; var _state = this.state, slideCount = _state.slideCount, currentSlide = _state.currentSlide; unevenOffset = slideCount % slidesToScroll !== 0; indexOffset = unevenOffset ? 0 : (slideCount - currentSlide) % slidesToScroll; if (options.message === 'previous') { slideOffset = indexOffset === 0 ? slidesToScroll : slidesToShow - indexOffset; targetSlide = currentSlide - slideOffset; if (this.props.lazyLoad && !this.props.infinite) { previousInt = currentSlide - slideOffset; targetSlide = previousInt === -1 ? slideCount - 1 : previousInt; } } else if (options.message === 'next') { slideOffset = indexOffset === 0 ? slidesToScroll : indexOffset; targetSlide = currentSlide + slideOffset; if (this.props.lazyLoad && !this.props.infinite) { targetSlide = (currentSlide + slidesToScroll) % slideCount + indexOffset; } } else if (options.message === 'dots' || options.message === 'children') { // Click on dots targetSlide = options.index * options.slidesToScroll; if (targetSlide === options.currentSlide) { return; } } else if (options.message === 'index') { targetSlide = Number(options.index); if (targetSlide === options.currentSlide) { return; } } this.slideHandler(targetSlide); }, // Accessiblity handler for previous and next keyHandler: function keyHandler(e) { //Dont slide if the cursor is inside the form fields and arrow keys are pressed if (!e.target.tagName.match('TEXTAREA|INPUT|SELECT')) { if (e.keyCode === 37 && this.props.accessibility === true) { this.changeSlide({ message: this.props.rtl === true ? 'next' : 'previous' }); } else if (e.keyCode === 39 && this.props.accessibility === true) { this.changeSlide({ message: this.props.rtl === true ? 'previous' : 'next' }); } } }, // Focus on selecting a slide (click handler on track) selectHandler: function selectHandler(options) { this.changeSlide(options); }, // invoked when swiping/dragging starts (just once) swipeStart: function swipeStart(e) { var touches, posX, posY; if (this.props.swipe === false || 'ontouchend' in document && this.props.swipe === false) { return; } else if (this.props.draggable === false && e.type.indexOf('mouse') !== -1) { return; } posX = e.touches !== undefined ? e.touches[0].pageX : e.clientX; posY = e.touches !== undefined ? e.touches[0].pageY : e.clientY; this.setState({ dragging: true, touchObject: { startX: posX, startY: posY, curX: posX, curY: posY } }); }, // continuous invokation while swiping/dragging is going on swipeMove: function swipeMove(e) { if (!this.state.dragging) { e.preventDefault(); return; } if (this.state.scrolling) { return; } if (this.state.animating) { e.preventDefault(); return; } if (this.props.vertical && this.props.swipeToSlide && this.props.verticalSwiping) { e.preventDefault(); } var swipeLeft; var curLeft, positionOffset; var touchObject = this.state.touchObject; curLeft = (0, _trackHelper.getTrackLeft)((0, _objectAssign2.default)({ slideIndex: this.state.currentSlide, trackRef: this.track }, this.props, this.state)); touchObject.curX = e.touches ? e.touches[0].pageX : e.clientX; touchObject.curY = e.touches ? e.touches[0].pageY : e.clientY; touchObject.swipeLength = Math.round(Math.sqrt(Math.pow(touchObject.curX - touchObject.startX, 2))); var verticalSwipeLength = Math.round(Math.sqrt(Math.pow(touchObject.curY - touchObject.startY, 2))); if (!this.props.verticalSwiping && !this.state.swiping && verticalSwipeLength > 4) { this.setState({ scrolling: true }); return; } if (this.props.verticalSwiping) { touchObject.swipeLength = verticalSwipeLength; } positionOffset = (this.props.rtl === false ? 1 : -1) * (touchObject.curX > touchObject.startX ? 1 : -1); if (this.props.verticalSwiping) { positionOffset = touchObject.curY > touchObject.startY ? 1 : -1; } var currentSlide = this.state.currentSlide; var dotCount = Math.ceil(this.state.slideCount / this.props.slidesToScroll); // this might not be correct, using getDotCount may be more accurate var swipeDirection = this.swipeDirection(this.state.touchObject); var touchSwipeLength = touchObject.swipeLength; if (this.props.infinite === false) { if (currentSlide === 0 && swipeDirection === 'right' || currentSlide + 1 >= dotCount && swipeDirection === 'left') { touchSwipeLength = touchObject.swipeLength * this.props.edgeFriction; if (this.state.edgeDragged === false && this.props.edgeEvent) { this.props.edgeEvent(swipeDirection); this.setState({ edgeDragged: true }); } } } if (this.state.swiped === false && this.props.swipeEvent) { this.props.swipeEvent(swipeDirection); this.setState({ swiped: true }); } if (!this.props.vertical) { if (!this.props.rtl) { swipeLeft = curLeft + touchSwipeLength * positionOffset; } else { swipeLeft = curLeft - touchSwipeLength * positionOffset; } } else { swipeLeft = curLeft + touchSwipeLength * (this.state.listHeight / this.state.listWidth) * positionOffset; } if (this.props.verticalSwiping) { swipeLeft = curLeft + touchSwipeLength * positionOffset; } this.setState({ touchObject: touchObject, swipeLeft: swipeLeft, trackStyle: (0, _trackHelper.getTrackCSS)((0, _objectAssign2.default)({ left: swipeLeft }, this.props, this.state)) }); if (Math.abs(touchObject.curX - touchObject.startX) < Math.abs(touchObject.curY - touchObject.startY) * 0.8) { return; } if (touchObject.swipeLength > 4) { this.setState({ swiping: true }); e.preventDefault(); } }, getNavigableIndexes: function getNavigableIndexes() { var max = void 0; var breakPoint = 0; var counter = 0; var indexes = []; if (!this.props.infinite) { max = this.state.slideCount; } else { breakPoint = this.props.slidesToShow * -1; counter = this.props.slidesToShow * -1; max = this.state.slideCount * 2; } while (breakPoint < max) { indexes.push(breakPoint); breakPoint = counter + this.props.slidesToScroll; counter += this.props.slidesToScroll <= this.props.slidesToShow ? this.props.slidesToScroll : this.props.slidesToShow; } return indexes; }, checkNavigable: function checkNavigable(index) { var navigables = this.getNavigableIndexes(); var prevNavigable = 0; if (index > navigables[navigables.length - 1]) { index = navigables[navigables.length - 1]; } else { for (var n in navigables) { if (index < navigables[n]) { index = prevNavigable; break; } prevNavigable = navigables[n]; } } return index; }, getSlideCount: function getSlideCount() { var _this = this; var centerOffset = this.props.centerMode ? this.state.slideWidth * Math.floor(this.props.slidesToShow / 2) : 0; if (this.props.swipeToSlide) { var swipedSlide = void 0; var slickList = _reactDom2.default.findDOMNode(this.list); var slides = slickList.querySelectorAll('.slick-slide'); Array.from(slides).every(function (slide) { if (!_this.props.vertical) { if (slide.offsetLeft - centerOffset + _this.getWidth(slide) / 2 > _this.state.swipeLeft * -1) { swipedSlide = slide; return false; } } else { if (slide.offsetTop + _this.getHeight(slide) / 2 > _this.state.swipeLeft * -1) { swipedSlide = slide; return false; } } return true; }); var currentIndex = this.props.rtl === true ? this.state.slideCount - this.state.currentSlide : this.state.currentSlide; var slidesTraversed = Math.abs(swipedSlide.dataset.index - currentIndex) || 1; return slidesTraversed; } else { return this.props.slidesToScroll; } }, swipeEnd: function swipeEnd(e) { if (!this.state.dragging) { if (this.props.swipe) { e.preventDefault(); } return; } var touchObject = this.state.touchObject; var minSwipe = this.state.listWidth / this.props.touchThreshold; var swipeDirection = this.swipeDirection(touchObject); if (this.props.verticalSwiping) { minSwipe = this.state.listHeight / this.props.touchThreshold; } var wasScrolling = this.state.scrolling; // reset the state of touch related state variables. this.setState({ dragging: false, edgeDragged: false, scrolling: false, swiping: false, swiped: false, swipeLeft: null, touchObject: {} }); if (wasScrolling) { return; } // Fix for #13 if (!touchObject.swipeLength) { return; } if (touchObject.swipeLength > minSwipe) { e.preventDefault(); var slideCount = void 0, newSlide = void 0; switch (swipeDirection) { case 'left': case 'down': newSlide = this.state.currentSlide + this.getSlideCount(); slideCount = this.props.swipeToSlide ? this.checkNavigable(newSlide) : newSlide; this.state.currentDirection = 0; break; case 'right': case 'up': newSlide = this.state.currentSlide - this.getSlideCount(); slideCount = this.props.swipeToSlide ? this.checkNavigable(newSlide) : newSlide; this.state.currentDirection = 1; break; default: slideCount = this.state.currentSlide; } this.slideHandler(slideCount); } else { // Adjust the track back to it's original position. var currentLeft = (0, _trackHelper.getTrackLeft)((0, _objectAssign2.default)({ slideIndex: this.state.currentSlide, trackRef: this.track }, this.props, this.state)); this.setState({ trackStyle: (0, _trackHelper.getTrackAnimateCSS)((0, _objectAssign2.default)({ left: currentLeft }, this.props, this.state)) }); } }, onInnerSliderEnter: function onInnerSliderEnter(e) { if (this.props.autoplay && this.props.pauseOnHover) { this.pause(); } }, onInnerSliderOver: function onInnerSliderOver(e) { if (this.props.autoplay && this.props.pauseOnHover) { this.pause(); } }, onInnerSliderLeave: function onInnerSliderLeave(e) { if (this.props.autoplay && this.props.pauseOnHover) { this.autoPlay(); } } }; exports.default = EventHandlers; /***/ }), /* 5 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.getTrackLeft = exports.getTrackAnimateCSS = exports.getTrackCSS = undefined; exports.getPreClones = getPreClones; exports.getPostClones = getPostClones; exports.getTotalSlides = getTotalSlides; var _reactDom = __webpack_require__(6); var _reactDom2 = _interopRequireDefault(_reactDom); var _objectAssign = __webpack_require__(7); var _objectAssign2 = _interopRequireDefault(_objectAssign); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // checks if spec is the superset of keys in keysArray, i.e., spec contains all the keys from keysArray var checkSpecKeys = function checkSpecKeys(spec, keysArray) { return keysArray.reduce(function (value, key) { return value && spec.hasOwnProperty(key); }, true) ? null : console.error('Keys Missing', spec); }; var getTrackCSS = exports.getTrackCSS = function getTrackCSS(spec) { checkSpecKeys(spec, ['left', 'variableWidth', 'slideCount', 'slidesToShow', 'slideWidth']); var trackWidth, trackHeight; var trackChildren = spec.slideCount + 2 * spec.slidesToShow; // this should probably be getTotalSlides if (!spec.vertical) { trackWidth = getTotalSlides(spec) * spec.slideWidth; trackWidth += spec.slideWidth / 2; // this is a temporary hack so that track div doesn't create new row for slight overflow } else { trackHeight = trackChildren * spec.slideHeight; } var style = { opacity: 1, WebkitTransform: !spec.vertical ? 'translate3d(' + spec.left + 'px, 0px, 0px)' : 'translate3d(0px, ' + spec.left + 'px, 0px)', transform: !spec.vertical ? 'translate3d(' + spec.left + 'px, 0px, 0px)' : 'translate3d(0px, ' + spec.left + 'px, 0px)', transition: '', WebkitTransition: '', msTransform: !spec.vertical ? 'translateX(' + spec.left + 'px)' : 'translateY(' + spec.left + 'px)' }; if (spec.fade) { style = { opacity: 1 }; } if (trackWidth) { (0, _objectAssign2.default)(style, { width: trackWidth }); } if (trackHeight) { (0, _objectAssign2.default)(style, { height: trackHeight }); } // Fallback for IE8 if (window && !window.addEventListener && window.attachEvent) { if (!spec.vertical) { style.marginLeft = spec.left + 'px'; } else { style.marginTop = spec.left + 'px'; } } return style; }; var getTrackAnimateCSS = exports.getTrackAnimateCSS = function getTrackAnimateCSS(spec) { checkSpecKeys(spec, ['left', 'variableWidth', 'slideCount', 'slidesToShow', 'slideWidth', 'speed', 'cssEase']); var style = getTrackCSS(spec); // useCSS is true by default so it can be undefined style.WebkitTransition = '-webkit-transform ' + spec.speed + 'ms ' + spec.cssEase; style.transition = 'transform ' + spec.speed + 'ms ' + spec.cssEase; return style; }; // gets total length of track that's on the left side of current slide var getTrackLeft = exports.getTrackLeft = function getTrackLeft(spec) { checkSpecKeys(spec, ['slideIndex', 'trackRef', 'infinite', 'centerMode', 'slideCount', 'slidesToShow', 'slidesToScroll', 'slideWidth', 'listWidth', 'variableWidth', 'slideHeight']); var slideIndex = spec.slideIndex, trackRef = spec.trackRef, infinite = spec.infinite, centerMode = spec.centerMode, slideCount = spec.slideCount, slidesToShow = spec.slidesToShow, slidesToScroll = spec.slidesToScroll, slideWidth = spec.slideWidth, listWidth = spec.listWidth, variableWidth = spec.variableWidth, slideHeight = spec.slideHeight, fade = spec.fade, vertical = spec.vertical; var slideOffset = 0; var targetLeft; var targetSlide; var verticalOffset = 0; if (fade || spec.slideCount === 1) { return 0; } var slidesToOffset = 0; if (infinite) { slidesToOffset = -getPreClones(spec); // bring active slide to the beginning of visual area // if next scroll doesn't have enough children, just reach till the end of original slides instead of shifting slidesToScroll children if (slideCount % slidesToScroll !== 0 && slideIndex + slidesToScroll > slideCount) { slidesToOffset = -(slideIndex > slideCount ? slidesToShow - (slideIndex - slideCount) : slideCount % slidesToScroll); } // shift current slide to center of the frame if (centerMode) { slidesToOffset += parseInt(slidesToShow / 2); } } else { if (slideCount % slidesToScroll !== 0 && slideIndex + slidesToScroll > slideCount) { slidesToOffset = slidesToShow - slideCount % slidesToScroll; } if (centerMode) { slidesToOffset = parseInt(slidesToShow / 2); } } slideOffset = slidesToOffset * slideWidth; verticalOffset = slidesToOffset * slideHeight; if (!vertical) { targetLeft = slideIndex * slideWidth * -1 + slideOffset; } else { targetLeft = slideIndex * slideHeight * -1 + verticalOffset; } if (variableWidth === true) { var targetSlideIndex; var lastSlide = _reactDom2.default.findDOMNode(trackRef).children[slideCount - 1]; var max = -lastSlide.offsetLeft + listWidth - lastSlide.offsetWidth; if (slideCount <= slidesToShow || infinite === false) { targetSlide = _reactDom2.default.findDOMNode(trackRef).childNodes[slideIndex]; } else { targetSlideIndex = slideIndex + slidesToShow; targetSlide = _reactDom2.default.findDOMNode(trackRef).childNodes[targetSlideIndex]; } targetLeft = targetSlide ? targetSlide.offsetLeft * -1 : 0; if (centerMode === true) { if (infinite === false) { targetSlide = _reactDom2.default.findDOMNode(trackRef).children[slideIndex]; } else { targetSlide = _reactDom2.default.findDOMNode(trackRef).children[slideIndex + slidesToShow + 1]; } if (targetSlide) { targetLeft = targetSlide.offsetLeft * -1 + (listWidth - targetSlide.offsetWidth) / 2; } } if (spec.infinite === false && targetLeft < max) { targetLeft = max; } } return targetLeft; }; function getPreClones(spec) { return spec.slidesToShow + (spec.centerMode ? 1 : 0); } function getPostClones(spec) { return spec.slideCount; } function getTotalSlides(spec) { if (spec.slideCount === 1) { return 1; } return getPreClones(spec) + spec.slideCount + getPostClones(spec); } /***/ }), /* 6 */ /***/ (function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_6__; /***/ }), /* 7 */ /***/ (function(module, exports) { /* object-assign (c) Sindre Sorhus @license MIT */ 'use strict'; /* eslint-disable no-unused-vars */ var getOwnPropertySymbols = Object.getOwnPropertySymbols; var hasOwnProperty = Object.prototype.hasOwnProperty; var propIsEnumerable = Object.prototype.propertyIsEnumerable; function toObject(val) { if (val === null || val === undefined) { throw new TypeError('Object.assign cannot be called with null or undefined'); } return Object(val); } function shouldUseNative() { try { if (!Object.assign) { return false; } // Detect buggy property enumeration order in older V8 versions. // https://bugs.chromium.org/p/v8/issues/detail?id=4118 var test1 = new String('abc'); // eslint-disable-line no-new-wrappers test1[5] = 'de'; if (Object.getOwnPropertyNames(test1)[0] === '5') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test2 = {}; for (var i = 0; i < 10; i++) { test2['_' + String.fromCharCode(i)] = i; } var order2 = Object.getOwnPropertyNames(test2).map(function (n) { return test2[n]; }); if (order2.join('') !== '0123456789') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test3 = {}; 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { test3[letter] = letter; }); if (Object.keys(Object.assign({}, test3)).join('') !== 'abcdefghijklmnopqrst') { return false; } return true; } catch (err) { // We don't expect any of the above to throw, but better to be safe. return false; } } module.exports = shouldUseNative() ? Object.assign : function (target, source) { var from; var to = toObject(target); var symbols; for (var s = 1; s < arguments.length; s++) { from = Object(arguments[s]); for (var key in from) { if (hasOwnProperty.call(from, key)) { to[key] = from[key]; } } if (getOwnPropertySymbols) { symbols = getOwnPropertySymbols(from); for (var i = 0; i < symbols.length; i++) { if (propIsEnumerable.call(from, symbols[i])) { to[symbols[i]] = from[symbols[i]]; } } } } return to; }; /***/ }), /* 8 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _reactDom = __webpack_require__(6); var _reactDom2 = _interopRequireDefault(_reactDom); var _trackHelper = __webpack_require__(5); var _objectAssign = __webpack_require__(7); var _objectAssign2 = _interopRequireDefault(_objectAssign); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var helpers = { // supposed to start autoplay of slides initialize: function initialize(props) { var slickList = _reactDom2.default.findDOMNode(this.list); var slideCount = _react2.default.Children.count(props.children); var listWidth = this.getWidth(slickList); var trackWidth = this.getWidth(_reactDom2.default.findDOMNode(this.track)); var slideWidth; if (!props.vertical) { var centerPaddingAdj = props.centerMode && parseInt(props.centerPadding) * 2; if (props.centerPadding.slice(-1) === '%') { centerPaddingAdj *= listWidth / 100; } slideWidth = (this.getWidth(_reactDom2.default.findDOMNode(this)) - centerPaddingAdj) / props.slidesToShow; } else { slideWidth = this.getWidth(_reactDom2.default.findDOMNode(this)); } var slideHeight = this.getHeight(slickList.querySelector('[data-index="0"]')); var listHeight = slideHeight * props.slidesToShow; var currentSlide = props.rtl ? slideCount - 1 - props.initialSlide : props.initialSlide; this.setState({ slideCount: slideCount, slideWidth: slideWidth, listWidth: listWidth, trackWidth: trackWidth, currentSlide: currentSlide, slideHeight: slideHeight, listHeight: listHeight }, function () { // this reference isn't lost due to mixin var targetLeft = (0, _trackHelper.getTrackLeft)((0, _objectAssign2.default)({ slideIndex: this.state.currentSlide, trackRef: this.track }, props, this.state)); // getCSS function needs previously set state var trackStyle = (0, _trackHelper.getTrackCSS)((0, _objectAssign2.default)({ left: targetLeft }, props, this.state)); this.setState({ trackStyle: trackStyle }); this.autoPlay(); // once we're set up, trigger the initial autoplay. }); }, update: function update(props) { var slickList = _reactDom2.default.findDOMNode(this.list); // This method has mostly same code as initialize method. // Refactor it var slideCount = _react2.default.Children.count(props.children); var listWidth = this.getWidth(slickList); var trackWidth = this.getWidth(_reactDom2.default.findDOMNode(this.track)); var slideWidth; if (!props.vertical) { var centerPaddingAdj = props.centerMode && parseInt(props.centerPadding) * 2; if (props.centerPadding.slice(-1) === '%') { centerPaddingAdj *= listWidth / 100; } slideWidth = (this.getWidth(_reactDom2.default.findDOMNode(this)) - centerPaddingAdj) / props.slidesToShow; } else { slideWidth = this.getWidth(_reactDom2.default.findDOMNode(this)); } var slideHeight = this.getHeight(slickList.querySelector('[data-index="0"]')); var listHeight = slideHeight * props.slidesToShow; // pause slider if autoplay is set to false if (!props.autoplay) { this.pause(); } else { this.autoPlay(); } this.setState({ slideCount: slideCount, slideWidth: slideWidth, listWidth: listWidth, trackWidth: trackWidth, slideHeight: slideHeight, listHeight: listHeight }, function () { var targetLeft = (0, _trackHelper.getTrackLeft)((0, _objectAssign2.default)({ slideIndex: this.state.currentSlide, trackRef: this.track }, props, this.state)); // getCSS function needs previously set state var trackStyle = (0, _trackHelper.getTrackCSS)((0, _objectAssign2.default)({ left: targetLeft }, props, this.state)); this.setState({ trackStyle: trackStyle }); }); }, getWidth: function getWidth(elem) { return elem && (elem.getBoundingClientRect().width || elem.offsetWidth) || 0; }, getHeight: function getHeight(elem) { return elem && (elem.getBoundingClientRect().height || elem.offsetHeight) || 0; }, adaptHeight: function adaptHeight() { if (this.props.adaptiveHeight) { var selector = '[data-index="' + this.state.currentSlide + '"]'; if (this.list) { var slickList = _reactDom2.default.findDOMNode(this.list); var elem = slickList.querySelector(selector) || {}; slickList.style.height = (elem.offsetHeight || 0) + 'px'; } } }, canGoNext: function canGoNext(opts) { var canGo = true; if (!opts.infinite) { if (opts.centerMode) { // check if current slide is last slide if (opts.currentSlide >= opts.slideCount - 1) { canGo = false; } } else { // check if all slides are shown in slider if (opts.slideCount <= opts.slidesToShow || opts.currentSlide >= opts.slideCount - opts.slidesToShow) { canGo = false; } } } return canGo; }, slideHandler: function slideHandler(index) { var _this = this; // index is target slide index // Functionality of animateSlide and postSlide is merged into this function var targetSlide, currentSlide; var targetLeft, currentLeft; var callback; if (this.props.waitForAnimate && this.state.animating) { return; } if (this.props.fade) { currentSlide = this.state.currentSlide; // Don't change slide if infinite=false and target slide is out of range if (this.props.infinite === false && (index < 0 || index >= this.state.slideCount)) { return; } // Shifting targetSlide back into the range if (index < 0) { targetSlide = index + this.state.slideCount; } else if (index >= this.state.slideCount) { targetSlide = index - this.state.slideCount; } else { targetSlide = index; } if (this.props.lazyLoad && this.state.lazyLoadedList.indexOf(targetSlide) < 0) { this.setState({ lazyLoadedList: this.state.lazyLoadedList.concat(targetSlide) }); } callback = function callback() { _this.setState({ animating: false }); if (_this.props.afterChange) { _this.props.afterChange(targetSlide); } delete _this.animationEndCallback; }; this.setState({ animating: true, currentSlide: targetSlide }, function () { this.animationEndCallback = setTimeout(callback, this.props.speed); }); if (this.props.beforeChange) { this.props.beforeChange(this.state.currentSlide, targetSlide); } this.autoPlay(); return; } targetSlide = index; if (targetSlide < 0) { if (this.props.infinite === false) { currentSlide = 0; } else if (this.state.slideCount % this.props.slidesToScroll !== 0) { currentSlide = this.state.slideCount - this.state.slideCount % this.props.slidesToScroll; } else { currentSlide = this.state.slideCount + targetSlide; } } else if (targetSlide >= this.state.slideCount) { if (this.props.infinite === false) { currentSlide = this.state.slideCount - this.props.slidesToShow; } else if (this.state.slideCount % this.props.slidesToScroll !== 0) { currentSlide = 0; } else { currentSlide = targetSlide - this.state.slideCount; } } else { currentSlide = targetSlide; } targetLeft = (0, _trackHelper.getTrackLeft)((0, _objectAssign2.default)({ slideIndex: targetSlide, trackRef: this.track }, this.props, this.state)); currentLeft = (0, _trackHelper.getTrackLeft)((0, _objectAssign2.default)({ slideIndex: currentSlide, trackRef: this.track }, this.props, this.state)); if (this.props.infinite === false) { if (targetLeft === currentLeft) { targetSlide = currentSlide; } targetLeft = currentLeft; } if (this.props.beforeChange) { this.props.beforeChange(this.state.currentSlide, currentSlide); } if (this.props.lazyLoad) { var slidesToLoad = []; var slideCount = this.state.slideCount; for (var i = targetSlide; i < targetSlide + this.props.slidesToShow; i++) { if (this.state.lazyLoadedList.indexOf(i) < 0) { slidesToLoad.push(i); } if (i >= slideCount && this.state.lazyLoadedList.indexOf(i - slideCount) < 0) { slidesToLoad.push(i - slideCount); } if (i < 0 && this.state.lazyLoadedList.indexOf(i + slideCount) < 0) { slidesToLoad.push(i + slideCount); } } if (slidesToLoad.length > 0) { this.setState({ lazyLoadedList: this.state.lazyLoadedList.concat(slidesToLoad) }); } } // Slide Transition happens here. // animated transition happens to target Slide and // non - animated transition happens to current Slide // If CSS transitions are false, directly go the current slide. if (this.props.useCSS === false) { this.setState({ currentSlide: currentSlide, trackStyle: (0, _trackHelper.getTrackCSS)((0, _objectAssign2.default)({ left: currentLeft }, this.props, this.state)) }, function () { if (this.props.afterChange) { this.props.afterChange(currentSlide); } }); } else { var nextStateChanges = { animating: false, currentSlide: currentSlide, trackStyle: (0, _trackHelper.getTrackCSS)((0, _objectAssign2.default)({ left: currentLeft }, this.props, this.state)), swipeLeft: null }; callback = function callback() { _this.setState(nextStateChanges, function () { if (_this.props.afterChange) { _this.props.afterChange(currentSlide); } delete _this.animationEndCallback; }); }; this.setState({ animating: true, currentSlide: currentSlide, trackStyle: (0, _trackHelper.getTrackAnimateCSS)((0, _objectAssign2.default)({ left: targetLeft }, this.props, this.state)) }, function () { this.animationEndCallback = setTimeout(callback, this.props.speed); }); } this.autoPlay(); }, swipeDirection: function swipeDirection(touchObject) { var xDist, yDist, r, swipeAngle; xDist = touchObject.startX - touchObject.curX; yDist = touchObject.startY - touchObject.curY; r = Math.atan2(yDist, xDist); swipeAngle = Math.round(r * 180 / Math.PI); if (swipeAngle < 0) { swipeAngle = 360 - Math.abs(swipeAngle); } if (swipeAngle <= 45 && swipeAngle >= 0 || swipeAngle <= 360 && swipeAngle >= 315) { return 'left'; } if (swipeAngle >= 135 && swipeAngle <= 225) { return 'right'; } if (this.props.verticalSwiping === true) { if (swipeAngle >= 35 && swipeAngle <= 135) { return 'down'; } else { return 'up'; } } return 'vertical'; }, play: function play() { var nextIndex; if (!this.state.mounted) { return false; } if (this.props.rtl) { nextIndex = this.state.currentSlide - this.props.slidesToScroll; } else { if (this.canGoNext(_extends({}, this.props, this.state))) { nextIndex = this.state.currentSlide + this.props.slidesToScroll; } else { return false; } } this.slideHandler(nextIndex); }, autoPlay: function autoPlay() { if (this.state.autoPlayTimer) { clearTimeout(this.state.autoPlayTimer); } if (this.props.autoplay) { this.setState({ autoPlayTimer: setTimeout(this.play, this.props.autoplaySpeed) }); } }, pause: function pause() { if (this.state.autoPlayTimer) { clearTimeout(this.state.autoPlayTimer); this.setState({ autoPlayTimer: null }); } } }; exports.default = helpers; /***/ }), /* 9 */ /***/ (function(module, exports) { "use strict"; var initialState = { animating: false, dragging: false, autoPlayTimer: null, currentDirection: 0, currentLeft: null, currentSlide: 0, direction: 1, listWidth: null, listHeight: null, scrolling: false, // loadIndex: 0, slideCount: null, slideWidth: null, slideHeight: null, swiping: false, // sliding: false, // slideOffset: 0, swipeLeft: null, touchObject: { startX: 0, startY: 0, curX: 0, curY: 0 }, lazyLoadedList: [], // added for react initialized: false, edgeDragged: false, swiped: false, // used by swipeEvent. differentites between touch and swipe. trackStyle: {}, trackWidth: 0 // Removed // transformsEnabled: false, // $nextArrow: null, // $prevArrow: null, // $dots: null, // $list: null, // $slideTrack: null, // $slides: null, }; module.exports = initialState; /***/ }), /* 10 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var defaultProps = { className: '', accessibility: true, adaptiveHeight: false, arrows: true, autoplay: false, autoplaySpeed: 3000, centerMode: false, centerPadding: '50px', cssEase: 'ease', customPaging: function customPaging(i) { return _react2.default.createElement( 'button', null, i + 1 ); }, dots: false, dotsClass: 'slick-dots', draggable: true, easing: 'linear', edgeFriction: 0.35, fade: false, focusOnSelect: false, infinite: true, initialSlide: 0, lazyLoad: false, pauseOnHover: true, responsive: null, rtl: false, slide: 'div', slidesToShow: 1, slidesToScroll: 1, speed: 500, swipe: true, swipeToSlide: false, touchMove: true, touchThreshold: 5, useCSS: true, variableWidth: false, vertical: false, waitForAnimate: true, afterChange: null, beforeChange: null, edgeEvent: null, // init: function hook that gets called right before InnerSlider mounts init: null, swipeEvent: null, // nextArrow, prevArrow should react componets nextArrow: null, prevArrow: null }; exports.default = defaultProps; /***/ }), /* 11 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var React = __webpack_require__(2); var factory = __webpack_require__(12); if (typeof React === 'undefined') { throw Error( 'create-react-class could not find the React object. If you are using script tags, ' + 'make sure that React is being loaded before create-react-class.' ); } // Hack to grab NoopUpdateQueue from isomorphic React var ReactNoopUpdateQueue = new React.Component().updater; module.exports = factory( React.Component, React.isValidElement, ReactNoopUpdateQueue ); /***/ }), /* 12 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _assign = __webpack_require__(7); var emptyObject = __webpack_require__(13); var _invariant = __webpack_require__(14); if ((undefined) !== 'production') { var warning = __webpack_require__(15); } var MIXINS_KEY = 'mixins'; // Helper function to allow the creation of anonymous functions which do not // have .name set to the name of the variable being assigned to. function identity(fn) { return fn; } var ReactPropTypeLocationNames; if ((undefined) !== 'production') { ReactPropTypeLocationNames = { prop: 'prop', context: 'context', childContext: 'child context' }; } else { ReactPropTypeLocationNames = {}; } function factory(ReactComponent, isValidElement, ReactNoopUpdateQueue) { /** * Policies that describe methods in `ReactClassInterface`. */ var injectedMixins = []; /** * Composite components are higher-level components that compose other composite * or host components. * * To create a new type of `ReactClass`, pass a specification of * your new class to `React.createClass`. The only requirement of your class * specification is that you implement a `render` method. * * var MyComponent = React.createClass({ * render: function() { * return <div>Hello World</div>; * } * }); * * The class specification supports a specific protocol of methods that have * special meaning (e.g. `render`). See `ReactClassInterface` for * more the comprehensive protocol. Any other properties and methods in the * class specification will be available on the prototype. * * @interface ReactClassInterface * @internal */ var ReactClassInterface = { /** * An array of Mixin objects to include when defining your component. * * @type {array} * @optional */ mixins: 'DEFINE_MANY', /** * An object containing properties and methods that should be defined on * the component's constructor instead of its prototype (static methods). * * @type {object} * @optional */ statics: 'DEFINE_MANY', /** * Definition of prop types for this component. * * @type {object} * @optional */ propTypes: 'DEFINE_MANY', /** * Definition of context types for this component. * * @type {object} * @optional */ contextTypes: 'DEFINE_MANY', /** * Definition of context types this component sets for its children. * * @type {object} * @optional */ childContextTypes: 'DEFINE_MANY', // ==== Definition methods ==== /** * Invoked when the component is mounted. Values in the mapping will be set on * `this.props` if that prop is not specified (i.e. using an `in` check). * * This method is invoked before `getInitialState` and therefore cannot rely * on `this.state` or use `this.setState`. * * @return {object} * @optional */ getDefaultProps: 'DEFINE_MANY_MERGED', /** * Invoked once before the component is mounted. The return value will be used * as the initial value of `this.state`. * * getInitialState: function() { * return { * isOn: false, * fooBaz: new BazFoo() * } * } * * @return {object} * @optional */ getInitialState: 'DEFINE_MANY_MERGED', /** * @return {object} * @optional */ getChildContext: 'DEFINE_MANY_MERGED', /** * Uses props from `this.props` and state from `this.state` to render the * structure of the component. * * No guarantees are made about when or how often this method is invoked, so * it must not have side effects. * * render: function() { * var name = this.props.name; * return <div>Hello, {name}!</div>; * } * * @return {ReactComponent} * @required */ render: 'DEFINE_ONCE', // ==== Delegate methods ==== /** * Invoked when the component is initially created and about to be mounted. * This may have side effects, but any external subscriptions or data created * by this method must be cleaned up in `componentWillUnmount`. * * @optional */ componentWillMount: 'DEFINE_MANY', /** * Invoked when the component has been mounted and has a DOM representation. * However, there is no guarantee that the DOM node is in the document. * * Use this as an opportunity to operate on the DOM when the component has * been mounted (initialized and rendered) for the first time. * * @param {DOMElement} rootNode DOM element representing the component. * @optional */ componentDidMount: 'DEFINE_MANY', /** * Invoked before the component receives new props. * * Use this as an opportunity to react to a prop transition by updating the * state using `this.setState`. Current props are accessed via `this.props`. * * componentWillReceiveProps: function(nextProps, nextContext) { * this.setState({ * likesIncreasing: nextProps.likeCount > this.props.likeCount * }); * } * * NOTE: There is no equivalent `componentWillReceiveState`. An incoming prop * transition may cause a state change, but the opposite is not true. If you * need it, you are probably looking for `componentWillUpdate`. * * @param {object} nextProps * @optional */ componentWillReceiveProps: 'DEFINE_MANY', /** * Invoked while deciding if the component should be updated as a result of * receiving new props, state and/or context. * * Use this as an opportunity to `return false` when you're certain that the * transition to the new props/state/context will not require a component * update. * * shouldComponentUpdate: function(nextProps, nextState, nextContext) { * return !equal(nextProps, this.props) || * !equal(nextState, this.state) || * !equal(nextContext, this.context); * } * * @param {object} nextProps * @param {?object} nextState * @param {?object} nextContext * @return {boolean} True if the component should update. * @optional */ shouldComponentUpdate: 'DEFINE_ONCE', /** * Invoked when the component is about to update due to a transition from * `this.props`, `this.state` and `this.context` to `nextProps`, `nextState` * and `nextContext`. * * Use this as an opportunity to perform preparation before an update occurs. * * NOTE: You **cannot** use `this.setState()` in this method. * * @param {object} nextProps * @param {?object} nextState * @param {?object} nextContext * @param {ReactReconcileTransaction} transaction * @optional */ componentWillUpdate: 'DEFINE_MANY', /** * Invoked when the component's DOM representation has been updated. * * Use this as an opportunity to operate on the DOM when the component has * been updated. * * @param {object} prevProps * @param {?object} prevState * @param {?object} prevContext * @param {DOMElement} rootNode DOM element representing the component. * @optional */ componentDidUpdate: 'DEFINE_MANY', /** * Invoked when the component is about to be removed from its parent and have * its DOM representation destroyed. * * Use this as an opportunity to deallocate any external resources. * * NOTE: There is no `componentDidUnmount` since your component will have been * destroyed by that point. * * @optional */ componentWillUnmount: 'DEFINE_MANY', // ==== Advanced methods ==== /** * Updates the component's currently mounted DOM representation. * * By default, this implements React's rendering and reconciliation algorithm. * Sophisticated clients may wish to override this. * * @param {ReactReconcileTransaction} transaction * @internal * @overridable */ updateComponent: 'OVERRIDE_BASE' }; /** * Mapping from class specification keys to special processing functions. * * Although these are declared like instance properties in the specification * when defining classes using `React.createClass`, they are actually static * and are accessible on the constructor instead of the prototype. Despite * being static, they must be defined outside of the "statics" key under * which all other static methods are defined. */ var RESERVED_SPEC_KEYS = { displayName: function(Constructor, displayName) { Constructor.displayName = displayName; }, mixins: function(Constructor, mixins) { if (mixins) { for (var i = 0; i < mixins.length; i++) { mixSpecIntoComponent(Constructor, mixins[i]); } } }, childContextTypes: function(Constructor, childContextTypes) { if ((undefined) !== 'production') { validateTypeDef(Constructor, childContextTypes, 'childContext'); } Constructor.childContextTypes = _assign( {}, Constructor.childContextTypes, childContextTypes ); }, contextTypes: function(Constructor, contextTypes) { if ((undefined) !== 'production') { validateTypeDef(Constructor, contextTypes, 'context'); } Constructor.contextTypes = _assign( {}, Constructor.contextTypes, contextTypes ); }, /** * Special case getDefaultProps which should move into statics but requires * automatic merging. */ getDefaultProps: function(Constructor, getDefaultProps) { if (Constructor.getDefaultProps) { Constructor.getDefaultProps = createMergedResultFunction( Constructor.getDefaultProps, getDefaultProps ); } else { Constructor.getDefaultProps = getDefaultProps; } }, propTypes: function(Constructor, propTypes) { if ((undefined) !== 'production') { validateTypeDef(Constructor, propTypes, 'prop'); } Constructor.propTypes = _assign({}, Constructor.propTypes, propTypes); }, statics: function(Constructor, statics) { mixStaticSpecIntoComponent(Constructor, statics); }, autobind: function() {} }; function validateTypeDef(Constructor, typeDef, location) { for (var propName in typeDef) { if (typeDef.hasOwnProperty(propName)) { // use a warning instead of an _invariant so components // don't show up in prod but only in __DEV__ if ((undefined) !== 'production') { warning( typeof typeDef[propName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', Constructor.displayName || 'ReactClass', ReactPropTypeLocationNames[location], propName ); } } } } function validateMethodOverride(isAlreadyDefined, name) { var specPolicy = ReactClassInterface.hasOwnProperty(name) ? ReactClassInterface[name] : null; // Disallow overriding of base class methods unless explicitly allowed. if (ReactClassMixin.hasOwnProperty(name)) { _invariant( specPolicy === 'OVERRIDE_BASE', 'ReactClassInterface: You are attempting to override ' + '`%s` from your class specification. Ensure that your method names ' + 'do not overlap with React methods.', name ); } // Disallow defining methods more than once unless explicitly allowed. if (isAlreadyDefined) { _invariant( specPolicy === 'DEFINE_MANY' || specPolicy === 'DEFINE_MANY_MERGED', 'ReactClassInterface: You are attempting to define ' + '`%s` on your component more than once. This conflict may be due ' + 'to a mixin.', name ); } } /** * Mixin helper which handles policy validation and reserved * specification keys when building React classes. */ function mixSpecIntoComponent(Constructor, spec) { if (!spec) { if ((undefined) !== 'production') { var typeofSpec = typeof spec; var isMixinValid = typeofSpec === 'object' && spec !== null; if ((undefined) !== 'production') { warning( isMixinValid, "%s: You're attempting to include a mixin that is either null " + 'or not an object. Check the mixins included by the component, ' + 'as well as any mixins they include themselves. ' + 'Expected object but got %s.', Constructor.displayName || 'ReactClass', spec === null ? null : typeofSpec ); } } return; } _invariant( typeof spec !== 'function', "ReactClass: You're attempting to " + 'use a component class or function as a mixin. Instead, just use a ' + 'regular object.' ); _invariant( !isValidElement(spec), "ReactClass: You're attempting to " + 'use a component as a mixin. Instead, just use a regular object.' ); var proto = Constructor.prototype; var autoBindPairs = proto.__reactAutoBindPairs; // By handling mixins before any other properties, we ensure the same // chaining order is applied to methods with DEFINE_MANY policy, whether // mixins are listed before or after these methods in the spec. if (spec.hasOwnProperty(MIXINS_KEY)) { RESERVED_SPEC_KEYS.mixins(Constructor, spec.mixins); } for (var name in spec) { if (!spec.hasOwnProperty(name)) { continue; } if (name === MIXINS_KEY) { // We have already handled mixins in a special case above. continue; } var property = spec[name]; var isAlreadyDefined = proto.hasOwnProperty(name); validateMethodOverride(isAlreadyDefined, name); if (RESERVED_SPEC_KEYS.hasOwnProperty(name)) { RESERVED_SPEC_KEYS[name](Constructor, property); } else { // Setup methods on prototype: // The following member methods should not be automatically bound: // 1. Expected ReactClass methods (in the "interface"). // 2. Overridden methods (that were mixed in). var isReactClassMethod = ReactClassInterface.hasOwnProperty(name); var isFunction = typeof property === 'function'; var shouldAutoBind = isFunction && !isReactClassMethod && !isAlreadyDefined && spec.autobind !== false; if (shouldAutoBind) { autoBindPairs.push(name, property); proto[name] = property; } else { if (isAlreadyDefined) { var specPolicy = ReactClassInterface[name]; // These cases should already be caught by validateMethodOverride. _invariant( isReactClassMethod && (specPolicy === 'DEFINE_MANY_MERGED' || specPolicy === 'DEFINE_MANY'), 'ReactClass: Unexpected spec policy %s for key %s ' + 'when mixing in component specs.', specPolicy, name ); // For methods which are defined more than once, call the existing // methods before calling the new property, merging if appropriate. if (specPolicy === 'DEFINE_MANY_MERGED') { proto[name] = createMergedResultFunction(proto[name], property); } else if (specPolicy === 'DEFINE_MANY') { proto[name] = createChainedFunction(proto[name], property); } } else { proto[name] = property; if ((undefined) !== 'production') { // Add verbose displayName to the function, which helps when looking // at profiling tools. if (typeof property === 'function' && spec.displayName) { proto[name].displayName = spec.displayName + '_' + name; } } } } } } } function mixStaticSpecIntoComponent(Constructor, statics) { if (!statics) { return; } for (var name in statics) { var property = statics[name]; if (!statics.hasOwnProperty(name)) { continue; } var isReserved = name in RESERVED_SPEC_KEYS; _invariant( !isReserved, 'ReactClass: You are attempting to define a reserved ' + 'property, `%s`, that shouldn\'t be on the "statics" key. Define it ' + 'as an instance property instead; it will still be accessible on the ' + 'constructor.', name ); var isInherited = name in Constructor; _invariant( !isInherited, 'ReactClass: You are attempting to define ' + '`%s` on your component more than once. This conflict may be ' + 'due to a mixin.', name ); Constructor[name] = property; } } /** * Merge two objects, but throw if both contain the same key. * * @param {object} one The first object, which is mutated. * @param {object} two The second object * @return {object} one after it has been mutated to contain everything in two. */ function mergeIntoWithNoDuplicateKeys(one, two) { _invariant( one && two && typeof one === 'object' && typeof two === 'object', 'mergeIntoWithNoDuplicateKeys(): Cannot merge non-objects.' ); for (var key in two) { if (two.hasOwnProperty(key)) { _invariant( one[key] === undefined, 'mergeIntoWithNoDuplicateKeys(): ' + 'Tried to merge two objects with the same key: `%s`. This conflict ' + 'may be due to a mixin; in particular, this may be caused by two ' + 'getInitialState() or getDefaultProps() methods returning objects ' + 'with clashing keys.', key ); one[key] = two[key]; } } return one; } /** * Creates a function that invokes two functions and merges their return values. * * @param {function} one Function to invoke first. * @param {function} two Function to invoke second. * @return {function} Function that invokes the two argument functions. * @private */ function createMergedResultFunction(one, two) { return function mergedResult() { var a = one.apply(this, arguments); var b = two.apply(this, arguments); if (a == null) { return b; } else if (b == null) { return a; } var c = {}; mergeIntoWithNoDuplicateKeys(c, a); mergeIntoWithNoDuplicateKeys(c, b); return c; }; } /** * Creates a function that invokes two functions and ignores their return vales. * * @param {function} one Function to invoke first. * @param {function} two Function to invoke second. * @return {function} Function that invokes the two argument functions. * @private */ function createChainedFunction(one, two) { return function chainedFunction() { one.apply(this, arguments); two.apply(this, arguments); }; } /** * Binds a method to the component. * * @param {object} component Component whose method is going to be bound. * @param {function} method Method to be bound. * @return {function} The bound method. */ function bindAutoBindMethod(component, method) { var boundMethod = method.bind(component); if ((undefined) !== 'production') { boundMethod.__reactBoundContext = component; boundMethod.__reactBoundMethod = method; boundMethod.__reactBoundArguments = null; var componentName = component.constructor.displayName; var _bind = boundMethod.bind; boundMethod.bind = function(newThis) { for ( var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++ ) { args[_key - 1] = arguments[_key]; } // User is trying to bind() an autobound method; we effectively will // ignore the value of "this" that the user is trying to use, so // let's warn. if (newThis !== component && newThis !== null) { if ((undefined) !== 'production') { warning( false, 'bind(): React component methods may only be bound to the ' + 'component instance. See %s', componentName ); } } else if (!args.length) { if ((undefined) !== 'production') { warning( false, 'bind(): You are binding a component method to the component. ' + 'React does this for you automatically in a high-performance ' + 'way, so you can safely remove this call. See %s', componentName ); } return boundMethod; } var reboundMethod = _bind.apply(boundMethod, arguments); reboundMethod.__reactBoundContext = component; reboundMethod.__reactBoundMethod = method; reboundMethod.__reactBoundArguments = args; return reboundMethod; }; } return boundMethod; } /** * Binds all auto-bound methods in a component. * * @param {object} component Component whose method is going to be bound. */ function bindAutoBindMethods(component) { var pairs = component.__reactAutoBindPairs; for (var i = 0; i < pairs.length; i += 2) { var autoBindKey = pairs[i]; var method = pairs[i + 1]; component[autoBindKey] = bindAutoBindMethod(component, method); } } var IsMountedPreMixin = { componentDidMount: function() { this.__isMounted = true; } }; var IsMountedPostMixin = { componentWillUnmount: function() { this.__isMounted = false; } }; /** * Add more to the ReactClass base class. These are all legacy features and * therefore not already part of the modern ReactComponent. */ var ReactClassMixin = { /** * TODO: This will be deprecated because state should always keep a consistent * type signature and the only use case for this, is to avoid that. */ replaceState: function(newState, callback) { this.updater.enqueueReplaceState(this, newState, callback); }, /** * Checks whether or not this composite component is mounted. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ isMounted: function() { if ((undefined) !== 'production') { warning( this.__didWarnIsMounted, '%s: isMounted is deprecated. Instead, make sure to clean up ' + 'subscriptions and pending requests in componentWillUnmount to ' + 'prevent memory leaks.', (this.constructor && this.constructor.displayName) || this.name || 'Component' ); this.__didWarnIsMounted = true; } return !!this.__isMounted; } }; var ReactClassComponent = function() {}; _assign( ReactClassComponent.prototype, ReactComponent.prototype, ReactClassMixin ); /** * Creates a composite component class given a class specification. * See https://facebook.github.io/react/docs/top-level-api.html#react.createclass * * @param {object} spec Class specification (which must define `render`). * @return {function} Component constructor function. * @public */ function createClass(spec) { // To keep our warnings more understandable, we'll use a little hack here to // ensure that Constructor.name !== 'Constructor'. This makes sure we don't // unnecessarily identify a class without displayName as 'Constructor'. var Constructor = identity(function(props, context, updater) { // This constructor gets overridden by mocks. The argument is used // by mocks to assert on what gets mounted. if ((undefined) !== 'production') { warning( this instanceof Constructor, 'Something is calling a React component directly. Use a factory or ' + 'JSX instead. See: https://fb.me/react-legacyfactory' ); } // Wire up auto-binding if (this.__reactAutoBindPairs.length) { bindAutoBindMethods(this); } this.props = props; this.context = context; this.refs = emptyObject; this.updater = updater || ReactNoopUpdateQueue; this.state = null; // ReactClasses doesn't have constructors. Instead, they use the // getInitialState and componentWillMount methods for initialization. var initialState = this.getInitialState ? this.getInitialState() : null; if ((undefined) !== 'production') { // We allow auto-mocks to proceed as if they're returning null. if ( initialState === undefined && this.getInitialState._isMockFunction ) { // This is probably bad practice. Consider warning here and // deprecating this convenience. initialState = null; } } _invariant( typeof initialState === 'object' && !Array.isArray(initialState), '%s.getInitialState(): must return an object or null', Constructor.displayName || 'ReactCompositeComponent' ); this.state = initialState; }); Constructor.prototype = new ReactClassComponent(); Constructor.prototype.constructor = Constructor; Constructor.prototype.__reactAutoBindPairs = []; injectedMixins.forEach(mixSpecIntoComponent.bind(null, Constructor)); mixSpecIntoComponent(Constructor, IsMountedPreMixin); mixSpecIntoComponent(Constructor, spec); mixSpecIntoComponent(Constructor, IsMountedPostMixin); // Initialize the defaultProps property after all mixins have been merged. if (Constructor.getDefaultProps) { Constructor.defaultProps = Constructor.getDefaultProps(); } if ((undefined) !== 'production') { // This is a tag to indicate that the use of these method names is ok, // since it's used with createClass. If it's not, then it's likely a // mistake so we'll warn you to use the static property, property // initializer or constructor respectively. if (Constructor.getDefaultProps) { Constructor.getDefaultProps.isReactClassApproved = {}; } if (Constructor.prototype.getInitialState) { Constructor.prototype.getInitialState.isReactClassApproved = {}; } } _invariant( Constructor.prototype.render, 'createClass(...): Class specification must implement a `render` method.' ); if ((undefined) !== 'production') { warning( !Constructor.prototype.componentShouldUpdate, '%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', spec.displayName || 'A component' ); warning( !Constructor.prototype.componentWillRecieveProps, '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', spec.displayName || 'A component' ); } // Reduce time spent doing lookups by setting these on the prototype. for (var methodName in ReactClassInterface) { if (!Constructor.prototype[methodName]) { Constructor.prototype[methodName] = null; } } return Constructor; } return createClass; } module.exports = factory; /***/ }), /* 13 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var emptyObject = {}; if ((undefined) !== 'production') { Object.freeze(emptyObject); } module.exports = emptyObject; /***/ }), /* 14 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; /** * Use invariant() to assert state which your program assumes to be true. * * Provide sprintf-style format (only %s is supported) and arguments * to provide information about what broke and what you were * expecting. * * The invariant message will be stripped in production, but the invariant * will remain to ensure logic does not differ in production. */ var validateFormat = function validateFormat(format) {}; if ((undefined) !== 'production') { validateFormat = function validateFormat(format) { if (format === undefined) { throw new Error('invariant requires an error message argument'); } }; } function invariant(condition, format, a, b, c, d, e, f) { validateFormat(format); if (!condition) { var error; if (format === undefined) { error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.'); } else { var args = [a, b, c, d, e, f]; var argIndex = 0; error = new Error(format.replace(/%s/g, function () { return args[argIndex++]; })); error.name = 'Invariant Violation'; } error.framesToPop = 1; // we don't care about invariant's own frame throw error; } } module.exports = invariant; /***/ }), /* 15 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2014-2015, 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'; var emptyFunction = __webpack_require__(16); /** * Similar to invariant but only logs a warning if the condition is not met. * This can be used to log issues in development environments in critical * paths. Removing the logging code for production environments will keep the * same logic and follow the same code paths. */ var warning = emptyFunction; if ((undefined) !== 'production') { var printWarning = function printWarning(format) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } var argIndex = 0; var message = 'Warning: ' + format.replace(/%s/g, function () { return args[argIndex++]; }); if (typeof console !== 'undefined') { console.error(message); } try { // --- Welcome to debugging React --- // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. throw new Error(message); } catch (x) {} }; warning = function warning(condition, format) { if (format === undefined) { throw new Error('`warning(condition, format, ...args)` requires a warning ' + 'message argument'); } if (format.indexOf('Failed Composite propType: ') === 0) { return; // Ignore CompositeComponent proptype check. } if (!condition) { for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) { args[_key2 - 2] = arguments[_key2]; } printWarning.apply(undefined, [format].concat(args)); } }; } module.exports = warning; /***/ }), /* 16 */ /***/ (function(module, exports) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ function makeEmptyFunction(arg) { return function () { return arg; }; } /** * This function accepts and discards inputs; it has no side effects. This is * primarily useful idiomatically for overridable function endpoints which * always need to be callable, since JS lacks a null-call idiom ala Cocoa. */ var emptyFunction = function emptyFunction() {}; emptyFunction.thatReturns = makeEmptyFunction; emptyFunction.thatReturnsFalse = makeEmptyFunction(false); emptyFunction.thatReturnsTrue = makeEmptyFunction(true); emptyFunction.thatReturnsNull = makeEmptyFunction(null); emptyFunction.thatReturnsThis = function () { return this; }; emptyFunction.thatReturnsArgument = function (arg) { return arg; }; module.exports = emptyFunction; /***/ }), /* 17 */ /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! Copyright (c) 2016 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames */ /* global define */ (function () { 'use strict'; var hasOwn = {}.hasOwnProperty; function classNames () { var classes = []; for (var i = 0; i < arguments.length; i++) { var arg = arguments[i]; if (!arg) continue; var argType = typeof arg; if (argType === 'string' || argType === 'number') { classes.push(arg); } else if (Array.isArray(arg)) { classes.push(classNames.apply(null, arg)); } else if (argType === 'object') { for (var key in arg) { if (hasOwn.call(arg, key) && arg[key]) { classes.push(key); } } } } return classes.join(' '); } if (typeof module !== 'undefined' && module.exports) { module.exports = classNames; } else if (true) { // register as 'classnames', consistent with npm package name !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function () { return classNames; }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else { window.classNames = classNames; } }()); /***/ }), /* 18 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.Track = undefined; var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _objectAssign = __webpack_require__(7); var _objectAssign2 = _interopRequireDefault(_objectAssign); var _classnames = __webpack_require__(17); var _classnames2 = _interopRequireDefault(_classnames); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } // given specifications/props for a slide, fetch all the classes that need to be applied to the slide var getSlideClasses = function getSlideClasses(spec) { // if spec has currentSlideIndex, we can also apply slickCurrent class according to that (https://github.com/kenwheeler/slick/blob/master/slick/slick.js#L2300-L2302) var slickActive, slickCenter, slickCloned; var centerOffset, index; if (spec.rtl) { // if we're going right to left, index is reversed index = spec.slideCount - 1 - spec.index; } else { // index of the slide index = spec.index; } slickCloned = index < 0 || index >= spec.slideCount; if (spec.centerMode) { centerOffset = Math.floor(spec.slidesToShow / 2); slickCenter = (index - spec.currentSlide) % spec.slideCount === 0; // concern: not sure if this should be correct (https://github.com/kenwheeler/slick/blob/master/slick/slick.js#L2328-L2346) if (index > spec.currentSlide - centerOffset - 1 && index <= spec.currentSlide + centerOffset) { slickActive = true; } } else { // concern: following can be incorrect in case where currentSlide is lastSlide in frame and rest of the slides to show have index smaller than currentSlideIndex slickActive = spec.currentSlide <= index && index < spec.currentSlide + spec.slidesToShow; } var slickCurrent = index === spec.currentSlide; return (0, _classnames2.default)({ 'slick-slide': true, 'slick-active': slickActive, 'slick-center': slickCenter, 'slick-cloned': slickCloned, 'slick-current': slickCurrent // dubious in case of RTL }); }; var getSlideStyle = function getSlideStyle(spec) { var style = {}; if (spec.variableWidth === undefined || spec.variableWidth === false) { style.width = spec.slideWidth; } if (spec.fade) { style.position = 'relative'; if (spec.vertical) { style.top = -spec.index * spec.slideHeight; } else { style.left = -spec.index * spec.slideWidth; } style.opacity = spec.currentSlide === spec.index ? 1 : 0; style.visibility = spec.currentSlide === spec.index ? 'visible' : 'hidden'; style.transition = 'opacity ' + spec.speed + 'ms ' + spec.cssEase + ', ' + 'visibility ' + spec.speed + 'ms ' + spec.cssEase; style.WebkitTransition = 'opacity ' + spec.speed + 'ms ' + spec.cssEase + ', ' + 'visibility ' + spec.speed + 'ms ' + spec.cssEase; } return style; }; var getKey = function getKey(child, fallbackKey) { return child.key || fallbackKey; }; var renderSlides = function renderSlides(spec) { var key; var slides = []; var preCloneSlides = []; var postCloneSlides = []; var childrenCount = _react2.default.Children.count(spec.children); _react2.default.Children.forEach(spec.children, function (elem, index) { var child = void 0; var childOnClickOptions = { message: 'children', index: index, slidesToScroll: spec.slidesToScroll, currentSlide: spec.currentSlide }; // in case of lazyLoad, whether or not we want to fetch the slide if (!spec.lazyLoad || spec.lazyLoad && spec.lazyLoadedList.indexOf(index) >= 0) { child = elem; } else { child = _react2.default.createElement('div', null); } var childStyle = getSlideStyle((0, _objectAssign2.default)({}, spec, { index: index })); var slideClass = child.props.className || ''; var onClick = function onClick(e) { child.props && child.props.onClick && child.props.onClick(e); if (spec.focusOnSelect) { spec.focusOnSelect(childOnClickOptions); } }; // push a cloned element of the desired slide slides.push(_react2.default.cloneElement(child, { key: 'original' + getKey(child, index), 'data-index': index, className: (0, _classnames2.default)(getSlideClasses((0, _objectAssign2.default)({ index: index }, spec)), slideClass), tabIndex: '-1', style: (0, _objectAssign2.default)({ outline: 'none' }, child.props.style || {}, childStyle), onClick: onClick })); // variableWidth doesn't wrap properly. // if slide needs to be precloned or postcloned if (spec.infinite && spec.fade === false) { var preCloneNo = childrenCount - index; if (preCloneNo <= spec.slidesToShow + (spec.centerMode ? 1 : 0) && childrenCount !== spec.slidesToShow) { key = -preCloneNo; preCloneSlides.push(_react2.default.cloneElement(child, { key: 'precloned' + getKey(child, key), 'data-index': key, className: (0, _classnames2.default)(getSlideClasses((0, _objectAssign2.default)({ index: key }, spec)), slideClass), style: (0, _objectAssign2.default)({}, child.props.style || {}, childStyle), onClick: onClick })); } if (childrenCount !== spec.slidesToShow) { key = childrenCount + index; postCloneSlides.push(_react2.default.cloneElement(child, { key: 'postcloned' + getKey(child, key), 'data-index': key, className: (0, _classnames2.default)(getSlideClasses((0, _objectAssign2.default)({ index: key }, spec)), slideClass), style: (0, _objectAssign2.default)({}, child.props.style || {}, childStyle), onClick: onClick })); } } }); if (spec.rtl) { return preCloneSlides.concat(slides, postCloneSlides).reverse(); } else { return preCloneSlides.concat(slides, postCloneSlides); } }; var Track = exports.Track = function (_React$Component) { _inherits(Track, _React$Component); function Track() { _classCallCheck(this, Track); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Track.prototype.render = function render() { // var slides = renderSlides.call(this, this.props); var slides = renderSlides(this.props); return _react2.default.createElement( 'div', { className: 'slick-track', style: this.props.trackStyle }, slides ); }; return Track; }(_react2.default.Component); /***/ }), /* 19 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.Dots = undefined; var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(17); var _classnames2 = _interopRequireDefault(_classnames); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var getDotCount = function getDotCount(spec) { var dots; if (spec.infinite) { dots = Math.ceil(spec.slideCount / spec.slidesToScroll); } else { dots = Math.ceil((spec.slideCount - spec.slidesToShow) / spec.slidesToScroll) + 1; } return dots; }; var Dots = exports.Dots = function (_React$Component) { _inherits(Dots, _React$Component); function Dots() { _classCallCheck(this, Dots); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Dots.prototype.clickHandler = function clickHandler(options, e) { // In Autoplay the focus stays on clicked button even after transition // to next slide. That only goes away by click somewhere outside e.preventDefault(); this.props.clickHandler(options); }; Dots.prototype.render = function render() { var _this2 = this; var dotCount = getDotCount({ slideCount: this.props.slideCount, slidesToScroll: this.props.slidesToScroll, slidesToShow: this.props.slidesToShow, infinite: this.props.infinite }); // Apply join & split to Array to pre-fill it for IE8 // // Credit: http://stackoverflow.com/a/13735425/1849458 var dots = Array.apply(null, Array(dotCount + 1).join('0').split('')).map(function (x, i) { var leftBound = i * _this2.props.slidesToScroll; var rightBound = i * _this2.props.slidesToScroll + (_this2.props.slidesToScroll - 1); var className = (0, _classnames2.default)({ 'slick-active': _this2.props.currentSlide >= leftBound && _this2.props.currentSlide <= rightBound }); var dotOptions = { message: 'dots', index: i, slidesToScroll: _this2.props.slidesToScroll, currentSlide: _this2.props.currentSlide }; var onClick = _this2.clickHandler.bind(_this2, dotOptions); return _react2.default.createElement( 'li', { key: i, className: className }, _react2.default.cloneElement(_this2.props.customPaging(i), { onClick: onClick }) ); }); return _react2.default.createElement( 'ul', { className: this.props.dotsClass, style: { display: 'block' } }, dots ); }; return Dots; }(_react2.default.Component); /***/ }), /* 20 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.NextArrow = exports.PrevArrow = undefined; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(17); var _classnames2 = _interopRequireDefault(_classnames); var _helpers = __webpack_require__(8); var _helpers2 = _interopRequireDefault(_helpers); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var PrevArrow = exports.PrevArrow = function (_React$Component) { _inherits(PrevArrow, _React$Component); function PrevArrow() { _classCallCheck(this, PrevArrow); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } PrevArrow.prototype.clickHandler = function clickHandler(options, e) { if (e) { e.preventDefault(); } this.props.clickHandler(options, e); }; PrevArrow.prototype.render = function render() { var prevClasses = { 'slick-arrow': true, 'slick-prev': true }; var prevHandler = this.clickHandler.bind(this, { message: 'previous' }); if (!this.props.infinite && (this.props.currentSlide === 0 || this.props.slideCount <= this.props.slidesToShow)) { prevClasses['slick-disabled'] = true; prevHandler = null; } var prevArrowProps = { key: '0', 'data-role': 'none', className: (0, _classnames2.default)(prevClasses), style: { display: 'block' }, onClick: prevHandler }; var customProps = { currentSlide: this.props.currentSlide, slideCount: this.props.slideCount }; var prevArrow = void 0; if (this.props.prevArrow) { prevArrow = _react2.default.cloneElement(this.props.prevArrow, _extends({}, prevArrowProps, customProps)); } else { prevArrow = _react2.default.createElement( 'button', _extends({ key: '0', type: 'button' }, prevArrowProps), ' Previous' ); } return prevArrow; }; return PrevArrow; }(_react2.default.Component); var NextArrow = exports.NextArrow = function (_React$Component2) { _inherits(NextArrow, _React$Component2); function NextArrow() { _classCallCheck(this, NextArrow); return _possibleConstructorReturn(this, _React$Component2.apply(this, arguments)); } NextArrow.prototype.clickHandler = function clickHandler(options, e) { if (e) { e.preventDefault(); } this.props.clickHandler(options, e); }; NextArrow.prototype.render = function render() { var nextClasses = { 'slick-arrow': true, 'slick-next': true }; var nextHandler = this.clickHandler.bind(this, { message: 'next' }); if (!_helpers2.default.canGoNext(this.props)) { nextClasses['slick-disabled'] = true; nextHandler = null; } var nextArrowProps = { key: '1', 'data-role': 'none', className: (0, _classnames2.default)(nextClasses), style: { display: 'block' }, onClick: nextHandler }; var customProps = { currentSlide: this.props.currentSlide, slideCount: this.props.slideCount }; var nextArrow = void 0; if (this.props.nextArrow) { nextArrow = _react2.default.cloneElement(this.props.nextArrow, _extends({}, nextArrowProps, customProps)); } else { nextArrow = _react2.default.createElement( 'button', _extends({ key: '1', type: 'button' }, nextArrowProps), ' Next' ); } return nextArrow; }; return NextArrow; }(_react2.default.Component); /***/ }), /* 21 */ /***/ (function(module, exports, __webpack_require__) { var camel2hyphen = __webpack_require__(22); var isDimension = function (feature) { var re = /[height|width]$/; return re.test(feature); }; var obj2mq = function (obj) { var mq = ''; var features = Object.keys(obj); features.forEach(function (feature, index) { var value = obj[feature]; feature = camel2hyphen(feature); // Add px to dimension features if (isDimension(feature) && typeof value === 'number') { value = value + 'px'; } if (value === true) { mq += feature; } else if (value === false) { mq += 'not ' + feature; } else { mq += '(' + feature + ': ' + value + ')'; } if (index < features.length-1) { mq += ' and ' } }); return mq; }; var json2mq = function (query) { var mq = ''; if (typeof query === 'string') { return query; } // Handling array of media queries if (query instanceof Array) { query.forEach(function (q, index) { mq += obj2mq(q); if (index < query.length-1) { mq += ', ' } }); return mq; } // Handling single media query return obj2mq(query); }; module.exports = json2mq; /***/ }), /* 22 */ /***/ (function(module, exports) { var camel2hyphen = function (str) { return str .replace(/[A-Z]/g, function (match) { return '-' + match.toLowerCase(); }) .toLowerCase(); }; module.exports = camel2hyphen; /***/ }), /* 23 */ /***/ (function(module, exports) { var canUseDOM = !!( typeof window !== 'undefined' && window.document && window.document.createElement ); module.exports = canUseDOM; /***/ }), /* 24 */ /***/ (function(module, exports, __webpack_require__) { var MediaQueryDispatch = __webpack_require__(25); module.exports = new MediaQueryDispatch(); /***/ }), /* 25 */ /***/ (function(module, exports, __webpack_require__) { var MediaQuery = __webpack_require__(26); var Util = __webpack_require__(28); var each = Util.each; var isFunction = Util.isFunction; var isArray = Util.isArray; /** * Allows for registration of query handlers. * Manages the query handler's state and is responsible for wiring up browser events * * @constructor */ function MediaQueryDispatch () { if(!window.matchMedia) { throw new Error('matchMedia not present, legacy browsers require a polyfill'); } this.queries = {}; this.browserIsIncapable = !window.matchMedia('only all').matches; } MediaQueryDispatch.prototype = { constructor : MediaQueryDispatch, /** * Registers a handler for the given media query * * @param {string} q the media query * @param {object || Array || Function} options either a single query handler object, a function, or an array of query handlers * @param {function} options.match fired when query matched * @param {function} [options.unmatch] fired when a query is no longer matched * @param {function} [options.setup] fired when handler first triggered * @param {boolean} [options.deferSetup=false] whether setup should be run immediately or deferred until query is first matched * @param {boolean} [shouldDegrade=false] whether this particular media query should always run on incapable browsers */ register : function(q, options, shouldDegrade) { var queries = this.queries, isUnconditional = shouldDegrade && this.browserIsIncapable; if(!queries[q]) { queries[q] = new MediaQuery(q, isUnconditional); } //normalise to object in an array if(isFunction(options)) { options = { match : options }; } if(!isArray(options)) { options = [options]; } each(options, function(handler) { if (isFunction(handler)) { handler = { match : handler }; } queries[q].addHandler(handler); }); return this; }, /** * unregisters a query and all it's handlers, or a specific handler for a query * * @param {string} q the media query to target * @param {object || function} [handler] specific handler to unregister */ unregister : function(q, handler) { var query = this.queries[q]; if(query) { if(handler) { query.removeHandler(handler); } else { query.clear(); delete this.queries[q]; } } return this; } }; module.exports = MediaQueryDispatch; /***/ }), /* 26 */ /***/ (function(module, exports, __webpack_require__) { var QueryHandler = __webpack_require__(27); var each = __webpack_require__(28).each; /** * Represents a single media query, manages it's state and registered handlers for this query * * @constructor * @param {string} query the media query string * @param {boolean} [isUnconditional=false] whether the media query should run regardless of whether the conditions are met. Primarily for helping older browsers deal with mobile-first design */ function MediaQuery(query, isUnconditional) { this.query = query; this.isUnconditional = isUnconditional; this.handlers = []; this.mql = window.matchMedia(query); var self = this; this.listener = function(mql) { // Chrome passes an MediaQueryListEvent object, while other browsers pass MediaQueryList directly self.mql = mql.currentTarget || mql; self.assess(); }; this.mql.addListener(this.listener); } MediaQuery.prototype = { constuctor : MediaQuery, /** * add a handler for this query, triggering if already active * * @param {object} handler * @param {function} handler.match callback for when query is activated * @param {function} [handler.unmatch] callback for when query is deactivated * @param {function} [handler.setup] callback for immediate execution when a query handler is registered * @param {boolean} [handler.deferSetup=false] should the setup callback be deferred until the first time the handler is matched? */ addHandler : function(handler) { var qh = new QueryHandler(handler); this.handlers.push(qh); this.matches() && qh.on(); }, /** * removes the given handler from the collection, and calls it's destroy methods * * @param {object || function} handler the handler to remove */ removeHandler : function(handler) { var handlers = this.handlers; each(handlers, function(h, i) { if(h.equals(handler)) { h.destroy(); return !handlers.splice(i,1); //remove from array and exit each early } }); }, /** * Determine whether the media query should be considered a match * * @return {Boolean} true if media query can be considered a match, false otherwise */ matches : function() { return this.mql.matches || this.isUnconditional; }, /** * Clears all handlers and unbinds events */ clear : function() { each(this.handlers, function(handler) { handler.destroy(); }); this.mql.removeListener(this.listener); this.handlers.length = 0; //clear array }, /* * Assesses the query, turning on all handlers if it matches, turning them off if it doesn't match */ assess : function() { var action = this.matches() ? 'on' : 'off'; each(this.handlers, function(handler) { handler[action](); }); } }; module.exports = MediaQuery; /***/ }), /* 27 */ /***/ (function(module, exports) { /** * Delegate to handle a media query being matched and unmatched. * * @param {object} options * @param {function} options.match callback for when the media query is matched * @param {function} [options.unmatch] callback for when the media query is unmatched * @param {function} [options.setup] one-time callback triggered the first time a query is matched * @param {boolean} [options.deferSetup=false] should the setup callback be run immediately, rather than first time query is matched? * @constructor */ function QueryHandler(options) { this.options = options; !options.deferSetup && this.setup(); } QueryHandler.prototype = { constructor : QueryHandler, /** * coordinates setup of the handler * * @function */ setup : function() { if(this.options.setup) { this.options.setup(); } this.initialised = true; }, /** * coordinates setup and triggering of the handler * * @function */ on : function() { !this.initialised && this.setup(); this.options.match && this.options.match(); }, /** * coordinates the unmatch event for the handler * * @function */ off : function() { this.options.unmatch && this.options.unmatch(); }, /** * called when a handler is to be destroyed. * delegates to the destroy or unmatch callbacks, depending on availability. * * @function */ destroy : function() { this.options.destroy ? this.options.destroy() : this.off(); }, /** * determines equality by reference. * if object is supplied compare options, if function, compare match callback * * @function * @param {object || function} [target] the target for comparison */ equals : function(target) { return this.options === target || this.options.match === target; } }; module.exports = QueryHandler; /***/ }), /* 28 */ /***/ (function(module, exports) { /** * Helper function for iterating over a collection * * @param collection * @param fn */ function each(collection, fn) { var i = 0, length = collection.length, cont; for(i; i < length; i++) { cont = fn(collection[i], i); if(cont === false) { break; //allow early exit } } } /** * Helper function for determining whether target object is an array * * @param target the object under test * @return {Boolean} true if array, false otherwise */ function isArray(target) { return Object.prototype.toString.apply(target) === '[object Array]'; } /** * Helper function for determining whether target object is a function * * @param target the object under test * @return {Boolean} true if function, false otherwise */ function isFunction(target) { return typeof target === 'function'; } module.exports = { isFunction : isFunction, isArray : isArray, each : each }; /***/ }) /******/ ]) }); ;
seogi1004/cdnjs
ajax/libs/react-slick/0.18.0/react-slick.js
JavaScript
mit
121,185
/** * @author mrdoob / http://mrdoob.com/ */ THREE.SoftwareRenderer2 = function () { console.log( 'THREE.SoftwareRenderer', THREE.REVISION ); var canvas = document.createElement( 'canvas' ); var context = canvas.getContext( '2d' ); var imagedata = context.getImageData( 0, 0, canvas.width, canvas.height ); var data = imagedata.data; var canvasWidth = canvas.width; var canvasHeight = canvas.height; var canvasWidthHalf = canvasWidth / 2; var canvasHeightHalf = canvasHeight / 2; var rectx1 = Infinity, recty1 = Infinity; var rectx2 = 0, recty2 = 0; var prevrectx1 = Infinity, prevrecty1 = Infinity; var prevrectx2 = 0, prevrecty2 = 0; var projector = new THREE.Projector(); this.domElement = canvas; this.autoClear = true; this.setSize = function ( width, height ) { canvas.width = width; canvas.height = height; canvasWidth = canvas.width; canvasHeight = canvas.height; canvasWidthHalf = width / 2; canvasHeightHalf = height / 2; imagedata = context.getImageData( 0, 0, width, height ); data = imagedata.data; }; this.clear = function () { clearRectangle( prevrectx1, prevrecty1, prevrectx2, prevrecty2 ); }; this.render = function ( scene, camera ) { rectx1 = Infinity; recty1 = Infinity; rectx2 = 0; recty2 = 0; if ( this.autoClear ) this.clear(); var renderData = projector.projectScene( scene, camera ); var elements = renderData.elements; elements.sort( numericalSort ); for ( var e = 0, el = elements.length; e < el; e ++ ) { var element = elements[ e ]; if ( element instanceof THREE.RenderableFace3 ) { var v1 = element.v1.positionScreen; var v2 = element.v2.positionScreen; var v3 = element.v3.positionScreen; drawTriangle( v1.x * canvasWidthHalf + canvasWidthHalf, - v1.y * canvasHeightHalf + canvasHeightHalf, v2.x * canvasWidthHalf + canvasWidthHalf, - v2.y * canvasHeightHalf + canvasHeightHalf, v3.x * canvasWidthHalf + canvasWidthHalf, - v3.y * canvasHeightHalf + canvasHeightHalf, normalToComponent( element.normalWorld.x ), normalToComponent( element.normalWorld.y ), normalToComponent( element.normalWorld.z ) ) } else if ( element instanceof THREE.RenderableFace4 ) { var v1 = element.v1.positionScreen; var v2 = element.v2.positionScreen; var v3 = element.v3.positionScreen; var v4 = element.v4.positionScreen; drawTriangle( v1.x * canvasWidthHalf + canvasWidthHalf, - v1.y * canvasHeightHalf + canvasHeightHalf, v2.x * canvasWidthHalf + canvasWidthHalf, - v2.y * canvasHeightHalf + canvasHeightHalf, v3.x * canvasWidthHalf + canvasWidthHalf, - v3.y * canvasHeightHalf + canvasHeightHalf, normalToComponent( element.normalWorld.x ), normalToComponent( element.normalWorld.y ), normalToComponent( element.normalWorld.z ) ); drawTriangle( v3.x * canvasWidthHalf + canvasWidthHalf, - v3.y * canvasHeightHalf + canvasHeightHalf, v4.x * canvasWidthHalf + canvasWidthHalf, - v4.y * canvasHeightHalf + canvasHeightHalf, v1.x * canvasWidthHalf + canvasWidthHalf, - v1.y * canvasHeightHalf + canvasHeightHalf, normalToComponent( element.normalWorld.x ), normalToComponent( element.normalWorld.y ), normalToComponent( element.normalWorld.z ) ); } } var x = Math.min( rectx1, prevrectx1 ); var y = Math.min( recty1, prevrecty1 ); var width = Math.max( rectx2, prevrectx2 ) - x; var height = Math.max( recty2, prevrecty2 ) - y; /* console.log( rectx1, recty1, rectx2, recty2 ); console.log( prevrectx1, prevrecty1, prevrectx2, prevrecty2 ); console.log( x, y, width, height ); console.log( canvasWidth, canvasHeight ); */ context.putImageData( imagedata, 0, 0, x, y, width, height ); prevrectx1 = rectx1; prevrecty1 = recty1; prevrectx2 = rectx2; prevrecty2 = recty2; }; function numericalSort( a, b ) { return a.z - b.z; } function drawPixel( x, y, r, g, b ) { var offset = ( x + y * canvasWidth ) * 4; if ( data[ offset + 3 ] ) return; data[ offset ] = r; data[ offset + 1 ] = g; data[ offset + 2 ] = b; data[ offset + 3 ] = 255; } function clearRectangle( x1, y1, x2, y2 ) { var xmin = Math.max( Math.min( x1, x2 ), 0 ); var xmax = Math.min( Math.max( x1, x2 ), canvasWidth ); var ymin = Math.max( Math.min( y1, y2 ), 0 ); var ymax = Math.min( Math.max( y1, y2 ), canvasHeight ); var offset = ( xmin + ymin * canvasWidth ) * 4 + 3; var linestep = ( canvasWidth - ( xmax - xmin ) ) * 4; for ( var y = ymin; y < ymax; y ++ ) { for ( var x = xmin; x < xmax; x ++ ) { data[ offset ] = 0; offset += 4; } offset += linestep; } } function drawTriangle( x1, y1, x2, y2, x3, y3, r, g, b ) { // http://devmaster.net/forums/topic/1145-advanced-rasterization/ // 28.4 fixed-point coordinates var x1 = Math.round( 16 * x1 ); var x2 = Math.round( 16 * x2 ); var x3 = Math.round( 16 * x3 ); var y1 = Math.round( 16 * y1 ); var y2 = Math.round( 16 * y2 ); var y3 = Math.round( 16 * y3 ); // Deltas var dx12 = x1 - x2; var dx23 = x2 - x3; var dx31 = x3 - x1; var dy12 = y1 - y2; var dy23 = y2 - y3; var dy31 = y3 - y1; // Fixed-point deltas var fdx12 = dx12 << 4; var fdx23 = dx23 << 4; var fdx31 = dx31 << 4; var fdy12 = dy12 << 4; var fdy23 = dy23 << 4; var fdy31 = dy31 << 4; // Bounding rectangle var xmin = Math.max( ( Math.min( x1, x2, x3 ) + 0xf ) >> 4, 0 ); var xmax = Math.min( ( Math.max( x1, x2, x3 ) + 0xf ) >> 4, canvasWidth ); var ymin = Math.max( ( Math.min( y1, y2, y3 ) + 0xf ) >> 4, 0 ); var ymax = Math.min( ( Math.max( y1, y2, y3 ) + 0xf ) >> 4, canvasHeight ); rectx1 = Math.min( xmin, rectx1 ); rectx2 = Math.max( xmax, rectx2 ); recty1 = Math.min( ymin, recty1 ); recty2 = Math.max( ymax, recty2 ); // Constant part of half-edge functions var c1 = dy12 * x1 - dx12 * y1; var c2 = dy23 * x2 - dx23 * y2; var c3 = dy31 * x3 - dx31 * y3; // Correct for fill convention if ( dy12 < 0 || ( dy12 == 0 && dx12 > 0 ) ) c1 ++; if ( dy23 < 0 || ( dy23 == 0 && dx23 > 0 ) ) c2 ++; if ( dy31 < 0 || ( dy31 == 0 && dx31 > 0 ) ) c3++; var cy1 = c1 + dx12 * ( ymin << 4 ) - dy12 * ( xmin << 4 ); var cy2 = c2 + dx23 * ( ymin << 4 ) - dy23 * ( xmin << 4 ); var cy3 = c3 + dx31 * ( ymin << 4 ) - dy31 * ( xmin << 4 ); // Scan through bounding rectangle for ( var y = ymin; y < ymax; y ++ ) { // Start value for horizontal scan var cx1 = cy1; var cx2 = cy2; var cx3 = cy3; for ( var x = xmin; x < xmax; x ++ ) { if ( cx1 > 0 && cx2 > 0 && cx3 > 0 ) { drawPixel( x, y, r, g, b ); } cx1 -= fdy12; cx2 -= fdy23; cx3 -= fdy31; } cy1 += fdx12; cy2 += fdx23; cy3 += fdx31; } } function drawTriangleColor3( x1, y1, x2, y2, x3, y3, color1, color2, color3 ) { // http://devmaster.net/forums/topic/1145-advanced-rasterization/ var r1 = color1 >> 16 & 255; var r2 = color2 >> 16 & 255; var r3 = color3 >> 16 & 255; var g1 = color1 >> 8 & 255; var g2 = color2 >> 8 & 255; var g3 = color3 >> 8 & 255; var b1 = color1 & 255; var b2 = color2 & 255; var b3 = color3 & 255; var deltasr = computeDelta( x1, y1, r1, x2, y2, r2, x3, y3, r3 ); var deltasg = computeDelta( x1, y1, g1, x2, y2, g2, x3, y3, g3 ); var deltasb = computeDelta( x1, y1, b1, x2, y2, b2, x3, y3, b3 ); // 28.4 fixed-point coordinates var X1 = Math.round( 16 * x1 ); var X2 = Math.round( 16 * x2 ); var X3 = Math.round( 16 * x3 ); var Y1 = Math.round( 16 * y1 ); var Y2 = Math.round( 16 * y2 ); var Y3 = Math.round( 16 * y3 ); // Deltas var dx12 = X1 - X2; var dx23 = X2 - X3; var dx31 = X3 - X1; var dy12 = Y1 - Y2; var dy23 = Y2 - Y3; var dy31 = Y3 - Y1; // Fixed-point deltas var fdx = [ dx12 << 4, dx23 << 4, dx31 << 4 ]; var fdy = [ dy12 << 4, dy23 << 4, dy31 << 4 ]; // Bounding rectangle var minx = Math.max( ( Math.min( X1, X2, X3 ) + 0xf ) >> 4, 0 ); var maxx = Math.min( ( Math.max( X1, X2, X3 ) + 0xf ) >> 4, canvasWidth ); var miny = Math.max( ( Math.min( Y1, Y2, Y3 ) + 0xf ) >> 4, 0 ); var maxy = Math.min( ( Math.max( Y1, Y2, Y3 ) + 0xf ) >> 4, canvasHeight ); // Constant part of half-edge functions var c1 = dy12 * X1 - dx12 * Y1; var c2 = dy23 * X2 - dx23 * Y2; var c3 = dy31 * X3 - dx31 * Y3; // Correct for fill convention if ( dy12 < 0 || ( dy12 == 0 && dx12 > 0 ) ) c1 ++; if ( dy23 < 0 || ( dy23 == 0 && dx23 > 0 ) ) c2 ++; if ( dy31 < 0 || ( dy31 == 0 && dx31 > 0 ) ) c3 ++; var cy1 = c1 + dx12 * ( miny << 4 ) - dy12 * ( minx << 4 ); var cy2 = c2 + dx23 * ( miny << 4 ) - dy23 * ( minx << 4 ); var cy3 = c3 + dx31 * ( miny << 4 ) - dy31 * ( minx << 4 ); // Scan through bounding rectangle var minyx1 = ( minx - x1 ); var minyy1 = ( miny - y1 ); var ry = deltasr[ 1 ] * minyy1; var gy = deltasg[ 1 ] * minyy1; var by = deltasb[ 1 ] * minyy1; for ( var y = miny; y < maxy; y ++ ) { // Start value for horizontal scan var cx1 = cy1; var cx2 = cy2; var cx3 = cy3; var rx = deltasr[ 0 ] * minyx1 + ry; var gx = deltasg[ 0 ] * minyx1 + gy; var bx = deltasb[ 0 ] * minyx1 + by; for ( var x = minx; x < maxx; x ++ ) { if ( cx1 > 0 && cx2 > 0 && cx3 > 0 ) { drawPixel( x, y, r1 + rx, g1 + gx, b1 + bx ); } cx1 -= fdy[ 0 ]; cx2 -= fdy[ 1 ]; cx3 -= fdy[ 2 ]; rx += deltasr[ 0 ]; gx += deltasg[ 0 ]; bx += deltasb[ 0 ]; } cy1 += fdx[ 0 ]; cy2 += fdx[ 1 ]; cy3 += fdx[ 2 ]; ry += deltasr[ 1 ]; gy += deltasg[ 1 ]; by += deltasb[ 1 ]; } } function normalToComponent( normal ) { var component = ( normal + 1 ) * 127; return component < 0 ? 0 : ( component > 255 ? 255 : component ); } };
christopheschwyzer/StopheWebLab
three/source/three/examples/js/renderers/SoftwareRenderer2.js
JavaScript
mit
9,867
define([], function() { /** Used to match template delimiters. */ var reInterpolate = /<%=([\s\S]+?)%>/g; return reInterpolate; });
tomek-f/shittets
require-js-amd/require-zepto-lodash/static/js/lib/lodash-amd/internal/reInterpolate.js
JavaScript
mit
140
// Copyright 2012 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 Ordinal rules. * * This file is autogenerated by script: * http://go/generate_pluralrules.py * File generated from CLDR ver. 30.0.2 * * Before check in, this file could have been manually edited. This is to * incorporate changes before we could fix CLDR. All manual modification must be * documented in this section, and should be removed after those changes land to * CLDR. */ // clang-format off goog.provide('goog.i18n.ordinalRules'); /** * Ordinal pattern keyword * @enum {string} */ goog.i18n.ordinalRules.Keyword = { ZERO: 'zero', ONE: 'one', TWO: 'two', FEW: 'few', MANY: 'many', OTHER: 'other' }; /** * Default Ordinal select rule. * @param {number} n The count of items. * @param {number=} opt_precision optional, precision. * @return {goog.i18n.ordinalRules.Keyword} Default value. * @private */ goog.i18n.ordinalRules.defaultSelect_ = function(n, opt_precision) { return goog.i18n.ordinalRules.Keyword.OTHER; }; /** * Returns the fractional part of a number (3.1416 => 1416) * @param {number} n The count of items. * @return {number} The fractional part. * @private */ goog.i18n.ordinalRules.decimals_ = function(n) { var str = n + ''; var result = str.indexOf('.'); return (result == -1) ? 0 : str.length - result - 1; }; /** * Calculates v and f as per CLDR plural rules. * The short names for parameters / return match the CLDR syntax and UTS #35 * (http://unicode.org/reports/tr35/tr35-numbers.html#Plural_rules_syntax) * @param {number} n The count of items. * @param {number=} opt_precision optional, precision. * @return {!{v:number, f:number}} The v and f. * @private */ goog.i18n.ordinalRules.get_vf_ = function(n, opt_precision) { var DEFAULT_DIGITS = 3; if (undefined === opt_precision) { var v = Math.min(goog.i18n.ordinalRules.decimals_(n), DEFAULT_DIGITS); } else { var v = opt_precision; } var base = Math.pow(10, v); var f = ((n * base) | 0) % base; return {v: v, f: f}; }; /** * Calculates w and t as per CLDR plural rules. * The short names for parameters / return match the CLDR syntax and UTS #35 * (http://unicode.org/reports/tr35/tr35-numbers.html#Plural_rules_syntax) * @param {number} v Calculated previously. * @param {number} f Calculated previously. * @return {!{w:number, t:number}} The w and t. * @private */ goog.i18n.ordinalRules.get_wt_ = function(v, f) { if (f === 0) { return {w: 0, t: 0}; } while ((f % 10) === 0) { f /= 10; v--; } return {w: v, t: f}; }; /** * Ordinal select rules for cy locale * * @param {number} n The count of items. * @param {number=} opt_precision Precision for number formatting, if not default. * @return {goog.i18n.ordinalRules.Keyword} Locale-specific ordinal value. * @private */ goog.i18n.ordinalRules.cySelect_ = function(n, opt_precision) { if (n == 0 || n == 7 || n == 8 || n == 9) { return goog.i18n.ordinalRules.Keyword.ZERO; } if (n == 1) { return goog.i18n.ordinalRules.Keyword.ONE; } if (n == 2) { return goog.i18n.ordinalRules.Keyword.TWO; } if (n == 3 || n == 4) { return goog.i18n.ordinalRules.Keyword.FEW; } if (n == 5 || n == 6) { return goog.i18n.ordinalRules.Keyword.MANY; } return goog.i18n.ordinalRules.Keyword.OTHER; }; /** * Ordinal select rules for en locale * * @param {number} n The count of items. * @param {number=} opt_precision Precision for number formatting, if not default. * @return {goog.i18n.ordinalRules.Keyword} Locale-specific ordinal value. * @private */ goog.i18n.ordinalRules.enSelect_ = function(n, opt_precision) { if (n % 10 == 1 && n % 100 != 11) { return goog.i18n.ordinalRules.Keyword.ONE; } if (n % 10 == 2 && n % 100 != 12) { return goog.i18n.ordinalRules.Keyword.TWO; } if (n % 10 == 3 && n % 100 != 13) { return goog.i18n.ordinalRules.Keyword.FEW; } return goog.i18n.ordinalRules.Keyword.OTHER; }; /** * Ordinal select rules for uk locale * * @param {number} n The count of items. * @param {number=} opt_precision Precision for number formatting, if not default. * @return {goog.i18n.ordinalRules.Keyword} Locale-specific ordinal value. * @private */ goog.i18n.ordinalRules.ukSelect_ = function(n, opt_precision) { if (n % 10 == 3 && n % 100 != 13) { return goog.i18n.ordinalRules.Keyword.FEW; } return goog.i18n.ordinalRules.Keyword.OTHER; }; /** * Ordinal select rules for it locale * * @param {number} n The count of items. * @param {number=} opt_precision Precision for number formatting, if not default. * @return {goog.i18n.ordinalRules.Keyword} Locale-specific ordinal value. * @private */ goog.i18n.ordinalRules.itSelect_ = function(n, opt_precision) { if (n == 11 || n == 8 || n == 80 || n == 800) { return goog.i18n.ordinalRules.Keyword.MANY; } return goog.i18n.ordinalRules.Keyword.OTHER; }; /** * Ordinal select rules for ne locale * * @param {number} n The count of items. * @param {number=} opt_precision Precision for number formatting, if not default. * @return {goog.i18n.ordinalRules.Keyword} Locale-specific ordinal value. * @private */ goog.i18n.ordinalRules.neSelect_ = function(n, opt_precision) { if (n >= 1 && n <= 4) { return goog.i18n.ordinalRules.Keyword.ONE; } return goog.i18n.ordinalRules.Keyword.OTHER; }; /** * Ordinal select rules for be locale * * @param {number} n The count of items. * @param {number=} opt_precision Precision for number formatting, if not default. * @return {goog.i18n.ordinalRules.Keyword} Locale-specific ordinal value. * @private */ goog.i18n.ordinalRules.beSelect_ = function(n, opt_precision) { if ((n % 10 == 2 || n % 10 == 3) && n % 100 != 12 && n % 100 != 13) { return goog.i18n.ordinalRules.Keyword.FEW; } return goog.i18n.ordinalRules.Keyword.OTHER; }; /** * Ordinal select rules for az locale * * @param {number} n The count of items. * @param {number=} opt_precision Precision for number formatting, if not default. * @return {goog.i18n.ordinalRules.Keyword} Locale-specific ordinal value. * @private */ goog.i18n.ordinalRules.azSelect_ = function(n, opt_precision) { var i = n | 0; if ((i % 10 == 1 || i % 10 == 2 || i % 10 == 5 || i % 10 == 7 || i % 10 == 8) || (i % 100 == 20 || i % 100 == 50 || i % 100 == 70 || i % 100 == 80)) { return goog.i18n.ordinalRules.Keyword.ONE; } if ((i % 10 == 3 || i % 10 == 4) || (i % 1000 == 100 || i % 1000 == 200 || i % 1000 == 300 || i % 1000 == 400 || i % 1000 == 500 || i % 1000 == 600 || i % 1000 == 700 || i % 1000 == 800 || i % 1000 == 900)) { return goog.i18n.ordinalRules.Keyword.FEW; } if (i == 0 || i % 10 == 6 || (i % 100 == 40 || i % 100 == 60 || i % 100 == 90)) { return goog.i18n.ordinalRules.Keyword.MANY; } return goog.i18n.ordinalRules.Keyword.OTHER; }; /** * Ordinal select rules for ka locale * * @param {number} n The count of items. * @param {number=} opt_precision Precision for number formatting, if not default. * @return {goog.i18n.ordinalRules.Keyword} Locale-specific ordinal value. * @private */ goog.i18n.ordinalRules.kaSelect_ = function(n, opt_precision) { var i = n | 0; if (i == 1) { return goog.i18n.ordinalRules.Keyword.ONE; } if (i == 0 || (i % 100 >= 2 && i % 100 <= 20 || i % 100 == 40 || i % 100 == 60 || i % 100 == 80)) { return goog.i18n.ordinalRules.Keyword.MANY; } return goog.i18n.ordinalRules.Keyword.OTHER; }; /** * Ordinal select rules for mr locale * * @param {number} n The count of items. * @param {number=} opt_precision Precision for number formatting, if not default. * @return {goog.i18n.ordinalRules.Keyword} Locale-specific ordinal value. * @private */ goog.i18n.ordinalRules.mrSelect_ = function(n, opt_precision) { if (n == 1) { return goog.i18n.ordinalRules.Keyword.ONE; } if (n == 2 || n == 3) { return goog.i18n.ordinalRules.Keyword.TWO; } if (n == 4) { return goog.i18n.ordinalRules.Keyword.FEW; } return goog.i18n.ordinalRules.Keyword.OTHER; }; /** * Ordinal select rules for sv locale * * @param {number} n The count of items. * @param {number=} opt_precision Precision for number formatting, if not default. * @return {goog.i18n.ordinalRules.Keyword} Locale-specific ordinal value. * @private */ goog.i18n.ordinalRules.svSelect_ = function(n, opt_precision) { if ((n % 10 == 1 || n % 10 == 2) && n % 100 != 11 && n % 100 != 12) { return goog.i18n.ordinalRules.Keyword.ONE; } return goog.i18n.ordinalRules.Keyword.OTHER; }; /** * Ordinal select rules for kk locale * * @param {number} n The count of items. * @param {number=} opt_precision Precision for number formatting, if not default. * @return {goog.i18n.ordinalRules.Keyword} Locale-specific ordinal value. * @private */ goog.i18n.ordinalRules.kkSelect_ = function(n, opt_precision) { if (n % 10 == 6 || n % 10 == 9 || n % 10 == 0 && n != 0) { return goog.i18n.ordinalRules.Keyword.MANY; } return goog.i18n.ordinalRules.Keyword.OTHER; }; /** * Ordinal select rules for mk locale * * @param {number} n The count of items. * @param {number=} opt_precision Precision for number formatting, if not default. * @return {goog.i18n.ordinalRules.Keyword} Locale-specific ordinal value. * @private */ goog.i18n.ordinalRules.mkSelect_ = function(n, opt_precision) { var i = n | 0; if (i % 10 == 1 && i % 100 != 11) { return goog.i18n.ordinalRules.Keyword.ONE; } if (i % 10 == 2 && i % 100 != 12) { return goog.i18n.ordinalRules.Keyword.TWO; } if ((i % 10 == 7 || i % 10 == 8) && i % 100 != 17 && i % 100 != 18) { return goog.i18n.ordinalRules.Keyword.MANY; } return goog.i18n.ordinalRules.Keyword.OTHER; }; /** * Ordinal select rules for hu locale * * @param {number} n The count of items. * @param {number=} opt_precision Precision for number formatting, if not default. * @return {goog.i18n.ordinalRules.Keyword} Locale-specific ordinal value. * @private */ goog.i18n.ordinalRules.huSelect_ = function(n, opt_precision) { if (n == 1 || n == 5) { return goog.i18n.ordinalRules.Keyword.ONE; } return goog.i18n.ordinalRules.Keyword.OTHER; }; /** * Ordinal select rules for fr locale * * @param {number} n The count of items. * @param {number=} opt_precision Precision for number formatting, if not default. * @return {goog.i18n.ordinalRules.Keyword} Locale-specific ordinal value. * @private */ goog.i18n.ordinalRules.frSelect_ = function(n, opt_precision) { if (n == 1) { return goog.i18n.ordinalRules.Keyword.ONE; } return goog.i18n.ordinalRules.Keyword.OTHER; }; /** * Ordinal select rules for sq locale * * @param {number} n The count of items. * @param {number=} opt_precision Precision for number formatting, if not default. * @return {goog.i18n.ordinalRules.Keyword} Locale-specific ordinal value. * @private */ goog.i18n.ordinalRules.sqSelect_ = function(n, opt_precision) { if (n == 1) { return goog.i18n.ordinalRules.Keyword.ONE; } if (n % 10 == 4 && n % 100 != 14) { return goog.i18n.ordinalRules.Keyword.MANY; } return goog.i18n.ordinalRules.Keyword.OTHER; }; /** * Ordinal select rules for ca locale * * @param {number} n The count of items. * @param {number=} opt_precision Precision for number formatting, if not default. * @return {goog.i18n.ordinalRules.Keyword} Locale-specific ordinal value. * @private */ goog.i18n.ordinalRules.caSelect_ = function(n, opt_precision) { if (n == 1 || n == 3) { return goog.i18n.ordinalRules.Keyword.ONE; } if (n == 2) { return goog.i18n.ordinalRules.Keyword.TWO; } if (n == 4) { return goog.i18n.ordinalRules.Keyword.FEW; } return goog.i18n.ordinalRules.Keyword.OTHER; }; /** * Ordinal select rules for gu locale * * @param {number} n The count of items. * @param {number=} opt_precision Precision for number formatting, if not default. * @return {goog.i18n.ordinalRules.Keyword} Locale-specific ordinal value. * @private */ goog.i18n.ordinalRules.guSelect_ = function(n, opt_precision) { if (n == 1) { return goog.i18n.ordinalRules.Keyword.ONE; } if (n == 2 || n == 3) { return goog.i18n.ordinalRules.Keyword.TWO; } if (n == 4) { return goog.i18n.ordinalRules.Keyword.FEW; } if (n == 6) { return goog.i18n.ordinalRules.Keyword.MANY; } return goog.i18n.ordinalRules.Keyword.OTHER; }; /** * Ordinal select rules for as locale * * @param {number} n The count of items. * @param {number=} opt_precision Precision for number formatting, if not default. * @return {goog.i18n.ordinalRules.Keyword} Locale-specific ordinal value. * @private */ goog.i18n.ordinalRules.asSelect_ = function(n, opt_precision) { if (n == 1 || n == 5 || n == 7 || n == 8 || n == 9 || n == 10) { return goog.i18n.ordinalRules.Keyword.ONE; } if (n == 2 || n == 3) { return goog.i18n.ordinalRules.Keyword.TWO; } if (n == 4) { return goog.i18n.ordinalRules.Keyword.FEW; } if (n == 6) { return goog.i18n.ordinalRules.Keyword.MANY; } return goog.i18n.ordinalRules.Keyword.OTHER; }; /** * Selected Ordinal rules by locale. */ goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.enSelect_; if (goog.LOCALE == 'af') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'am') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'ar') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'az') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.azSelect_; } if (goog.LOCALE == 'be') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.beSelect_; } if (goog.LOCALE == 'bg') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'bn') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.asSelect_; } if (goog.LOCALE == 'br') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'bs') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'ca') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.caSelect_; } if (goog.LOCALE == 'chr') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'cs') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'cy') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.cySelect_; } if (goog.LOCALE == 'da') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'de') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'de_AT' || goog.LOCALE == 'de-AT') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'de_CH' || goog.LOCALE == 'de-CH') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'el') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'en') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.enSelect_; } if (goog.LOCALE == 'en_AU' || goog.LOCALE == 'en-AU') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.enSelect_; } if (goog.LOCALE == 'en_CA' || goog.LOCALE == 'en-CA') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.enSelect_; } if (goog.LOCALE == 'en_GB' || goog.LOCALE == 'en-GB') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.enSelect_; } if (goog.LOCALE == 'en_IE' || goog.LOCALE == 'en-IE') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.enSelect_; } if (goog.LOCALE == 'en_IN' || goog.LOCALE == 'en-IN') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.enSelect_; } if (goog.LOCALE == 'en_SG' || goog.LOCALE == 'en-SG') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.enSelect_; } if (goog.LOCALE == 'en_US' || goog.LOCALE == 'en-US') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.enSelect_; } if (goog.LOCALE == 'en_ZA' || goog.LOCALE == 'en-ZA') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.enSelect_; } if (goog.LOCALE == 'es') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'es_419' || goog.LOCALE == 'es-419') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'es_ES' || goog.LOCALE == 'es-ES') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'es_MX' || goog.LOCALE == 'es-MX') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'es_US' || goog.LOCALE == 'es-US') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'et') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'eu') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'fa') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'fi') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'fil') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.frSelect_; } if (goog.LOCALE == 'fr') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.frSelect_; } if (goog.LOCALE == 'fr_CA' || goog.LOCALE == 'fr-CA') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.frSelect_; } if (goog.LOCALE == 'ga') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.frSelect_; } if (goog.LOCALE == 'gl') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'gsw') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'gu') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.guSelect_; } if (goog.LOCALE == 'haw') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'he') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'hi') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.guSelect_; } if (goog.LOCALE == 'hr') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'hu') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.huSelect_; } if (goog.LOCALE == 'hy') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.frSelect_; } if (goog.LOCALE == 'id') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'in') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'is') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'it') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.itSelect_; } if (goog.LOCALE == 'iw') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'ja') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'ka') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.kaSelect_; } if (goog.LOCALE == 'kk') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.kkSelect_; } if (goog.LOCALE == 'km') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'kn') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'ko') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'ky') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'ln') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'lo') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.frSelect_; } if (goog.LOCALE == 'lt') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'lv') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'mk') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.mkSelect_; } if (goog.LOCALE == 'ml') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'mn') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'mo') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.frSelect_; } if (goog.LOCALE == 'mr') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.mrSelect_; } if (goog.LOCALE == 'ms') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.frSelect_; } if (goog.LOCALE == 'mt') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'my') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'nb') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'ne') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.neSelect_; } if (goog.LOCALE == 'nl') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'no') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'no_NO' || goog.LOCALE == 'no-NO') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'or') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'pa') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'pl') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'pt') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'pt_BR' || goog.LOCALE == 'pt-BR') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'pt_PT' || goog.LOCALE == 'pt-PT') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'ro') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.frSelect_; } if (goog.LOCALE == 'ru') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'sh') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'si') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'sk') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'sl') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'sq') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.sqSelect_; } if (goog.LOCALE == 'sr') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'sr_Latn' || goog.LOCALE == 'sr-Latn') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'sv') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.svSelect_; } if (goog.LOCALE == 'sw') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'ta') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'te') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'th') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'tl') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.frSelect_; } if (goog.LOCALE == 'tr') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'uk') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.ukSelect_; } if (goog.LOCALE == 'ur') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'uz') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'vi') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.frSelect_; } if (goog.LOCALE == 'zh') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'zh_CN' || goog.LOCALE == 'zh-CN') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'zh_HK' || goog.LOCALE == 'zh-HK') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'zh_TW' || goog.LOCALE == 'zh-TW') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; } if (goog.LOCALE == 'zu') { goog.i18n.ordinalRules.select = goog.i18n.ordinalRules.defaultSelect_; }
fieldenms/tg
platform-web-ui/src/main/resources/polymer/accessibility-developer-tools/lib/closure-library/closure/goog/i18n/ordinalrules.js
JavaScript
mit
25,427
var assert = require("assert"); var FirebaseTokenGenerator = require("../../../dist/firebase-token-generator-node.js"); function _decodeJWTPart(part) { return JSON.parse(new Buffer(part.replace("-", "+").replace("_", "/"), "base64").toString()); } describe("FirebaseTokenGenerator", function() { var obj = new FirebaseTokenGenerator("omgsekrit"); it("should construct a valid FirebaseTokenGenerator object", function() { assert.equal(typeof obj, typeof {}); assert.equal(obj.mSecret, "omgsekrit"); }); it("should return something that looks like a JWT with no arguments", function() { var token = obj.createToken({ 'blah': 5, 'uid': 'blah' }); var parts = token.split("."); var header = _decodeJWTPart(parts[0]); assert.equal(typeof token, typeof ""); assert.equal(parts.length, 3); assert.equal(header.typ, "JWT"); assert.equal(header.alg, "HS256"); }); it("should accept iat in options", function() { var iat = 1365028233; var token = obj.createToken({uid: 'bar'}, {iat: iat}); assert.equal(token, "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjEzNjUwMjgyMzMsInYiOjAsImQiOnsidWlkIjoiYmFyIn19.6CsfeobxRCRd65pYddGjyeN2fh6sWvIRob1866VqDNI"); }); it("should preserve all provided options", function() { var iat = Math.round(new Date().getTime()); var expires = iat + 1000; var notBefore = iat + 10; var token = obj.createToken({foo: "bar", uid: 'blah'}, { iat: iat, expires: expires, notBefore: notBefore, admin: false, debug: true }); var body = _decodeJWTPart(token.split(".")[1]); assert.equal(body.iat, iat); assert.equal(body.exp, expires); assert.equal(body.nbf, notBefore); assert.equal(body.admin, false); assert.equal(body.debug, true); assert.equal(body.d.foo, "bar"); }); it("should support native Date objects", function() { var expires = new Date(); var notBefore = new Date(); var token = obj.createToken({ "uid": "1" }, {expires: expires, notBefore: notBefore}); var body = _decodeJWTPart(token.split(".")[1]); assert.equal(body.exp, Math.round(expires.getTime() / 1000)); assert.equal(body.nbf, Math.round(notBefore.getTime() / 1000)); }); });
prasad47/firebase-set-data
node_modules/firebase-token-generator/js/test/mocha/nodetests.spec.js
JavaScript
mit
2,238
/* flatpickr v4.2.2, @license MIT */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (factory((global.ar = {}))); }(this, (function (exports) { 'use strict'; var fp = typeof window !== "undefined" && window.flatpickr !== undefined ? window.flatpickr : { l10ns: {}, }; var Arabic = { weekdays: { shorthand: ["أحد", "اثنين", "ثلاثاء", "أربعاء", "خميس", "جمعة", "سبت"], longhand: [ "الأحد", "الاثنين", "الثلاثاء", "الأربعاء", "الخميس", "الجمعة", "السبت", ], }, months: { shorthand: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"], longhand: [ "يناير", "فبراير", "مارس", "أبريل", "مايو", "يونيو", "يوليو", "أغسطس", "سبتمبر", "أكتوبر", "نوفمبر", "ديسمبر", ], }, }; fp.l10ns.ar = Arabic; var ar = fp.l10ns; exports.Arabic = Arabic; exports['default'] = ar; Object.defineProperty(exports, '__esModule', { value: true }); })));
wout/cdnjs
ajax/libs/flatpickr/4.2.2/l10n/ar.js
JavaScript
mit
1,471
/* ======================================================================== * Bootstrap: modal.js v3.0.0 * http://twbs.github.com/bootstrap/javascript.html#modals * ======================================================================== * Copyright 2012 Twitter, 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. * ======================================================================== */ +function ($) { "use strict"; // MODAL CLASS DEFINITION // ====================== var Modal = function (element, options) { this.options = options this.$element = $(element).on('click.dismiss.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this)) this.$backdrop = this.isShown = null if (this.options.remote) this.$element.find('.modal-body').load(this.options.remote) } Modal.DEFAULTS = { backdrop: true , keyboard: true , show: true } Modal.prototype.toggle = function () { return this[!this.isShown ? 'show' : 'hide']() } Modal.prototype.show = function () { var that = this var e = $.Event('show.bs.modal') this.$element.trigger(e) if (this.isShown || e.isDefaultPrevented()) return this.isShown = true this.escape() this.backdrop(function () { var transition = $.support.transition && that.$element.hasClass('fade') if (!that.$element.parent().length) { that.$element.appendTo(document.body) // don't move modals dom position } that.$element.show() if (transition) { that.$element[0].offsetWidth // force reflow } that.$element .addClass('in') .attr('aria-hidden', false) that.enforceFocus() transition ? that.$element .one($.support.transition.end, function () { that.$element.focus().trigger('shown.bs.modal') }) .emulateTransitionEnd(300) : that.$element.focus().trigger('shown.bs.modal') }) } Modal.prototype.hide = function (e) { if (e) e.preventDefault() e = $.Event('hide.bs.modal') this.$element.trigger(e) if (!this.isShown || e.isDefaultPrevented()) return this.isShown = false this.escape() $(document).off('focusin.bs.modal') this.$element .removeClass('in') .attr('aria-hidden', true) $.support.transition && this.$element.hasClass('fade') ? this.$element .one($.support.transition.end, $.proxy(this.hideModal, this)) .emulateTransitionEnd(300) : this.hideModal() } Modal.prototype.enforceFocus = function () { $(document) .off('focusin.bs.modal') // guard against infinite focus loop .on('focusin.bs.modal', $.proxy(function (e) { if (this.$element[0] !== e.target && !this.$element.has(e.target).length) { this.$element.focus() } }, this)) } Modal.prototype.escape = function () { if (this.isShown && this.options.keyboard) { this.$element.on('keyup.dismiss.bs.modal', $.proxy(function (e) { e.which == 27 && this.hide() }, this)) } else if (!this.isShown) { this.$element.off('keyup.dismiss.bs.modal') } } Modal.prototype.hideModal = function () { var that = this this.$element.hide() this.backdrop(function () { that.removeBackdrop() that.$element.trigger('hidden.bs.modal') }) } Modal.prototype.removeBackdrop = function () { this.$backdrop && this.$backdrop.remove() this.$backdrop = null } Modal.prototype.backdrop = function (callback) { var that = this var animate = this.$element.hasClass('fade') ? 'fade' : '' if (this.isShown && this.options.backdrop) { var doAnimate = $.support.transition && animate this.$backdrop = $('<div class="modal-backdrop ' + animate + '" />') .appendTo(document.body) this.$element.on('click', $.proxy(function (e) { if (e.target !== e.currentTarget) return this.options.backdrop == 'static' ? this.$element[0].focus.call(this.$element[0]) : this.hide.call(this) }, this)) if (doAnimate) this.$backdrop[0].offsetWidth // force reflow this.$backdrop.addClass('in') if (!callback) return doAnimate ? this.$backdrop .one($.support.transition.end, callback) .emulateTransitionEnd(150) : callback() } else if (!this.isShown && this.$backdrop) { this.$backdrop.removeClass('in') $.support.transition && this.$element.hasClass('fade')? this.$backdrop .one($.support.transition.end, callback) .emulateTransitionEnd(150) : callback() } else if (callback) { callback() } } // MODAL PLUGIN DEFINITION // ======================= var old = $.fn.modal $.fn.modal = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.modal') var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option) if (!data) $this.data('bs.modal', (data = new Modal(this, options))) if (typeof option == 'string') data[option]() else if (options.show) data.show() }) } $.fn.modal.Constructor = Modal // MODAL NO CONFLICT // ================= $.fn.modal.noConflict = function () { $.fn.modal = old return this } // MODAL DATA-API // ============== $(document).on('click.bs.modal.data-api', '[data-toggle="modal"]', function (e) { var $this = $(this) var href = $this.attr('href') var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) //strip for ie7 var option = $target.data('modal') ? 'toggle' : $.extend({ remote:!/#/.test(href) && href }, $target.data(), $this.data()) e.preventDefault() $target .modal(option) .one('hide', function () { $this.is(':visible') && $this.focus() }) }) $(function () { var $body = $(document.body) .on('shown.bs.modal', '.modal', function () { $body.addClass('modal-open') }) .on('hidden.bs.modal', '.modal', function () { $body.removeClass('modal-open') }) }) }(window.jQuery);
ajalovec/aj-cms-sandbox
web/js/bootstrap_modal_9.js
JavaScript
mit
6,747
/*! * twitter-text-js 1.8.0 * * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this work except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 */ (function() { if (typeof twttr === "undefined" || twttr === null) { var twttr = {}; } twttr.txt = {}; twttr.txt.regexen = {}; var HTML_ENTITIES = { '&': '&amp;', '>': '&gt;', '<': '&lt;', '"': '&quot;', "'": '&#39;' }; // HTML escaping twttr.txt.htmlEscape = function(text) { return text && text.replace(/[&"'><]/g, function(character) { return HTML_ENTITIES[character]; }); }; // Builds a RegExp function regexSupplant(regex, flags) { flags = flags || ""; if (typeof regex !== "string") { if (regex.global && flags.indexOf("g") < 0) { flags += "g"; } if (regex.ignoreCase && flags.indexOf("i") < 0) { flags += "i"; } if (regex.multiline && flags.indexOf("m") < 0) { flags += "m"; } regex = regex.source; } return new RegExp(regex.replace(/#\{(\w+)\}/g, function(match, name) { var newRegex = twttr.txt.regexen[name] || ""; if (typeof newRegex !== "string") { newRegex = newRegex.source; } return newRegex; }), flags); } twttr.txt.regexSupplant = regexSupplant; // simple string interpolation function stringSupplant(str, values) { return str.replace(/#\{(\w+)\}/g, function(match, name) { return values[name] || ""; }); } twttr.txt.stringSupplant = stringSupplant; function addCharsToCharClass(charClass, start, end) { var s = String.fromCharCode(start); if (end !== start) { s += "-" + String.fromCharCode(end); } charClass.push(s); return charClass; } twttr.txt.addCharsToCharClass = addCharsToCharClass; // Space is more than %20, U+3000 for example is the full-width space used with Kanji. Provide a short-hand // to access both the list of characters and a pattern suitible for use with String#split // Taken from: ActiveSupport::Multibyte::Handlers::UTF8Handler::UNICODE_WHITESPACE var fromCode = String.fromCharCode; var UNICODE_SPACES = [ fromCode(0x0020), // White_Space # Zs SPACE fromCode(0x0085), // White_Space # Cc <control-0085> fromCode(0x00A0), // White_Space # Zs NO-BREAK SPACE fromCode(0x1680), // White_Space # Zs OGHAM SPACE MARK fromCode(0x180E), // White_Space # Zs MONGOLIAN VOWEL SEPARATOR fromCode(0x2028), // White_Space # Zl LINE SEPARATOR fromCode(0x2029), // White_Space # Zp PARAGRAPH SEPARATOR fromCode(0x202F), // White_Space # Zs NARROW NO-BREAK SPACE fromCode(0x205F), // White_Space # Zs MEDIUM MATHEMATICAL SPACE fromCode(0x3000) // White_Space # Zs IDEOGRAPHIC SPACE ]; addCharsToCharClass(UNICODE_SPACES, 0x009, 0x00D); // White_Space # Cc [5] <control-0009>..<control-000D> addCharsToCharClass(UNICODE_SPACES, 0x2000, 0x200A); // White_Space # Zs [11] EN QUAD..HAIR SPACE var INVALID_CHARS = [ fromCode(0xFFFE), fromCode(0xFEFF), // BOM fromCode(0xFFFF) // Special ]; addCharsToCharClass(INVALID_CHARS, 0x202A, 0x202E); // Directional change twttr.txt.regexen.spaces_group = regexSupplant(UNICODE_SPACES.join("")); twttr.txt.regexen.spaces = regexSupplant("[" + UNICODE_SPACES.join("") + "]"); twttr.txt.regexen.invalid_chars_group = regexSupplant(INVALID_CHARS.join("")); twttr.txt.regexen.punct = /\!'#%&'\(\)*\+,\\\-\.\/:;<=>\?@\[\]\^_{|}~\$/; twttr.txt.regexen.rtl_chars = /[\u0600-\u06FF]|[\u0750-\u077F]|[\u0590-\u05FF]|[\uFE70-\uFEFF]/mg; twttr.txt.regexen.non_bmp_code_pairs = /[\uD800-\uDBFF][\uDC00-\uDFFF]/mg; var nonLatinHashtagChars = []; // Cyrillic addCharsToCharClass(nonLatinHashtagChars, 0x0400, 0x04ff); // Cyrillic addCharsToCharClass(nonLatinHashtagChars, 0x0500, 0x0527); // Cyrillic Supplement addCharsToCharClass(nonLatinHashtagChars, 0x2de0, 0x2dff); // Cyrillic Extended A addCharsToCharClass(nonLatinHashtagChars, 0xa640, 0xa69f); // Cyrillic Extended B // Hebrew addCharsToCharClass(nonLatinHashtagChars, 0x0591, 0x05bf); // Hebrew addCharsToCharClass(nonLatinHashtagChars, 0x05c1, 0x05c2); addCharsToCharClass(nonLatinHashtagChars, 0x05c4, 0x05c5); addCharsToCharClass(nonLatinHashtagChars, 0x05c7, 0x05c7); addCharsToCharClass(nonLatinHashtagChars, 0x05d0, 0x05ea); addCharsToCharClass(nonLatinHashtagChars, 0x05f0, 0x05f4); addCharsToCharClass(nonLatinHashtagChars, 0xfb12, 0xfb28); // Hebrew Presentation Forms addCharsToCharClass(nonLatinHashtagChars, 0xfb2a, 0xfb36); addCharsToCharClass(nonLatinHashtagChars, 0xfb38, 0xfb3c); addCharsToCharClass(nonLatinHashtagChars, 0xfb3e, 0xfb3e); addCharsToCharClass(nonLatinHashtagChars, 0xfb40, 0xfb41); addCharsToCharClass(nonLatinHashtagChars, 0xfb43, 0xfb44); addCharsToCharClass(nonLatinHashtagChars, 0xfb46, 0xfb4f); // Arabic addCharsToCharClass(nonLatinHashtagChars, 0x0610, 0x061a); // Arabic addCharsToCharClass(nonLatinHashtagChars, 0x0620, 0x065f); addCharsToCharClass(nonLatinHashtagChars, 0x066e, 0x06d3); addCharsToCharClass(nonLatinHashtagChars, 0x06d5, 0x06dc); addCharsToCharClass(nonLatinHashtagChars, 0x06de, 0x06e8); addCharsToCharClass(nonLatinHashtagChars, 0x06ea, 0x06ef); addCharsToCharClass(nonLatinHashtagChars, 0x06fa, 0x06fc); addCharsToCharClass(nonLatinHashtagChars, 0x06ff, 0x06ff); addCharsToCharClass(nonLatinHashtagChars, 0x0750, 0x077f); // Arabic Supplement addCharsToCharClass(nonLatinHashtagChars, 0x08a0, 0x08a0); // Arabic Extended A addCharsToCharClass(nonLatinHashtagChars, 0x08a2, 0x08ac); addCharsToCharClass(nonLatinHashtagChars, 0x08e4, 0x08fe); addCharsToCharClass(nonLatinHashtagChars, 0xfb50, 0xfbb1); // Arabic Pres. Forms A addCharsToCharClass(nonLatinHashtagChars, 0xfbd3, 0xfd3d); addCharsToCharClass(nonLatinHashtagChars, 0xfd50, 0xfd8f); addCharsToCharClass(nonLatinHashtagChars, 0xfd92, 0xfdc7); addCharsToCharClass(nonLatinHashtagChars, 0xfdf0, 0xfdfb); addCharsToCharClass(nonLatinHashtagChars, 0xfe70, 0xfe74); // Arabic Pres. Forms B addCharsToCharClass(nonLatinHashtagChars, 0xfe76, 0xfefc); addCharsToCharClass(nonLatinHashtagChars, 0x200c, 0x200c); // Zero-Width Non-Joiner // Thai addCharsToCharClass(nonLatinHashtagChars, 0x0e01, 0x0e3a); addCharsToCharClass(nonLatinHashtagChars, 0x0e40, 0x0e4e); // Hangul (Korean) addCharsToCharClass(nonLatinHashtagChars, 0x1100, 0x11ff); // Hangul Jamo addCharsToCharClass(nonLatinHashtagChars, 0x3130, 0x3185); // Hangul Compatibility Jamo addCharsToCharClass(nonLatinHashtagChars, 0xA960, 0xA97F); // Hangul Jamo Extended-A addCharsToCharClass(nonLatinHashtagChars, 0xAC00, 0xD7AF); // Hangul Syllables addCharsToCharClass(nonLatinHashtagChars, 0xD7B0, 0xD7FF); // Hangul Jamo Extended-B addCharsToCharClass(nonLatinHashtagChars, 0xFFA1, 0xFFDC); // half-width Hangul // Japanese and Chinese addCharsToCharClass(nonLatinHashtagChars, 0x30A1, 0x30FA); // Katakana (full-width) addCharsToCharClass(nonLatinHashtagChars, 0x30FC, 0x30FE); // Katakana Chouon and iteration marks (full-width) addCharsToCharClass(nonLatinHashtagChars, 0xFF66, 0xFF9F); // Katakana (half-width) addCharsToCharClass(nonLatinHashtagChars, 0xFF70, 0xFF70); // Katakana Chouon (half-width) addCharsToCharClass(nonLatinHashtagChars, 0xFF10, 0xFF19); // \ addCharsToCharClass(nonLatinHashtagChars, 0xFF21, 0xFF3A); // - Latin (full-width) addCharsToCharClass(nonLatinHashtagChars, 0xFF41, 0xFF5A); // / addCharsToCharClass(nonLatinHashtagChars, 0x3041, 0x3096); // Hiragana addCharsToCharClass(nonLatinHashtagChars, 0x3099, 0x309E); // Hiragana voicing and iteration mark addCharsToCharClass(nonLatinHashtagChars, 0x3400, 0x4DBF); // Kanji (CJK Extension A) addCharsToCharClass(nonLatinHashtagChars, 0x4E00, 0x9FFF); // Kanji (Unified) // -- Disabled as it breaks the Regex. //addCharsToCharClass(nonLatinHashtagChars, 0x20000, 0x2A6DF); // Kanji (CJK Extension B) addCharsToCharClass(nonLatinHashtagChars, 0x2A700, 0x2B73F); // Kanji (CJK Extension C) addCharsToCharClass(nonLatinHashtagChars, 0x2B740, 0x2B81F); // Kanji (CJK Extension D) addCharsToCharClass(nonLatinHashtagChars, 0x2F800, 0x2FA1F); // Kanji (CJK supplement) addCharsToCharClass(nonLatinHashtagChars, 0x3003, 0x3003); // Kanji iteration mark addCharsToCharClass(nonLatinHashtagChars, 0x3005, 0x3005); // Kanji iteration mark addCharsToCharClass(nonLatinHashtagChars, 0x303B, 0x303B); // Han iteration mark twttr.txt.regexen.nonLatinHashtagChars = regexSupplant(nonLatinHashtagChars.join("")); var latinAccentChars = []; // Latin accented characters (subtracted 0xD7 from the range, it's a confusable multiplication sign. Looks like "x") addCharsToCharClass(latinAccentChars, 0x00c0, 0x00d6); addCharsToCharClass(latinAccentChars, 0x00d8, 0x00f6); addCharsToCharClass(latinAccentChars, 0x00f8, 0x00ff); // Latin Extended A and B addCharsToCharClass(latinAccentChars, 0x0100, 0x024f); // assorted IPA Extensions addCharsToCharClass(latinAccentChars, 0x0253, 0x0254); addCharsToCharClass(latinAccentChars, 0x0256, 0x0257); addCharsToCharClass(latinAccentChars, 0x0259, 0x0259); addCharsToCharClass(latinAccentChars, 0x025b, 0x025b); addCharsToCharClass(latinAccentChars, 0x0263, 0x0263); addCharsToCharClass(latinAccentChars, 0x0268, 0x0268); addCharsToCharClass(latinAccentChars, 0x026f, 0x026f); addCharsToCharClass(latinAccentChars, 0x0272, 0x0272); addCharsToCharClass(latinAccentChars, 0x0289, 0x0289); addCharsToCharClass(latinAccentChars, 0x028b, 0x028b); // Okina for Hawaiian (it *is* a letter character) addCharsToCharClass(latinAccentChars, 0x02bb, 0x02bb); // Combining diacritics addCharsToCharClass(latinAccentChars, 0x0300, 0x036f); // Latin Extended Additional addCharsToCharClass(latinAccentChars, 0x1e00, 0x1eff); twttr.txt.regexen.latinAccentChars = regexSupplant(latinAccentChars.join("")); // A hashtag must contain characters, numbers and underscores, but not all numbers. twttr.txt.regexen.hashSigns = /[##]/; twttr.txt.regexen.hashtagAlpha = regexSupplant(/[a-z_#{latinAccentChars}#{nonLatinHashtagChars}]/i); twttr.txt.regexen.hashtagAlphaNumeric = regexSupplant(/[a-z0-9_#{latinAccentChars}#{nonLatinHashtagChars}]/i); twttr.txt.regexen.endHashtagMatch = regexSupplant(/^(?:#{hashSigns}|:\/\/)/); twttr.txt.regexen.hashtagBoundary = regexSupplant(/(?:^|$|[^&a-z0-9_#{latinAccentChars}#{nonLatinHashtagChars}])/); twttr.txt.regexen.validHashtag = regexSupplant(/(#{hashtagBoundary})(#{hashSigns})(#{hashtagAlphaNumeric}*#{hashtagAlpha}#{hashtagAlphaNumeric}*)/gi); // Mention related regex collection twttr.txt.regexen.validMentionPrecedingChars = /(?:^|[^a-zA-Z0-9_!#$%&*@@]|(?:rt|RT|rT|Rt):?)/; twttr.txt.regexen.atSigns = /[@@]/; twttr.txt.regexen.validMentionOrList = regexSupplant( '(#{validMentionPrecedingChars})' + // $1: Preceding character '(#{atSigns})' + // $2: At mark '([a-zA-Z0-9_]{1,20})' + // $3: Screen name '(\/[a-zA-Z][a-zA-Z0-9_\-]{0,24})?' // $4: List (optional) , 'g'); twttr.txt.regexen.validReply = regexSupplant(/^(?:#{spaces})*#{atSigns}([a-zA-Z0-9_]{1,20})/); twttr.txt.regexen.endMentionMatch = regexSupplant(/^(?:#{atSigns}|[#{latinAccentChars}]|:\/\/)/); // URL related regex collection twttr.txt.regexen.validUrlPrecedingChars = regexSupplant(/(?:[^A-Za-z0-9@@$###{invalid_chars_group}]|^)/); twttr.txt.regexen.invalidUrlWithoutProtocolPrecedingChars = /[-_.\/]$/; twttr.txt.regexen.invalidDomainChars = stringSupplant("#{punct}#{spaces_group}#{invalid_chars_group}", twttr.txt.regexen); twttr.txt.regexen.validDomainChars = regexSupplant(/[^#{invalidDomainChars}]/); twttr.txt.regexen.validSubdomain = regexSupplant(/(?:(?:#{validDomainChars}(?:[_-]|#{validDomainChars})*)?#{validDomainChars}\.)/); twttr.txt.regexen.validDomainName = regexSupplant(/(?:(?:#{validDomainChars}(?:-|#{validDomainChars})*)?#{validDomainChars}\.)/); twttr.txt.regexen.validGTLD = regexSupplant(RegExp( '(?:(?:academy|aero|agency|arpa|asia|bargains|berlin|bike|biz|blue|boutique|build|builders|buzz|cab|camera|camp|careers|cat|catering|' + 'center|ceo|cheap|cleaning|clothing|club|codes|coffee|com|community|company|computer|construction|contractors|cool|coop|cruises|' + 'dance|dating|democrat|diamonds|directory|domains|edu|education|email|enterprises|equipment|estate|events|expert|exposed|farm|' + 'flights|florist|gallery|gift|glass|gov|graphics|guitars|guru|holdings|holiday|house|immobilien|info|institute|int|international|' + 'jobs|kaufen|kim|kitchen|kiwi|land|lighting|limo|link|luxury|management|marketing|menu|mil|mobi|moda|monash|museum|nagoya|name|net|' + 'ninja|onl|org|partners|photo|photography|photos|pics|pink|plumbing|post|pro|properties|recipes|red|rentals|repair|report|rich|ruhr|' + 'sexy|shiksha|shoes|singles|social|solar|solutions|support|systems|tattoo|technology|tel|tienda|tips|today|tokyo|tools|training|' + 'travel|uno|ventures|viajes|voting|voyage|wang|watch|wed|wien|works|xxx|zone)(?=[^0-9a-zA-Z@]|$))')); twttr.txt.regexen.validCCTLD = regexSupplant(RegExp( '(?:(?:ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|' + 'ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cs|cu|cv|cx|cy|cz|dd|de|dj|dk|dm|do|dz|ec|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|' + 'ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|' + 'ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|' + 'na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|' + 'sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|ss|st|su|sv|sx|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|' + 'ua|ug|uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|za|zm|zw)(?=[^0-9a-zA-Z@]|$))')); twttr.txt.regexen.validPunycode = regexSupplant(/(?:xn--[0-9a-z]+)/); twttr.txt.regexen.validDomain = regexSupplant(/(?:#{validSubdomain}*#{validDomainName}(?:#{validGTLD}|#{validCCTLD}|#{validPunycode}))/); twttr.txt.regexen.validAsciiDomain = regexSupplant(/(?:(?:[\-a-z0-9#{latinAccentChars}]+)\.)+(?:#{validGTLD}|#{validCCTLD}|#{validPunycode})/gi); twttr.txt.regexen.invalidShortDomain = regexSupplant(/^#{validDomainName}#{validCCTLD}$/); twttr.txt.regexen.validPortNumber = regexSupplant(/[0-9]+/); twttr.txt.regexen.validGeneralUrlPathChars = regexSupplant(/[a-z0-9!\*';:=\+,\.\$\/%#\[\]\-_~@|&#{latinAccentChars}]/i); // Allow URL paths to contain up to two nested levels of balanced parens // 1. Used in Wikipedia URLs like /Primer_(film) // 2. Used in IIS sessions like /S(dfd346)/ // 3. Used in Rdio URLs like /track/We_Up_(Album_Version_(Edited))/ twttr.txt.regexen.validUrlBalancedParens = regexSupplant( '\\(' + '(?:' + '#{validGeneralUrlPathChars}+' + '|' + // allow one nested level of balanced parentheses '(?:' + '#{validGeneralUrlPathChars}*' + '\\(' + '#{validGeneralUrlPathChars}+' + '\\)' + '#{validGeneralUrlPathChars}*' + ')' + ')' + '\\)' , 'i'); // Valid end-of-path chracters (so /foo. does not gobble the period). // 1. Allow =&# for empty URL parameters and other URL-join artifacts twttr.txt.regexen.validUrlPathEndingChars = regexSupplant(/[\+\-a-z0-9=_#\/#{latinAccentChars}]|(?:#{validUrlBalancedParens})/i); // Allow @ in a url, but only in the middle. Catch things like http://example.com/@user/ twttr.txt.regexen.validUrlPath = regexSupplant('(?:' + '(?:' + '#{validGeneralUrlPathChars}*' + '(?:#{validUrlBalancedParens}#{validGeneralUrlPathChars}*)*' + '#{validUrlPathEndingChars}'+ ')|(?:@#{validGeneralUrlPathChars}+\/)'+ ')', 'i'); twttr.txt.regexen.validUrlQueryChars = /[a-z0-9!?\*'@\(\);:&=\+\$\/%#\[\]\-_\.,~|]/i; twttr.txt.regexen.validUrlQueryEndingChars = /[a-z0-9_&=#\/]/i; twttr.txt.regexen.extractUrl = regexSupplant( '(' + // $1 total match '(#{validUrlPrecedingChars})' + // $2 Preceeding chracter '(' + // $3 URL '(https?:\\/\\/)?' + // $4 Protocol (optional) '(#{validDomain})' + // $5 Domain(s) '(?::(#{validPortNumber}))?' + // $6 Port number (optional) '(\\/#{validUrlPath}*)?' + // $7 URL Path '(\\?#{validUrlQueryChars}*#{validUrlQueryEndingChars})?' + // $8 Query String ')' + ')' , 'gi'); twttr.txt.regexen.validTcoUrl = /^https?:\/\/t\.co\/[a-z0-9]+/i; twttr.txt.regexen.urlHasProtocol = /^https?:\/\//i; twttr.txt.regexen.urlHasHttps = /^https:\/\//i; // cashtag related regex twttr.txt.regexen.cashtag = /[a-z]{1,6}(?:[._][a-z]{1,2})?/i; twttr.txt.regexen.validCashtag = regexSupplant('(^|#{spaces})(\\$)(#{cashtag})(?=$|\\s|[#{punct}])', 'gi'); // These URL validation pattern strings are based on the ABNF from RFC 3986 twttr.txt.regexen.validateUrlUnreserved = /[a-z0-9\-._~]/i; twttr.txt.regexen.validateUrlPctEncoded = /(?:%[0-9a-f]{2})/i; twttr.txt.regexen.validateUrlSubDelims = /[!$&'()*+,;=]/i; twttr.txt.regexen.validateUrlPchar = regexSupplant('(?:' + '#{validateUrlUnreserved}|' + '#{validateUrlPctEncoded}|' + '#{validateUrlSubDelims}|' + '[:|@]' + ')', 'i'); twttr.txt.regexen.validateUrlScheme = /(?:[a-z][a-z0-9+\-.]*)/i; twttr.txt.regexen.validateUrlUserinfo = regexSupplant('(?:' + '#{validateUrlUnreserved}|' + '#{validateUrlPctEncoded}|' + '#{validateUrlSubDelims}|' + ':' + ')*', 'i'); twttr.txt.regexen.validateUrlDecOctet = /(?:[0-9]|(?:[1-9][0-9])|(?:1[0-9]{2})|(?:2[0-4][0-9])|(?:25[0-5]))/i; twttr.txt.regexen.validateUrlIpv4 = regexSupplant(/(?:#{validateUrlDecOctet}(?:\.#{validateUrlDecOctet}){3})/i); // Punting on real IPv6 validation for now twttr.txt.regexen.validateUrlIpv6 = /(?:\[[a-f0-9:\.]+\])/i; // Also punting on IPvFuture for now twttr.txt.regexen.validateUrlIp = regexSupplant('(?:' + '#{validateUrlIpv4}|' + '#{validateUrlIpv6}' + ')', 'i'); // This is more strict than the rfc specifies twttr.txt.regexen.validateUrlSubDomainSegment = /(?:[a-z0-9](?:[a-z0-9_\-]*[a-z0-9])?)/i; twttr.txt.regexen.validateUrlDomainSegment = /(?:[a-z0-9](?:[a-z0-9\-]*[a-z0-9])?)/i; twttr.txt.regexen.validateUrlDomainTld = /(?:[a-z](?:[a-z0-9\-]*[a-z0-9])?)/i; twttr.txt.regexen.validateUrlDomain = regexSupplant(/(?:(?:#{validateUrlSubDomainSegment]}\.)*(?:#{validateUrlDomainSegment]}\.)#{validateUrlDomainTld})/i); twttr.txt.regexen.validateUrlHost = regexSupplant('(?:' + '#{validateUrlIp}|' + '#{validateUrlDomain}' + ')', 'i'); // Unencoded internationalized domains - this doesn't check for invalid UTF-8 sequences twttr.txt.regexen.validateUrlUnicodeSubDomainSegment = /(?:(?:[a-z0-9]|[^\u0000-\u007f])(?:(?:[a-z0-9_\-]|[^\u0000-\u007f])*(?:[a-z0-9]|[^\u0000-\u007f]))?)/i; twttr.txt.regexen.validateUrlUnicodeDomainSegment = /(?:(?:[a-z0-9]|[^\u0000-\u007f])(?:(?:[a-z0-9\-]|[^\u0000-\u007f])*(?:[a-z0-9]|[^\u0000-\u007f]))?)/i; twttr.txt.regexen.validateUrlUnicodeDomainTld = /(?:(?:[a-z]|[^\u0000-\u007f])(?:(?:[a-z0-9\-]|[^\u0000-\u007f])*(?:[a-z0-9]|[^\u0000-\u007f]))?)/i; twttr.txt.regexen.validateUrlUnicodeDomain = regexSupplant(/(?:(?:#{validateUrlUnicodeSubDomainSegment}\.)*(?:#{validateUrlUnicodeDomainSegment}\.)#{validateUrlUnicodeDomainTld})/i); twttr.txt.regexen.validateUrlUnicodeHost = regexSupplant('(?:' + '#{validateUrlIp}|' + '#{validateUrlUnicodeDomain}' + ')', 'i'); twttr.txt.regexen.validateUrlPort = /[0-9]{1,5}/; twttr.txt.regexen.validateUrlUnicodeAuthority = regexSupplant( '(?:(#{validateUrlUserinfo})@)?' + // $1 userinfo '(#{validateUrlUnicodeHost})' + // $2 host '(?::(#{validateUrlPort}))?' //$3 port , "i"); twttr.txt.regexen.validateUrlAuthority = regexSupplant( '(?:(#{validateUrlUserinfo})@)?' + // $1 userinfo '(#{validateUrlHost})' + // $2 host '(?::(#{validateUrlPort}))?' // $3 port , "i"); twttr.txt.regexen.validateUrlPath = regexSupplant(/(\/#{validateUrlPchar}*)*/i); twttr.txt.regexen.validateUrlQuery = regexSupplant(/(#{validateUrlPchar}|\/|\?)*/i); twttr.txt.regexen.validateUrlFragment = regexSupplant(/(#{validateUrlPchar}|\/|\?)*/i); // Modified version of RFC 3986 Appendix B twttr.txt.regexen.validateUrlUnencoded = regexSupplant( '^' + // Full URL '(?:' + '([^:/?#]+):\\/\\/' + // $1 Scheme ')?' + '([^/?#]*)' + // $2 Authority '([^?#]*)' + // $3 Path '(?:' + '\\?([^#]*)' + // $4 Query ')?' + '(?:' + '#(.*)' + // $5 Fragment ')?$' , "i"); // Default CSS class for auto-linked lists (along with the url class) var DEFAULT_LIST_CLASS = "tweet-url list-slug"; // Default CSS class for auto-linked usernames (along with the url class) var DEFAULT_USERNAME_CLASS = "tweet-url username"; // Default CSS class for auto-linked hashtags (along with the url class) var DEFAULT_HASHTAG_CLASS = "tweet-url hashtag"; // Default CSS class for auto-linked cashtags (along with the url class) var DEFAULT_CASHTAG_CLASS = "tweet-url cashtag"; // Options which should not be passed as HTML attributes var OPTIONS_NOT_ATTRIBUTES = {'urlClass':true, 'listClass':true, 'usernameClass':true, 'hashtagClass':true, 'cashtagClass':true, 'usernameUrlBase':true, 'listUrlBase':true, 'hashtagUrlBase':true, 'cashtagUrlBase':true, 'usernameUrlBlock':true, 'listUrlBlock':true, 'hashtagUrlBlock':true, 'linkUrlBlock':true, 'usernameIncludeSymbol':true, 'suppressLists':true, 'suppressNoFollow':true, 'targetBlank':true, 'suppressDataScreenName':true, 'urlEntities':true, 'symbolTag':true, 'textWithSymbolTag':true, 'urlTarget':true, 'invisibleTagAttrs':true, 'linkAttributeBlock':true, 'linkTextBlock': true, 'htmlEscapeNonEntities': true }; var BOOLEAN_ATTRIBUTES = {'disabled':true, 'readonly':true, 'multiple':true, 'checked':true}; // Simple object cloning function for simple objects function clone(o) { var r = {}; for (var k in o) { if (o.hasOwnProperty(k)) { r[k] = o[k]; } } return r; } twttr.txt.tagAttrs = function(attributes) { var htmlAttrs = ""; for (var k in attributes) { var v = attributes[k]; if (BOOLEAN_ATTRIBUTES[k]) { v = v ? k : null; } if (v == null) continue; htmlAttrs += " " + twttr.txt.htmlEscape(k) + "=\"" + twttr.txt.htmlEscape(v.toString()) + "\""; } return htmlAttrs; }; twttr.txt.linkToText = function(entity, text, attributes, options) { if (!options.suppressNoFollow) { attributes.rel = "nofollow"; } // if linkAttributeBlock is specified, call it to modify the attributes if (options.linkAttributeBlock) { options.linkAttributeBlock(entity, attributes); } // if linkTextBlock is specified, call it to get a new/modified link text if (options.linkTextBlock) { text = options.linkTextBlock(entity, text); } var d = { text: text, attr: twttr.txt.tagAttrs(attributes) }; return stringSupplant("<a#{attr}>#{text}</a>", d); }; twttr.txt.linkToTextWithSymbol = function(entity, symbol, text, attributes, options) { var taggedSymbol = options.symbolTag ? "<" + options.symbolTag + ">" + symbol + "</"+ options.symbolTag + ">" : symbol; text = twttr.txt.htmlEscape(text); var taggedText = options.textWithSymbolTag ? "<" + options.textWithSymbolTag + ">" + text + "</"+ options.textWithSymbolTag + ">" : text; if (options.usernameIncludeSymbol || !symbol.match(twttr.txt.regexen.atSigns)) { return twttr.txt.linkToText(entity, taggedSymbol + taggedText, attributes, options); } else { return taggedSymbol + twttr.txt.linkToText(entity, taggedText, attributes, options); } }; twttr.txt.linkToHashtag = function(entity, text, options) { var hash = text.substring(entity.indices[0], entity.indices[0] + 1); var hashtag = twttr.txt.htmlEscape(entity.hashtag); var attrs = clone(options.htmlAttrs || {}); attrs.href = options.hashtagUrlBase + hashtag; attrs.title = "#" + hashtag; attrs["class"] = options.hashtagClass; if (hashtag.charAt(0).match(twttr.txt.regexen.rtl_chars)){ attrs["class"] += " rtl"; } if (options.targetBlank) { attrs.target = '_blank'; } return twttr.txt.linkToTextWithSymbol(entity, hash, hashtag, attrs, options); }; twttr.txt.linkToCashtag = function(entity, text, options) { var cashtag = twttr.txt.htmlEscape(entity.cashtag); var attrs = clone(options.htmlAttrs || {}); attrs.href = options.cashtagUrlBase + cashtag; attrs.title = "$" + cashtag; attrs["class"] = options.cashtagClass; if (options.targetBlank) { attrs.target = '_blank'; } return twttr.txt.linkToTextWithSymbol(entity, "$", cashtag, attrs, options); }; twttr.txt.linkToMentionAndList = function(entity, text, options) { var at = text.substring(entity.indices[0], entity.indices[0] + 1); var user = twttr.txt.htmlEscape(entity.screenName); var slashListname = twttr.txt.htmlEscape(entity.listSlug); var isList = entity.listSlug && !options.suppressLists; var attrs = clone(options.htmlAttrs || {}); attrs["class"] = (isList ? options.listClass : options.usernameClass); attrs.href = isList ? options.listUrlBase + user + slashListname : options.usernameUrlBase + user; if (!isList && !options.suppressDataScreenName) { attrs['data-screen-name'] = user; } if (options.targetBlank) { attrs.target = '_blank'; } return twttr.txt.linkToTextWithSymbol(entity, at, isList ? user + slashListname : user, attrs, options); }; twttr.txt.linkToUrl = function(entity, text, options) { var url = entity.url; var displayUrl = url; var linkText = twttr.txt.htmlEscape(displayUrl); // If the caller passed a urlEntities object (provided by a Twitter API // response with include_entities=true), we use that to render the display_url // for each URL instead of it's underlying t.co URL. var urlEntity = (options.urlEntities && options.urlEntities[url]) || entity; if (urlEntity.display_url) { linkText = twttr.txt.linkTextWithEntity(urlEntity, options); } var attrs = clone(options.htmlAttrs || {}); if (!url.match(twttr.txt.regexen.urlHasProtocol)) { url = "http://" + url; } attrs.href = url; if (options.targetBlank) { attrs.target = '_blank'; } // set class only if urlClass is specified. if (options.urlClass) { attrs["class"] = options.urlClass; } // set target only if urlTarget is specified. if (options.urlTarget) { attrs.target = options.urlTarget; } if (!options.title && urlEntity.display_url) { attrs.title = urlEntity.expanded_url; } return twttr.txt.linkToText(entity, linkText, attrs, options); }; twttr.txt.linkTextWithEntity = function (entity, options) { var displayUrl = entity.display_url; var expandedUrl = entity.expanded_url; // Goal: If a user copies and pastes a tweet containing t.co'ed link, the resulting paste // should contain the full original URL (expanded_url), not the display URL. // // Method: Whenever possible, we actually emit HTML that contains expanded_url, and use // font-size:0 to hide those parts that should not be displayed (because they are not part of display_url). // Elements with font-size:0 get copied even though they are not visible. // Note that display:none doesn't work here. Elements with display:none don't get copied. // // Additionally, we want to *display* ellipses, but we don't want them copied. To make this happen we // wrap the ellipses in a tco-ellipsis class and provide an onCopy handler that sets display:none on // everything with the tco-ellipsis class. // // Exception: pic.twitter.com images, for which expandedUrl = "https://twitter.com/#!/username/status/1234/photo/1 // For those URLs, display_url is not a substring of expanded_url, so we don't do anything special to render the elided parts. // For a pic.twitter.com URL, the only elided part will be the "https://", so this is fine. var displayUrlSansEllipses = displayUrl.replace(/…/g, ""); // We have to disregard ellipses for matching // Note: we currently only support eliding parts of the URL at the beginning or the end. // Eventually we may want to elide parts of the URL in the *middle*. If so, this code will // become more complicated. We will probably want to create a regexp out of display URL, // replacing every ellipsis with a ".*". if (expandedUrl.indexOf(displayUrlSansEllipses) != -1) { var displayUrlIndex = expandedUrl.indexOf(displayUrlSansEllipses); var v = { displayUrlSansEllipses: displayUrlSansEllipses, // Portion of expandedUrl that precedes the displayUrl substring beforeDisplayUrl: expandedUrl.substr(0, displayUrlIndex), // Portion of expandedUrl that comes after displayUrl afterDisplayUrl: expandedUrl.substr(displayUrlIndex + displayUrlSansEllipses.length), precedingEllipsis: displayUrl.match(/^…/) ? "…" : "", followingEllipsis: displayUrl.match(/…$/) ? "…" : "" }; for (var k in v) { if (v.hasOwnProperty(k)) { v[k] = twttr.txt.htmlEscape(v[k]); } } // As an example: The user tweets "hi http://longdomainname.com/foo" // This gets shortened to "hi http://t.co/xyzabc", with display_url = "…nname.com/foo" // This will get rendered as: // <span class='tco-ellipsis'> <!-- This stuff should get displayed but not copied --> // … // <!-- There's a chance the onCopy event handler might not fire. In case that happens, // we include an &nbsp; here so that the … doesn't bump up against the URL and ruin it. // The &nbsp; is inside the tco-ellipsis span so that when the onCopy handler *does* // fire, it doesn't get copied. Otherwise the copied text would have two spaces in a row, // e.g. "hi http://longdomainname.com/foo". // <span style='font-size:0'>&nbsp;</span> // </span> // <span style='font-size:0'> <!-- This stuff should get copied but not displayed --> // http://longdomai // </span> // <span class='js-display-url'> <!-- This stuff should get displayed *and* copied --> // nname.com/foo // </span> // <span class='tco-ellipsis'> <!-- This stuff should get displayed but not copied --> // <span style='font-size:0'>&nbsp;</span> // … // </span> v['invisible'] = options.invisibleTagAttrs; return stringSupplant("<span class='tco-ellipsis'>#{precedingEllipsis}<span #{invisible}>&nbsp;</span></span><span #{invisible}>#{beforeDisplayUrl}</span><span class='js-display-url'>#{displayUrlSansEllipses}</span><span #{invisible}>#{afterDisplayUrl}</span><span class='tco-ellipsis'><span #{invisible}>&nbsp;</span>#{followingEllipsis}</span>", v); } return displayUrl; }; twttr.txt.autoLinkEntities = function(text, entities, options) { options = clone(options || {}); options.hashtagClass = options.hashtagClass || DEFAULT_HASHTAG_CLASS; options.hashtagUrlBase = options.hashtagUrlBase || "https://twitter.com/#!/search?q=%23"; options.cashtagClass = options.cashtagClass || DEFAULT_CASHTAG_CLASS; options.cashtagUrlBase = options.cashtagUrlBase || "https://twitter.com/#!/search?q=%24"; options.listClass = options.listClass || DEFAULT_LIST_CLASS; options.usernameClass = options.usernameClass || DEFAULT_USERNAME_CLASS; options.usernameUrlBase = options.usernameUrlBase || "https://twitter.com/"; options.listUrlBase = options.listUrlBase || "https://twitter.com/"; options.htmlAttrs = twttr.txt.extractHtmlAttrsFromOptions(options); options.invisibleTagAttrs = options.invisibleTagAttrs || "style='position:absolute;left:-9999px;'"; // remap url entities to hash var urlEntities, i, len; if(options.urlEntities) { urlEntities = {}; for(i = 0, len = options.urlEntities.length; i < len; i++) { urlEntities[options.urlEntities[i].url] = options.urlEntities[i]; } options.urlEntities = urlEntities; } var result = ""; var beginIndex = 0; // sort entities by start index entities.sort(function(a,b){ return a.indices[0] - b.indices[0]; }); var nonEntity = options.htmlEscapeNonEntities ? twttr.txt.htmlEscape : function(text) { return text; }; for (var i = 0; i < entities.length; i++) { var entity = entities[i]; result += nonEntity(text.substring(beginIndex, entity.indices[0])); if (entity.url) { result += twttr.txt.linkToUrl(entity, text, options); } else if (entity.hashtag) { result += twttr.txt.linkToHashtag(entity, text, options); } else if (entity.screenName) { result += twttr.txt.linkToMentionAndList(entity, text, options); } else if (entity.cashtag) { result += twttr.txt.linkToCashtag(entity, text, options); } beginIndex = entity.indices[1]; } result += nonEntity(text.substring(beginIndex, text.length)); return result; }; twttr.txt.autoLinkWithJSON = function(text, json, options) { // map JSON entity to twitter-text entity if (json.user_mentions) { for (var i = 0; i < json.user_mentions.length; i++) { // this is a @mention json.user_mentions[i].screenName = json.user_mentions[i].screen_name; } } if (json.hashtags) { for (var i = 0; i < json.hashtags.length; i++) { // this is a #hashtag json.hashtags[i].hashtag = json.hashtags[i].text; } } if (json.symbols) { for (var i = 0; i < json.symbols.length; i++) { // this is a $CASH tag json.symbols[i].cashtag = json.symbols[i].text; } } // concatenate all entities var entities = []; for (var key in json) { entities = entities.concat(json[key]); } // modify indices to UTF-16 twttr.txt.modifyIndicesFromUnicodeToUTF16(text, entities); return twttr.txt.autoLinkEntities(text, entities, options); }; twttr.txt.extractHtmlAttrsFromOptions = function(options) { var htmlAttrs = {}; for (var k in options) { var v = options[k]; if (OPTIONS_NOT_ATTRIBUTES[k]) continue; if (BOOLEAN_ATTRIBUTES[k]) { v = v ? k : null; } if (v == null) continue; htmlAttrs[k] = v; } return htmlAttrs; }; twttr.txt.autoLink = function(text, options) { var entities = twttr.txt.extractEntitiesWithIndices(text, {extractUrlsWithoutProtocol: false}); return twttr.txt.autoLinkEntities(text, entities, options); }; twttr.txt.autoLinkUsernamesOrLists = function(text, options) { var entities = twttr.txt.extractMentionsOrListsWithIndices(text); return twttr.txt.autoLinkEntities(text, entities, options); }; twttr.txt.autoLinkHashtags = function(text, options) { var entities = twttr.txt.extractHashtagsWithIndices(text); return twttr.txt.autoLinkEntities(text, entities, options); }; twttr.txt.autoLinkCashtags = function(text, options) { var entities = twttr.txt.extractCashtagsWithIndices(text); return twttr.txt.autoLinkEntities(text, entities, options); }; twttr.txt.autoLinkUrlsCustom = function(text, options) { var entities = twttr.txt.extractUrlsWithIndices(text, {extractUrlsWithoutProtocol: false}); return twttr.txt.autoLinkEntities(text, entities, options); }; twttr.txt.removeOverlappingEntities = function(entities) { entities.sort(function(a,b){ return a.indices[0] - b.indices[0]; }); var prev = entities[0]; for (var i = 1; i < entities.length; i++) { if (prev.indices[1] > entities[i].indices[0]) { entities.splice(i, 1); i--; } else { prev = entities[i]; } } }; twttr.txt.extractEntitiesWithIndices = function(text, options) { var entities = twttr.txt.extractUrlsWithIndices(text, options) .concat(twttr.txt.extractMentionsOrListsWithIndices(text)) .concat(twttr.txt.extractHashtagsWithIndices(text, {checkUrlOverlap: false})) .concat(twttr.txt.extractCashtagsWithIndices(text)); if (entities.length == 0) { return []; } twttr.txt.removeOverlappingEntities(entities); return entities; }; twttr.txt.extractMentions = function(text) { var screenNamesOnly = [], screenNamesWithIndices = twttr.txt.extractMentionsWithIndices(text); for (var i = 0; i < screenNamesWithIndices.length; i++) { var screenName = screenNamesWithIndices[i].screenName; screenNamesOnly.push(screenName); } return screenNamesOnly; }; twttr.txt.extractMentionsWithIndices = function(text) { var mentions = [], mentionOrList, mentionsOrLists = twttr.txt.extractMentionsOrListsWithIndices(text); for (var i = 0 ; i < mentionsOrLists.length; i++) { mentionOrList = mentionsOrLists[i]; if (mentionOrList.listSlug == '') { mentions.push({ screenName: mentionOrList.screenName, indices: mentionOrList.indices }); } } return mentions; }; /** * Extract list or user mentions. * (Presence of listSlug indicates a list) */ twttr.txt.extractMentionsOrListsWithIndices = function(text) { if (!text || !text.match(twttr.txt.regexen.atSigns)) { return []; } var possibleNames = [], slashListname; text.replace(twttr.txt.regexen.validMentionOrList, function(match, before, atSign, screenName, slashListname, offset, chunk) { var after = chunk.slice(offset + match.length); if (!after.match(twttr.txt.regexen.endMentionMatch)) { slashListname = slashListname || ''; var startPosition = offset + before.length; var endPosition = startPosition + screenName.length + slashListname.length + 1; possibleNames.push({ screenName: screenName, listSlug: slashListname, indices: [startPosition, endPosition] }); } }); return possibleNames; }; twttr.txt.extractReplies = function(text) { if (!text) { return null; } var possibleScreenName = text.match(twttr.txt.regexen.validReply); if (!possibleScreenName || RegExp.rightContext.match(twttr.txt.regexen.endMentionMatch)) { return null; } return possibleScreenName[1]; }; twttr.txt.extractUrls = function(text, options) { var urlsOnly = [], urlsWithIndices = twttr.txt.extractUrlsWithIndices(text, options); for (var i = 0; i < urlsWithIndices.length; i++) { urlsOnly.push(urlsWithIndices[i].url); } return urlsOnly; }; twttr.txt.extractUrlsWithIndices = function(text, options) { if (!options) { options = {extractUrlsWithoutProtocol: true}; } if (!text || (options.extractUrlsWithoutProtocol ? !text.match(/\./) : !text.match(/:/))) { return []; } var urls = []; while (twttr.txt.regexen.extractUrl.exec(text)) { var before = RegExp.$2, url = RegExp.$3, protocol = RegExp.$4, domain = RegExp.$5, path = RegExp.$7; var endPosition = twttr.txt.regexen.extractUrl.lastIndex, startPosition = endPosition - url.length; // if protocol is missing and domain contains non-ASCII characters, // extract ASCII-only domains. if (!protocol) { if (!options.extractUrlsWithoutProtocol || before.match(twttr.txt.regexen.invalidUrlWithoutProtocolPrecedingChars)) { continue; } var lastUrl = null, lastUrlInvalidMatch = false, asciiEndPosition = 0; domain.replace(twttr.txt.regexen.validAsciiDomain, function(asciiDomain) { var asciiStartPosition = domain.indexOf(asciiDomain, asciiEndPosition); asciiEndPosition = asciiStartPosition + asciiDomain.length; lastUrl = { url: asciiDomain, indices: [startPosition + asciiStartPosition, startPosition + asciiEndPosition] }; lastUrlInvalidMatch = asciiDomain.match(twttr.txt.regexen.invalidShortDomain); if (!lastUrlInvalidMatch) { urls.push(lastUrl); } }); // no ASCII-only domain found. Skip the entire URL. if (lastUrl == null) { continue; } // lastUrl only contains domain. Need to add path and query if they exist. if (path) { if (lastUrlInvalidMatch) { urls.push(lastUrl); } lastUrl.url = url.replace(domain, lastUrl.url); lastUrl.indices[1] = endPosition; } } else { // In the case of t.co URLs, don't allow additional path characters. if (url.match(twttr.txt.regexen.validTcoUrl)) { url = RegExp.lastMatch; endPosition = startPosition + url.length; } urls.push({ url: url, indices: [startPosition, endPosition] }); } } return urls; }; twttr.txt.extractHashtags = function(text) { var hashtagsOnly = [], hashtagsWithIndices = twttr.txt.extractHashtagsWithIndices(text); for (var i = 0; i < hashtagsWithIndices.length; i++) { hashtagsOnly.push(hashtagsWithIndices[i].hashtag); } return hashtagsOnly; }; twttr.txt.extractHashtagsWithIndices = function(text, options) { if (!options) { options = {checkUrlOverlap: true}; } if (!text || !text.match(twttr.txt.regexen.hashSigns)) { return []; } var tags = []; text.replace(twttr.txt.regexen.validHashtag, function(match, before, hash, hashText, offset, chunk) { var after = chunk.slice(offset + match.length); if (after.match(twttr.txt.regexen.endHashtagMatch)) return; var startPosition = offset + before.length; var endPosition = startPosition + hashText.length + 1; tags.push({ hashtag: hashText, indices: [startPosition, endPosition] }); }); if (options.checkUrlOverlap) { // also extract URL entities var urls = twttr.txt.extractUrlsWithIndices(text); if (urls.length > 0) { var entities = tags.concat(urls); // remove overlap twttr.txt.removeOverlappingEntities(entities); // only push back hashtags tags = []; for (var i = 0; i < entities.length; i++) { if (entities[i].hashtag) { tags.push(entities[i]); } } } } return tags; }; twttr.txt.extractCashtags = function(text) { var cashtagsOnly = [], cashtagsWithIndices = twttr.txt.extractCashtagsWithIndices(text); for (var i = 0; i < cashtagsWithIndices.length; i++) { cashtagsOnly.push(cashtagsWithIndices[i].cashtag); } return cashtagsOnly; }; twttr.txt.extractCashtagsWithIndices = function(text) { if (!text || text.indexOf("$") == -1) { return []; } var tags = []; text.replace(twttr.txt.regexen.validCashtag, function(match, before, dollar, cashtag, offset, chunk) { var startPosition = offset + before.length; var endPosition = startPosition + cashtag.length + 1; tags.push({ cashtag: cashtag, indices: [startPosition, endPosition] }); }); return tags; }; twttr.txt.modifyIndicesFromUnicodeToUTF16 = function(text, entities) { twttr.txt.convertUnicodeIndices(text, entities, false); }; twttr.txt.modifyIndicesFromUTF16ToUnicode = function(text, entities) { twttr.txt.convertUnicodeIndices(text, entities, true); }; twttr.txt.getUnicodeTextLength = function(text) { return text.replace(twttr.txt.regexen.non_bmp_code_pairs, ' ').length; }; twttr.txt.convertUnicodeIndices = function(text, entities, indicesInUTF16) { if (entities.length == 0) { return; } var charIndex = 0; var codePointIndex = 0; // sort entities by start index entities.sort(function(a,b){ return a.indices[0] - b.indices[0]; }); var entityIndex = 0; var entity = entities[0]; while (charIndex < text.length) { if (entity.indices[0] == (indicesInUTF16 ? charIndex : codePointIndex)) { var len = entity.indices[1] - entity.indices[0]; entity.indices[0] = indicesInUTF16 ? codePointIndex : charIndex; entity.indices[1] = entity.indices[0] + len; entityIndex++; if (entityIndex == entities.length) { // no more entity break; } entity = entities[entityIndex]; } var c = text.charCodeAt(charIndex); if (0xD800 <= c && c <= 0xDBFF && charIndex < text.length - 1) { // Found high surrogate char c = text.charCodeAt(charIndex + 1); if (0xDC00 <= c && c <= 0xDFFF) { // Found surrogate pair charIndex++; } } codePointIndex++; charIndex++; } }; // this essentially does text.split(/<|>/) // except that won't work in IE, where empty strings are ommitted // so "<>".split(/<|>/) => [] in IE, but is ["", "", ""] in all others // but "<<".split("<") => ["", "", ""] twttr.txt.splitTags = function(text) { var firstSplits = text.split("<"), secondSplits, allSplits = [], split; for (var i = 0; i < firstSplits.length; i += 1) { split = firstSplits[i]; if (!split) { allSplits.push(""); } else { secondSplits = split.split(">"); for (var j = 0; j < secondSplits.length; j += 1) { allSplits.push(secondSplits[j]); } } } return allSplits; }; twttr.txt.hitHighlight = function(text, hits, options) { var defaultHighlightTag = "em"; hits = hits || []; options = options || {}; if (hits.length === 0) { return text; } var tagName = options.tag || defaultHighlightTag, tags = ["<" + tagName + ">", "</" + tagName + ">"], chunks = twttr.txt.splitTags(text), i, j, result = "", chunkIndex = 0, chunk = chunks[0], prevChunksLen = 0, chunkCursor = 0, startInChunk = false, chunkChars = chunk, flatHits = [], index, hit, tag, placed, hitSpot; for (i = 0; i < hits.length; i += 1) { for (j = 0; j < hits[i].length; j += 1) { flatHits.push(hits[i][j]); } } for (index = 0; index < flatHits.length; index += 1) { hit = flatHits[index]; tag = tags[index % 2]; placed = false; while (chunk != null && hit >= prevChunksLen + chunk.length) { result += chunkChars.slice(chunkCursor); if (startInChunk && hit === prevChunksLen + chunkChars.length) { result += tag; placed = true; } if (chunks[chunkIndex + 1]) { result += "<" + chunks[chunkIndex + 1] + ">"; } prevChunksLen += chunkChars.length; chunkCursor = 0; chunkIndex += 2; chunk = chunks[chunkIndex]; chunkChars = chunk; startInChunk = false; } if (!placed && chunk != null) { hitSpot = hit - prevChunksLen; result += chunkChars.slice(chunkCursor, hitSpot) + tag; chunkCursor = hitSpot; if (index % 2 === 0) { startInChunk = true; } else { startInChunk = false; } } else if(!placed) { placed = true; result += tag; } } if (chunk != null) { if (chunkCursor < chunkChars.length) { result += chunkChars.slice(chunkCursor); } for (index = chunkIndex + 1; index < chunks.length; index += 1) { result += (index % 2 === 0 ? chunks[index] : "<" + chunks[index] + ">"); } } return result; }; var MAX_LENGTH = 140; // Characters not allowed in Tweets var INVALID_CHARACTERS = [ // BOM fromCode(0xFFFE), fromCode(0xFEFF), // Special fromCode(0xFFFF), // Directional Change fromCode(0x202A), fromCode(0x202B), fromCode(0x202C), fromCode(0x202D), fromCode(0x202E) ]; // Returns the length of Tweet text with consideration to t.co URL replacement // and chars outside the basic multilingual plane that use 2 UTF16 code points twttr.txt.getTweetLength = function(text, options) { if (!options) { options = { // These come from https://api.twitter.com/1/help/configuration.json // described by https://dev.twitter.com/docs/api/1/get/help/configuration short_url_length: 22, short_url_length_https: 23 }; } var textLength = twttr.txt.getUnicodeTextLength(text), urlsWithIndices = twttr.txt.extractUrlsWithIndices(text); twttr.txt.modifyIndicesFromUTF16ToUnicode(text, urlsWithIndices); for (var i = 0; i < urlsWithIndices.length; i++) { // Subtract the length of the original URL textLength += urlsWithIndices[i].indices[0] - urlsWithIndices[i].indices[1]; // Add 23 characters for URL starting with https:// // Otherwise add 22 characters if (urlsWithIndices[i].url.toLowerCase().match(twttr.txt.regexen.urlHasHttps)) { textLength += options.short_url_length_https; } else { textLength += options.short_url_length; } } return textLength; }; // Check the text for any reason that it may not be valid as a Tweet. This is meant as a pre-validation // before posting to api.twitter.com. There are several server-side reasons for Tweets to fail but this pre-validation // will allow quicker feedback. // // Returns false if this text is valid. Otherwise one of the following strings will be returned: // // "too_long": if the text is too long // "empty": if the text is nil or empty // "invalid_characters": if the text contains non-Unicode or any of the disallowed Unicode characters twttr.txt.isInvalidTweet = function(text) { if (!text) { return "empty"; } // Determine max length independent of URL length if (twttr.txt.getTweetLength(text) > MAX_LENGTH) { return "too_long"; } for (var i = 0; i < INVALID_CHARACTERS.length; i++) { if (text.indexOf(INVALID_CHARACTERS[i]) >= 0) { return "invalid_characters"; } } return false; }; twttr.txt.isValidTweetText = function(text) { return !twttr.txt.isInvalidTweet(text); }; twttr.txt.isValidUsername = function(username) { if (!username) { return false; } var extracted = twttr.txt.extractMentions(username); // Should extract the username minus the @ sign, hence the .slice(1) return extracted.length === 1 && extracted[0] === username.slice(1); }; var VALID_LIST_RE = regexSupplant(/^#{validMentionOrList}$/); twttr.txt.isValidList = function(usernameList) { var match = usernameList.match(VALID_LIST_RE); // Must have matched and had nothing before or after return !!(match && match[1] == "" && match[4]); }; twttr.txt.isValidHashtag = function(hashtag) { if (!hashtag) { return false; } var extracted = twttr.txt.extractHashtags(hashtag); // Should extract the hashtag minus the # sign, hence the .slice(1) return extracted.length === 1 && extracted[0] === hashtag.slice(1); }; twttr.txt.isValidUrl = function(url, unicodeDomains, requireProtocol) { if (unicodeDomains == null) { unicodeDomains = true; } if (requireProtocol == null) { requireProtocol = true; } if (!url) { return false; } var urlParts = url.match(twttr.txt.regexen.validateUrlUnencoded); if (!urlParts || urlParts[0] !== url) { return false; } var scheme = urlParts[1], authority = urlParts[2], path = urlParts[3], query = urlParts[4], fragment = urlParts[5]; if (!( (!requireProtocol || (isValidMatch(scheme, twttr.txt.regexen.validateUrlScheme) && scheme.match(/^https?$/i))) && isValidMatch(path, twttr.txt.regexen.validateUrlPath) && isValidMatch(query, twttr.txt.regexen.validateUrlQuery, true) && isValidMatch(fragment, twttr.txt.regexen.validateUrlFragment, true) )) { return false; } return (unicodeDomains && isValidMatch(authority, twttr.txt.regexen.validateUrlUnicodeAuthority)) || (!unicodeDomains && isValidMatch(authority, twttr.txt.regexen.validateUrlAuthority)); }; function isValidMatch(string, regex, optional) { if (!optional) { // RegExp["$&"] is the text of the last match // blank strings are ok, but are falsy, so we check stringiness instead of truthiness return ((typeof string === "string") && string.match(regex) && RegExp["$&"] === string); } // RegExp["$&"] is the text of the last match return (!string || (string.match(regex) && RegExp["$&"] === string)); } if (typeof module != 'undefined' && module.exports) { module.exports = twttr.txt; } if (typeof window != 'undefined') { if (window.twttr) { for (var prop in twttr) { window.twttr[prop] = twttr[prop]; } } else { window.twttr = twttr; } } })();
andrezimpel/djron
wp-content/themes/djron/assets/bower_components/twitter-text/pkg/twitter-text-1.8.0.js
JavaScript
gpl-2.0
55,165
// Authors: // Eric Butler <eric@codebutler.com> register({ name: 'Harvest', sessionCookieNames: [ '_harvest_sess' ], matchPacket: function (packet) { return (packet.host.match(/\.harvestapp.com$/)); }, processPacket: function () { this.siteUrl = 'http://' + this.firstPacket.host; var cookie = this.firstPacket.cookies['_harvest_sess']; var railsSession = RailsHelper.parseSessionCookie(cookie); if (!railsSession.user_id) { this.sessionId = null; return; } this.sessionId = railsSession.session_id; this.firstPacket._harvest_sess = railsSession; }, identifyUser: function () { var resp = this.httpGet(this.siteUrl + '/overview'); this.userName = resp.body.querySelector('.user-area').textContent.split('|')[0].trim(); var company = resp.body.querySelector('#company_bar strong').textContent; this.siteName = 'Harvest (' + company + ')'; } });
gregory-nisbet/firesheep
xpi/handlers/harvest.js
JavaScript
gpl-3.0
929
/* Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'toolbar', 'mn', { toolbarCollapse: 'Collapse Toolbar', // MISSING toolbarExpand: 'Expand Toolbar', // MISSING toolbarGroups: { document: 'Document', clipboard: 'Clipboard/Undo', editing: 'Editing', forms: 'Forms', basicstyles: 'Basic Styles', paragraph: 'Paragraph', links: 'Холбоосууд', insert: 'Оруулах', styles: 'Загварууд', colors: 'Онгөнүүд', tools: 'Хэрэгслүүд' }, toolbars: 'Болосруулагчийн хэрэгслийн самбар' } );
gmuro/dolibarr
htdocs/includes/ckeditor/ckeditor/_source/plugins/toolbar/lang/mn.js
JavaScript
gpl-3.0
694
/** * Sample plugin. */ Draw.loadPlugin(function(ui) { // Adds custom sidebar entry ui.sidebar.addPalette('esolia', 'eSolia', true, function(content) { // content.appendChild(ui.sidebar.createVertexTemplate(null, 120, 60)); content.appendChild(ui.sidebar.createVertexTemplate('shape=image;image=http://download.esolia.net.s3.amazonaws.com/img/eSolia-Logo-Color.svg;resizable=0;movable=0;rotatable=0', 100, 100)); content.appendChild(ui.sidebar.createVertexTemplate('text;spacingTop=-5;fontFamily=Courier New;fontSize=8;fontColor=#999999;resizable=0;movable=0;rotatable=0', 100, 100)); content.appendChild(ui.sidebar.createVertexTemplate('rounded=1;whiteSpace=wrap;gradientColor=none;fillColor=#004C99;shadow=1;strokeColor=#FFFFFF;align=center;fontColor=#FFFFFF;strokeWidth=3;fontFamily=Courier New;verticalAlign=middle', 100, 100)); content.appendChild(ui.sidebar.createVertexTemplate('curved=1;strokeColor=#004C99;endArrow=oval;endFill=0;strokeWidth=3;shadow=1;dashed=1', 100, 100)); }); // Collapses default sidebar entry and inserts this before var c = ui.sidebar.container; c.firstChild.click(); c.insertBefore(c.lastChild, c.firstChild); c.insertBefore(c.lastChild, c.firstChild); // Adds logo to footer ui.footerContainer.innerHTML = '<img width=50px height=17px align="right" style="margin-top:14px;margin-right:12px;" ' + 'src="http://download.esolia.net.s3.amazonaws.com/img/eSolia-Logo-Color.svg"/>'; // Adds variables in labels (%today, %filename%) var superGetLabel = ui.editor.graph.getLabel; ui.editor.graph.getLabel = function(cell) { var result = superGetLabel.apply(this, arguments); if (result != null) { var today = new Date().toLocaleString(); var file = ui.getCurrentFile(); var filename = (file != null && file.getTitle() != null) ? file.getTitle() : ''; result = result.replace('%today%', today).replace('%filename%', filename); } return result; }; // // Adds resource for action // mxResources.parse('helloWorldAction=Hello, World!'); // // // Adds action // ui.actions.addAction('helloWorldAction', function() { // var ran = Math.floor((Math.random() * 100) + 1); // mxUtils.alert('A random number is ' + ran); // }); // // // Adds menu // ui.menubar.addMenu('Hello, World Menu', function(menu, parent) { // ui.menus.addMenuItem(menu, 'helloWorldAction'); // }); // // // Reorders menubar // ui.menubar.container.insertBefore(ui.menubar.container.lastChild, // ui.menubar.container.lastChild.previousSibling.previousSibling); // // // Adds toolbar button // ui.toolbar.addSeparator(); // var elt = ui.toolbar.addItem('', 'helloWorldAction'); // // // Cannot use built-in sprites // elt.firstChild.style.backgroundImage = 'url(https://www.draw.io/images/logo-small.gif)'; // elt.firstChild.style.backgroundPosition = '2px 3px'; });
wangan/draw.io
war/plugins/p1.js
JavaScript
gpl-3.0
2,961
/** * Copyright 2018 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. */ import {dict} from '../../../src/utils/object'; /** @enum {string} */ export const GrantReason = { 'SUBSCRIBER': 'SUBSCRIBER', 'METERING': 'METERING', }; /** * The single entitlement object. */ export class Entitlement { /** * @param {string} service * @return {!Entitlement} */ static empty(service) { return new Entitlement({ source: '', raw: '', service, granted: false, }); } /** * @param {Object} input * @param {string} [input.source] * @param {string} [input.raw] * @param {string} [input.service] * @param {boolean} [input.granted] * @param {?GrantReason} [input.grantReason] * @param {?JsonObject} [input.dataObject] * @param {?string} [input.decryptedDocumentKey] */ constructor({ source, raw = '', service, granted = false, grantReason = '', dataObject, decryptedDocumentKey, }) { /** @const {string} */ this.raw = raw; /** @const {string} */ this.source = source; /** @type {string} */ this.service = service; /** @const {boolean} */ this.granted = granted; /** @const {?string} */ this.grantReason = grantReason; /** @const {?JsonObject} */ this.data = dataObject; /** @const {?string} */ this.decryptedDocumentKey = decryptedDocumentKey; } /** * Returns json format of entitlements * @return {!JsonObject} */ json() { const entitlementJson = dict({ 'source': this.source, 'service': this.service, 'granted': this.granted, 'grantReason': this.grantReason, 'data': this.data, }); return entitlementJson; } /** * Returns json to be used for pingback. * * @return {!JsonObject} */ jsonForPingback() { return /** @type {!JsonObject} */ (Object.assign( {}, {'raw': this.raw}, this.json() )); } /** * @param {?JsonObject} json * @param {?string} rawData * @return {!Entitlement} */ static parseFromJson(json, rawData = null) { if (!json) { json = dict(); } const raw = rawData || JSON.stringify(json); const source = json['source'] || ''; const granted = json['granted'] || false; const grantReason = json['grantReason']; const dataObject = json['data'] || null; const decryptedDocumentKey = json['decryptedDocumentKey'] || null; return new Entitlement({ source, raw, service: '', granted, grantReason, dataObject, decryptedDocumentKey, }); } /** * Returns if the user is a subscriber. * @return {boolean} */ isSubscriber() { return this.granted && this.grantReason === GrantReason.SUBSCRIBER; } }
dotandads/amphtml
extensions/amp-subscriptions/0.1/entitlement.js
JavaScript
apache-2.0
3,338
import { buildField } from './helpers/builders'; import { expectThatTyping } from './helpers/expectations'; import Keysim from 'keysim'; import FieldKit from '../../src'; import {expect} from 'chai'; testsWithAllKeyboards('FieldKit.CardTextField', function() { var textField; var visa = '4111 1111 1111 1111'; beforeEach(function() { textField = buildField(FieldKit.CardTextField); }); it('uses an adaptive card formatter by default', function() { expect(textField.formatter() instanceof FieldKit.AdaptiveCardFormatter).to.be.true; }); describe('#cardType', function() { it('is VISA when the card number starts with 4', function() { textField.setValue('4'); expect(textField.cardType()).to.equal('visa'); }); it('is DISCOVER when the card number matches', function() { textField.setValue('6011'); expect(textField.cardType()).to.equal('discover'); }); it('is MASTERCARD when the card number matches', function() { textField.setValue('51'); expect(textField.cardType()).to.equal('mastercard'); }); it('is AMEX when the card number matches', function() { textField.setValue('34'); expect(textField.cardType()).to.equal('amex'); }); }); describe('#cardMaskStrategy', function() { describe('when set to None (the default)', function() { beforeEach(function() { textField.setCardMaskStrategy(FieldKit.CardTextField.CardMaskStrategy.None); }); it('does not change the displayed card number on end editing', function() { textField.textFieldDidBeginEditing(); expectThatTyping(visa) .into(textField) .before(() => textField.textFieldDidEndEditing()) .willChange('|') .to(`${visa}|`); }); }); describe('when set to DoneEditing', function() { beforeEach(function() { textField.setCardMaskStrategy(FieldKit.CardTextField.CardMaskStrategy.DoneEditing); }); it('does not change the displayed card number while typing', function() { textField.textFieldDidBeginEditing(); expectThatTyping(visa) .into(textField) .willChange('|') .to(`${visa}|`); }); it('masks the displayed card number on end editing', function() { textField.textFieldDidBeginEditing(); expectThatTyping(visa) .into(textField) .before(() => textField.textFieldDidEndEditing.call(textField)) .willChange('|') .to('•••• •••• •••• 1111|'); }); it('does change the selected range on end editing', function() { textField.textFieldDidBeginEditing(); expectThatTyping('enter').into(textField).willChange(`|${visa}>`).to('•••• •••• •••• 1111|'); }); it('restores the original value on beginning editing', function() { textField.textFieldDidBeginEditing(); expectThatTyping(visa) .into(textField) .before(() => { textField.textFieldDidEndEditing(); textField.textFieldDidBeginEditing(); }) .willChange('|') .to(`${visa}|`); }); it('masks when a value is set before editing', function() { textField.setValue('1234567890123456'); expect(textField.element.value).to.equal('•••• •••• •••• 3456'); }); // PENDING // // it('restores the original value when disabling masking', function() { // type(visa).into(textField); // textField.textFieldDidEndEditing(); // textField.setCardMaskStrategy(FieldKit.CardTextField.CardMaskStrategy.None); // expect(textField.element.value).to.equal(visa); // }); // PENDING // // it('masks the value when enabling masking', function() { // type(visa).into(textField); // textField.textFieldDidEndEditing(); // textField.setCardMaskStrategy(FieldKit.CardTextField.CardMaskStrategy.None); // textField.setCardMaskStrategy(FieldKit.CardTextField.CardMaskStrategy.DoneEditing); // expect(textField.element.value).to.equal('•••• •••• •••• 1111'); // }); }); }); });
square/fieldkit
test/unit/card_text_field_test.js
JavaScript
apache-2.0
4,282
function QueryString() { this.parameters = []; } QueryString.prototype.parameters = function() { for ( var i = 0; i < arguments.length; i++ ) this.addValueParameter( arguments[i] ); } QueryString.prototype.addValueParameter = function( name, identifier, decoder, encoder ) { if ( identifier === undefined || identifier === null ) identifier = name; if ( encoder === undefined || encoder === null ) if ( decoder === undefined || decoder === null ) encoder = "str"; else encoder = decoder; if ( decoder === undefined || decoder === null ) decoder = "str"; var parameter = { 'name' : name, 'identifier' : identifier, 'isArray' : false, 'decoder' : this.valueDecoder( decoder ), 'encoder' : this.valueEncoder( encoder ) } this.parameters.push( parameter ); return this; } QueryString.prototype.addArrayParameter = function( name, identifier, decoder, encoder ) { if ( identifier === undefined || identifier === null ) identifier = name; if ( encoder === undefined || encoder === null ) if ( decoder === undefined || decoder === null ) encoder = "str"; else encoder = decoder; if ( decoder === undefined || decoder === null ) decoder = "str"; var parameter = { 'name' : name, 'identifier' : identifier, 'isArray' : true, 'decoder' : this.arrayDecoder( decoder ), 'encoder' : this.arrayEncoder( encoder ) } this.parameters.push( parameter ); return this; } QueryString.prototype.valueDecoder = function( decoder ) { if ( typeof decoder == "function" ) return decoder; if ( typeof decoder == "string" ) { if ( decoder == "int" ) return function(d) { return parseInt(d,10) } if ( decoder == "float" ) return function(d) { return parseFloat(d) } return function(d) { return d }; } return null; } QueryString.prototype.valueEncoder = function( encoder ) { if ( typeof encoder == "function" ) return encoder; if ( typeof encoder == "string" ) { return function(d) { return String(d) }; } return null; } QueryString.prototype.arrayDecoder = function( decoder ) { if ( typeof decoder == "function" ) return decoder; var g = function(values) { var f = this.valueDecoder(decoder); var states = []; values.forEach( function(d) { states.push( f(d) ) } ); return states; } return g.bind(this); } QueryString.prototype.arrayEncoder = function( encoder ) { if ( typeof encoder == "function" ) return encoder; var g = function(states) { var f = this.valueEncoder(encoder); var values = []; states.forEach( function(d) { values.push( f(d) ) } ); return values; } return g.bind(this); } QueryString.prototype.read = function( states ) { if ( states === undefined || states === null ) states = {}; for ( var i in this.parameters ) { var p = this.parameters[i]; if ( p.isArray ) { var values = this.getValues( p.identifier ); if ( values.length > 0 ) states[p.name] = p.decoder( values ); } else { var value = this.getValue( p.identifier ); if ( value != null ) states[p.name] = p.decoder( value ); } } return states; } QueryString.prototype.write = function( states, replaceBrowserHistoryEntry, pageStates, pageTitle ) { if ( replaceBrowserHistoryEntry === undefined || typeof replaceBrowserHistoryEntry != "boolean" ) replaceBrowserHistoryEntry = false; if ( pageStates === undefined ) pageStates = null; if ( pageTitle === undefined ) pageTitle = null; var s = []; for ( var i in this.parameters ) { var p = this.parameters[i]; if ( p.name in states ) { if ( p.isArray ) { var values = p.encoder( states[p.name] ); for ( var j in values ) if ( values[j].length > 0 ) s.push( p.identifier + "=" + escape( values[j] ) ); } else { var value = p.encoder( states[p.name] ); if ( value.length > 0 ) s.push( p.identifier + "=" + escape( value ) ); } } } var protocol = window.location.protocol; var server = window.location.host; var path = window.location.pathname; var pageURL = protocol + '//' + server + path + ( s.length > 0 ? "?" + s.join( "&" ) : "" ); if ( replaceBrowserHistoryEntry ) history.replaceState( pageStates, pageTitle, pageURL ); else history.pushState( pageStates, pageTitle, pageURL ); } QueryString.prototype.getValue = function( key ) { var regex = this.getKeyRegex( key ); var match = regex.exec( window.location.href ); if ( match === null ) return null; else return unescape( match[1] ); } QueryString.prototype.getValues = function( key ) { var regex = this.getKeyRegex( key ); var matches = window.location.href.match( regex ); if ( matches === null ) return []; else { for ( var i = 0; i < matches.length; i ++ ) { var regex = this.getKeyRegex( key ); var match = regex.exec( matches[i] ); matches[i] = unescape( match[1] ); } return matches; } } QueryString.prototype.getKeyRegex = function( key ) { return new RegExp( "[\\?&]" + key + "=([^&]*)", "g" ); }
YingHsuan/termite_data_server
server_src/static/TermTopicMatrix1/js/QueryString.js
JavaScript
bsd-3-clause
5,152
(async function(testRunner) { var {page, session, dp} = await testRunner.startBlank(` Tests that turning on device emulation with a non-1 device pixel ratio sets the appropriate initial scale. Page scale is reflected by the innerWidth and innerHeight properties. Since the layout width is set to 980 (in the viewport meta tag), and the emulated viewport width is 490 px, the initial scale should be 490/980 = 0.5. i.e. innerWidth=980 innerHeight=640.`); var DeviceEmulator = await testRunner.loadScript('../resources/device-emulator.js'); var deviceEmulator = new DeviceEmulator(testRunner, session); // 980px viewport loaded into a 490x320 screen should load at 0.5 scale. await deviceEmulator.emulate(490, 320, 3); var viewport = 'w=980'; testRunner.log(`Loading page with viewport=${viewport}`); await session.navigate('../resources/device-emulation.html?' + viewport); testRunner.log(await session.evaluate(`dumpMetrics(true)`)); testRunner.completeTest(); })
nwjs/chromium.src
third_party/blink/web_tests/inspector-protocol/emulation/device-emulation-initial-scale.js
JavaScript
bsd-3-clause
1,007
ReactIntl.__addLocaleData({"locale":"tk","pluralRuleFunction":function (n,ord){if(ord)return"other";return n==1?"one":"other"},"fields":{"year":{"displayName":"Year","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}},"month":{"displayName":"Month","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"day":{"displayName":"Day","relative":{"0":"today","1":"tomorrow","-1":"yesterday"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"hour":{"displayName":"Hour","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"minute":{"displayName":"Minute","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"second":{"displayName":"Second","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}}}});
redbrick9/liquid
web-console/src/main/webapp/resources/react-intl/locale-data/tk.js
JavaScript
apache-2.0
966
/* YUI 3.17.2 (build 9c3c78e) Copyright 2014 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add('pjax-base', function (Y, NAME) { /** `Y.Router` extension that provides the core plumbing for enhanced navigation implemented using the pjax technique (HTML5 pushState + Ajax). @module pjax @submodule pjax-base @since 3.5.0 **/ var win = Y.config.win, // The CSS class name used to filter link clicks from only the links which // the pjax enhanced navigation should be used. CLASS_PJAX = Y.ClassNameManager.getClassName('pjax'), /** Fired when navigating to a URL via Pjax. When the `navigate()` method is called or a pjax link is clicked, this event will be fired if the browser supports HTML5 history _and_ the router has a route handler for the specified URL. This is a useful event to listen to for adding a visual loading indicator while the route handlers are busy handling the URL change. @event navigate @param {String} url The URL that the router will dispatch to its route handlers in order to fulfill the enhanced navigation "request". @param {Boolean} [force=false] Whether the enhanced navigation should occur even in browsers without HTML5 history. @param {String} [hash] The hash-fragment (including "#") of the `url`. This will be present when the `url` differs from the current URL only by its hash and `navigateOnHash` has been set to `true`. @param {Event} [originEvent] The event that caused the navigation. Usually this would be a click event from a "pjax" anchor element. @param {Boolean} [replace] Whether or not the current history entry will be replaced, or a new entry will be created. Will default to `true` if the specified `url` is the same as the current URL. @since 3.5.0 **/ EVT_NAVIGATE = 'navigate'; /** `Y.Router` extension that provides the core plumbing for enhanced navigation implemented using the pjax technique (HTML5 `pushState` + Ajax). This makes it easy to enhance the navigation between the URLs of an application in HTML5 history capable browsers by delegating to the router to fulfill the "request" and seamlessly falling-back to using standard full-page reloads in older, less-capable browsers. The `PjaxBase` class isn't useful on its own, but can be mixed into a `Router`-based class to add Pjax functionality to that Router. For a pre-made standalone Pjax router, see the `Pjax` class. var MyRouter = Y.Base.create('myRouter', Y.Router, [Y.PjaxBase], { // ... }); @class PjaxBase @extensionfor Router @since 3.5.0 **/ function PjaxBase() {} PjaxBase.prototype = { // -- Protected Properties ------------------------------------------------- /** Holds the delegated pjax-link click handler. @property _pjaxEvents @type EventHandle @protected @since 3.5.0 **/ // -- Lifecycle Methods ---------------------------------------------------- initializer: function () { this.publish(EVT_NAVIGATE, {defaultFn: this._defNavigateFn}); // Pjax is all about progressively enhancing the navigation between // "pages", so by default we only want to handle and route link clicks // in HTML5 `pushState`-compatible browsers. if (this.get('html5')) { this._pjaxBindUI(); } }, destructor: function () { if (this._pjaxEvents) { this._pjaxEvents.detach(); } }, // -- Public Methods ------------------------------------------------------- /** Navigates to the specified URL if there is a route handler that matches. In browsers capable of using HTML5 history, the navigation will be enhanced by firing the `navigate` event and having the router handle the "request". Non-HTML5 browsers will navigate to the new URL via manipulation of `window.location`. When there is a route handler for the specified URL and it is being navigated to, this method will return `true`, otherwise it will return `false`. **Note:** The specified URL _must_ be of the same origin as the current URL, otherwise an error will be logged and navigation will not occur. This is intended as both a security constraint and a purposely imposed limitation as it does not make sense to tell the router to navigate to a URL on a different scheme, host, or port. @method navigate @param {String} url The URL to navigate to. This must be of the same origin as the current URL. @param {Object} [options] Additional options to configure the navigation. These are mixed into the `navigate` event facade. @param {Boolean} [options.replace] Whether or not the current history entry will be replaced, or a new entry will be created. Will default to `true` if the specified `url` is the same as the current URL. @param {Boolean} [options.force=false] Whether the enhanced navigation should occur even in browsers without HTML5 history. @return {Boolean} `true` if the URL was navigated to, `false` otherwise. @since 3.5.0 **/ navigate: function (url, options) { // The `_navigate()` method expects fully-resolved URLs. url = this._resolveURL(url); if (this._navigate(url, options)) { return true; } if (!this._hasSameOrigin(url)) { Y.error('Security error: The new URL must be of the same origin as the current URL.'); } return false; }, // -- Protected Methods ---------------------------------------------------- /** Utility method to test whether a specified link/anchor node's `href` is of the same origin as the page's current location. This normalize browser inconsistencies with how the `port` is reported for anchor elements (IE reports a value for the default port, e.g. "80"). @method _isLinkSameOrigin @param {Node} link The anchor element to test whether its `href` is of the same origin as the page's current location. @return {Boolean} Whether or not the link's `href` is of the same origin as the page's current location. @protected @since 3.6.0 **/ _isLinkSameOrigin: function (link) { var location = Y.getLocation(), protocol = location.protocol, hostname = location.hostname, port = parseInt(location.port, 10) || null, linkPort; // Link must have the same `protocol` and `hostname` as the page's // currrent location. if (link.get('protocol') !== protocol || link.get('hostname') !== hostname) { return false; } linkPort = parseInt(link.get('port'), 10) || null; // Normalize ports. In most cases browsers use an empty string when the // port is the default port, but IE does weird things with anchor // elements, so to be sure, this will re-assign the default ports before // they are compared. if (protocol === 'http:') { port || (port = 80); linkPort || (linkPort = 80); } else if (protocol === 'https:') { port || (port = 443); linkPort || (linkPort = 443); } // Finally, to be from the same origin, the link's `port` must match the // page's current `port`. return linkPort === port; }, /** Underlying implementation for `navigate()`. @method _navigate @param {String} url The fully-resolved URL that the router should dispatch to its route handlers to fulfill the enhanced navigation "request", or use to update `window.location` in non-HTML5 history capable browsers. @param {Object} [options] Additional options to configure the navigation. These are mixed into the `navigate` event facade. @param {Boolean} [options.replace] Whether or not the current history entry will be replaced, or a new entry will be created. Will default to `true` if the specified `url` is the same as the current URL. @param {Boolean} [options.force=false] Whether the enhanced navigation should occur even in browsers without HTML5 history. @return {Boolean} `true` if the URL was navigated to, `false` otherwise. @protected @since 3.5.0 **/ _navigate: function (url, options) { url = this._upgradeURL(url); // Navigation can only be enhanced if there is a route-handler. if (!this.hasRoute(url)) { return false; } // Make a copy of `options` before modifying it. options = Y.merge(options, {url: url}); var currentURL = this._getURL(), hash, hashlessURL; // Captures the `url`'s hash and returns a URL without that hash. hashlessURL = url.replace(/(#.*)$/, function (u, h, i) { hash = h; return u.substring(i); }); if (hash && hashlessURL === currentURL.replace(/#.*$/, '')) { // When the specified `url` and current URL only differ by the hash, // the browser should handle this in-page navigation normally. if (!this.get('navigateOnHash')) { return false; } options.hash = hash; } // When navigating to the same URL as the current URL, behave like a // browser and replace the history entry instead of creating a new one. 'replace' in options || (options.replace = url === currentURL); // The `navigate` event will only fire and therefore enhance the // navigation to the new URL in HTML5 history enabled browsers or when // forced. Otherwise it will fallback to assigning or replacing the URL // on `window.location`. if (this.get('html5') || options.force) { this.fire(EVT_NAVIGATE, options); } else if (win) { if (options.replace) { win.location.replace(url); } else { win.location = url; } } return true; }, /** Binds the delegation of link-click events that match the `linkSelector` to the `_onLinkClick()` handler. By default this method will only be called if the browser is capable of using HTML5 history. @method _pjaxBindUI @protected @since 3.5.0 **/ _pjaxBindUI: function () { // Only bind link if we haven't already. if (!this._pjaxEvents) { this._pjaxEvents = Y.one('body').delegate('click', this._onLinkClick, this.get('linkSelector'), this); } }, // -- Protected Event Handlers --------------------------------------------- /** Default handler for the `navigate` event. Adds a new history entry or replaces the current entry for the specified URL and will scroll the page to the top if configured to do so. @method _defNavigateFn @param {EventFacade} e @protected @since 3.5.0 **/ _defNavigateFn: function (e) { this[e.replace ? 'replace' : 'save'](e.url); if (win && this.get('scrollToTop')) { // Scroll to the top of the page. The timeout ensures that the // scroll happens after navigation begins, so that the current // scroll position will be restored if the user clicks the back // button. setTimeout(function () { win.scroll(0, 0); }, 1); } }, /** Handler for delegated link-click events which match the `linkSelector`. This will attempt to enhance the navigation to the link element's `href` by passing the URL to the `_navigate()` method. When the navigation is being enhanced, the default action is prevented. If the user clicks a link with the middle/right mouse buttons, or is holding down the Ctrl or Command keys, this method's behavior is not applied and allows the native behavior to occur. Similarly, if the router is not capable or handling the URL because no route-handlers match, the link click will behave natively. @method _onLinkClick @param {EventFacade} e @protected @since 3.5.0 **/ _onLinkClick: function (e) { var link, url, navigated; // Allow the native behavior on middle/right-click, or when Ctrl or // Command are pressed. if (e.button !== 1 || e.ctrlKey || e.metaKey) { return; } link = e.currentTarget; // Only allow anchor elements because we need access to its `protocol`, // `host`, and `href` attributes. if (link.get('tagName').toUpperCase() !== 'A') { return; } // Same origin check to prevent trying to navigate to URLs from other // sites or things like mailto links. if (!this._isLinkSameOrigin(link)) { return; } // All browsers fully resolve an anchor's `href` property. url = link.get('href'); // Try and navigate to the URL via the router, and prevent the default // link-click action if we do. if (url) { navigated = this._navigate(url, {originEvent: e}); if (navigated) { e.preventDefault(); } } } }; PjaxBase.ATTRS = { /** CSS selector string used to filter link click events so that only the links which match it will have the enhanced navigation behavior of Pjax applied. When a link is clicked and that link matches this selector, Pjax will attempt to dispatch to any route handlers matching the link's `href` URL. If HTML5 history is not supported or if no route handlers match, the link click will be handled by the browser just like any old link. @attribute linkSelector @type String|Function @default "a.yui3-pjax" @initOnly @since 3.5.0 **/ linkSelector: { value : 'a.' + CLASS_PJAX, writeOnce: 'initOnly' }, /** Whether navigating to a hash-fragment identifier on the current page should be enhanced and cause the `navigate` event to fire. By default Pjax allows the browser to perform its default action when a user is navigating within a page by clicking in-page links (e.g. `<a href="#top">Top of page</a>`) and does not attempt to interfere or enhance in-page navigation. @attribute navigateOnHash @type Boolean @default false @since 3.5.0 **/ navigateOnHash: { value: false }, /** Whether the page should be scrolled to the top after navigating to a URL. When the user clicks the browser's back button, the previous scroll position will be maintained. @attribute scrollToTop @type Boolean @default true @since 3.5.0 **/ scrollToTop: { value: true } }; Y.PjaxBase = PjaxBase; }, '3.17.2', {"requires": ["classnamemanager", "node-event-delegate", "router"]});
gdomingos/Wegas
wegas-resources/src/main/webapp/lib/yui3/build/pjax-base/pjax-base.js
JavaScript
mit
15,159
'use strict'; /** Highest positive signed 32-bit float value */ const maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1 /** Bootstring parameters */ const base = 36; const tMin = 1; const tMax = 26; const skew = 38; const damp = 700; const initialBias = 72; const initialN = 128; // 0x80 const delimiter = '-'; // '\x2D' /** Regular expressions */ const regexPunycode = /^xn--/; const regexNonASCII = /[^\x20-\x7E]/; // unprintable ASCII chars + non-ASCII chars const regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators /** Error messages */ const errors = { 'overflow': 'Overflow: input needs wider integers to process', 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', 'invalid-input': 'Invalid input' }; /** Convenience shortcuts */ const baseMinusTMin = base - tMin; const floor = Math.floor; const stringFromCharCode = String.fromCharCode; /*--------------------------------------------------------------------------*/ /** * A generic error utility function. * @private * @param {String} type The error type. * @returns {Error} Throws a `RangeError` with the applicable error message. */ function error(type) { throw new RangeError(errors[type]); } /** * A generic `Array#map` utility function. * @private * @param {Array} array The array to iterate over. * @param {Function} callback The function that gets called for every array * item. * @returns {Array} A new array of values returned by the callback function. */ function map(array, fn) { const result = []; let length = array.length; while (length--) { result[length] = fn(array[length]); } return result; } /** * A simple `Array#map`-like wrapper to work with domain name strings or email * addresses. * @private * @param {String} domain The domain name or email address. * @param {Function} callback The function that gets called for every * character. * @returns {Array} A new string of characters returned by the callback * function. */ function mapDomain(string, fn) { const parts = string.split('@'); let result = ''; if (parts.length > 1) { // In email addresses, only the domain name should be punycoded. Leave // the local part (i.e. everything up to `@`) intact. result = parts[0] + '@'; string = parts[1]; } // Avoid `split(regex)` for IE8 compatibility. See #17. string = string.replace(regexSeparators, '\x2E'); const labels = string.split('.'); const encoded = map(labels, fn).join('.'); return result + encoded; } /** * Creates an array containing the numeric code points of each Unicode * character in the string. While JavaScript uses UCS-2 internally, * this function will convert a pair of surrogate halves (each of which * UCS-2 exposes as separate characters) into a single code point, * matching UTF-16. * @see `punycode.ucs2.encode` * @see <https://mathiasbynens.be/notes/javascript-encoding> * @memberOf punycode.ucs2 * @name decode * @param {String} string The Unicode input string (UCS-2). * @returns {Array} The new array of code points. */ function ucs2decode(string) { const output = []; let counter = 0; const length = string.length; while (counter < length) { const value = string.charCodeAt(counter++); if (value >= 0xD800 && value <= 0xDBFF && counter < length) { // It's a high surrogate, and there is a next character. const extra = string.charCodeAt(counter++); if ((extra & 0xFC00) == 0xDC00) { // Low surrogate. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); } else { // It's an unmatched surrogate; only append this code unit, in case the // next code unit is the high surrogate of a surrogate pair. output.push(value); counter--; } } else { output.push(value); } } return output; } /** * Creates a string based on an array of numeric code points. * @see `punycode.ucs2.decode` * @memberOf punycode.ucs2 * @name encode * @param {Array} codePoints The array of numeric code points. * @returns {String} The new Unicode string (UCS-2). */ const ucs2encode = array => String.fromCodePoint(...array); /** * Converts a basic code point into a digit/integer. * @see `digitToBasic()` * @private * @param {Number} codePoint The basic numeric code point value. * @returns {Number} The numeric value of a basic code point (for use in * representing integers) in the range `0` to `base - 1`, or `base` if * the code point does not represent a value. */ const basicToDigit = function(codePoint) { if (codePoint - 0x30 < 0x0A) { return codePoint - 0x16; } if (codePoint - 0x41 < 0x1A) { return codePoint - 0x41; } if (codePoint - 0x61 < 0x1A) { return codePoint - 0x61; } return base; }; /** * Converts a digit/integer into a basic code point. * @see `basicToDigit()` * @private * @param {Number} digit The numeric value of a basic code point. * @returns {Number} The basic code point whose value (when used for * representing integers) is `digit`, which needs to be in the range * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is * used; else, the lowercase form is used. The behavior is undefined * if `flag` is non-zero and `digit` has no uppercase form. */ const digitToBasic = function(digit, flag) { // 0..25 map to ASCII a..z or A..Z // 26..35 map to ASCII 0..9 return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); }; /** * Bias adaptation function as per section 3.4 of RFC 3492. * https://tools.ietf.org/html/rfc3492#section-3.4 * @private */ const adapt = function(delta, numPoints, firstTime) { let k = 0; delta = firstTime ? floor(delta / damp) : delta >> 1; delta += floor(delta / numPoints); for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { delta = floor(delta / baseMinusTMin); } return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); }; /** * Converts a Punycode string of ASCII-only symbols to a string of Unicode * symbols. * @memberOf punycode * @param {String} input The Punycode string of ASCII-only symbols. * @returns {String} The resulting string of Unicode symbols. */ const decode = function(input) { // Don't use UCS-2. const output = []; const inputLength = input.length; let i = 0; let n = initialN; let bias = initialBias; // Handle the basic code points: let `basic` be the number of input code // points before the last delimiter, or `0` if there is none, then copy // the first basic code points to the output. let basic = input.lastIndexOf(delimiter); if (basic < 0) { basic = 0; } for (var j = 0; j < basic; ++j) { // if it's not a basic code point if (input.charCodeAt(j) >= 0x80) { error('not-basic'); } output.push(input.charCodeAt(j)); } // Main decoding loop: start just after the last delimiter if any basic code // points were copied; start at the beginning otherwise. for (var index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { // `index` is the index of the next character to be consumed. // Decode a generalized variable-length integer into `delta`, // which gets added to `i`. The overflow checking is easier // if we increase `i` as we go, then subtract off its starting // value at the end to obtain `delta`. let oldi = i; for (var w = 1, k = base; /* no condition */; k += base) { if (index >= inputLength) { error('invalid-input'); } const digit = basicToDigit(input.charCodeAt(index++)); if (digit >= base || digit > floor((maxInt - i) / w)) { error('overflow'); } i += digit * w; const t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); if (digit < t) { break; } const baseMinusT = base - t; if (w > floor(maxInt / baseMinusT)) { error('overflow'); } w *= baseMinusT; } const out = output.length + 1; bias = adapt(i - oldi, out, oldi == 0); // `i` was supposed to wrap around from `out` to `0`, // incrementing `n` each time, so we'll fix that now: if (floor(i / out) > maxInt - n) { error('overflow'); } n += floor(i / out); i %= out; // Insert `n` at position `i` of the output. output.splice(i++, 0, n); } return String.fromCodePoint(...output); }; /** * Converts a string of Unicode symbols (e.g. a domain name label) to a * Punycode string of ASCII-only symbols. * @memberOf punycode * @param {String} input The string of Unicode symbols. * @returns {String} The resulting Punycode string of ASCII-only symbols. */ const encode = function(input) { const output = []; // Convert the input in UCS-2 to an array of Unicode code points. input = ucs2decode(input); // Cache the length. let inputLength = input.length; // Initialize the state. let n = initialN; let delta = 0; let bias = initialBias; // Handle the basic code points. for (const currentValue of input) { if (currentValue < 0x80) { output.push(stringFromCharCode(currentValue)); } } let basicLength = output.length; let handledCPCount = basicLength; // `handledCPCount` is the number of code points that have been handled; // `basicLength` is the number of basic code points. // Finish the basic string with a delimiter unless it's empty. if (basicLength) { output.push(delimiter); } // Main encoding loop: while (handledCPCount < inputLength) { // All non-basic code points < n have been handled already. Find the next // larger one: let m = maxInt; for (const currentValue of input) { if (currentValue >= n && currentValue < m) { m = currentValue; } } // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>, // but guard against overflow. const handledCPCountPlusOne = handledCPCount + 1; if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { error('overflow'); } delta += (m - n) * handledCPCountPlusOne; n = m; for (const currentValue of input) { if (currentValue < n && ++delta > maxInt) { error('overflow'); } if (currentValue == n) { // Represent delta as a generalized variable-length integer. let q = delta; for (var k = base; /* no condition */; k += base) { const t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); if (q < t) { break; } const qMinusT = q - t; const baseMinusT = base - t; output.push( stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) ); q = floor(qMinusT / baseMinusT); } output.push(stringFromCharCode(digitToBasic(q, 0))); bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); delta = 0; ++handledCPCount; } } ++delta; ++n; } return output.join(''); }; /** * Converts a Punycode string representing a domain name or an email address * to Unicode. Only the Punycoded parts of the input will be converted, i.e. * it doesn't matter if you call it on a string that has already been * converted to Unicode. * @memberOf punycode * @param {String} input The Punycoded domain name or email address to * convert to Unicode. * @returns {String} The Unicode representation of the given Punycode * string. */ const toUnicode = function(input) { return mapDomain(input, function(string) { return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string; }); }; /** * Converts a Unicode string representing a domain name or an email address to * Punycode. Only the non-ASCII parts of the domain name will be converted, * i.e. it doesn't matter if you call it with a domain that's already in * ASCII. * @memberOf punycode * @param {String} input The domain name or email address to convert, as a * Unicode string. * @returns {String} The Punycode representation of the given domain name or * email address. */ const toASCII = function(input) { return mapDomain(input, function(string) { return regexNonASCII.test(string) ? 'xn--' + encode(string) : string; }); }; /*--------------------------------------------------------------------------*/ /** Define the public API */ const punycode = { /** * A string representing the current Punycode.js version number. * @memberOf punycode * @type String */ 'version': '2.0.0', /** * An object of methods to convert from JavaScript's internal character * representation (UCS-2) to Unicode code points, and back. * @see <https://mathiasbynens.be/notes/javascript-encoding> * @memberOf punycode * @type Object */ 'ucs2': { 'decode': ucs2decode, 'encode': ucs2encode }, 'decode': decode, 'encode': encode, 'toASCII': toASCII, 'toUnicode': toUnicode }; module.exports = punycode;
MTASZTAKI/ApertusVR
plugins/languageAPI/jsAPI/3rdParty/nodejs/10.1.0/source/lib/punycode.js
JavaScript
mit
12,589
var TabsSelect = React.createClass({ getInitialState: function() { return { key: '1' }; }, handleSelect: function(key) { console.log('你点击了:', key); this.setState({ key: key }); }, render: function() { return ( <Tabs defaultActiveKey={this.state.key} onSelect={this.handleSelect}> <Tabs.Item eventKey="1" title="恣意"> 置身人群中<br />你只需要被淹没 享受 沉默<br />退到人群后<br />你只需给予双手 微笑 等候 </Tabs.Item> <Tabs.Item eventKey="2" title="等候"> 走在忠孝东路<br />徘徊在茫然中<br />在我的人生旅途<br />选择了多少错误<br />我在睡梦中惊醒<br />感叹悔言无尽<br />恨我不能说服自己<br />接受一切教训<br />让生命去等候<br />等候下一个漂流<br />让生命去等候<br />等候下一个伤口 </Tabs.Item> <Tabs.Item eventKey="3" title="流浪" disabled> 我就这样告别山下的家,我实在不愿轻易让眼泪留下。我以为我并不差不会害怕,我就这样自己照顾自己长大。我不想因为现实把头低下,我以为我并不差能学会虚假。怎样才能够看穿面具里的谎话?别让我的真心散的像沙。如果有一天我变得更复杂,还能不能唱出歌声里的那幅画? </Tabs.Item> </Tabs> ); } }); React.render(<TabsSelect />, mountNode);
Pyiner/amazeui-react
docs/tabs/03-select.js
JavaScript
mit
1,461