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 todomvc */
(function () {
'use strict';
/**
* The main controller for the app. The controller:
* - retrieves and persists the model via the todoStorage service
* - exposes the model to the template and provides event handlers
*/
todomvc.controller('TodoCtrl', function TodoCtrl($scope, $location, todoStorage, filterFilter, $speechRecognition) {
var todos = $scope.todos = todoStorage.get();
$scope.newTodo = '';
$scope.remainingCount = filterFilter(todos, {completed: false}).length;
$scope.editedTodo = null;
if ($location.path() === '') {
$location.path('/');
}
$scope.location = $location;
$scope.$watch('location.path()', function (path) {
$scope.statusFilter = (path === '/active') ?
{ completed: false } : (path === '/completed') ?
{ completed: true } : null;
});
$scope.$watch('remainingCount == 0', function (val) {
$scope.allChecked = val;
});
$scope.addTodo = function () {
var newTodo = $scope.newTodo.trim();
console.log(newTodo);
if (newTodo.length === 0) {
return;
}
todos.push({
title: newTodo,
completed: false
});
todoStorage.put(todos);
console.log(todos);
$scope.newTodo = '';
$scope.remainingCount++;
};
$scope.editTodo = function (todo) {
$scope.editedTodo = todo;
};
$scope.doneEditing = function (todo) {
$scope.editedTodo = null;
todo.title = todo.title.trim();
if (!todo.title) {
$scope.removeTodo(todo);
}
todoStorage.put(todos);
};
$scope.removeTodo = function (todo) {
$scope.remainingCount -= todo.completed ? 0 : 1;
todos.splice(todos.indexOf(todo), 1);
todoStorage.put(todos);
};
$scope.todoCompleted = function (todo) {
if (todo.completed) {
$scope.remainingCount--;
} else {
$scope.remainingCount++;
}
todoStorage.put(todos);
};
$scope.clearCompletedTodos = function () {
$scope.todos = todos = todos.filter(function (val) {
return !val.completed;
});
todoStorage.put(todos);
};
$scope.markAll = function (completed) {
todos.forEach(function (todo) {
todo.completed = completed;
});
$scope.remainingCount = completed ? 0 : todos.length;
todoStorage.put(todos);
};
/**
* Need to be added for speech recognition
*/
var findTodo = function(title){
for (var i=0; i<todos.length; i++){
if (todos[i].title === title) {
return todos[i];
}
}
return null;
};
var completeTodo = function(title){
for (var i=0; i<todos.length; i++){
if (todos[i].title === title) {
todos[i].completed = ! todos[i].completed;
$scope.todoCompleted(todos[i]);
$scope.$apply();
return true;
}
}
};
var LANG = 'en-US';
$speechRecognition.onstart(function(e){
$speechRecognition.speak('Yes? How can I help you?');
});
$speechRecognition.onerror(function(e){
var error = (e.error || '');
alert('An error occurred ' + error);
});
$speechRecognition.payAttention();
// $speechRecognition.setLang(LANG);
$speechRecognition.listen();
$scope.recognition = {};
$scope.recognition['en-US'] = {
'addToList': {
'regex': /^do .+/gi,
'lang': 'en-US',
'call': function(utterance){
var parts = utterance.split(' ');
if (parts.length > 1) {
$scope.newTodo = parts.slice(1).join(' ');
$scope.addTodo();
$scope.$apply();
}
}
},
'show-all': {
'regex': /show.*all/gi,
'lang': 'en-US',
'call': function(utterance){
$location.path('/');
$scope.$apply();
}
},
'show-active': {
'regex': /show.*active/gi,
'lang': 'en-US',
'call': function(utterance){
$location.path('/active');
$scope.$apply();
}
},
'show-completed': {
'regex': /show.*complete/gi,
'lang': 'en-US',
'call': function(utterance){
$location.path('/completed');
$scope.$apply();
}
},
'mark-all': {
'regex': /^mark/gi,
'lang': 'en-US',
'call': function(utterance){
$scope.markAll(1);
$scope.$apply();
}
},
'unmark-all': {
'regex': /^unmark/gi,
'lang': 'en-US',
'call': function(utterance){
$scope.markAll(1);
$scope.$apply();
}
},
'clear-completed': {
'regex': /clear.*/gi,
'lang': 'en-US',
'call': function(utterance){
$scope.clearCompletedTodos();
$scope.$apply();
}
},
'listTasks': [{
'regex': /^complete .+/gi,
'lang': 'en-US',
'call': function(utterance){
var parts = utterance.split(' ');
if (parts.length > 1) {
completeTodo(parts.slice(1).join(' '));
}
}
},{
'regex': /^remove .+/gi,
'lang': 'en-US',
'call': function(utterance){
var parts = utterance.split(' ');
if (parts.length > 1) {
var todo = findTodo(parts.slice(1).join(' '));
console.log(todo);
if (todo) {
$scope.removeTodo(todo);
$scope.$apply();
}
}
}
}]
};
var ignoreUtterance = {};
ignoreUtterance['addToList'] = $speechRecognition.listenUtterance($scope.recognition['en-US']['addToList']);
ignoreUtterance['show-all'] = $speechRecognition.listenUtterance($scope.recognition['en-US']['show-all']);
ignoreUtterance['show-active'] = $speechRecognition.listenUtterance($scope.recognition['en-US']['show-active']);
ignoreUtterance['show-completed'] = $speechRecognition.listenUtterance($scope.recognition['en-US']['show-completed']);
ignoreUtterance['mark-all'] = $speechRecognition.listenUtterance($scope.recognition['en-US']['mark-all']);
ignoreUtterance['unmark-all'] = $speechRecognition.listenUtterance($scope.recognition['en-US']['unmark-all']);
ignoreUtterance['clear-completed'] = $speechRecognition.listenUtterance($scope.recognition['en-US']['clear-completed']);
/*
to ignore listener call returned function
*/
// ignoreUtterance['addToList']();
});
}()); | xtrasmal/adaptive-speech | demo/js/controllers/todoCtrl.js | JavaScript | mit | 5,691 |
'use strict';
var gulp = require('gulp');
var shell = require('gulp-shell');
module.exports = function () {
gulp.task('git-add', function () {
return gulp.src('*.js', {
read: false
}).pipe(shell(['git ls-files --others docroot/sites/all | egrep \'.css|.js|.png|.map\' | xargs git add -f']));
});
};
| six519/disclose.ph | gulp/git.js | JavaScript | mit | 318 |
#!/usr/bin/env node
'use strict';
/**
* bitcoind.js example
*/
process.title = 'bitcoind.js';
/**
* daemon
*/
var daemon = require('../').daemon({
datadir: process.env.BITCOINDJS_DIR || '~/.bitcoin',
});
daemon.on('ready', function() {
console.log('ready');
});
daemon.on('tx', function(txid) {
console.log('txid', txid);
});
daemon.on('error', function(err) {
daemon.log('error="%s"', err.message);
});
daemon.on('open', function(status) {
daemon.log('status="%s"', status);
});
| bankonme/bitcoind.js | example/index.js | JavaScript | mit | 502 |
var path = require('path');
var util = require('util');
var Item = require('./item');
var constants = process.binding('constants');
/**
* A directory.
* @constructor
*/
function Directory() {
Item.call(this);
/**
* Items in this directory.
* @type {Object.<string, Item>}
*/
this._items = {};
/**
* Permissions.
*/
this._mode = 0777;
}
util.inherits(Directory, Item);
/**
* Add an item to the directory.
* @param {string} name The name to give the item.
* @param {Item} item The item to add.
* @return {Item} The added item.
*/
Directory.prototype.addItem = function(name, item) {
if (this._items.hasOwnProperty(name)) {
throw new Error('Item with the same name already exists: ' + name);
}
this._items[name] = item;
++item.links;
if (item instanceof Directory) {
// for '.' entry
++item.links;
// for subdirectory
++this.links;
}
this.setMTime(new Date());
return item;
};
/**
* Get a named item.
* @param {string} name Item name.
* @return {Item} The named item (or null if none).
*/
Directory.prototype.getItem = function(name) {
var item = null;
if (this._items.hasOwnProperty(name)) {
item = this._items[name];
}
return item;
};
/**
* Remove an item.
* @param {string} name Name of item to remove.
* @return {Item} The orphan item.
*/
Directory.prototype.removeItem = function(name) {
if (!this._items.hasOwnProperty(name)) {
throw new Error('Item does not exist in directory: ' + name);
}
var item = this._items[name];
delete this._items[name];
--item.links;
if (item instanceof Directory) {
// for '.' entry
--item.links;
// for subdirectory
--this.links;
}
this.setMTime(new Date());
return item;
};
/**
* Get list of item names in this directory.
* @return {Array.<string>} Item names.
*/
Directory.prototype.list = function() {
return Object.keys(this._items).sort();
};
/**
* Get directory stats.
* @return {Object} Stats properties.
*/
Directory.prototype.getStats = function() {
var stats = Item.prototype.getStats.call(this);
stats.mode = this.getMode() | constants.S_IFDIR;
stats.size = 1;
stats.blocks = 1;
return stats;
};
/**
* Export the constructor.
* @type {function()}
*/
exports = module.exports = Directory;
| wenjoy/homePage | node_modules/node-captcha/node_modules/canvas/node_modules/mocha/node_modules/mkdirp/node_modules/mock-fs/lib/directory.js | JavaScript | mit | 2,300 |
// Copyright 2006 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 Wrapper class for handling XmlHttpRequests.
*
* One off requests can be sent through goog.net.XhrIo.send() or an
* instance can be created to send multiple requests. Each request uses its
* own XmlHttpRequest object and handles clearing of the event callback to
* ensure no leaks.
*
* XhrIo is event based, it dispatches events on success, failure, finishing,
* ready-state change, or progress (download and upload).
*
* The ready-state or timeout event fires first, followed by
* a generic completed event. Then the abort, error, or success event
* is fired as appropriate. Progress events are fired as they are
* received. Lastly, the ready event will fire to indicate that the
* object may be used to make another request.
*
* The error event may also be called before completed and
* ready-state-change if the XmlHttpRequest.open() or .send() methods throw.
*
* This class does not support multiple requests, queuing, or prioritization.
*
* When progress events are supported by the browser, and progress is
* enabled via .setProgressEventsEnabled(true), the
* goog.net.EventType.PROGRESS event will be the re-dispatched browser
* progress event. Additionally, a DOWNLOAD_PROGRESS or UPLOAD_PROGRESS event
* will be fired for download and upload progress respectively.
*
*/
goog.provide('goog.net.XhrIo');
goog.provide('goog.net.XhrIo.ResponseType');
goog.require('goog.Timer');
goog.require('goog.array');
goog.require('goog.asserts');
goog.require('goog.debug.entryPointRegistry');
goog.require('goog.events.EventTarget');
goog.require('goog.json');
goog.require('goog.log');
goog.require('goog.net.ErrorCode');
goog.require('goog.net.EventType');
goog.require('goog.net.HttpStatus');
goog.require('goog.net.XmlHttp');
goog.require('goog.object');
goog.require('goog.string');
goog.require('goog.structs');
goog.require('goog.structs.Map');
goog.require('goog.uri.utils');
goog.require('goog.userAgent');
goog.forwardDeclare('goog.Uri');
/**
* Basic class for handling XMLHttpRequests.
* @param {goog.net.XmlHttpFactory=} opt_xmlHttpFactory Factory to use when
* creating XMLHttpRequest objects.
* @constructor
* @extends {goog.events.EventTarget}
*/
goog.net.XhrIo = function(opt_xmlHttpFactory) {
goog.net.XhrIo.base(this, 'constructor');
/**
* Map of default headers to add to every request, use:
* XhrIo.headers.set(name, value)
* @type {!goog.structs.Map}
*/
this.headers = new goog.structs.Map();
/**
* Optional XmlHttpFactory
* @private {goog.net.XmlHttpFactory}
*/
this.xmlHttpFactory_ = opt_xmlHttpFactory || null;
/**
* Whether XMLHttpRequest is active. A request is active from the time send()
* is called until onReadyStateChange() is complete, or error() or abort()
* is called.
* @private {boolean}
*/
this.active_ = false;
/**
* The XMLHttpRequest object that is being used for the transfer.
* @private {?goog.net.XhrLike.OrNative}
*/
this.xhr_ = null;
/**
* The options to use with the current XMLHttpRequest object.
* @private {Object}
*/
this.xhrOptions_ = null;
/**
* Last URL that was requested.
* @private {string|goog.Uri}
*/
this.lastUri_ = '';
/**
* Method for the last request.
* @private {string}
*/
this.lastMethod_ = '';
/**
* Last error code.
* @private {!goog.net.ErrorCode}
*/
this.lastErrorCode_ = goog.net.ErrorCode.NO_ERROR;
/**
* Last error message.
* @private {Error|string}
*/
this.lastError_ = '';
/**
* Used to ensure that we don't dispatch an multiple ERROR events. This can
* happen in IE when it does a synchronous load and one error is handled in
* the ready statte change and one is handled due to send() throwing an
* exception.
* @private {boolean}
*/
this.errorDispatched_ = false;
/**
* Used to make sure we don't fire the complete event from inside a send call.
* @private {boolean}
*/
this.inSend_ = false;
/**
* Used in determining if a call to {@link #onReadyStateChange_} is from
* within a call to this.xhr_.open.
* @private {boolean}
*/
this.inOpen_ = false;
/**
* Used in determining if a call to {@link #onReadyStateChange_} is from
* within a call to this.xhr_.abort.
* @private {boolean}
*/
this.inAbort_ = false;
/**
* Number of milliseconds after which an incomplete request will be aborted
* and a {@link goog.net.EventType.TIMEOUT} event raised; 0 means no timeout
* is set.
* @private {number}
*/
this.timeoutInterval_ = 0;
/**
* Timer to track request timeout.
* @private {?number}
*/
this.timeoutId_ = null;
/**
* The requested type for the response. The empty string means use the default
* XHR behavior.
* @private {goog.net.XhrIo.ResponseType}
*/
this.responseType_ = goog.net.XhrIo.ResponseType.DEFAULT;
/**
* Whether a "credentialed" request is to be sent (one that is aware of
* cookies and authentication). This is applicable only for cross-domain
* requests and more recent browsers that support this part of the HTTP Access
* Control standard.
*
* @see http://www.w3.org/TR/XMLHttpRequest/#the-withcredentials-attribute
*
* @private {boolean}
*/
this.withCredentials_ = false;
/**
* Whether progress events are enabled for this request. This is
* disabled by default because setting a progress event handler
* causes pre-flight OPTIONS requests to be sent for CORS requests,
* even in cases where a pre-flight request would not otherwise be
* sent.
*
* @see http://xhr.spec.whatwg.org/#security-considerations
*
* Note that this can cause problems for Firefox 22 and below, as an
* older "LSProgressEvent" will be dispatched by the browser. That
* progress event is no longer supported, and can lead to failures,
* including throwing exceptions.
*
* @see http://bugzilla.mozilla.org/show_bug.cgi?id=845631
* @see b/23469793
*
* @private {boolean}
*/
this.progressEventsEnabled_ = false;
/**
* True if we can use XMLHttpRequest's timeout directly.
* @private {boolean}
*/
this.useXhr2Timeout_ = false;
};
goog.inherits(goog.net.XhrIo, goog.events.EventTarget);
/**
* Response types that may be requested for XMLHttpRequests.
* @enum {string}
* @see http://www.w3.org/TR/XMLHttpRequest/#the-responsetype-attribute
*/
goog.net.XhrIo.ResponseType = {
DEFAULT: '',
TEXT: 'text',
DOCUMENT: 'document',
// Not supported as of Chrome 10.0.612.1 dev
BLOB: 'blob',
ARRAY_BUFFER: 'arraybuffer'
};
/**
* A reference to the XhrIo logger
* @private {goog.debug.Logger}
* @const
*/
goog.net.XhrIo.prototype.logger_ = goog.log.getLogger('goog.net.XhrIo');
/**
* The Content-Type HTTP header name
* @type {string}
*/
goog.net.XhrIo.CONTENT_TYPE_HEADER = 'Content-Type';
/**
* The pattern matching the 'http' and 'https' URI schemes
* @type {!RegExp}
*/
goog.net.XhrIo.HTTP_SCHEME_PATTERN = /^https?$/i;
/**
* The methods that typically come along with form data. We set different
* headers depending on whether the HTTP action is one of these.
*/
goog.net.XhrIo.METHODS_WITH_FORM_DATA = ['POST', 'PUT'];
/**
* The Content-Type HTTP header value for a url-encoded form
* @type {string}
*/
goog.net.XhrIo.FORM_CONTENT_TYPE =
'application/x-www-form-urlencoded;charset=utf-8';
/**
* The XMLHttpRequest Level two timeout delay ms property name.
*
* @see http://www.w3.org/TR/XMLHttpRequest/#the-timeout-attribute
*
* @private {string}
* @const
*/
goog.net.XhrIo.XHR2_TIMEOUT_ = 'timeout';
/**
* The XMLHttpRequest Level two ontimeout handler property name.
*
* @see http://www.w3.org/TR/XMLHttpRequest/#the-timeout-attribute
*
* @private {string}
* @const
*/
goog.net.XhrIo.XHR2_ON_TIMEOUT_ = 'ontimeout';
/**
* All non-disposed instances of goog.net.XhrIo created
* by {@link goog.net.XhrIo.send} are in this Array.
* @see goog.net.XhrIo.cleanup
* @private {!Array<!goog.net.XhrIo>}
*/
goog.net.XhrIo.sendInstances_ = [];
/**
* Static send that creates a short lived instance of XhrIo to send the
* request.
* @see goog.net.XhrIo.cleanup
* @param {string|goog.Uri} url Uri to make request to.
* @param {?function(this:goog.net.XhrIo, ?)=} opt_callback Callback function
* for when request is complete.
* @param {string=} opt_method Send method, default: GET.
* @param {ArrayBuffer|ArrayBufferView|Blob|Document|FormData|string=}
* opt_content Body data.
* @param {Object|goog.structs.Map=} opt_headers Map of headers to add to the
* request.
* @param {number=} opt_timeoutInterval Number of milliseconds after which an
* incomplete request will be aborted; 0 means no timeout is set.
* @param {boolean=} opt_withCredentials Whether to send credentials with the
* request. Default to false. See {@link goog.net.XhrIo#setWithCredentials}.
* @return {!goog.net.XhrIo} The sent XhrIo.
*/
goog.net.XhrIo.send = function(
url, opt_callback, opt_method, opt_content, opt_headers,
opt_timeoutInterval, opt_withCredentials) {
var x = new goog.net.XhrIo();
goog.net.XhrIo.sendInstances_.push(x);
if (opt_callback) {
x.listen(goog.net.EventType.COMPLETE, opt_callback);
}
x.listenOnce(goog.net.EventType.READY, x.cleanupSend_);
if (opt_timeoutInterval) {
x.setTimeoutInterval(opt_timeoutInterval);
}
if (opt_withCredentials) {
x.setWithCredentials(opt_withCredentials);
}
x.send(url, opt_method, opt_content, opt_headers);
return x;
};
/**
* Disposes all non-disposed instances of goog.net.XhrIo created by
* {@link goog.net.XhrIo.send}.
* {@link goog.net.XhrIo.send} cleans up the goog.net.XhrIo instance
* it creates when the request completes or fails. However, if
* the request never completes, then the goog.net.XhrIo is not disposed.
* This can occur if the window is unloaded before the request completes.
* We could have {@link goog.net.XhrIo.send} return the goog.net.XhrIo
* it creates and make the client of {@link goog.net.XhrIo.send} be
* responsible for disposing it in this case. However, this makes things
* significantly more complicated for the client, and the whole point
* of {@link goog.net.XhrIo.send} is that it's simple and easy to use.
* Clients of {@link goog.net.XhrIo.send} should call
* {@link goog.net.XhrIo.cleanup} when doing final
* cleanup on window unload.
*/
goog.net.XhrIo.cleanup = function() {
var instances = goog.net.XhrIo.sendInstances_;
while (instances.length) {
instances.pop().dispose();
}
};
/**
* Installs exception protection for all entry point introduced by
* goog.net.XhrIo instances which are not protected by
* {@link goog.debug.ErrorHandler#protectWindowSetTimeout},
* {@link goog.debug.ErrorHandler#protectWindowSetInterval}, or
* {@link goog.events.protectBrowserEventEntryPoint}.
*
* @param {goog.debug.ErrorHandler} errorHandler Error handler with which to
* protect the entry point(s).
*/
goog.net.XhrIo.protectEntryPoints = function(errorHandler) {
goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_ =
errorHandler.protectEntryPoint(
goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_);
};
/**
* Disposes of the specified goog.net.XhrIo created by
* {@link goog.net.XhrIo.send} and removes it from
* {@link goog.net.XhrIo.pendingStaticSendInstances_}.
* @private
*/
goog.net.XhrIo.prototype.cleanupSend_ = function() {
this.dispose();
goog.array.remove(goog.net.XhrIo.sendInstances_, this);
};
/**
* Returns the number of milliseconds after which an incomplete request will be
* aborted, or 0 if no timeout is set.
* @return {number} Timeout interval in milliseconds.
*/
goog.net.XhrIo.prototype.getTimeoutInterval = function() {
return this.timeoutInterval_;
};
/**
* Sets the number of milliseconds after which an incomplete request will be
* aborted and a {@link goog.net.EventType.TIMEOUT} event raised; 0 means no
* timeout is set.
* @param {number} ms Timeout interval in milliseconds; 0 means none.
*/
goog.net.XhrIo.prototype.setTimeoutInterval = function(ms) {
this.timeoutInterval_ = Math.max(0, ms);
};
/**
* Sets the desired type for the response. At time of writing, this is only
* supported in very recent versions of WebKit (10.0.612.1 dev and later).
*
* If this is used, the response may only be accessed via {@link #getResponse}.
*
* @param {goog.net.XhrIo.ResponseType} type The desired type for the response.
*/
goog.net.XhrIo.prototype.setResponseType = function(type) {
this.responseType_ = type;
};
/**
* Gets the desired type for the response.
* @return {goog.net.XhrIo.ResponseType} The desired type for the response.
*/
goog.net.XhrIo.prototype.getResponseType = function() {
return this.responseType_;
};
/**
* Sets whether a "credentialed" request that is aware of cookie and
* authentication information should be made. This option is only supported by
* browsers that support HTTP Access Control. As of this writing, this option
* is not supported in IE.
*
* @param {boolean} withCredentials Whether this should be a "credentialed"
* request.
*/
goog.net.XhrIo.prototype.setWithCredentials = function(withCredentials) {
this.withCredentials_ = withCredentials;
};
/**
* Gets whether a "credentialed" request is to be sent.
* @return {boolean} The desired type for the response.
*/
goog.net.XhrIo.prototype.getWithCredentials = function() {
return this.withCredentials_;
};
/**
* Sets whether progress events are enabled for this request. Note
* that progress events require pre-flight OPTIONS request handling
* for CORS requests, and may cause trouble with older browsers. See
* progressEventsEnabled_ for details.
* @param {boolean} enabled Whether progress events should be enabled.
*/
goog.net.XhrIo.prototype.setProgressEventsEnabled = function(enabled) {
this.progressEventsEnabled_ = enabled;
};
/**
* Gets whether progress events are enabled.
* @return {boolean} Whether progress events are enabled for this request.
*/
goog.net.XhrIo.prototype.getProgressEventsEnabled = function() {
return this.progressEventsEnabled_;
};
/**
* Instance send that actually uses XMLHttpRequest to make a server call.
* @param {string|goog.Uri} url Uri to make request to.
* @param {string=} opt_method Send method, default: GET.
* @param {ArrayBuffer|ArrayBufferView|Blob|Document|FormData|string=}
* opt_content Body data.
* @param {Object|goog.structs.Map=} opt_headers Map of headers to add to the
* request.
*/
goog.net.XhrIo.prototype.send = function(
url, opt_method, opt_content, opt_headers) {
if (this.xhr_) {
throw Error(
'[goog.net.XhrIo] Object is active with another request=' +
this.lastUri_ + '; newUri=' + url);
}
var method = opt_method ? opt_method.toUpperCase() : 'GET';
this.lastUri_ = url;
this.lastError_ = '';
this.lastErrorCode_ = goog.net.ErrorCode.NO_ERROR;
this.lastMethod_ = method;
this.errorDispatched_ = false;
this.active_ = true;
// Use the factory to create the XHR object and options
this.xhr_ = this.createXhr();
this.xhrOptions_ = this.xmlHttpFactory_ ? this.xmlHttpFactory_.getOptions() :
goog.net.XmlHttp.getOptions();
// Set up the onreadystatechange callback
this.xhr_.onreadystatechange = goog.bind(this.onReadyStateChange_, this);
// Set up upload/download progress events, if progress events are supported.
if (this.getProgressEventsEnabled() && 'onprogress' in this.xhr_) {
this.xhr_.onprogress =
goog.bind(function(e) { this.onProgressHandler_(e, true); }, this);
if (this.xhr_.upload) {
this.xhr_.upload.onprogress = goog.bind(this.onProgressHandler_, this);
}
}
/**
* Try to open the XMLHttpRequest (always async), if an error occurs here it
* is generally permission denied
* @preserveTry
*/
try {
goog.log.fine(this.logger_, this.formatMsg_('Opening Xhr'));
this.inOpen_ = true;
this.xhr_.open(method, String(url), true); // Always async!
this.inOpen_ = false;
} catch (err) {
goog.log.fine(
this.logger_, this.formatMsg_('Error opening Xhr: ' + err.message));
this.error_(goog.net.ErrorCode.EXCEPTION, err);
return;
}
// We can't use null since this won't allow requests with form data to have a
// content length specified which will cause some proxies to return a 411
// error.
var content = opt_content || '';
var headers = this.headers.clone();
// Add headers specific to this request
if (opt_headers) {
goog.structs.forEach(
opt_headers, function(value, key) { headers.set(key, value); });
}
// Find whether a content type header is set, ignoring case.
// HTTP header names are case-insensitive. See:
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2
var contentTypeKey =
goog.array.find(headers.getKeys(), goog.net.XhrIo.isContentTypeHeader_);
var contentIsFormData =
(goog.global['FormData'] && (content instanceof goog.global['FormData']));
if (goog.array.contains(goog.net.XhrIo.METHODS_WITH_FORM_DATA, method) &&
!contentTypeKey && !contentIsFormData) {
// For requests typically with form data, default to the url-encoded form
// content type unless this is a FormData request. For FormData,
// the browser will automatically add a multipart/form-data content type
// with an appropriate multipart boundary.
headers.set(
goog.net.XhrIo.CONTENT_TYPE_HEADER, goog.net.XhrIo.FORM_CONTENT_TYPE);
}
// Add the headers to the Xhr object
headers.forEach(function(value, key) {
this.xhr_.setRequestHeader(key, value);
}, this);
if (this.responseType_) {
this.xhr_.responseType = this.responseType_;
}
if (goog.object.containsKey(this.xhr_, 'withCredentials')) {
this.xhr_.withCredentials = this.withCredentials_;
}
/**
* Try to send the request, or other wise report an error (404 not found).
* @preserveTry
*/
try {
this.cleanUpTimeoutTimer_(); // Paranoid, should never be running.
if (this.timeoutInterval_ > 0) {
this.useXhr2Timeout_ = goog.net.XhrIo.shouldUseXhr2Timeout_(this.xhr_);
goog.log.fine(
this.logger_, this.formatMsg_(
'Will abort after ' + this.timeoutInterval_ +
'ms if incomplete, xhr2 ' + this.useXhr2Timeout_));
if (this.useXhr2Timeout_) {
this.xhr_[goog.net.XhrIo.XHR2_TIMEOUT_] = this.timeoutInterval_;
this.xhr_[goog.net.XhrIo.XHR2_ON_TIMEOUT_] =
goog.bind(this.timeout_, this);
} else {
this.timeoutId_ =
goog.Timer.callOnce(this.timeout_, this.timeoutInterval_, this);
}
}
goog.log.fine(this.logger_, this.formatMsg_('Sending request'));
this.inSend_ = true;
this.xhr_.send(content);
this.inSend_ = false;
} catch (err) {
goog.log.fine(this.logger_, this.formatMsg_('Send error: ' + err.message));
this.error_(goog.net.ErrorCode.EXCEPTION, err);
}
};
/**
* Determines if the argument is an XMLHttpRequest that supports the level 2
* timeout value and event.
*
* Currently, FF 21.0 OS X has the fields but won't actually call the timeout
* handler. Perhaps the confusion in the bug referenced below hasn't
* entirely been resolved.
*
* @see http://www.w3.org/TR/XMLHttpRequest/#the-timeout-attribute
* @see https://bugzilla.mozilla.org/show_bug.cgi?id=525816
*
* @param {!goog.net.XhrLike.OrNative} xhr The request.
* @return {boolean} True if the request supports level 2 timeout.
* @private
*/
goog.net.XhrIo.shouldUseXhr2Timeout_ = function(xhr) {
return goog.userAgent.IE && goog.userAgent.isVersionOrHigher(9) &&
goog.isNumber(xhr[goog.net.XhrIo.XHR2_TIMEOUT_]) &&
goog.isDef(xhr[goog.net.XhrIo.XHR2_ON_TIMEOUT_]);
};
/**
* @param {string} header An HTTP header key.
* @return {boolean} Whether the key is a content type header (ignoring
* case.
* @private
*/
goog.net.XhrIo.isContentTypeHeader_ = function(header) {
return goog.string.caseInsensitiveEquals(
goog.net.XhrIo.CONTENT_TYPE_HEADER, header);
};
/**
* Creates a new XHR object.
* @return {!goog.net.XhrLike.OrNative} The newly created XHR object.
* @protected
*/
goog.net.XhrIo.prototype.createXhr = function() {
return this.xmlHttpFactory_ ? this.xmlHttpFactory_.createInstance() :
goog.net.XmlHttp();
};
/**
* The request didn't complete after {@link goog.net.XhrIo#timeoutInterval_}
* milliseconds; raises a {@link goog.net.EventType.TIMEOUT} event and aborts
* the request.
* @private
*/
goog.net.XhrIo.prototype.timeout_ = function() {
if (typeof goog == 'undefined') {
// If goog is undefined then the callback has occurred as the application
// is unloading and will error. Thus we let it silently fail.
} else if (this.xhr_) {
this.lastError_ =
'Timed out after ' + this.timeoutInterval_ + 'ms, aborting';
this.lastErrorCode_ = goog.net.ErrorCode.TIMEOUT;
goog.log.fine(this.logger_, this.formatMsg_(this.lastError_));
this.dispatchEvent(goog.net.EventType.TIMEOUT);
this.abort(goog.net.ErrorCode.TIMEOUT);
}
};
/**
* Something errorred, so inactivate, fire error callback and clean up
* @param {goog.net.ErrorCode} errorCode The error code.
* @param {Error} err The error object.
* @private
*/
goog.net.XhrIo.prototype.error_ = function(errorCode, err) {
this.active_ = false;
if (this.xhr_) {
this.inAbort_ = true;
this.xhr_.abort(); // Ensures XHR isn't hung (FF)
this.inAbort_ = false;
}
this.lastError_ = err;
this.lastErrorCode_ = errorCode;
this.dispatchErrors_();
this.cleanUpXhr_();
};
/**
* Dispatches COMPLETE and ERROR in case of an error. This ensures that we do
* not dispatch multiple error events.
* @private
*/
goog.net.XhrIo.prototype.dispatchErrors_ = function() {
if (!this.errorDispatched_) {
this.errorDispatched_ = true;
this.dispatchEvent(goog.net.EventType.COMPLETE);
this.dispatchEvent(goog.net.EventType.ERROR);
}
};
/**
* Abort the current XMLHttpRequest
* @param {goog.net.ErrorCode=} opt_failureCode Optional error code to use -
* defaults to ABORT.
*/
goog.net.XhrIo.prototype.abort = function(opt_failureCode) {
if (this.xhr_ && this.active_) {
goog.log.fine(this.logger_, this.formatMsg_('Aborting'));
this.active_ = false;
this.inAbort_ = true;
this.xhr_.abort();
this.inAbort_ = false;
this.lastErrorCode_ = opt_failureCode || goog.net.ErrorCode.ABORT;
this.dispatchEvent(goog.net.EventType.COMPLETE);
this.dispatchEvent(goog.net.EventType.ABORT);
this.cleanUpXhr_();
}
};
/**
* Nullifies all callbacks to reduce risks of leaks.
* @override
* @protected
*/
goog.net.XhrIo.prototype.disposeInternal = function() {
if (this.xhr_) {
// We explicitly do not call xhr_.abort() unless active_ is still true.
// This is to avoid unnecessarily aborting a successful request when
// dispose() is called in a callback triggered by a complete response, but
// in which browser cleanup has not yet finished.
// (See http://b/issue?id=1684217.)
if (this.active_) {
this.active_ = false;
this.inAbort_ = true;
this.xhr_.abort();
this.inAbort_ = false;
}
this.cleanUpXhr_(true);
}
goog.net.XhrIo.base(this, 'disposeInternal');
};
/**
* Internal handler for the XHR object's readystatechange event. This method
* checks the status and the readystate and fires the correct callbacks.
* If the request has ended, the handlers are cleaned up and the XHR object is
* nullified.
* @private
*/
goog.net.XhrIo.prototype.onReadyStateChange_ = function() {
if (this.isDisposed()) {
// This method is the target of an untracked goog.Timer.callOnce().
return;
}
if (!this.inOpen_ && !this.inSend_ && !this.inAbort_) {
// Were not being called from within a call to this.xhr_.send
// this.xhr_.abort, or this.xhr_.open, so this is an entry point
this.onReadyStateChangeEntryPoint_();
} else {
this.onReadyStateChangeHelper_();
}
};
/**
* Used to protect the onreadystatechange handler entry point. Necessary
* as {#onReadyStateChange_} maybe called from within send or abort, this
* method is only called when {#onReadyStateChange_} is called as an
* entry point.
* {@see #protectEntryPoints}
* @private
*/
goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_ = function() {
this.onReadyStateChangeHelper_();
};
/**
* Helper for {@link #onReadyStateChange_}. This is used so that
* entry point calls to {@link #onReadyStateChange_} can be routed through
* {@link #onReadyStateChangeEntryPoint_}.
* @private
*/
goog.net.XhrIo.prototype.onReadyStateChangeHelper_ = function() {
if (!this.active_) {
// can get called inside abort call
return;
}
if (typeof goog == 'undefined') {
// NOTE(user): If goog is undefined then the callback has occurred as the
// application is unloading and will error. Thus we let it silently fail.
} else if (
this.xhrOptions_[goog.net.XmlHttp.OptionType.LOCAL_REQUEST_ERROR] &&
this.getReadyState() == goog.net.XmlHttp.ReadyState.COMPLETE &&
this.getStatus() == 2) {
// NOTE(user): In IE if send() errors on a *local* request the readystate
// is still changed to COMPLETE. We need to ignore it and allow the
// try/catch around send() to pick up the error.
goog.log.fine(
this.logger_,
this.formatMsg_('Local request error detected and ignored'));
} else {
// In IE when the response has been cached we sometimes get the callback
// from inside the send call and this usually breaks code that assumes that
// XhrIo is asynchronous. If that is the case we delay the callback
// using a timer.
if (this.inSend_ &&
this.getReadyState() == goog.net.XmlHttp.ReadyState.COMPLETE) {
goog.Timer.callOnce(this.onReadyStateChange_, 0, this);
return;
}
this.dispatchEvent(goog.net.EventType.READY_STATE_CHANGE);
// readyState indicates the transfer has finished
if (this.isComplete()) {
goog.log.fine(this.logger_, this.formatMsg_('Request complete'));
this.active_ = false;
try {
// Call the specific callbacks for success or failure. Only call the
// success if the status is 200 (HTTP_OK) or 304 (HTTP_CACHED)
if (this.isSuccess()) {
this.dispatchEvent(goog.net.EventType.COMPLETE);
this.dispatchEvent(goog.net.EventType.SUCCESS);
} else {
this.lastErrorCode_ = goog.net.ErrorCode.HTTP_ERROR;
this.lastError_ =
this.getStatusText() + ' [' + this.getStatus() + ']';
this.dispatchErrors_();
}
} finally {
this.cleanUpXhr_();
}
}
}
};
/**
* Internal handler for the XHR object's onprogress event. Fires both a generic
* PROGRESS event and either a DOWNLOAD_PROGRESS or UPLOAD_PROGRESS event to
* allow specific binding for each XHR progress event.
* @param {!ProgressEvent} e XHR progress event.
* @param {boolean=} opt_isDownload Whether the current progress event is from a
* download. Used to determine whether DOWNLOAD_PROGRESS or UPLOAD_PROGRESS
* event should be dispatched.
* @private
*/
goog.net.XhrIo.prototype.onProgressHandler_ = function(e, opt_isDownload) {
goog.asserts.assert(
e.type === goog.net.EventType.PROGRESS,
'goog.net.EventType.PROGRESS is of the same type as raw XHR progress.');
this.dispatchEvent(
goog.net.XhrIo.buildProgressEvent_(e, goog.net.EventType.PROGRESS));
this.dispatchEvent(
goog.net.XhrIo.buildProgressEvent_(
e, opt_isDownload ? goog.net.EventType.DOWNLOAD_PROGRESS :
goog.net.EventType.UPLOAD_PROGRESS));
};
/**
* Creates a representation of the native ProgressEvent. IE doesn't support
* constructing ProgressEvent via "new", and the alternatives (e.g.,
* ProgressEvent.initProgressEvent) are non-standard or deprecated.
* @param {!ProgressEvent} e XHR progress event.
* @param {!goog.net.EventType} eventType The type of the event.
* @return {!ProgressEvent} The progress event.
* @private
*/
goog.net.XhrIo.buildProgressEvent_ = function(e, eventType) {
return /** @type {!ProgressEvent} */ ({
type: eventType,
lengthComputable: e.lengthComputable,
loaded: e.loaded,
total: e.total
});
};
/**
* Remove the listener to protect against leaks, and nullify the XMLHttpRequest
* object.
* @param {boolean=} opt_fromDispose If this is from the dispose (don't want to
* fire any events).
* @private
*/
goog.net.XhrIo.prototype.cleanUpXhr_ = function(opt_fromDispose) {
if (this.xhr_) {
// Cancel any pending timeout event handler.
this.cleanUpTimeoutTimer_();
// Save reference so we can mark it as closed after the READY event. The
// READY event may trigger another request, thus we must nullify this.xhr_
var xhr = this.xhr_;
var clearedOnReadyStateChange =
this.xhrOptions_[goog.net.XmlHttp.OptionType.USE_NULL_FUNCTION] ?
goog.nullFunction :
null;
this.xhr_ = null;
this.xhrOptions_ = null;
if (!opt_fromDispose) {
this.dispatchEvent(goog.net.EventType.READY);
}
try {
// NOTE(user): Not nullifying in FireFox can still leak if the callbacks
// are defined in the same scope as the instance of XhrIo. But, IE doesn't
// allow you to set the onreadystatechange to NULL so nullFunction is
// used.
xhr.onreadystatechange = clearedOnReadyStateChange;
} catch (e) {
// This seems to occur with a Gears HTTP request. Delayed the setting of
// this onreadystatechange until after READY is sent out and catching the
// error to see if we can track down the problem.
goog.log.error(
this.logger_,
'Problem encountered resetting onreadystatechange: ' + e.message);
}
}
};
/**
* Make sure the timeout timer isn't running.
* @private
*/
goog.net.XhrIo.prototype.cleanUpTimeoutTimer_ = function() {
if (this.xhr_ && this.useXhr2Timeout_) {
this.xhr_[goog.net.XhrIo.XHR2_ON_TIMEOUT_] = null;
}
if (goog.isNumber(this.timeoutId_)) {
goog.Timer.clear(this.timeoutId_);
this.timeoutId_ = null;
}
};
/**
* @return {boolean} Whether there is an active request.
*/
goog.net.XhrIo.prototype.isActive = function() {
return !!this.xhr_;
};
/**
* @return {boolean} Whether the request has completed.
*/
goog.net.XhrIo.prototype.isComplete = function() {
return this.getReadyState() == goog.net.XmlHttp.ReadyState.COMPLETE;
};
/**
* @return {boolean} Whether the request completed with a success.
*/
goog.net.XhrIo.prototype.isSuccess = function() {
var status = this.getStatus();
// A zero status code is considered successful for local files.
return goog.net.HttpStatus.isSuccess(status) ||
status === 0 && !this.isLastUriEffectiveSchemeHttp_();
};
/**
* @return {boolean} whether the effective scheme of the last URI that was
* fetched was 'http' or 'https'.
* @private
*/
goog.net.XhrIo.prototype.isLastUriEffectiveSchemeHttp_ = function() {
var scheme = goog.uri.utils.getEffectiveScheme(String(this.lastUri_));
return goog.net.XhrIo.HTTP_SCHEME_PATTERN.test(scheme);
};
/**
* Get the readystate from the Xhr object
* Will only return correct result when called from the context of a callback
* @return {goog.net.XmlHttp.ReadyState} goog.net.XmlHttp.ReadyState.*.
*/
goog.net.XhrIo.prototype.getReadyState = function() {
return this.xhr_ ?
/** @type {goog.net.XmlHttp.ReadyState} */ (this.xhr_.readyState) :
goog.net.XmlHttp.ReadyState
.UNINITIALIZED;
};
/**
* Get the status from the Xhr object
* Will only return correct result when called from the context of a callback
* @return {number} Http status.
*/
goog.net.XhrIo.prototype.getStatus = function() {
/**
* IE doesn't like you checking status until the readystate is greater than 2
* (i.e. it is receiving or complete). The try/catch is used for when the
* page is unloading and an ERROR_NOT_AVAILABLE may occur when accessing xhr_.
* @preserveTry
*/
try {
return this.getReadyState() > goog.net.XmlHttp.ReadyState.LOADED ?
this.xhr_.status :
-1;
} catch (e) {
return -1;
}
};
/**
* Get the status text from the Xhr object
* Will only return correct result when called from the context of a callback
* @return {string} Status text.
*/
goog.net.XhrIo.prototype.getStatusText = function() {
/**
* IE doesn't like you checking status until the readystate is greater than 2
* (i.e. it is receiving or complete). The try/catch is used for when the
* page is unloading and an ERROR_NOT_AVAILABLE may occur when accessing xhr_.
* @preserveTry
*/
try {
return this.getReadyState() > goog.net.XmlHttp.ReadyState.LOADED ?
this.xhr_.statusText :
'';
} catch (e) {
goog.log.fine(this.logger_, 'Can not get status: ' + e.message);
return '';
}
};
/**
* Get the last Uri that was requested
* @return {string} Last Uri.
*/
goog.net.XhrIo.prototype.getLastUri = function() {
return String(this.lastUri_);
};
/**
* Get the response text from the Xhr object
* Will only return correct result when called from the context of a callback.
* @return {string} Result from the server, or '' if no result available.
*/
goog.net.XhrIo.prototype.getResponseText = function() {
/** @preserveTry */
try {
return this.xhr_ ? this.xhr_.responseText : '';
} catch (e) {
// http://www.w3.org/TR/XMLHttpRequest/#the-responsetext-attribute
// states that responseText should return '' (and responseXML null)
// when the state is not LOADING or DONE. Instead, IE can
// throw unexpected exceptions, for example when a request is aborted
// or no data is available yet.
goog.log.fine(this.logger_, 'Can not get responseText: ' + e.message);
return '';
}
};
/**
* Get the response body from the Xhr object. This property is only available
* in IE since version 7 according to MSDN:
* http://msdn.microsoft.com/en-us/library/ie/ms534368(v=vs.85).aspx
* Will only return correct result when called from the context of a callback.
*
* One option is to construct a VBArray from the returned object and convert
* it to a JavaScript array using the toArray method:
* {@code (new window['VBArray'](xhrIo.getResponseBody())).toArray()}
* This will result in an array of numbers in the range of [0..255]
*
* Another option is to use the VBScript CStr method to convert it into a
* string as outlined in http://stackoverflow.com/questions/1919972
*
* @return {Object} Binary result from the server or null if not available.
*/
goog.net.XhrIo.prototype.getResponseBody = function() {
/** @preserveTry */
try {
if (this.xhr_ && 'responseBody' in this.xhr_) {
return this.xhr_['responseBody'];
}
} catch (e) {
// IE can throw unexpected exceptions, for example when a request is aborted
// or no data is yet available.
goog.log.fine(this.logger_, 'Can not get responseBody: ' + e.message);
}
return null;
};
/**
* Get the response XML from the Xhr object
* Will only return correct result when called from the context of a callback.
* @return {Document} The DOM Document representing the XML file, or null
* if no result available.
*/
goog.net.XhrIo.prototype.getResponseXml = function() {
/** @preserveTry */
try {
return this.xhr_ ? this.xhr_.responseXML : null;
} catch (e) {
goog.log.fine(this.logger_, 'Can not get responseXML: ' + e.message);
return null;
}
};
/**
* Get the response and evaluates it as JSON from the Xhr object
* Will only return correct result when called from the context of a callback
* @param {string=} opt_xssiPrefix Optional XSSI prefix string to use for
* stripping of the response before parsing. This needs to be set only if
* your backend server prepends the same prefix string to the JSON response.
* @return {Object|undefined} JavaScript object.
*/
goog.net.XhrIo.prototype.getResponseJson = function(opt_xssiPrefix) {
if (!this.xhr_) {
return undefined;
}
var responseText = this.xhr_.responseText;
if (opt_xssiPrefix && responseText.indexOf(opt_xssiPrefix) == 0) {
responseText = responseText.substring(opt_xssiPrefix.length);
}
return goog.json.parse(responseText);
};
/**
* Get the response as the type specificed by {@link #setResponseType}. At time
* of writing, this is only directly supported in very recent versions of WebKit
* (10.0.612.1 dev and later). If the field is not supported directly, we will
* try to emulate it.
*
* Emulating the response means following the rules laid out at
* http://www.w3.org/TR/XMLHttpRequest/#the-response-attribute
*
* On browsers with no support for this (Chrome < 10, Firefox < 4, etc), only
* response types of DEFAULT or TEXT may be used, and the response returned will
* be the text response.
*
* On browsers with Mozilla's draft support for array buffers (Firefox 4, 5),
* only response types of DEFAULT, TEXT, and ARRAY_BUFFER may be used, and the
* response returned will be either the text response or the Mozilla
* implementation of the array buffer response.
*
* On browsers will full support, any valid response type supported by the
* browser may be used, and the response provided by the browser will be
* returned.
*
* @return {*} The response.
*/
goog.net.XhrIo.prototype.getResponse = function() {
/** @preserveTry */
try {
if (!this.xhr_) {
return null;
}
if ('response' in this.xhr_) {
return this.xhr_.response;
}
switch (this.responseType_) {
case goog.net.XhrIo.ResponseType.DEFAULT:
case goog.net.XhrIo.ResponseType.TEXT:
return this.xhr_.responseText;
// DOCUMENT and BLOB don't need to be handled here because they are
// introduced in the same spec that adds the .response field, and would
// have been caught above.
// ARRAY_BUFFER needs an implementation for Firefox 4, where it was
// implemented using a draft spec rather than the final spec.
case goog.net.XhrIo.ResponseType.ARRAY_BUFFER:
if ('mozResponseArrayBuffer' in this.xhr_) {
return this.xhr_.mozResponseArrayBuffer;
}
}
// Fell through to a response type that is not supported on this browser.
goog.log.error(
this.logger_, 'Response type ' + this.responseType_ + ' is not ' +
'supported on this browser');
return null;
} catch (e) {
goog.log.fine(this.logger_, 'Can not get response: ' + e.message);
return null;
}
};
/**
* Get the value of the response-header with the given name from the Xhr object
* Will only return correct result when called from the context of a callback
* and the request has completed
* @param {string} key The name of the response-header to retrieve.
* @return {string|undefined} The value of the response-header named key.
*/
goog.net.XhrIo.prototype.getResponseHeader = function(key) {
return this.xhr_ && this.isComplete() ? this.xhr_.getResponseHeader(key) :
undefined;
};
/**
* Gets the text of all the headers in the response.
* Will only return correct result when called from the context of a callback
* and the request has completed.
* @return {string} The value of the response headers or empty string.
*/
goog.net.XhrIo.prototype.getAllResponseHeaders = function() {
return this.xhr_ && this.isComplete() ? this.xhr_.getAllResponseHeaders() :
'';
};
/**
* Returns all response headers as a key-value map.
* Multiple values for the same header key can be combined into one,
* separated by a comma and a space.
* Note that the native getResponseHeader method for retrieving a single header
* does a case insensitive match on the header name. This method does not
* include any case normalization logic, it will just return a key-value
* representation of the headers.
* See: http://www.w3.org/TR/XMLHttpRequest/#the-getresponseheader()-method
* @return {!Object<string, string>} An object with the header keys as keys
* and header values as values.
*/
goog.net.XhrIo.prototype.getResponseHeaders = function() {
var headersObject = {};
var headersArray = this.getAllResponseHeaders().split('\r\n');
for (var i = 0; i < headersArray.length; i++) {
if (goog.string.isEmptyOrWhitespace(headersArray[i])) {
continue;
}
var keyValue = goog.string.splitLimit(headersArray[i], ': ', 2);
if (headersObject[keyValue[0]]) {
headersObject[keyValue[0]] += ', ' + keyValue[1];
} else {
headersObject[keyValue[0]] = keyValue[1];
}
}
return headersObject;
};
/**
* Get the last error message
* @return {goog.net.ErrorCode} Last error code.
*/
goog.net.XhrIo.prototype.getLastErrorCode = function() {
return this.lastErrorCode_;
};
/**
* Get the last error message
* @return {string} Last error message.
*/
goog.net.XhrIo.prototype.getLastError = function() {
return goog.isString(this.lastError_) ? this.lastError_ :
String(this.lastError_);
};
/**
* Adds the last method, status and URI to the message. This is used to add
* this information to the logging calls.
* @param {string} msg The message text that we want to add the extra text to.
* @return {string} The message with the extra text appended.
* @private
*/
goog.net.XhrIo.prototype.formatMsg_ = function(msg) {
return msg + ' [' + this.lastMethod_ + ' ' + this.lastUri_ + ' ' +
this.getStatus() + ']';
};
// Register the xhr handler as an entry point, so that
// it can be monitored for exception handling, etc.
goog.debug.entryPointRegistry.register(
/**
* @param {function(!Function): !Function} transformer The transforming
* function.
*/
function(transformer) {
goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_ =
transformer(goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_);
});
| cbetheridge/simpleclassroom | static/third-party/closure-library/closure/goog/net/xhrio.js | JavaScript | mit | 43,124 |
'use strict';
const Code = require('code');
const Constants = require('../../../../../../client/pages/admin/statuses/search/constants');
const FluxConstant = require('flux-constant');
const Lab = require('lab');
const Proxyquire = require('proxyquire');
const lab = exports.lab = Lab.script();
const stub = {
ApiActions: {
get: function () {
stub.ApiActions.get.mock.apply(null, arguments);
},
post: function () {
stub.ApiActions.post.mock.apply(null, arguments);
}
},
Store: {
dispatch: function () {
stub.Store.dispatch.mock.apply(null, arguments);
}
},
ReactRouter: {
browserHistory: {
push: () => {},
replace: () => {}
}
}
};
const Actions = Proxyquire('../../../../../../client/pages/admin/statuses/search/actions', {
'../../../../actions/api': stub.ApiActions,
'./store': stub.Store,
'react-router': stub.ReactRouter
});
lab.experiment('Admin Statuses Search Actions', () => {
lab.test('it calls ApiActions.get from getResults', (done) => {
stub.ApiActions.get.mock = function (url, data, store, typeReq, typeRes, callback) {
Code.expect(url).to.be.a.string();
Code.expect(data).to.be.an.object();
Code.expect(store).to.be.an.object();
Code.expect(typeReq).to.be.an.instanceof(FluxConstant);
Code.expect(typeRes).to.be.an.instanceof(FluxConstant);
Code.expect(callback).to.not.exist();
done();
};
Actions.getResults({});
});
lab.test('it calls browserHistory.push from changeSearchQuery', (done) => {
const scrollTo = global.window.scrollTo;
global.window.scrollTo = function () {
global.window.scrollTo = scrollTo;
done();
};
stub.ReactRouter.browserHistory.push = function (config) {
stub.ReactRouter.browserHistory.push = () => {};
Code.expect(config.pathname).to.be.a.string();
Code.expect(config.query).to.be.an.object();
};
Actions.changeSearchQuery({});
});
lab.test('it calls dispatch from showCreateNew', (done) => {
stub.Store.dispatch.mock = function (action) {
if (action.type === Constants.SHOW_CREATE_NEW) {
done();
}
};
Actions.showCreateNew();
});
lab.test('it calls dispatch from hideCreateNew', (done) => {
stub.Store.dispatch.mock = function (action) {
if (action.type === Constants.HIDE_CREATE_NEW) {
done();
}
};
Actions.hideCreateNew();
});
lab.test('it calls ApiActions.post from createNew (success)', (done) => {
stub.Store.dispatch.mock = () => {};
stub.ReactRouter.browserHistory.replace = function (location) {
stub.ReactRouter.browserHistory.replace = () => {};
Code.expect(location).to.be.an.object();
done();
};
stub.ApiActions.post.mock = function (url, data, store, typeReq, typeRes, callback) {
Code.expect(url).to.be.a.string();
Code.expect(data).to.be.an.object();
Code.expect(store).to.be.an.object();
Code.expect(typeReq).to.be.an.instanceof(FluxConstant);
Code.expect(typeRes).to.be.an.instanceof(FluxConstant);
Code.expect(callback).to.exist();
callback(null, {});
};
Actions.createNew({});
});
lab.test('it calls ApiActions.post from createNew (failure)', (done) => {
stub.ApiActions.post.mock = function (url, data, store, typeReq, typeRes, callback) {
Code.expect(url).to.be.a.string();
Code.expect(data).to.be.an.object();
Code.expect(store).to.be.an.object();
Code.expect(typeReq).to.be.an.instanceof(FluxConstant);
Code.expect(typeRes).to.be.an.instanceof(FluxConstant);
Code.expect(callback).to.exist();
callback(new Error('sorry pal'));
done();
};
Actions.createNew({});
});
});
| fahidRM/aqua-couch-test | test/client/pages/admin/statuses/search/actions.js | JavaScript | mit | 4,225 |
version https://git-lfs.github.com/spec/v1
oid sha256:3e7e8daeb7e94086c854616e881862ffc0555684031d339b30c0b67afa82b530
size 492
| yogeshsaroya/new-cdnjs | ajax/libs/bootstrap-datepicker/1.2.0-rc.1/js/locales/bootstrap-datepicker.et.min.js | JavaScript | mit | 128 |
import { getCell, getColumnByCell, getRowIdentity } from './util';
import ElCheckbox from 'element-ui/packages/checkbox';
export default {
components: {
ElCheckbox
},
props: {
store: {
required: true
},
context: {},
layout: {
required: true
},
rowClassName: [String, Function],
rowStyle: [Object, Function],
fixed: String,
highlight: Boolean
},
render(h) {
const columnsHidden = this.columns.map((column, index) => this.isColumnHidden(index));
return (
<table
class="el-table__body"
cellspacing="0"
cellpadding="0"
border="0">
<colgroup>
{
this._l(this.columns, column =>
<col
name={ column.id }
width={ column.realWidth || column.width }
/>)
}
</colgroup>
<tbody>
{
this._l(this.data, (row, $index) =>
[<tr
style={ this.rowStyle ? this.getRowStyle(row, $index) : null }
key={ this.table.rowKey ? this.getKeyOfRow(row, $index) : $index }
on-dblclick={ ($event) => this.handleDoubleClick($event, row) }
on-click={ ($event) => this.handleClick($event, row) }
on-contextmenu={ ($event) => this.handleContextMenu($event, row) }
on-mouseenter={ _ => this.handleMouseEnter($index) }
on-mouseleave={ _ => this.handleMouseLeave() }
class={ [this.getRowClass(row, $index)] }>
{
this._l(this.columns, (column, cellIndex) =>
<td
class={ [column.id, column.align, column.className || '', columnsHidden[cellIndex] ? 'is-hidden' : '' ] }
on-mouseenter={ ($event) => this.handleCellMouseEnter($event, row) }
on-mouseleave={ this.handleCellMouseLeave }>
{
column.renderCell.call(this._renderProxy, h, { row, column, $index, store: this.store, _self: this.context || this.table.$vnode.context }, columnsHidden[cellIndex])
}
</td>
)
}
{
!this.fixed && this.layout.scrollY && this.layout.gutterWidth ? <td class="gutter" /> : ''
}
</tr>,
this.store.states.expandRows.indexOf(row) > -1
? (<tr>
<td colspan={ this.columns.length } class="el-table__expanded-cell">
{ this.table.renderExpanded ? this.table.renderExpanded(h, { row, $index, store: this.store }) : ''}
</td>
</tr>)
: ''
]
)
}
</tbody>
</table>
);
},
watch: {
'store.states.hoverRow'(newVal, oldVal) {
if (!this.store.states.isComplex) return;
const el = this.$el;
if (!el) return;
const rows = el.querySelectorAll('tbody > tr');
const oldRow = rows[oldVal];
const newRow = rows[newVal];
if (oldRow) {
oldRow.classList.remove('hover-row');
}
if (newRow) {
newRow.classList.add('hover-row');
}
},
'store.states.currentRow'(newVal, oldVal) {
if (!this.highlight) return;
const el = this.$el;
if (!el) return;
const data = this.store.states.data;
const rows = el.querySelectorAll('tbody > tr');
const oldRow = rows[data.indexOf(oldVal)];
const newRow = rows[data.indexOf(newVal)];
if (oldRow) {
oldRow.classList.remove('current-row');
} else if (rows) {
[].forEach.call(rows, row => row.classList.remove('current-row'));
}
if (newRow) {
newRow.classList.add('current-row');
}
}
},
computed: {
table() {
return this.$parent;
},
data() {
return this.store.states.data;
},
columnsCount() {
return this.store.states.columns.length;
},
leftFixedCount() {
return this.store.states.fixedColumns.length;
},
rightFixedCount() {
return this.store.states.rightFixedColumns.length;
},
columns() {
return this.store.states.columns;
}
},
data() {
return {
tooltipDisabled: true
};
},
methods: {
getKeyOfRow(row, index) {
const rowKey = this.table.rowKey;
if (rowKey) {
return getRowIdentity(row, rowKey);
}
return index;
},
isColumnHidden(index) {
if (this.fixed === true || this.fixed === 'left') {
return index >= this.leftFixedCount;
} else if (this.fixed === 'right') {
return index < this.columnsCount - this.rightFixedCount;
} else {
return (index < this.leftFixedCount) || (index >= this.columnsCount - this.rightFixedCount);
}
},
getRowStyle(row, index) {
const rowStyle = this.rowStyle;
if (typeof rowStyle === 'function') {
return rowStyle.call(null, row, index);
}
return rowStyle;
},
getRowClass(row, index) {
const classes = [];
const rowClassName = this.rowClassName;
if (typeof rowClassName === 'string') {
classes.push(rowClassName);
} else if (typeof rowClassName === 'function') {
classes.push(rowClassName.call(null, row, index) || '');
}
return classes.join(' ');
},
handleCellMouseEnter(event, row) {
const table = this.table;
const cell = getCell(event);
if (cell) {
const column = getColumnByCell(table, cell);
const hoverState = table.hoverState = {cell, column, row};
table.$emit('cell-mouse-enter', hoverState.row, hoverState.column, hoverState.cell, event);
}
// 判断是否text-overflow, 如果是就显示tooltip
const cellChild = event.target.querySelector('.cell');
this.tooltipDisabled = cellChild.scrollWidth <= cellChild.offsetWidth;
},
handleCellMouseLeave(event) {
const cell = getCell(event);
if (!cell) return;
const oldHoverState = this.table.hoverState;
this.table.$emit('cell-mouse-leave', oldHoverState.row, oldHoverState.column, oldHoverState.cell, event);
},
handleMouseEnter(index) {
this.store.commit('setHoverRow', index);
},
handleMouseLeave() {
this.store.commit('setHoverRow', null);
},
handleContextMenu(event, row) {
this.handleEvent(event, row, 'contextmenu');
},
handleDoubleClick(event, row) {
this.handleEvent(event, row, 'dblclick');
},
handleClick(event, row) {
this.store.commit('setCurrentRow', row);
this.handleEvent(event, row, 'click');
},
handleEvent(event, row, name) {
const table = this.table;
const cell = getCell(event);
let column;
if (cell) {
column = getColumnByCell(table, cell);
if (column) {
table.$emit(`cell-${name}`, row, column, cell, event);
}
}
table.$emit(`row-${name}`, row, event, column);
},
handleExpandClick(row) {
this.store.commit('toggleRowExpanded', row);
}
}
};
| imyzf/element | packages/table/src/table-body.js | JavaScript | mit | 7,259 |
var searchData=
[
['w',['w',['../structedda_1_1dist_1_1GMMTuple.html#a3f52857178189dcb76b5132a60c0a50a',1,'edda::dist::GMMTuple']]],
['weights',['weights',['../classedda_1_1dist_1_1JointGMM.html#a479a4af061d7414da3a2b42df3f2e87f',1,'edda::dist::JointGMM']]],
['width',['width',['../structBMPImage.html#a35875dd635eb414965fd87e169b8fb25',1,'BMPImage']]]
];
| GRAVITYLab/edda | html/search/variables_15.js | JavaScript | mit | 362 |
var Data = {};
Data.matrix = {
valueName: 'Wert',
stakeholdersName : 'Berührungs​gruppe',
negativeCriteriaName : 'Negativ-Kriterien',
values : [
'Menschen​würde',
'Solidarität',
'Ökologische Nachhaltigkeit',
'Soziale Gerechtigkeit',
'Demokratische Mitbestimmung & Transparenz'
],
stakeholders : [
{
shortcode : 'A',
name: 'Lieferant​Innen',
values: [
{
shortcode : 'A1',
shortcodeSlug : 'a1',
title: 'Ethisches Beschaffungsmanagement',
content: 'Aktive Auseinandersetzung mit den Risiken zugekaufter Produkte / Dienstleistungen, Berücksichtigung sozialer und ökologischer Aspekte bei der Auswahl von LieferantInnen und DienstleistungsnehmerInnen.',
points: 90,
soleProprietorship: true
}
]
},
{
shortcode : 'B',
name: 'Geldgeber​Innen',
values: [
{
shortcode : 'B1',
shortcodeSlug : 'b1',
title: 'Ethisches Finanzmanagement',
content: 'Berücksichtigung sozialer und ökologischer Aspekte bei der Auswahl der Finanzdienstleistungen; gemeinwohlorienterte Veranlagung und Finanzierung',
points: 30,
soleProprietorship: true
}
]
},
{
shortcode : 'C',
name: 'Mitarbeiter​Innen inklusive Eigentümer​Innen',
values: [
{
shortcode : 'C1',
shortcodeSlug : 'c1',
title: 'Arbeitsplatz​qualität und Gleichstellung',
content: 'Mitarbeiter​orientierte Organisations-kultur und –strukturen, Faire Beschäftigungs- und Entgeltpolitik, Arbeitsschutz und Gesundheits​förderung einschließlich Work-Life-Balance/flexible Arbeitszeiten, Gleichstellung und Diversität',
points: 90,
soleProprietorship: true
},
{
shortcode : 'C2',
shortcodeSlug : 'c2',
title: 'Gerechte Verteilung der Erwerbsarbeit',
content: 'Abbau von Überstunden, Verzicht auf All-inclusive-Verträge, Reduktion der Regelarbeitszeit, Beitrag zur Reduktion der Arbeitslosigkeit',
points: 50,
soleProprietorship: true
},
{
shortcode : 'C3',
shortcodeSlug : 'c3',
title: 'Förderung ökologischen Verhaltens der Mitarbeiter​Innen',
content: 'Aktive Förderung eines nachhaltigen Lebensstils der MitarbeiterInnen (Mobilität, Ernährung), Weiterbildung und Bewusstsein schaffende Maßnahmen, nachhaltige Organisationskultur',
points: 30,
soleProprietorship: true
},
{
shortcode : 'C4',
shortcodeSlug : 'c4',
title: 'Gerechte Verteilung des Einkommens',
content: 'Geringe innerbetriebliche Einkommens​spreizung (netto), Einhaltung von Mindest​einkommen und Höchst​einkommen',
points: 60,
soleProprietorship: false
},
{
shortcode : 'C5',
shortcodeSlug : 'c5',
title: 'Inner​betriebliche Demokratie und Transparenz',
content: 'Umfassende innerbetriebliche Transparenz, Wahl der Führungskräfte durch die Mitarbeiter, konsensuale Mitbestimmung bei Grundsatz- und Rahmen​entscheidungen, Übergabe Eigentum an MitarbeiterInnen. Z.B. Soziokratie',
points: 90,
soleProprietorship: false
}
]
},
{
shortcode : 'D',
name: 'KundInnen / Produkte / Dienst​leistungen / Mit​unternehmen',
values: [
{
shortcode : 'D1',
shortcodeSlug : 'd1',
title: 'Ethische Kunden​beziehung',
content: 'Ethischer Umgang mit KundInnen, KundInnen​orientierung/ - mitbestimmung, gemeinsame Produkt​entwicklung, hohe Servicequalität, hohe Produkt​transparenz',
points: 50,
soleProprietorship: true
},
{
shortcode : 'D2',
shortcodeSlug : 'd2',
title: 'Solidarität mit Mit​unternehmen',
content: 'Weitergabe von Information, Know-how, Arbeitskräften, Aufträgen, zinsfreien Krediten; Beteiligung an kooperativem Marketing und kooperativer Krisenbewältigung',
points: 70,
soleProprietorship: true
},
{
shortcode : 'D3',
shortcodeSlug : 'd3',
title: 'Ökologische Gestaltung der Produkte und Dienst​leistungen',
content: 'Angebot ökologisch höherwertiger Produkte / Dienstleistungen; Bewusstsein schaffende Maßnahmen; Berücksichtigung ökologischer Aspekte bei der KundInnenwahl',
points: 90,
soleProprietorship: true
},
{
shortcode : 'D4',
shortcodeSlug : 'd4',
title: 'Soziale Gestaltung der Produkte und Dienst​leistungen',
content: 'Informationen / Produkten / Dienstleistungen für benachteiligte KundInnen-Gruppen. Unterstützung förderungs​würdiger Marktstrukturen.',
points: 30,
soleProprietorship: true
},
{
shortcode : 'D5',
shortcodeSlug : 'd5',
title: 'Erhöhung der sozialen und ökologischen Branchen​standards',
content: 'Vorbildwirkung, Entwicklung von höheren Standards mit MitbewerberInnen, Lobbying',
points: 30,
soleProprietorship: true
}
]
},
{
shortcode : 'E',
name: 'Gesell​schaftliches Umfeld:',
explanation: 'Region, Souverän, zukünftige Generationen, Zivil​gesellschaft, Mitmenschen und Natur',
values: [
{
shortcode : 'E1',
shortcodeSlug : 'e1',
title: 'Sinn und Gesell​schaftliche Wirkung der Produkte / Dienst​leistungen',
content: 'P/DL decken den Grundbedarf oder dienen der Entwicklung der Menschen / der Gemeinschaft / der Erde und generieren positiven Nutzen.',
points: 50,
soleProprietorship: true
},
{
shortcode : 'E2',
shortcodeSlug : 'e2',
title: 'Beitrag zum Gemeinwesen',
content: 'Gegenseitige Unterstützung und Kooperation durch Finanzmittel, Dienstleistungen, Produkte, Logistik, Zeit, Know-How, Wissen, Kontakte, Einfluss',
points: 40,
soleProprietorship: true
},
{
shortcode : 'E3',
shortcodeSlug : 'e3',
title: 'Reduktion ökologischer Auswirkungen',
content: 'Reduktion der Umwelt​auswirkungen auf ein zukunftsfähiges Niveau: Ressourcen, Energie & Klima, Emissionen, Abfälle etc.',
points: 70,
soleProprietorship: true
},
{
shortcode : 'E4',
shortcodeSlug : 'e4',
title: 'Gemeinwohl​orientierte Gewinn-Verteilung',
content: 'Sinkende / keine Gewinn​ausschüttung an Externe, Ausschüttung an Mitarbeiter, Stärkung des Eigenkapitals, sozial-ökologische Investitionen',
points: 60,
soleProprietorship: false
},
{
shortcode : 'E5',
shortcodeSlug : 'e5',
title: 'Gesellschaft​liche Transparenz und Mitbestimmung',
content: 'Gemeinwohl- oder Nachhaltigkeits​bericht, Mitbestimmung von regionalen und zivilgesell​schaftlichen Berührungs​gruppen',
points: 30,
soleProprietorship: true
}
]
}
],
negativeCriteria : [
{
values: [
{
shortcode : 'N1',
shortcodeSlug : 'n1',
titleShort: 'Verletzung der ILO-Arbeitsnormen / Menschenrechte',
points: -200,
soleProprietorship: true
},
{
shortcode : 'N2',
shortcodeSlug : 'n2',
titleShort: 'Menschen​unwürdige Produkte, z.B. Tretminen, Atomstrom, GMO',
title: 'Menschenunwürdige Produkte und Dienstleistungen',
points: -200,
soleProprietorship: true
},
{
shortcode : 'N3',
shortcodeSlug : 'n3',
titleShort: 'Beschaffung bei / Kooperation mit Unternehmen, welche die Menschenwürde verletzen',
title: 'Menschenunwürdige Produkte und Dienstbeschaffung bei bzt. Kooperation mit Unternehmen, welche die Menschenwürde verletzen',
points: -150,
soleProprietorship: true
}
]
},
{
values: [
{
shortcode : 'N4',
shortcodeSlug : 'n4',
titleShort: 'Feindliche Übernahme',
title: 'Feindliche Übernahme',
points: -200,
soleProprietorship: true
},
{
shortcode : 'N5',
shortcodeSlug : 'n5',
titleShort: 'Sperrpatente',
title: 'Sperrpatente',
points: -100,
soleProprietorship: true
},
{
shortcode : 'N6',
shortcodeSlug : 'n6',
titleShort: 'Dumping​preise',
title: 'Dumpingpreise',
points: -200,
soleProprietorship: true
}
]
},
{
values: [
{
shortcode : 'N7',
shortcodeSlug : 'n7',
titleShort: 'Illegitime Umweltbelastungen',
title: 'Illegitime Umweltbelastungen',
points: -200,
soleProprietorship: true
},
{
shortcode : 'N8',
shortcodeSlug : 'n8',
titleShort: 'Verstöße gegen Umweltauflagen',
title: 'Verstöße gegen Umweltauflagen',
points: -200,
soleProprietorship: true
},
{
shortcode : 'N9',
shortcodeSlug : 'n9',
titleShort: 'Geplante Obsoleszenz (kurze Lebensdauer der Produkte)',
title: 'Geplante Obsoleszenz',
points: -100,
soleProprietorship: true
}
]
},
{
values: [
{
shortcode : 'N10',
shortcodeSlug : 'n10',
titleShort: 'Arbeits​rechtliches Fehlverhalten seitens des Unternehmens',
title: 'Arbeitsrechtliches Fehlverhalten seitens des Unternehmens',
points: -200,
soleProprietorship: true
},
{
shortcode : 'N11',
shortcodeSlug : 'n11',
titleShort: 'Arbeitsplatz​abbau oder Standortverlagerung bei Gewinn',
title: 'Arbeitsplatzabbau oder Standortverlagerung trotz Gewinn',
points: -150,
soleProprietorship: true
},
{
shortcode : 'N12',
shortcodeSlug : 'n12',
titleShort: 'Umgehung der Steuerpflicht',
title: 'Arbeitsplatzabbau oder Standortverlagerung trotz Gewinn',
points: -200,
soleProprietorship: true
},
{
shortcode : 'N13',
shortcodeSlug : 'n13',
titleShort: 'Keine unangemessene Verzinsung für nicht mitarbeitende Gesellschafter',
title: 'Keine unangemessene Verzinsung für nicht mitarbeitende Gesellschafter',
points: -200,
soleProprietorship: true
}
]
},
{
values: [
{
shortcode : 'N14',
shortcodeSlug : 'n14',
titleShort: 'Nicht​offenlegung aller Beteiligungen und Töchter',
title: 'Nichtoffenlegung aller Beteiligungen und Töchter',
points: -100,
soleProprietorship: true
},
{
shortcode : 'N15',
shortcodeSlug : 'n15',
titleShort: 'Verhinderung eines Betriebsrats',
title: 'Verhinderung eines Betriebsrats',
points: -150,
soleProprietorship: true
},
{
shortcode : 'N16',
shortcodeSlug : 'n16',
titleShort: 'Nicht​offenlegung aller Finanzflüsse an Lobbies / Eintragung in das EU-Lobbyregister',
title: 'Nichtoffenlegung aller Finanzflüsse an Lobbyisten und Lobby-Organisationen / Nichteintragung ins Lobby-Register der EU',
points: -200,
soleProprietorship: true
},
{
shortcode : 'N17',
shortcodeSlug : 'n17',
titleShort: 'Exzessive Einkommensspreizung',
title: 'Exzessive Einkommensspreizung',
points: -100,
soleProprietorship: true
}
]
}
]
};
exports.Data = Data;
| sinnwerkstatt/common-good-online-balance | ecg_balancing/templates/ecg_balancing/dustjs/gwoe-matrix-data_en.js | JavaScript | mit | 15,425 |
/**
* Module dependencies.
*/
var finalhandler = require('finalhandler');
var flatten = require('./utils').flatten;
var Router = require('./router');
var methods = require('methods');
var middleware = require('./middleware/init');
var query = require('./middleware/query');
var debug = require('debug')('express:application');
var View = require('./view');
var http = require('http');
var compileETag = require('./utils').compileETag;
var compileQueryParser = require('./utils').compileQueryParser;
var compileTrust = require('./utils').compileTrust;
var deprecate = require('depd')('express');
var merge = require('utils-merge');
var resolve = require('path').resolve;
var slice = Array.prototype.slice;
/**
* Application prototype.
*/
var app = exports = module.exports = {};
/**
* Initialize the server.
*
* - setup default configuration
* - setup default middleware
* - setup route reflection methods
*
* @api private
*/
app.init = function(){
this.cache = {};
this.settings = {};
this.engines = {};
this.defaultConfiguration();
};
/**
* Initialize application configuration.
*
* @api private
*/
app.defaultConfiguration = function(){
// default settings
this.enable('x-powered-by');
this.set('etag', 'weak');
var env = process.env.NODE_ENV || 'development';
this.set('env', env);
this.set('query parser', 'extended');
this.set('subdomain offset', 2);
this.set('trust proxy', false);
debug('booting in %s mode', env);
// inherit protos
this.on('mount', function(parent){
this.request.__proto__ = parent.request;
this.response.__proto__ = parent.response;
this.engines.__proto__ = parent.engines;
this.settings.__proto__ = parent.settings;
});
// setup locals
this.locals = Object.create(null);
// top-most app is mounted at /
this.mountpath = '/';
// default locals
this.locals.settings = this.settings;
// default configuration
this.set('view', View);
this.set('views', resolve('views'));
this.set('jsonp callback name', 'callback');
if (env === 'production') {
this.enable('view cache');
}
Object.defineProperty(this, 'router', {
get: function() {
throw new Error('\'app.router\' is deprecated!\nPlease see the 3.x to 4.x migration guide for details on how to update your app.');
}
});
};
/**
* lazily adds the base router if it has not yet been added.
*
* We cannot add the base router in the defaultConfiguration because
* it reads app settings which might be set after that has run.
*
* @api private
*/
app.lazyrouter = function() {
if (!this._router) {
this._router = new Router({
caseSensitive: this.enabled('case sensitive routing'),
strict: this.enabled('strict routing')
});
this._router.use(query(this.get('query parser fn')));
this._router.use(middleware.init(this));
}
};
/**
* Dispatch a req, res pair into the application. Starts pipeline processing.
*
* If no _done_ callback is provided, then default error handlers will respond
* in the event of an error bubbling through the stack.
*
* @api private
*/
app.handle = function(req, res, done) {
var router = this._router;
// final handler
done = done || finalhandler(req, res, {
env: this.get('env'),
onerror: logerror.bind(this)
});
// no routes
if (!router) {
debug('no routes defined on app');
done();
return;
}
router.handle(req, res, done);
};
/**
* Proxy `Router#use()` to add middleware to the app router.
* See Router#use() documentation for details.
*
* If the _fn_ parameter is an express app, then it will be
* mounted at the _route_ specified.
*
* @api public
*/
app.use = function use(fn) {
var offset = 0;
var path = '/';
// default path to '/'
// disambiguate app.use([fn])
if (typeof fn !== 'function') {
var arg = fn;
while (Array.isArray(arg) && arg.length !== 0) {
arg = arg[0];
}
// first arg is the path
if (typeof arg !== 'function') {
offset = 1;
path = fn;
}
}
var fns = flatten(slice.call(arguments, offset));
if (fns.length === 0) {
throw new TypeError('app.use() requires middleware functions');
}
// setup router
this.lazyrouter();
var router = this._router;
fns.forEach(function (fn) {
// non-express app
if (!fn || !fn.handle || !fn.set) {
return router.use(path, fn);
}
debug('.use app under %s', path);
fn.mountpath = path;
fn.parent = this;
// restore .app property on req and res
router.use(path, function mounted_app(req, res, next) {
var orig = req.app;
fn.handle(req, res, function (err) {
req.__proto__ = orig.request;
res.__proto__ = orig.response;
next(err);
});
});
// mounted an app
fn.emit('mount', this);
}, this);
return this;
};
/**
* Proxy to the app `Router#route()`
* Returns a new `Route` instance for the _path_.
*
* Routes are isolated middleware stacks for specific paths.
* See the Route api docs for details.
*
* @api public
*/
app.route = function(path){
this.lazyrouter();
return this._router.route(path);
};
/**
* Register the given template engine callback `fn`
* as `ext`.
*
* By default will `require()` the engine based on the
* file extension. For example if you try to render
* a "foo.jade" file Express will invoke the following internally:
*
* app.engine('jade', require('jade').__express);
*
* For engines that do not provide `.__express` out of the box,
* or if you wish to "map" a different extension to the template engine
* you may use this method. For example mapping the EJS template engine to
* ".html" files:
*
* app.engine('html', require('ejs').renderFile);
*
* In this case EJS provides a `.renderFile()` method with
* the same signature that Express expects: `(path, options, callback)`,
* though note that it aliases this method as `ejs.__express` internally
* so if you're using ".ejs" extensions you dont need to do anything.
*
* Some template engines do not follow this convention, the
* [Consolidate.js](https://github.com/tj/consolidate.js)
* library was created to map all of node's popular template
* engines to follow this convention, thus allowing them to
* work seamlessly within Express.
*
* @param {String} ext
* @param {Function} fn
* @return {app} for chaining
* @api public
*/
app.engine = function(ext, fn){
if ('function' != typeof fn) throw new Error('callback function required');
if ('.' != ext[0]) ext = '.' + ext;
this.engines[ext] = fn;
return this;
};
/**
* Proxy to `Router#param()` with one added api feature. The _name_ parameter
* can be an array of names.
*
* See the Router#param() docs for more details.
*
* @param {String|Array} name
* @param {Function} fn
* @return {app} for chaining
* @api public
*/
app.param = function(name, fn){
this.lazyrouter();
if (Array.isArray(name)) {
name.forEach(function(key) {
this.param(key, fn);
}, this);
return this;
}
this._router.param(name, fn);
return this;
};
/**
* Assign `setting` to `val`, or return `setting`'s value.
*
* app.set('foo', 'bar');
* app.get('foo');
* // => "bar"
*
* Mounted servers inherit their parent server's settings.
*
* @param {String} setting
* @param {*} [val]
* @return {Server} for chaining
* @api public
*/
app.set = function(setting, val){
if (arguments.length === 1) {
// app.get(setting)
return this.settings[setting];
}
// set value
this.settings[setting] = val;
// trigger matched settings
switch (setting) {
case 'etag':
debug('compile etag %s', val);
this.set('etag fn', compileETag(val));
break;
case 'query parser':
debug('compile query parser %s', val);
this.set('query parser fn', compileQueryParser(val));
break;
case 'trust proxy':
debug('compile trust proxy %s', val);
this.set('trust proxy fn', compileTrust(val));
break;
}
return this;
};
/**
* Return the app's absolute pathname
* based on the parent(s) that have
* mounted it.
*
* For example if the application was
* mounted as "/admin", which itself
* was mounted as "/blog" then the
* return value would be "/blog/admin".
*
* @return {String}
* @api private
*/
app.path = function(){
return this.parent
? this.parent.path() + this.mountpath
: '';
};
/**
* Check if `setting` is enabled (truthy).
*
* app.enabled('foo')
* // => false
*
* app.enable('foo')
* app.enabled('foo')
* // => true
*
* @param {String} setting
* @return {Boolean}
* @api public
*/
app.enabled = function(setting){
return !!this.set(setting);
};
/**
* Check if `setting` is disabled.
*
* app.disabled('foo')
* // => true
*
* app.enable('foo')
* app.disabled('foo')
* // => false
*
* @param {String} setting
* @return {Boolean}
* @api public
*/
app.disabled = function(setting){
return !this.set(setting);
};
/**
* Enable `setting`.
*
* @param {String} setting
* @return {app} for chaining
* @api public
*/
app.enable = function(setting){
return this.set(setting, true);
};
/**
* Disable `setting`.
*
* @param {String} setting
* @return {app} for chaining
* @api public
*/
app.disable = function(setting){
return this.set(setting, false);
};
/**
* Delegate `.VERB(...)` calls to `router.VERB(...)`.
*/
methods.forEach(function(method){
app[method] = function(path){
if ('get' == method && 1 == arguments.length) return this.set(path);
this.lazyrouter();
var route = this._router.route(path);
route[method].apply(route, slice.call(arguments, 1));
return this;
};
});
/**
* Special-cased "all" method, applying the given route `path`,
* middleware, and callback to _every_ HTTP method.
*
* @param {String} path
* @param {Function} ...
* @return {app} for chaining
* @api public
*/
app.all = function(path){
this.lazyrouter();
var route = this._router.route(path);
var args = slice.call(arguments, 1);
methods.forEach(function(method){
route[method].apply(route, args);
});
return this;
};
// del -> delete alias
app.del = deprecate.function(app.d | wenjoy/homePage | node_modules/node-captcha/node_modules/canvas/node_modules/mocha/node_modules/mkdirp/node_modules/mock-fs/node_modules/rewire/node_modules/expect.js/node_modules/serve/node_modules/less-middleware/node_modules/express/lib/application.js | JavaScript | mit | 10,240 |
'use strict';
var bitcore = require('bitcore-lib');
var $ = bitcore.util.preconditions;
var _ = bitcore.deps._;
var path = require('path');
var fs = require('fs');
var utils = require('../utils');
/**
* Will return the path and bitcore-node configuration
* @param {String} cwd - The absolute path to the current working directory
*/
function findConfig(cwd) {
$.checkArgument(_.isString(cwd), 'Argument should be a string');
$.checkArgument(utils.isAbsolutePath(cwd), 'Argument should be an absolute path');
var directory = String(cwd);
while (!fs.existsSync(path.resolve(directory, 'bitcore-node.json'))) {
directory = path.resolve(directory, '../');
if (directory === '/') {
return false;
}
}
return {
path: directory,
config: require(path.resolve(directory, 'bitcore-node.json'))
};
}
module.exports = findConfig;
| braydonf/bitcore-node | lib/scaffold/find-config.js | JavaScript | mit | 863 |
const DOUBLE_QUOTE_STRING_STATE = 'double-quote-string-state';
const SINGLE_QUOTE_STRING_STATE = 'single-quote-string-state';
const LINE_COMMENT_STATE = 'line-comment-state';
const BLOCK_COMMENT_STATE = 'block-comment-state';
const ETC_STATE = 'etc-state';
function extractComments(str) {
let state = ETC_STATE;
let i = 0;
const comments = [];
let currentComment = null;
while (i + 1 < str.length) {
if (state === ETC_STATE && str[i] === '/' && str[i + 1] === '/') {
state = LINE_COMMENT_STATE;
currentComment = {
type: 'LineComment',
range: [i]
};
i += 2;
continue;
}
if (state === LINE_COMMENT_STATE && str[i] === '\n') {
state = ETC_STATE;
currentComment.range.push(i);
comments.push(currentComment);
currentComment = null;
i += 1;
continue;
}
if (state === ETC_STATE && str[i] === '/' && str[i + 1] === '*') {
state = BLOCK_COMMENT_STATE;
currentComment = {
type: 'BlockComment',
range: [i]
};
i += 2;
continue;
}
if (state === BLOCK_COMMENT_STATE && str[i] === '*' && str[i + 1] === '/') {
state = ETC_STATE;
currentComment.range.push(i + 2);
comments.push(currentComment);
currentComment = null;
i += 2;
continue;
}
if (state === ETC_STATE && str[i] === '"') {
state = DOUBLE_QUOTE_STRING_STATE;
i += 1;
continue;
}
if (
state === DOUBLE_QUOTE_STRING_STATE &&
str[i] === '"' &&
(str[i - 1] !== '\\' || str[i - 2] === '\\') // ignore previous backslash unless it's escaped
) {
state = ETC_STATE;
i += 1;
continue;
}
if (state === ETC_STATE && str[i] === "'") {
state = SINGLE_QUOTE_STRING_STATE;
i += 1;
continue;
}
if (
state === SINGLE_QUOTE_STRING_STATE &&
str[i] === "'" &&
(str[i - 1] !== '\\' || str[i - 2] === '\\') // ignore previous backslash unless it's escaped
) {
state = ETC_STATE;
i += 1;
continue;
}
i += 1;
}
if (currentComment !== null && currentComment.type === 'LineComment') {
if (str[i] === '\n') {
currentComment.range.push(str.length - 1);
} else {
currentComment.range.push(str.length);
}
comments.push(currentComment);
}
return comments.map((comment) => {
const start = comment.range[0] + 2;
const end =
comment.type === 'LineComment' ? comment.range[1] : comment.range[1] - 2;
const raw = str.slice(start, end);
// removing the leading asterisks from the value is necessary for jsdoc-style comments
let value = raw;
if (comment.type === 'BlockComment') {
value = value
.split('\n')
.map((x) => x.replace(/^\s*\*/, ''))
.join('\n')
.trimRight();
}
return {
...comment,
raw,
value
};
});
}
module.exports = extractComments;
| glenngillen/dotfiles | .vscode/extensions/juanblanco.solidity-0.0.120/node_modules/solidity-comments-extractor/index.js | JavaScript | mit | 2,960 |
var util = require('util');
/**
* @class Recorder
* @param {{retention: <Number>}} [options]
*/
var Recorder = function(options) {
this._records = [];
this._options = _.defaults(options || {}, {
retention: 300, // seconds
recordMaxSize: 200, // nb records
jsonMaxSize: 50,
format: '[{date} {level}] {message}'
});
};
Recorder.prototype = {
/**
* @returns {String}
*/
getFormattedRecords: function() {
return _.map(this.getRecords(), function(record) {
return this._recordFormatter(record);
}, this).join('\n');
},
/**
* @returns {{date: {Date}, messages: *[], context: {Object}}[]}
*/
getRecords: function() {
return this._records;
},
/**
* @param {*[]} messages
* @param {Object} context
*/
addRecord: function(messages, context) {
var record = {
date: this._getDate(),
messages: messages,
context: context
};
this._records.push(record);
this._cleanupRecords();
},
flushRecords: function() {
this._records = [];
},
/**
* @private
*/
_cleanupRecords: function() {
var retention = this._options.retention;
var recordMaxSize = this._options.recordMaxSize;
if (retention > 0) {
var retentionTime = this._getDate() - (retention * 1000);
this._records = _.filter(this._records, function(record) {
return record.date > retentionTime;
});
}
if (recordMaxSize > 0 && this._records.length > recordMaxSize) {
this._records = this._records.slice(-recordMaxSize);
}
},
/**
* @param {{date: {Date}, messages: *[], context: {Object}}} record
* @returns {String}
* @private
*/
_recordFormatter: function(record) {
var log = this._options.format;
_.each({
date: record.date.toISOString(),
level: record.context.level.name,
message: this._messageFormatter(record.messages)
}, function(value, key) {
var pattern = new RegExp('{' + key + '}', 'g');
log = log.replace(pattern, value);
});
return log;
},
/**
* @param {*[]} messages
* @returns {String}
* @private
*/
_messageFormatter: function(messages) {
var clone = _.toArray(messages);
var index, value, encoded;
for (index = 0; index < clone.length; index++) {
encoded = value = clone[index];
if (_.isString(value) && 0 === index) {
// about console.log and util.format substitution,
// see https://developers.google.com/web/tools/chrome-devtools/debug/console/console-write#string-substitution-and-formatting
// and https://nodejs.org/api/util.html#util_util_format_format
value = value.replace(/%[idfoO]/g, '%s');
} else if (value instanceof RegExp) {
value = value.toString();
} else if (value instanceof Date) {
value = value.toISOString();
} else if (_.isObject(value) && value._class) {
value = '[' + value._class + (value._id && value._id.id ? ':' + value._id.id : '') + ']';
} else if (_.isObject(value) && /^\[object ((?!Object).)+\]$/.test(value.toString())) {
value = value.toString();
}
try {
if (_.isString(value) || _.isNumber(value)) {
encoded = value;
} else {
encoded = JSON.stringify(value);
if (encoded.length > this._options.jsonMaxSize) {
encoded = encoded.slice(0, this._options.jsonMaxSize - 4) + '…' + encoded[encoded.length - 1];
}
}
} catch (e) {
if (_.isUndefined(value)) {
encoded = 'undefined';
} else if (_.isNull(value)) {
encoded = 'null';
} else {
encoded = '[unknown]'
}
}
clone[index] = encoded;
}
return util.format.apply(util.format, clone);
},
/**
* @returns {Date}
* @private
*/
_getDate: function() {
return new Date();
}
};
module.exports = Recorder;
| njam/CM | client-vendor/source/logger/handlers/recorder.js | JavaScript | mit | 3,930 |
ReactDOM.render(React.createElement(
'div',
null,
React.createElement(Content, null)
), document.getElementById('content')); | azat-co/react-quickly | spare-parts/ch05-es5/logger/js/script.js | JavaScript | mit | 130 |
export * from './components/ajax-bar/index.js'
export * from './components/avatar/index.js'
export * from './components/badge/index.js'
export * from './components/banner/index.js'
export * from './components/bar/index.js'
export * from './components/breadcrumbs/index.js'
export * from './components/btn/index.js'
export * from './components/btn-dropdown/index.js'
export * from './components/btn-group/index.js'
export * from './components/btn-toggle/index.js'
export * from './components/card/index.js'
export * from './components/carousel/index.js'
export * from './components/chat/index.js'
export * from './components/checkbox/index.js'
export * from './components/chip/index.js'
export * from './components/circular-progress/index.js'
export * from './components/color/index.js'
export * from './components/date/index.js'
export * from './components/dialog/index.js'
export * from './components/drawer/index.js'
export * from './components/editor/index.js'
export * from './components/expansion-item/index.js'
export * from './components/fab/index.js'
export * from './components/field/index.js'
export * from './components/file/index.js'
export * from './components/footer/index.js'
export * from './components/form/index.js'
export * from './components/header/index.js'
export * from './components/icon/index.js'
export * from './components/img/index.js'
export * from './components/infinite-scroll/index.js'
export * from './components/inner-loading/index.js'
export * from './components/input/index.js'
export * from './components/intersection/index.js'
export * from './components/item/index.js'
export * from './components/knob/index.js'
export * from './components/layout/index.js'
export * from './components/markup-table/index.js'
export * from './components/menu/index.js'
export * from './components/no-ssr/index.js'
export * from './components/option-group/index.js'
export * from './components/page/index.js'
export * from './components/page-scroller/index.js'
export * from './components/page-sticky/index.js'
export * from './components/pagination/index.js'
export * from './components/parallax/index.js'
export * from './components/popup-edit/index.js'
export * from './components/popup-proxy/index.js'
export * from './components/linear-progress/index.js'
export * from './components/pull-to-refresh/index.js'
export * from './components/radio/index.js'
export * from './components/range/index.js'
export * from './components/rating/index.js'
export * from './components/resize-observer/index.js'
export * from './components/responsive/index.js'
export * from './components/scroll-area/index.js'
export * from './components/scroll-observer/index.js'
export * from './components/select/index.js'
export * from './components/separator/index.js'
export * from './components/skeleton/index.js'
export * from './components/slide-item/index.js'
export * from './components/slide-transition/index.js'
export * from './components/slider/index.js'
export * from './components/space/index.js'
export * from './components/spinner/index.js'
export * from './components/splitter/index.js'
export * from './components/stepper/index.js'
export * from './components/tab-panels/index.js'
export * from './components/table/index.js'
export * from './components/tabs/index.js'
export * from './components/time/index.js'
export * from './components/timeline/index.js'
export * from './components/toggle/index.js'
export * from './components/toolbar/index.js'
export * from './components/tooltip/index.js'
export * from './components/tree/index.js'
export * from './components/uploader/index.js'
export * from './components/video/index.js'
export * from './components/virtual-scroll/index.js'
| rstoenescu/quasar-framework | ui/src/components.js | JavaScript | mit | 3,696 |
/* */
define(['exports', 'core-js', 'aurelia-pal', 'aurelia-history'], function (exports, _coreJs, _aureliaPal, _aureliaHistory) {
'use strict';
exports.__esModule = true;
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; }; })();
exports.configure = configure;
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
var LinkHandler = (function () {
function LinkHandler() {
_classCallCheck(this, LinkHandler);
}
LinkHandler.prototype.activate = function activate(history) {};
LinkHandler.prototype.deactivate = function deactivate() {};
return LinkHandler;
})();
exports.LinkHandler = LinkHandler;
var DefaultLinkHandler = (function (_LinkHandler) {
_inherits(DefaultLinkHandler, _LinkHandler);
function DefaultLinkHandler() {
var _this = this;
_classCallCheck(this, DefaultLinkHandler);
_LinkHandler.call(this);
this.handler = function (e) {
var _DefaultLinkHandler$getEventInfo = DefaultLinkHandler.getEventInfo(e);
var shouldHandleEvent = _DefaultLinkHandler$getEventInfo.shouldHandleEvent;
var href = _DefaultLinkHandler$getEventInfo.href;
if (shouldHandleEvent) {
e.preventDefault();
_this.history.navigate(href);
}
};
}
DefaultLinkHandler.prototype.activate = function activate(history) {
if (history._hasPushState) {
this.history = history;
_aureliaPal.DOM.addEventListener('click', this.handler, true);
}
};
DefaultLinkHandler.prototype.deactivate = function deactivate() {
_aureliaPal.DOM.removeEventListener('click', this.handler);
};
DefaultLinkHandler.getEventInfo = function getEventInfo(event) {
var info = {
shouldHandleEvent: false,
href: null,
anchor: null
};
var target = DefaultLinkHandler.findClosestAnchor(event.target);
if (!target || !DefaultLinkHandler.targetIsThisWindow(target)) {
return info;
}
if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) {
return info;
}
var href = target.getAttribute('href');
info.anchor = target;
info.href = href;
var hasModifierKey = event.altKey || event.ctrlKey || event.metaKey || event.shiftKey;
var isRelative = href && !(href.charAt(0) === '#' || /^[a-z]+:/i.test(href));
info.shouldHandleEvent = !hasModifierKey && isRelative;
return info;
};
DefaultLinkHandler.findClosestAnchor = function findClosestAnchor(el) {
while (el) {
if (el.tagName === 'A') {
return el;
}
el = el.parentNode;
}
};
DefaultLinkHandler.targetIsThisWindow = function targetIsThisWindow(target) {
var targetWindow = target.getAttribute('target');
var win = _aureliaPal.PLATFORM.global;
return !targetWindow || targetWindow === win.name || targetWindow === '_self' || targetWindow === 'top' && win === win.top;
};
return DefaultLinkHandler;
})(LinkHandler);
exports.DefaultLinkHandler = DefaultLinkHandler;
function configure(config) {
config.singleton(_aureliaHistory.History, BrowserHistory);
config.transient(LinkHandler, DefaultLinkHandler);
}
var BrowserHistory = (function (_History) {
_inherits(BrowserHistory, _History);
_createClass(BrowserHistory, null, [{
key: 'inject',
value: [LinkHandler],
enumerable: true
}]);
function BrowserHistory(linkHandler) {
_classCallCheck(this, BrowserHistory);
_History.call(this);
this._isActive = false;
this._checkUrlCallback = this._checkUrl.bind(this);
this.location = _aureliaPal.PLATFORM.location;
this.history = _aureliaPal.PLATFORM.history;
this.linkHandler = linkHandler;
}
BrowserHistory.prototype.activate = function activate(options) {
if (this._isActive) {
throw new Error('History has already been activated.');
}
var wantsPushState = !!options.pushState;
this._isActive = true;
this.options = Object.assign({}, { root: '/' }, this.options, options);
this.root = ('/' + this.options.root + '/').replace(rootStripper, '/');
this._wantsHashChange = this.options.hashChange !== false;
this._hasPushState = !!(this.options.pushState && this.history && this.history.pushState);
var eventName = undefined;
if (this._hasPushState) {
eventName = 'popstate';
} else if (this._wantsHashChange) {
eventName = 'hashchange';
}
_aureliaPal.PLATFORM.addEventListener(eventName, this._checkUrlCallback);
if (this._wantsHashChange && wantsPushState) {
var loc = this.location;
var atRoot = loc.pathname.replace(/[^\/]$/, '$&/') === this.root;
if (!this._hasPushState && !atRoot) {
this.fragment = this._getFragment(null, true);
this.location.replace(this.root + this.location.search + '#' + this.fragment);
return true;
} else if (this._hasPushState && atRoot && loc.hash) {
this.fragment = this._getHash().replace(routeStripper, '');
this.history.replaceState({}, _aureliaPal.DOM.title, this.root + this.fragment + loc.search);
}
}
if (!this.fragment) {
this.fragment = this._getFragment();
}
this.linkHandler.activate(this);
if (!this.options.silent) {
return this._loadUrl();
}
};
BrowserHistory.prototype.deactivate = function deactivate() {
_aureliaPal.PLATFORM.removeEventListener('popstate', this._checkUrlCallback);
_aureliaPal.PLATFORM.removeEventListener('hashchange', this._checkUrlCallback);
this._isActive = false;
this.linkHandler.deactivate();
};
BrowserHistory.prototype.navigate = function navigate(fragment) {
var _ref = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var _ref$trigger = _ref.trigger;
var trigger = _ref$trigger === undefined ? true : _ref$trigger;
var _ref$replace = _ref.replace;
var replace = _ref$replace === undefined ? false : _ref$replace;
if (fragment && absoluteUrl.test(fragment)) {
this.location.href = fragment;
return true;
}
if (!this._isActive) {
return false;
}
fragment = this._getFragment(fragment || '');
if (this.fragment === fragment && !replace) {
return false;
}
this.fragment = fragment;
var url = this.root + fragment;
if (fragment === '' && url !== '/') {
url = url.slice(0, -1);
}
if (this._hasPushState) {
url = url.replace('//', '/');
this.history[replace ? 'replaceState' : 'pushState']({}, _aureliaPal.DOM.title, url);
} else if (this._wantsHashChange) {
updateHash(this.location, fragment, replace);
} else {
return this.location.assign(url);
}
if (trigger) {
return this._loadUrl(fragment);
}
};
BrowserHistory.prototype.navigateBack = function navigateBack() {
this.history.back();
};
BrowserHistory.prototype.setTitle = function setTitle(title) {
_aureliaPal.DOM.title = title;
};
BrowserHistory.prototype._getHash = function _getHash() {
return this.location.hash.substr(1);
};
BrowserHistory.prototype._getFragment = function _getFragment(fragment, forcePushState) {
var root = undefined;
if (!fragment) {
if (this._hasPushState || !this._wantsHashChange || forcePushState) {
fragment = this.location.pathname + this.location.search;
root = this.root.replace(trailingSlash, '');
if (!fragment.indexOf(root)) {
fragment = fragment.substr(root.length);
}
} else {
fragment = this._getHash();
}
}
return '/' + fragment.replace(routeStripper, '');
};
BrowserHistory.prototype._checkUrl = function _checkUrl() {
var current = this._getFragment();
if (current !== this.fragment) {
this._loadUrl();
}
};
BrowserHistory.prototype._loadUrl = function _loadUrl(fragmentOverride) {
var fragment = this.fragment = this._getFragment(fragmentOverride);
return this.options.routeHandler ? this.options.routeHandler(fragment) : false;
};
return BrowserHistory;
})(_aureliaHistory.History);
exports.BrowserHistory = BrowserHistory;
var routeStripper = /^#?\/*|\s+$/g;
var rootStripper = /^\/+|\/+$/g;
var trailingSlash = /\/$/;
var absoluteUrl = /^([a-z][a-z0-9+\-.]*:)?\/\//i;
function updateHash(location, fragment, replace) {
if (replace) {
var href = location.href.replace(/(javascript:|#).*$/, '');
location.replace(href + '#' + fragment);
} else {
location.hash = '#' + fragment;
}
}
}); | mbroadst/aurelia-plunker | jspm_packages/npm/[email protected]/aurelia-history-browser.js | JavaScript | mit | 10,044 |
/**
* Copyright (c) 2015-present, Alibaba Group Holding Limited.
* All rights reserved.
*
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* @providesModule ReactNavigatorNavigationBarStylesAndroid
*/
'use strict';
import buildStyleInterpolator from './polyfills/buildStyleInterpolator';
import merge from './polyfills/merge';
// Android Material Design
var NAV_BAR_HEIGHT = 56;
var TITLE_LEFT = 72;
var BUTTON_SIZE = 24;
var TOUCH_TARGT_SIZE = 48;
var BUTTON_HORIZONTAL_MARGIN = 16;
var BUTTON_EFFECTIVE_MARGIN = BUTTON_HORIZONTAL_MARGIN - (TOUCH_TARGT_SIZE - BUTTON_SIZE) / 2;
var NAV_ELEMENT_HEIGHT = NAV_BAR_HEIGHT;
var BASE_STYLES = {
Title: {
position: 'absolute',
bottom: 0,
left: 0,
right: 0,
alignItems: 'flex-start',
height: NAV_ELEMENT_HEIGHT,
backgroundColor: 'transparent',
marginLeft: TITLE_LEFT,
},
LeftButton: {
position: 'absolute',
top: 0,
left: BUTTON_EFFECTIVE_MARGIN,
overflow: 'hidden',
height: NAV_ELEMENT_HEIGHT,
backgroundColor: 'transparent',
},
RightButton: {
position: 'absolute',
top: 0,
right: BUTTON_EFFECTIVE_MARGIN,
overflow: 'hidden',
alignItems: 'flex-end',
height: NAV_ELEMENT_HEIGHT,
backgroundColor: 'transparent',
},
};
// There are 3 stages: left, center, right. All previous navigation
// items are in the left stage. The current navigation item is in the
// center stage. All upcoming navigation items are in the right stage.
// Another way to think of the stages is in terms of transitions. When
// we move forward in the navigation stack, we perform a
// right-to-center transition on the new navigation item and a
// center-to-left transition on the current navigation item.
var Stages = {
Left: {
Title: merge(BASE_STYLES.Title, { opacity: 0 }),
LeftButton: merge(BASE_STYLES.LeftButton, { opacity: 0 }),
RightButton: merge(BASE_STYLES.RightButton, { opacity: 0 }),
},
Center: {
Title: merge(BASE_STYLES.Title, { opacity: 1 }),
LeftButton: merge(BASE_STYLES.LeftButton, { opacity: 1 }),
RightButton: merge(BASE_STYLES.RightButton, { opacity: 1 }),
},
Right: {
Title: merge(BASE_STYLES.Title, { opacity: 0 }),
LeftButton: merge(BASE_STYLES.LeftButton, { opacity: 0 }),
RightButton: merge(BASE_STYLES.RightButton, { opacity: 0 }),
},
};
var opacityRatio = 100;
function buildSceneInterpolators(startStyles, endStyles) {
return {
Title: buildStyleInterpolator({
opacity: {
type: 'linear',
from: startStyles.Title.opacity,
to: endStyles.Title.opacity,
min: 0,
max: 1,
},
left: {
type: 'linear',
from: startStyles.Title.left,
to: endStyles.Title.left,
min: 0,
max: 1,
extrapolate: true,
},
}),
LeftButton: buildStyleInterpolator({
opacity: {
type: 'linear',
from: startStyles.LeftButton.opacity,
to: endStyles.LeftButton.opacity,
min: 0,
max: 1,
round: opacityRatio,
},
left: {
type: 'linear',
from: startStyles.LeftButton.left,
to: endStyles.LeftButton.left,
min: 0,
max: 1,
},
}),
RightButton: buildStyleInterpolator({
opacity: {
type: 'linear',
from: startStyles.RightButton.opacity,
to: endStyles.RightButton.opacity,
min: 0,
max: 1,
round: opacityRatio,
},
left: {
type: 'linear',
from: startStyles.RightButton.left,
to: endStyles.RightButton.left,
min: 0,
max: 1,
extrapolate: true,
},
}),
};
}
var Interpolators = {
// Animating *into* the center stage from the right
RightToCenter: buildSceneInterpolators(Stages.Right, Stages.Center),
// Animating out of the center stage, to the left
CenterToLeft: buildSceneInterpolators(Stages.Center, Stages.Left),
// Both stages (animating *past* the center stage)
RightToLeft: buildSceneInterpolators(Stages.Right, Stages.Left),
};
module.exports = {
General: {
NavBarHeight: NAV_BAR_HEIGHT,
StatusBarHeight: 0,
TotalNavHeight: NAV_BAR_HEIGHT,
},
Interpolators,
Stages,
};
| typesettin/NativeCMS | node_modules/react-web/Libraries/Navigator/NavigatorNavigationBarStylesAndroid.js | JavaScript | mit | 4,250 |
(function () {
'use strict';
/** This directive is used to render out the current variant tabs and properties and exposes an API for other directives to consume */
function tabbedContentDirective($timeout, $filter, contentEditingHelper, contentTypeHelper) {
function link($scope, $element) {
var appRootNode = $element[0];
// Directive for cached property groups.
var propertyGroupNodesDictionary = {};
var scrollableNode = appRootNode.closest(".umb-scrollable");
$scope.activeTabAlias = null;
$scope.tabs = [];
$scope.$watchCollection('content.tabs', (newValue) => {
contentTypeHelper.defineParentAliasOnGroups(newValue);
contentTypeHelper.relocateDisorientedGroups(newValue);
// make a collection with only tabs and not all groups
$scope.tabs = $filter("filter")(newValue, (tab) => {
return tab.type === contentTypeHelper.TYPE_TAB;
});
if ($scope.tabs.length > 0) {
// if we have tabs and some groups that doesn't belong to a tab we need to render those on an "Other" tab.
contentEditingHelper.registerGenericTab(newValue);
$scope.setActiveTab($scope.tabs[0]);
scrollableNode.removeEventListener("scroll", onScroll);
scrollableNode.removeEventListener("mousewheel", cancelScrollTween);
// only trigger anchor scroll when there are no tabs
} else {
scrollableNode.addEventListener("scroll", onScroll);
scrollableNode.addEventListener("mousewheel", cancelScrollTween);
}
});
function onScroll(event) {
var viewFocusY = scrollableNode.scrollTop + scrollableNode.clientHeight * .5;
for(var i in $scope.content.tabs) {
var group = $scope.content.tabs[i];
var node = propertyGroupNodesDictionary[group.id];
if (!node) {
return;
}
if (viewFocusY >= node.offsetTop && viewFocusY <= node.offsetTop + node.clientHeight) {
setActiveAnchor(group);
return;
}
}
}
function setActiveAnchor(tab) {
if (tab.active !== true) {
var i = $scope.content.tabs.length;
while(i--) {
$scope.content.tabs[i].active = false;
}
tab.active = true;
}
}
function getActiveAnchor() {
var i = $scope.content.tabs.length;
while(i--) {
if ($scope.content.tabs[i].active === true)
return $scope.content.tabs[i];
}
return false;
}
function getScrollPositionFor(id) {
if (propertyGroupNodesDictionary[id]) {
return propertyGroupNodesDictionary[id].offsetTop - 20;// currently only relative to closest relatively positioned parent
}
return null;
}
function scrollTo(id) {
var y = getScrollPositionFor(id);
if (getScrollPositionFor !== null) {
var viewportHeight = scrollableNode.clientHeight;
var from = scrollableNode.scrollTop;
var to = Math.min(y, scrollableNode.scrollHeight - viewportHeight);
var animeObject = {_y: from};
$scope.scrollTween = anime({
targets: animeObject,
_y: to,
easing: 'easeOutExpo',
duration: 200 + Math.min(Math.abs(to-from)/viewportHeight*100, 400),
update: () => {
scrollableNode.scrollTo(0, animeObject._y);
}
});
}
}
function jumpTo(id) {
var y = getScrollPositionFor(id);
if (getScrollPositionFor !== null) {
cancelScrollTween();
scrollableNode.scrollTo(0, y);
}
}
function cancelScrollTween() {
if($scope.scrollTween) {
$scope.scrollTween.pause();
}
}
$scope.registerPropertyGroup = function(element, appAnchor) {
propertyGroupNodesDictionary[appAnchor] = element;
};
$scope.setActiveTab = function(tab) {
$scope.activeTabAlias = tab.alias;
$scope.tabs.forEach(tab => tab.active = false);
tab.active = true;
};
$scope.$on("editors.apps.appChanged", function($event, $args) {
// if app changed to this app, then we want to scroll to the current anchor
if($args.app.alias === "umbContent" && $scope.tabs.length === 0) {
var activeAnchor = getActiveAnchor();
$timeout(jumpTo.bind(null, [activeAnchor.id]));
}
});
$scope.$on("editors.apps.appAnchorChanged", function($event, $args) {
if($args.app.alias === "umbContent") {
setActiveAnchor($args.anchor);
scrollTo($args.anchor.id);
}
});
//ensure to unregister from all dom-events
$scope.$on('$destroy', function () {
cancelScrollTween();
scrollableNode.removeEventListener("scroll", onScroll);
scrollableNode.removeEventListener("mousewheel", cancelScrollTween);
});
}
function controller($scope) {
//expose the property/methods for other directives to use
this.content = $scope.content;
if($scope.contentNodeModel) {
$scope.defaultVariant = _.find($scope.contentNodeModel.variants, variant => {
// defaultVariant will never have segment. Wether it has a language or not depends on the setup.
return !variant.segment && ((variant.language && variant.language.isDefault) || (!variant.language));
});
}
$scope.unlockInvariantValue = function(property) {
property.unlockInvariantValue = !property.unlockInvariantValue;
};
$scope.$watch("tabbedContentForm.$dirty",
function (newValue, oldValue) {
if (newValue === true) {
$scope.content.isDirty = true;
}
}
);
$scope.propertyEditorDisabled = function (property) {
if (property.unlockInvariantValue) {
return false;
}
var contentLanguage = $scope.content.language;
var canEditCulture = !contentLanguage ||
// If the property culture equals the content culture it can be edited
property.culture === contentLanguage.culture ||
// A culture-invariant property can only be edited by the default language variant
(property.culture == null && contentLanguage.isDefault);
var canEditSegment = property.segment === $scope.content.segment;
return !canEditCulture || !canEditSegment;
}
}
var directive = {
restrict: 'E',
replace: true,
templateUrl: 'views/components/content/umb-tabbed-content.html',
controller: controller,
link: link,
scope: {
content: "=", // in this context the content is the variant model.
contentNodeModel: "=?", //contentNodeModel is the content model for the node,
contentApp: "=?" // contentApp is the origin app model for this view
}
};
return directive;
}
angular.module('umbraco.directives').directive('umbTabbedContent', tabbedContentDirective);
})();
| umbraco/Umbraco-CMS | src/Umbraco.Web.UI.Client/src/common/directives/components/content/umbtabbedcontent.directive.js | JavaScript | mit | 8,522 |
import { __decorate } from 'tslib';
import { NgModule } from '@angular/core';
import { ANGULARTICS2_TOKEN, RouterlessTracking, Angulartics2, Angulartics2OnModule } from 'angulartics2';
var Angulartics2RouterlessModule_1;
let Angulartics2RouterlessModule = Angulartics2RouterlessModule_1 = class Angulartics2RouterlessModule {
static forRoot(settings = {}) {
return {
ngModule: Angulartics2RouterlessModule_1,
providers: [
{ provide: ANGULARTICS2_TOKEN, useValue: { settings } },
RouterlessTracking,
Angulartics2,
],
};
}
};
Angulartics2RouterlessModule = Angulartics2RouterlessModule_1 = __decorate([
NgModule({
imports: [Angulartics2OnModule],
})
], Angulartics2RouterlessModule);
export { Angulartics2RouterlessModule };
//# sourceMappingURL=angulartics2-routerlessmodule.js.map
| cdnjs/cdnjs | ajax/libs/angulartics2/8.3.0/routerlessmodule/fesm2015/angulartics2-routerlessmodule.js | JavaScript | mit | 907 |
define(['events', 'libraryBrowser', 'imageLoader', 'listView', 'emby-itemscontainer'], function (events, libraryBrowser, imageLoader, listView) {
return function (view, params, tabContent) {
var self = this;
var data = {};
function getPageData(context) {
var key = getSavedQueryKey(context);
var pageData = data[key];
if (!pageData) {
pageData = data[key] = {
query: {
SortBy: "Album,SortName",
SortOrder: "Ascending",
IncludeItemTypes: "Audio",
Recursive: true,
Fields: "AudioInfo,ParentId",
Limit: 100,
StartIndex: 0,
ImageTypeLimit: 1,
EnableImageTypes: "Primary"
}
};
pageData.query.ParentId = params.topParentId;
libraryBrowser.loadSavedQueryValues(key, pageData.query);
}
return pageData;
}
function getQuery(context) {
return getPageData(context).query;
}
function getSavedQueryKey(context) {
if (!context.savedQueryKey) {
context.savedQueryKey = libraryBrowser.getSavedQueryKey('songs');
}
return context.savedQueryKey;
}
function reloadItems(page) {
Dashboard.showLoadingMsg();
var query = getQuery(page);
ApiClient.getItems(Dashboard.getCurrentUserId(), query).then(function (result) {
// Scroll back up so they can see the results from the beginning
window.scrollTo(0, 0);
updateFilterControls(page);
var pagingHtml = LibraryBrowser.getQueryPagingHtml({
startIndex: query.StartIndex,
limit: query.Limit,
totalRecordCount: result.TotalRecordCount,
showLimit: false,
updatePageSizeSetting: false,
addLayoutButton: false,
sortButton: false,
filterButton: false
});
var html = listView.getListViewHtml({
items: result.Items,
action: 'playallfromhere',
smallIcon: true
});
var i, length;
var elems = tabContent.querySelectorAll('.paging');
for (i = 0, length = elems.length; i < length; i++) {
elems[i].innerHTML = pagingHtml;
}
function onNextPageClick() {
query.StartIndex += query.Limit;
reloadItems(tabContent);
}
function onPreviousPageClick() {
query.StartIndex -= query.Limit;
reloadItems(tabContent);
}
elems = tabContent.querySelectorAll('.btnNextPage');
for (i = 0, length = elems.length; i < length; i++) {
elems[i].addEventListener('click', onNextPageClick);
}
elems = tabContent.querySelectorAll('.btnPreviousPage');
for (i = 0, length = elems.length; i < length; i++) {
elems[i].addEventListener('click', onPreviousPageClick);
}
var itemsContainer = tabContent.querySelector('.itemsContainer');
itemsContainer.innerHTML = html;
imageLoader.lazyChildren(itemsContainer);
libraryBrowser.saveQueryValues(getSavedQueryKey(page), query);
Dashboard.hideLoadingMsg();
});
}
self.showFilterMenu = function () {
require(['components/filterdialog/filterdialog'], function (filterDialogFactory) {
var filterDialog = new filterDialogFactory({
query: getQuery(tabContent),
mode: 'songs'
});
Events.on(filterDialog, 'filterchange', function () {
getQuery(tabContent).StartIndex = 0;
reloadItems(tabContent);
});
filterDialog.show();
});
}
function updateFilterControls(tabContent) {
}
function initPage(tabContent) {
tabContent.querySelector('.btnFilter').addEventListener('click', function () {
self.showFilterMenu();
});
tabContent.querySelector('.btnSort').addEventListener('click', function (e) {
libraryBrowser.showSortMenu({
items: [{
name: Globalize.translate('OptionTrackName'),
id: 'Name'
},
{
name: Globalize.translate('OptionAlbum'),
id: 'Album,SortName'
},
{
name: Globalize.translate('OptionAlbumArtist'),
id: 'AlbumArtist,Album,SortName'
},
{
name: Globalize.translate('OptionArtist'),
id: 'Artist,Album,SortName'
},
{
name: Globalize.translate('OptionDateAdded'),
id: 'DateCreated,SortName'
},
{
name: Globalize.translate('OptionDatePlayed'),
id: 'DatePlayed,SortName'
},
{
name: Globalize.translate('OptionPlayCount'),
id: 'PlayCount,SortName'
},
{
name: Globalize.translate('OptionReleaseDate'),
id: 'PremiereDate,AlbumArtist,Album,SortName'
},
{
name: Globalize.translate('OptionRuntime'),
id: 'Runtime,AlbumArtist,Album,SortName'
}],
callback: function () {
getQuery(tabContent).StartIndex = 0;
reloadItems(tabContent);
},
query: getQuery(tabContent),
button: e.target
});
});
}
self.getCurrentViewStyle = function () {
return getPageData(tabContent).view;
};
initPage(tabContent);
self.renderTab = function () {
reloadItems(tabContent);
updateFilterControls(tabContent);
};
self.destroy = function () {
};
};
}); | 7illusions/Emby | MediaBrowser.WebDashboard/dashboard-ui/scripts/songs.js | JavaScript | gpl-2.0 | 7,309 |
var armorSetPvPSuperior = new armorSetObject("pvpsuperior");
armorSetPvPSuperior.slotsArray = new Array();
t = 0;
armorSetPvPSuperior.slotsArray[t] = "head"; t++;
armorSetPvPSuperior.slotsArray[t] = "shoulder"; t++;
armorSetPvPSuperior.slotsArray[t] = "chest"; t++;
armorSetPvPSuperior.slotsArray[t] = "hands"; t++;
armorSetPvPSuperior.slotsArray[t] = "legs"; t++;
armorSetPvPSuperior.slotsArray[t] = "feet"; t++;
armorSetPvPSuperior.slotsNumber = armorSetPvPSuperior.slotsArray.length;
armorSetPvPSuperior.statsArray = new Array();
armorSetPvPSuperior.itemNameArray = new Array();
armorSetPvPSuperior.setNameArray = new Array();
t = 0;
armorSetPvPSuperior.setNamesArray = new Array();
x = 0;
armorSetPvPSuperior.setNamesArray[x] = "Refuge"; x++;
armorSetPvPSuperior.setNamesArray[x] = "Pursuance"; x++;
armorSetPvPSuperior.setNamesArray[x] = "Arcanum"; x++;
armorSetPvPSuperior.setNamesArray[x] = "Redoubt"; x++;
armorSetPvPSuperior.setNamesArray[x] = "Investiture"; x++;
armorSetPvPSuperior.setNamesArray[x] = "Guard"; x++;
armorSetPvPSuperior.setNamesArray[x] = "Stormcaller"; x++;
armorSetPvPSuperior.setNamesArray[x] = "Dreadgear"; x++;
armorSetPvPSuperior.setNamesArray[x] = "Battlearmor"; x++;
classCounter = 0;
//DONT LOCALIZE ABOVE THIS COMMENT LINE
//LOCALIZE EVERYTHING BELOW THIS COMMENT LINE
//druid begin
var sanctuaryBlue = '<span class = "myGreen">\
(2) Set: +40 Attack Power<br>\
(4) Set: Increases your movement speed by 15% while in Bear, Cat, or Travel Form. Only active outdoors.<br>\
(6) Set: +20 Stamina\
</span>';
armorSetPvPSuperior.setNameArray[classCounter] = ['<span class = "myYellow">\
Lieutenant Commander\'s Refuge (0/6)<br>\
</span><span class = "myGray">\
Lieutenant Commander\'s Dragonhide Shoulders<br>\
Lieutenant Commander\'s Dragonhide Headguard<br>\
Knight-Captain\'s Dragonhide Leggings<br>\
Knight-Captain\'s Dragonhide Chestpiece<br>\
Knight-Lieutenant\'s Dragonhide Treads<br>\
Knight-Lieutenant\'s Dragonhide Grips<br>\
</span>'+ sanctuaryBlue, '<span class = "myYellow">\
Champion\'s Refuge (0/6)<br>\
</span><span class = "myGray">\
Blood Guard\'s Dragonhide Treads<br>\
Blood Guard\'s Dragonhide Grips<br>\
Legionnaire\'s Dragonhide Chestpiece<br>\
Legionnaire\'s Dragonhide Leggings<br>\
Champion\'s Dragonhide Headguard<br>\
Champion\'s Dragonhide Shoulders<br>\
</span>'+ sanctuaryBlue];
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Dragonhide Headguard', '<span class = "myBlue">\
Champion\'s Dragonhide Headguard'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Head\
</span></td><td align = "right"><span class = "myTable">\
Leather\
</span></td></tr></table>\
198 Armor<br>\
+16 Strength<br>\
+12 Agility<br>\
+16 Stamina<br>\
+16 Intellect<br>\
+8 Spirit<br>\
Classes: Druid<br>\
Durability 60/60<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 18.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Dragonhide Shoulders', '<span class = "myBlue">\
Champion\'s Dragonhide Shoulders'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Shoulders\
</span></td><td align = "right"><span class = "myTable">\
Leather\
</span></td></tr></table>\
206 Armor<br>\
+12 Strength<br>\
+6 Agility<br>\
+12 Stamina<br>\
+12 Intellect<br>\
+6 Spirit<br>\
Classes: Druid<br>\
Durability 60/60<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 14.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Dragonhide Chestpiece', '<span class = "myBlue">\
Legionnaire\'s Dragonhide Chestpiece'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Chest\
</span></td><td align = "right"><span class = "myTable">\
Leather\
</span></td></tr></table>\
218 Armor<br>\
+13 Strength<br>\
+12 Agility<br>\
+13 Stamina<br>\
+12 Intellect<br>\
Classes: Druid<br>\
Durability 100/100<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 1%.<br>\
Equip: Increases damage and healing done by magical spells and effects by up to 15.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Dragonhide Grips', '<span class = "myBlue">\
Blood Guard\'s Dragonhide Grips'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Hands\
</span></td><td align = "right"><span class = "myTable">\
Leather\
</span></td></tr></table>\
115 Armor<br>\
+13 Strength<br>\
+10 Agility<br>\
+12 Stamina<br>\
+9 Intellect<br>\
Classes: Druid<br>\
Durability 35/35<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Slightly increases your stealth detection.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Dragonhide Leggings', '<span class = "myBlue">\
Legionnaire\'s Dragonhide Leggings'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Legs\
</span></td><td align = "right"><span class = "myTable">\
Leather\
</span></td></tr></table>\
215 Armor<br>\
+12 Strength<br>\
+12 Agility<br>\
+12 Stamina<br>\
+12 Intellect<br>\
+5 Spirit<br>\
Classes: Druid<br>\
Durability 75/75<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike with spells by 1%.<br>\
Equip: Increases damage and healing done by magical spells and effects by up to 14.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Dragonhide Treads', '<span class = "myBlue">\
Blood Guard\'s Dragonhide Treads'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Feet\
</span></td><td align = "right"><span class = "myTable">\
Leather\
</span></td></tr></table>\
126 Armor<br>\
+13 Strength<br>\
+6 Agility<br>\
+13 Stamina<br>\
+6 Intellect<br>\
+6 Spirit<br>\
Classes: Druid<br>\
Durability 50/50<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 14.</span>\
<p>';
//druid end
classCounter++;
//hunter begin
var pursuitBlue = '<span class = "myGreen">\
(2) Set: +20 Agility.<br>\
(4) Set: Reduces the cooldown of your Concussive Shot by 1 sec.<br>\
(6) Set: +20 Stamina.\
</span>';
armorSetPvPSuperior.setNameArray[classCounter] = ['<span class = "myYellow">\
Lieutenant Commander\'s Pursuance (0/6)<br>\
</span><span class = "myGray">\
Lieutenant Commander\'s Chain Shoulders<br>\
Lieutenant Commander\'s Chain Helm<br>\
Knight-Captain\'s Chain Legguards<br>\
Knight-Captain\'s Chain Hauberk<br>\
Knight-Lieutenant\'s Chain Greaves<br>\
Knight-Lieutenant\'s Chain Vices<br>\
</span>'+ pursuitBlue, '<span class = "myYellow">\
Champion\'s Pursuance (0/6)<br>\
</span><span class = "myGray">\
Blood Guard\'s Chain Greaves<br>\
Blood Guard\'s Chain Vices<br>\
Legionnaire\'s Chain Hauberk<br>\
Legionnaire\'s Chain Legguards<br>\
Champion\'s Chain Helm<br>\
Champion\'s Chain Shoulders<br>\
</span>'+ pursuitBlue];
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Chain Helm', '<span class = "myBlue">\
Champion\'s Chain Helm'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Head\
</span></td><td align = "right"><span class = "myTable">\
Mail\
</span></td></tr></table>\
337 Armor<br>\
+18 Agility<br>\
+14 Stamina<br>\
+9 Intellect<br>\
Classes: Hunter<br>\
Durability 70/70<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 2%.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Chain Shoulders', '<span class = "myBlue">\
Champion\'s Chain Shoulders'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Shoulders\
</span></td><td align = "right"><span class = "myTable">\
Mail\
</span></td></tr></table>\
311 Armor<br>\
+18 Agility<br>\
+13 Stamina<br>\
Classes: Hunter<br>\
Durability 70/70<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 1%.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Chain Hauberk', '<span class = "myBlue">\
Legionnaire\'s Chain Hauberk'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Chest\
</span></td><td align = "right"><span class = "myTable">\
Mail\
</span></td></tr></table>\
398 Armor<br>\
+16 Agility<br>\
+13 Stamina<br>\
+6 Intellect<br>\
Classes: Hunter<br>\
Durability 120/120<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 2%.\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Chain Vices', '<span class = "myBlue">\
Blood Guard\'s Chain Vices'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Hands\
</span></td><td align = "right"><span class = "myTable">\
Mail\
</span></td></tr></table>\
242 Armor<br>\
+18 Agility<br>\
+16 Stamina<br>\
Classes: Hunter<br>\
Durability 40/40<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Increases the damage done by your Multi-Shot by 4%.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Chain Legguards', '<span class = "myBlue">\
Legionnaire\'s Chain Legguards'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Legs\
</span></td><td align = "right"><span class = "myTable">\
Mail\
</span></td></tr></table>\
348 Armor<br>\
+16 Agility<br>\
+13 Stamina<br>\
+6 Intellect<br>\
Classes: Hunter<br>\
Durability 90/90<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 2%.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Chain Greaves', '<span class = "myBlue">\
Blood Guard\'s Chain Greaves'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Feet\
</span></td><td align = "right"><span class = "myTable">\
Mail\
</span></td></tr></table>\
266 Armor<br>\
+20 Agility<br>\
+19 Stamina<br>\
Classes: Hunter<br>\
Durability 60/60<br>\
Requires Level 60<br>\
Requires Rank 7\
<span class = "myGreen">\
</span>\
<p>';
//hunter end
classCounter++;
//mage begin
var regaliaBlue = '<span class = "myGreen">\
(2) Set: Increases damage and healing done by magical spells and effects by up to 23.<br>\
(4) Set: Reduces the cooldown of your Blink spell by 1.5 sec.<br>\
(6) Set: +20 Stamina.\
</span>';
armorSetPvPSuperior.setNameArray[classCounter] = ['<span class = "myYellow">\
Lieutenant Commander\'s Arcanum (0/6)<br>\
</span><span class = "myGray">\
Lieutenant Commander\'s Silk Mantle<br>\
Lieutenant Commander\'s Silk Cowl<br>\
Knight-Captain\'s Silk Legguards<br>\
Knight-Captain\'s Silk Tunic<br>\
Knight-Lieutenant\'s Silk Walkers<br>\
Knight-Lieutenant\'s Silk Handwraps<br>\
</span>'+ regaliaBlue, '<span class = "myYellow">\
Champion\'s Arcanum (0/6)<br>\
</span><span class = "myGray">\
Blood Guard\'s Silk Walkers<br>\
Blood Guard\'s Silk Handwraps<br>\
Legionnaire\'s Silk Tunic<br>\
Legionnaire\'s Silk Legguards<br>\
Champion\'s Silk Cowl<br>\
Champion\'s Silk Mantle<br>\
</span>'+ regaliaBlue];
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Silk Cowl', '<span class = "myBlue">\
Champion\'s Silk Cowl'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Head\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
141 Armor<br>\
+19 Stamina<br>\
+18 Intellect<br>\
+6 Spirit<br>\
Classes: Mage<br>\
Durability 50/50<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike with spells by 1%.<br>\
Equip: Increases damage and healing done by magical spells and effects by up to 21.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Silk Mantle', '<span class = "myBlue">\
Champion\'s Silk Mantle'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Shoulders\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
135 Armor<br>\
+14 Stamina<br>\
+11 Intellect<br>\
+4 Spirit<br>\
Classes: Mage<br>\
Durability 50/50<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 15.<br>\
Equp: Improves your chance to get a critical strike with spells by 1%.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Silk Tunic', '<span class = "myBlue">\
Legionnaires\'s Silk Tunic'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Chest\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
156 Armor<br>\
+18 Stamina<br>\
+17 Intellect<br>\
+5 Spirit<br>\
Classes: Mage<br>\
Durability 80/80<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike with spells by 1%.<br>\
Equip: Increases damage and healing done by magical spells and effects by up to 21.\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Silk Handwraps', '<span class = "myBlue">\
Blood Guard\'s Silk Handwraps'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Hands\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
98 Armor<br>\
+12 Stamina<br>\
+10 Intellect<br>\
Classes: Mage<br>\
Durability 30/30<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Increases the damage absorbed by your Mana Shield by 285.<br>\
Equip: Increases damage and healing done by magical spells and effects by up to 18.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Silk Legguards', '<span class = "myBlue">\
Legionnaire\'s Silk Legguards'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Legs\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
144 Armor<br>\
+18 Stamina<br>\
+17 Intellect<br>\
+5 Spirit<br>\
Classes: Mage<br>\
Durability 65/65<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 21.<br>\
Equip: Improves your chance to get a critical strike with spells by 1%.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Silk Walkers', '<span class = "myBlue">\
Blood Guard\'s Silk Walkers'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Feet\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
104 Armor<br>\
+15 Stamina<br>\
+10 Intellect<br>\
Classes: Mage<br>\
Durability 40/40<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 15.<br>\
Equip: Improves your chance to hit with spells by 1%.</span>\
<p>';
//mage end
classCounter++;
//paladin begin
var aegisBlue = '<span class = "myGreen">\
(2) Set: Increases damage and healing done by magical spells and effects by up to 23.<br>\
(4) Set: Reduces the cooldown of your Hammer of Justice by 10 sec.<br>\
(6) Set: +20 Stamina.\
</span>';
armorSetPvPSuperior.setNameArray[classCounter] = ['<span class = "myYellow">\
Lieutenant Commander\'s Redoubt (0/6)<br>\
</span><span class = "myGray">\
Lieutenant Commander\'s Lamellar Shoulders<br>\
Lieutenant Commander\'s Lamellar Headguard<br>\
Knight-Captain\'s Lamellar Leggings<br>\
Knight-Captain\'s Lamellar Breastplate<br>\
Knight-Lieutenant\'s Lamellar Sabatons<br>\
Knight-Lieutenant\'s Lamellar Gauntlets<br>\
</span>'+ aegisBlue, ''];
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Lamellar Headguard', ''];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Head\
</span></td><td align = "right"><span class = "myTable">\
Plate\
</span></td></tr></table>\
598 Armor<br>\
+18 Strength<br>\
+19 Stamina<br>\
+12 Intellect<br>\
Classes: Paladin<br>\
Durability 80/80<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Increases damage and healing done by magical spells and effects by up to 26.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Lamellar Shoulders', ''];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Shoulders\
</span></td><td align = "right"><span class = "myTable">\
Plate\
</span></td></tr></table>\
552 Armor<br>\
+14 Strength<br>\
+14 Stamina<br>\
+8 Intellect<br>\
Classes: Paladin<br>\
Durability 80/80<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 20.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Lamellar Breastplate', ''];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Chest\
</span></td><td align = "right"><span class = "myTable">\
Plate\
</span></td></tr></table>\
706 Armor<br>\
+17 Strength<br>\
+18 Stamina<br>\
+12 Intellect<br>\
Classes: Paladin<br>\
Durability 135/135<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 25.\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Lamellar Gauntlets', ''];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Hands\
</span></td><td align = "right"><span class = "myTable">\
Plate\
</span></td></tr></table>\
429 Armor<br>\
+12 Strength<br>\
+13 Stamina<br>\
Classes: Paladin<br>\
Durability 45/45<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Increases the Holy damage bonus of your Judgement of the Crusader by 10.<br>\
Equip: Improves your chance to get a critical strike by 1%.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Lamellar Leggings', ''];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Legs\
</span></td><td align = "right"><span class = "myTable">\
Plate\
</span></td></tr></table>\
618 Armor<br>\
+18 Strength<br>\
+17 Stamina<br>\
+12 Intellect<br>\
Classes: Paladin<br>\
Durability 100/100<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 25.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Lamellar Sabatons', ''];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Feet\
</span></td><td align = "right"><span class = "myTable">\
Plate\
</span></td></tr></table>\
472 Armor<br>\
+12 Strength<br>\
+12 Stamina<br>\
+12 Intellect<br>\
Classes: Paladin<br>\
Durability 65/65<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 15.\
</span>\
<p>';
//Paladin end
classCounter++;
//priest begin
var raimentBlue = '<span class = "myGreen">\
(2) Set: Increases damage and healing done by magical spells and effects by up to 23.<br>\
(4) Set: Increases the duration of your Psychic Scream spell by 1 sec.<br>\
(6) Set: +20 Stamina.\
</span>';
armorSetPvPSuperior.setNameArray[classCounter] = ['<span class = "myYellow">\
Lieutenant Commander\'s Investiture (0/6)<br>\
</span><span class = "myGray">\
Lieutenant Commander\'s Satin Mantle<br>\
Lieutenant Commander\'s Satin Hood<br>\
Knight-Captain\'s Satin Legguards<br>\
Knight-Captain\'s Satin Tunic<br>\
Knight-Lieutenant\'s Satin Walkers<br>\
Knight-Lieutenant\'s Satin Handwraps<br>\
</span>'+ raimentBlue, '<span class = "myYellow">\
Champion\'s Investiture (0/6)<br>\
</span><span class = "myGray">\
Blood Guard\'s Satin Walkers<br>\
Blood Guard\'s Satin Handwraps<br>\
Legionnaire\'s Satin Tunic<br>\
Legionnaire\'s Satin Legguards<br>\
Champion\'s Satin Hood<br>\
Champion\'s Satin Mantle<br>\
</span>'+ raimentBlue];
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Satin Hood', '<span class = "myBlue">\
Champion\'s Satin Hood'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Head\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
131 Armor<br>\
+20 Stamina<br>\
+18 Intellect<br>\
Classes: Priest<br>\
Durability 50/50<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 21.<br>\
Equip: Restores 6 mana per 5 sec.\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Satin Mantle', '<span class = "myBlue">\
Champion\'s Satin Mantle'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Shoulders\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
115 Armor<br>\
+14 Stamina<br>\
+12 Intellect<br>\
Classes: Priest<br>\
Durability 50/50<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 16.<br>\
Equip: Restores 6 mana per 5 sec.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Satin Tunic', '<span class = "myBlue">\
Legionnaire\'s Satin Tunic'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Chest\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
156 Armor<br>\
+19 Stamina<br>\
+15 Intellect<br>\
Classes: Priest<br>\
Durability 80/80<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 21.<br>\
Equip: Restores 6 mana per 5 sec.\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Satin Handwraps', '<span class = "myBlue">\
Blood Guard\'s Satin Handwraps'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Hands\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
98 Armor<br>\
+12 Stamina<br>\
+5 Intellect<br>\
Classes: Priest<br>\
Durability 30/30<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Gives you a 50% chance to avoid interruption caused by damage while casting Mind Blast.<br>\
Equip: Increases damage and healing done by magical spells and effects by up to 21.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Satin Legguards', '<span class = "myBlue">\
Legionnaire\'s Satin Legguards'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Legs\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
144 Armor<br>\
+19 Stamina<br>\
+15 Intellect<br>\
Classes: Priest<br>\
Durability 65/65<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 21.<br>\
Equip: Restores 6 mana per 5 sec.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Satin Walkers', '<span class = "myBlue">\
Blood Guard\'s Satin Walkers'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Feet\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
64 Armor<br>\
+17 Stamina<br>\
+15 Intellect<br>\
Classes: Priest<br>\
Durability 40/40<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 14.</span>\
<p>';
//priest end
classCounter++;
//rogue begin
var vestmentsBlue = '<span class = "myGreen">\
(2) Set: +40 Attack Power.<br>\
(4) Set: Reduces the cooldown of your Gouge ability by 1 sec.<br>\
(6) Set: +20 Stamina.\
</span>';
armorSetPvPSuperior.setNameArray[classCounter] = ['<span class = "myYellow">\
Lieutenant Commander\'s Guard (0/6)<br>\
</span><span class = "myGray">\
Lieutenant Commander\'s Leather Helm<br>\
Lieutenant Commander\'s Leather Shoulders<br>\
Knight-Captain\'s Leather Legguards<br>\
Knight-Captain\'s Leather Chestpiece<br>\
Knight-Lieutenant\'s Leather Walkers<br>\
Knight-Lieutenant\'s Leather Grips<br>\
</span>'+ vestmentsBlue, '<span class = "myYellow">\
Champion\'s Guard (0/6)<br>\
</span><span class = "myGray">\
Blood Guard\'s Leather Walkers<br>\
Blood Guard\'s Leather Grips<br>\
Legionnaire\'s Leather Chestpiece<br>\
Legionnaire\'s Leather Legguards<br>\
Champion\'s Leather Helm<br>\
Champion\'s Leather Shoulders<br>\
</span>'+ vestmentsBlue];
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Leather Helm', '<span class = "myBlue">\
Champion\'s Leather Helm'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Head\
</span></td><td align = "right"><span class = "myTable">\
Leather\
</span></td></tr></table>\
238 Armor<br>\
+23 Stamina<br>\
Classes: Rogue<br>\
Durability 60/60<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 1%.<br>\
Equip: +36 Attack Power.<br>\
Equip: Improves your chance to hit by 1%.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Leather Shoulders', '<span class = "myBlue">\
Champion\'s Leather Shoulders'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Shoulders\
</span></td><td align = "right"><span class = "myTable">\
Leather\
</span></td></tr></table>\
196 Armor<br>\
+17 Stamina<br>\
Classes: Rogue<br>\
Durability 60/60<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: +22 Attack Power.<br>\
Equip: Improves your chance to get a critical strike by 1%.<br>\
Equip: Improves your chance to hit by 1%.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Leather Chestpiece', '<span class = "myBlue">\
Legionnaire\'s Leather Chestpiece'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Chest\
</span></td><td align = "right"><span class = "myTable">\
Leather\
</span></td></tr></table>\
248 Armor<br>\
+22 Stamina<br>\
Classes: Rogue<br>\
Durability 100/100<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 1%.<br>\
Equip: Improves your chance to hit by 1%.<br>\
Equip: +34 Attack Power.\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Leather Grips', '<span class = "myBlue">\
Blood Guard\'s Leather Grips'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Hands\
</span></td><td align = "right"><span class = "myTable">\
Leather\
</span></td></tr></table>\
155 Armor<br>\
+18 Stamina<br>\
Classes: Rogue<br>\
Durability 35/35<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: +20 Attack Power.<br>\
Equip: Improves your chance to get a critical strike by 1%.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Leather Legguards', '<span class = "myBlue">\
Legionnaire\'s Leather Legguards'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Legs\
</span></td><td align = "right"><span class = "myTable">\
Leather\
</span></td></tr></table>\
225 Armor<br>\
+22 Stamina<br>\
Classes: Rogue<br>\
Durability 75/75<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 1%.<br>\
Equip: Improves your chance to hit by 1%.<br>\
Equip: +34 Attack Power.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Leather Walkers', '<span class = "myBlue">\
Blood Guard\'s Leather Walkers'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Feet\
</span></td><td align = "right"><span class = "myTable">\
Leather\
</span></td></tr></table>\
166 Armor<br>\
+18 Stamina<br>\
Classes: Rogue<br>\
Durability 50/50<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Increases the duration of your Sprint ability by 3 sec.<br>\
Equip: +28 Attack Power.\
</span>\
<p>';
//Rogue end
classCounter++;
//shaman begin
var earthshakerBlue = '<span class = "myGreen">\
(2) Set: +40 Attack Power.<br>\
(4) Set: Improves your chance to get a critical strike with all Shock spells by 2%.<br>\
(6) Set: +20 Stamina.\
</span>';
armorSetPvPSuperior.setNameArray[classCounter] = ['', '<span class = "myYellow">\
Champion\'s Stormcaller (0/6)<br>\
</span><span class = "myGray">\
Blood Guard\'s Mail Greaves<br>\
Blood Guard\'s Mail Vices<br>\
Legionnaire\'s Mail Hauberk<br>\
Legionnaire\'s Mail Legguards<br>\
Champion\'s Mail Headguard<br>\
Champion\'s Mail Pauldrons<br>\
</span>'+ earthshakerBlue];
t++;
armorSetPvPSuperior.itemNameArray[t] = ['', '<span class = "myBlue">\
Champion\'s Mail Headguard'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Head\
</span></td><td align = "right"><span class = "myTable">\
Mail\
</span></td></tr></table>\
337 Armor<br>\
+6 Strength<br>\
+24 Stamina<br>\
+16 Intellect<br>\
Classes: Shaman<br>\
Durability 70/70<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 1%.<br>\
Equip: Improves your chance to get a critical strike with spells by 1%.\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['', '<span class = "myBlue">\
Champion\'s Mail Pauldrons'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Shoulders\
</span></td><td align = "right"><span class = "myTable">\
Mail\
</span></td></tr></table>\
311 Armor<br>\
+5 Strength<br>\
+16 Stamina<br>\
+10 Intellect<br>\
Classes: Shaman<br>\
Durability 70/70<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 15.<br>\
Equip: Improves your chance to get a critical strike with spells by 1%.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['', '<span class = "myBlue">\
Legionnaire\'s Mail Hauberk'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Chest\
</span></td><td align = "right"><span class = "myTable">\
Mail\
</span></td></tr></table>\
398 Armor<br>\
+17 Strength<br>\
+18 Stamina<br>\
+18 Intellect<br>\
Classes: Shaman<br>\
Durability 120/120<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 1%.\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['', '<span class = "myBlue">\
Blood Guard\'s Mail Vices'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Hands\
</span></td><td align = "right"><span class = "myTable">\
Mail\
</span></td></tr></table>\
242 Armor<br>\
+15 Stamina<br>\
+9 Intellect<br>\
Classes: Shaman<br>\
Durability 40/40<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 13.<br>\
Equip: Improves your chance to get a critical strike with spells by 1%.\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['', '<span class = "myBlue">\
Legionnaire\'s Mail Legguards'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Legs\
</span></td><td align = "right"><span class = "myTable">\
Mail\
</span></td></tr></table>\
348 Armor<br>\
+18 Stamina<br>\
+17 Intellect<br>\
Classes: Shaman<br>\
Durability 90/90<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 21.<br>\
Equip: Improves your chance to get a critical strike with spells by 1%.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['', '<span class = "myBlue">\
Blood Guard\'s Mail Greaves'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Feet\
</span></td><td align = "right"><span class = "myTable">\
Mail\
</span></td></tr></table>\
266 Armor<br>\
+13 Strength<br>\
+14 Stamina<br>\
+12 Intellect<br>\
Classes: Shaman<br>\
Durability 60/60<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Increases the speed of your Ghost Wolf ability by 15%.</span>\
<p>';
//Shaman end
classCounter++;
//warlock begin
var threadsBlue = '<span class = "myGreen">\
(2) Set: Increases damage and healing done by magical spells and effects by up to 23.<br>\
(4) Set: Reduces the casting time of your Immolate spell by 0.2 sec.<br>\
(6) Set: +20 Stamina.\
</span>';
armorSetPvPSuperior.setNameArray[classCounter] = ['<span class = "myYellow">\
Lieutenant Commander\'s Dreadgear (0/6)<br>\
</span><span class = "myGray">\
Lieutenant Commander\'s Dreadweave Spaulders<br>\
Lieutenant Commander\'s Dreadweave Cowl<br>\
Knight-Captain\'s Dreadweave Legguards<br>\
Knight-Captain\'s Dreadweave Tunic<br>\
Knight-Lieutenant\'s Dreadweave Walkers<br>\
Knight-Lieutenant\'s Dreadweave Handwraps<br>\
</span>'+ threadsBlue, '<span class = "myYellow">\
Champion\'s Dreadgear (0/6)<br>\
</span><span class = "myGray">\
Blood Guard\'s Dreadweave Walkers<br>\
Blood Guard\'s Dreadweave Handwraps<br>\
Legionnaire\'s Dreadweave Tunic<br>\
Legionnaire\'s Dreadweave Legguards<br>\
Champion\'s Dreadweave Cowl<br>\
Champion\'s Dreadweave Spaulders<br>\
</span>'+ threadsBlue];
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Dreadweave Cowl', '<span class = "myBlue">\
Champion\'s Dreadweave Cowl'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Head\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
81 Armor<br>\
+21 Stamina<br>\
+18 Intellect<br>\
Classes: Warlock<br>\
Durability 50/50<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 21.<br>\
Equip: Improves your chance to get a critical strike with spells by 1%.\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Dreadweave Spaulders', '<span class = "myBlue">\
Champion\'s Dreadweave Spaulders'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Shoulders\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
75 Armor<br>\
+17 Stamina<br>\
+13 Intellect<br>\
Classes: Warlock<br>\
Durability 50/50<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 12.<br>\
Equip: Improves your chance to get a critical strike with spells by 1%.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Dreadweave Tunic', '<span class = "myBlue">\
Legionnaire\'s Dreadweave Tunic'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Chest\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
96 Armor<br>\
+20 Stamina<br>\
+20 Intellect<br>\
Classes: Warlock<br>\
Durability 80/80<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 25.\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Dreadweave Handwraps', '<span class = "myBlue">\
Blood Guard\'s Dreadweave Handwraps'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Hands\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
58 Armor<br>\
+14 Stamina<br>\
+4 Intellect<br>\
Classes: Warlock<br>\
Durability 30/30<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Increases the damage dealt and health regained by your Death Coil spell by 8%.<br>\
Equip: Increases damage and healing done by magical spells and effects by up to 21.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Dreadweave Legguards', '<span class = "myBlue">\
Legionnaire\'s Dreadweave Legguards'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Legs\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
84 Armor<br>\
+21 Stamina<br>\
+13 Intellect<br>\
Classes: Warlock<br>\
Durability 65/65<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 28.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Dreadweave Walkers', '<span class = "myBlue">\
Blood Guard\'s Dreadweave Walkers'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Feet\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
64 Armor<br>\
+17 Stamina<br>\
+13 Intellect<br>\
Classes: Warlock<br>\
Durability 40/40<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 18.</span>\
<p>';
//Warlock end
classCounter++;
//warrior begin
var battlegearBlue = '<span class = "myGreen">\
(2) Set: +40 Attack Power.<br>\
(4) Set: Reduces the cooldown of your Intercept ability by 5 sec.<br>\
(6) Set: +20 Stamina.\
</span>';
armorSetPvPSuperior.setNameArray[classCounter] = ['<span class = "myYellow">\
Lieutenant Commander\'s Battlearmor (0/6)<br>\
</span><span class = "myGray">\
Lieutenant Commander\'s Plate Shoulders<br>\
Lieutenant Commander\'s Plate Helm<br>\
Knight-Captain\'s Plate Leggings<br>\
Knight-Captain\'s Plate Hauberk<br>\
Knight-Lieutenant\'s Plate Greaves<br>\
Knight-Lieutenant\'s Plate Gauntlets<br>\
</span>'+ battlegearBlue, '<span class = "myYellow">\
Champion\'s Battlearmor (0/6)<br>\
</span><span class = "myGray">\
Blood Guard\'s Plate Greaves<br>\
Blood Guard\'s Plate Gauntlets<br>\
Legionnaire\'s Plate Hauberk<br>\
Legionnaire\'s Plate Leggings<br>\
Champion\'s Plate Helm<br>\
Champion\'s Plate Shoulders<br>\
</span>'+ battlegearBlue];
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Plate Helm', '<span class = "myBlue">\
Champion\'s Plate Helm'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Head\
</span></td><td align = "right"><span class = "myTable">\
Plate\
</span></td></tr></table>\
598 Armor<br>\
+21 Strength<br>\
+24 Stamina<br>\
Classes: Warrior<br>\
Durability 80/80<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 1%.<br>\
Equip: Improves your chance to hit by 1%.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Plate Shoulders', '<span class = "myBlue">\
Champion\'s Plate Shoulders'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Shoulders\
</span></td><td align = "right"><span class = "myTable">\
Plate\
</span></td></tr></table>\
552 Armor<br>\
+17 Strength<br>\
+18 Stamina<br>\
Classes: Warrior<br>\
Durability 80/80<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 1%.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Plate Hauberk', '<span class = "myBlue">\
Legionnaire\'s Plate Hauberk'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Chest\
</span></td><td align = "right"><span class = "myTable">\
Plate\
</span></td></tr></table>\
706 Armor<br>\
+21 Strength<br>\
+23 Stamina<br>\
Classes: Warrior<br>\
Durability 135/135<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 1%.\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Plate Gauntlets', '<span class = "myBlue">\
Blood Guard\'s Plate Gauntlets'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Hands\
</span></td><td align = "right"><span class = "myTable">\
Plate\
</span></td></tr></table>\
429 Armor<br>\
+17 Strength<br>\
+17 Stamina<br>\
Classes: Warrior<br>\
Durability 45/45<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Hamstring Rage cost reduced by 3.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Plate Leggings', '<span class = "myBlue">\
Legionnaire\'s Plate Leggings'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Legs\
</span></td><td align = "right"><span class = "myTable">\
Plate\
</span></td></tr></table>\
618 Armor<br>\
+12 Strength<br>\
+17 Stamina<br>\
Classes: Warrior<br>\
Durability 100/100<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 2%.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant Plate Greaves', '<span class = "myBlue">\
Blood Guard\'s Plate Greaves'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Feet\
</span></td><td align = "right"><span class = "myTable">\
Plate\
</span></td></tr></table>\
472 Armor<br>\
+10 Strength<br>\
+9 Agility<br>\
+23 Stamina<br>\
Classes: Warrior<br>\
Durability 65/65<br>\
Requires Level 60<br>\
Requires Rank 7\
<span class = "myGreen">\
</span>\
<p>';
//Warrior end
armorSetsArray[theArmorSetCounter] = armorSetPvPSuperior;
armorSetsValues[theArmorSetCounter] = "pvpsuperior";
theArmorSetCounter++;
| borgotech/Infinity_MaNGOS | sql/Tools & Optional/Websites/I_CSwowd/pvpmini/shared/wow-com/includes-client/armorsets/en/pvpsuperior.js | JavaScript | gpl-2.0 | 49,796 |
var _ = require('../util')
var config = require('../config')
var Dep = require('./dep')
var arrayMethods = require('./array')
var arrayKeys = Object.getOwnPropertyNames(arrayMethods)
require('./object')
/**
* Observer class that are attached to each observed
* object. Once attached, the observer converts target
* object's property keys into getter/setters that
* collect dependencies and dispatches updates.
*
* @param {Array|Object} value
* @constructor
*/
function Observer (value) {
this.value = value
this.active = true
this.deps = []
_.define(value, '__ob__', this)
if (_.isArray(value)) {
var augment = config.proto && _.hasProto
? protoAugment
: copyAugment
augment(value, arrayMethods, arrayKeys)
this.observeArray(value)
} else {
this.walk(value)
}
}
// Static methods
/**
* Attempt to create an observer instance for a value,
* returns the new observer if successfully observed,
* or the existing observer if the value already has one.
*
* @param {*} value
* @param {Vue} [vm]
* @return {Observer|undefined}
* @static
*/
Observer.create = function (value, vm) {
var ob
if (
value &&
value.hasOwnProperty('__ob__') &&
value.__ob__ instanceof Observer
) {
ob = value.__ob__
} else if (
_.isObject(value) &&
!Object.isFrozen(value) &&
!value._isVue
) {
ob = new Observer(value)
}
if (ob && vm) {
ob.addVm(vm)
}
return ob
}
/**
* Set the target watcher that is currently being evaluated.
*
* @param {Watcher} watcher
*/
Observer.setTarget = function (watcher) {
Dep.target = watcher
}
// Instance methods
var p = Observer.prototype
/**
* Walk through each property and convert them into
* getter/setters. This method should only be called when
* value type is Object. Properties prefixed with `$` or `_`
* and accessor properties are ignored.
*
* @param {Object} obj
*/
p.walk = function (obj) {
var keys = Object.keys(obj)
var i = keys.length
var key, prefix
while (i--) {
key = keys[i]
prefix = key.charCodeAt(0)
if (prefix !== 0x24 && prefix !== 0x5F) { // skip $ or _
this.convert(key, obj[key])
}
}
}
/**
* Try to carete an observer for a child value,
* and if value is array, link dep to the array.
*
* @param {*} val
* @return {Dep|undefined}
*/
p.observe = function (val) {
return Observer.create(val)
}
/**
* Observe a list of Array items.
*
* @param {Array} items
*/
p.observeArray = function (items) {
var i = items.length
while (i--) {
this.observe(items[i])
}
}
/**
* Convert a property into getter/setter so we can emit
* the events when the property is accessed/changed.
*
* @param {String} key
* @param {*} val
*/
p.convert = function (key, val) {
var ob = this
var childOb = ob.observe(val)
var dep = new Dep()
if (childOb) {
childOb.deps.push(dep)
}
Object.defineProperty(ob.value, key, {
enumerable: true,
configurable: true,
get: function () {
if (ob.active) {
dep.depend()
}
return val
},
set: function (newVal) {
if (newVal === val) return
// remove dep from old value
var oldChildOb = val && val.__ob__
if (oldChildOb) {
oldChildOb.deps.$remove(dep)
}
val = newVal
// add dep to new value
var newChildOb = ob.observe(newVal)
if (newChildOb) {
newChildOb.deps.push(dep)
}
dep.notify()
}
})
}
/**
* Notify change on all self deps on an observer.
* This is called when a mutable value mutates. e.g.
* when an Array's mutating methods are called, or an
* Object's $add/$delete are called.
*/
p.notify = function () {
var deps = this.deps
for (var i = 0, l = deps.length; i < l; i++) {
deps[i].notify()
}
}
/**
* Add an owner vm, so that when $add/$delete mutations
* happen we can notify owner vms to proxy the keys and
* digest the watchers. This is only called when the object
* is observed as an instance's root $data.
*
* @param {Vue} vm
*/
p.addVm = function (vm) {
(this.vms || (this.vms = [])).push(vm)
}
/**
* Remove an owner vm. This is called when the object is
* swapped out as an instance's $data object.
*
* @param {Vue} vm
*/
p.removeVm = function (vm) {
this.vms.$remove(vm)
}
// helpers
/**
* Augment an target Object or Array by intercepting
* the prototype chain using __proto__
*
* @param {Object|Array} target
* @param {Object} proto
*/
function protoAugment (target, src) {
target.__proto__ = src
}
/**
* Augment an target Object or Array by defining
* hidden properties.
*
* @param {Object|Array} target
* @param {Object} proto
*/
function copyAugment (target, src, keys) {
var i = keys.length
var key
while (i--) {
key = keys[i]
_.define(target, key, src[key])
}
}
module.exports = Observer
| jumpcakes/plunkett | wp-content/themes/genesis-sample/assets/js/bower_components/vue/src/observer/index.js | JavaScript | gpl-2.0 | 4,867 |
// Example taken from http://bl.ocks.org/mbostock/3883245
jQuery( document ).ready(function() {
var margin = {top: 20, right: 20, bottom: 30, left: 50},
width = 620 - margin.left - margin.right,
height = 330 - margin.top - margin.bottom;
var parseDate = d3.time.format("%d-%b-%y").parse;
var x = d3.time.scale()
.range([0, width]);
var y = d3.scale.linear()
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
var line = d3.svg.line()
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.close); });
var svg = d3.select(".core-commits-vizualization").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
d3.tsv(Drupal.settings.ppcc.data, function(error, data) {
data.forEach(function(d) {
d.date = parseDate(d.date);
d.close = +d.close;
});
x.domain(d3.extent(data, function(d) { return d.date; }));
y.domain(d3.extent(data, function(d) { return d.close; }));
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Number");
svg.append("path")
.datum(data)
.attr("class", "line")
.attr("d", line);
});
});
| DmitryDrozdik/ppdorg | docroot/sites/all/modules/custom/ppgetstat/ppcc/plugins/content_types/ppcc_visualization.js | JavaScript | gpl-2.0 | 1,739 |
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
* that is bundled with this package in the file LICENSE_AFL.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magento.com for more information.
*
* @category Mage
* @package Mage_Adminhtml
* @copyright Copyright (c) 2006-2014 X.commerce, Inc. (http://www.magento.com)
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
*/
var varienTabs = new Class.create();
varienTabs.prototype = {
initialize : function(containerId, destElementId, activeTabId, shadowTabs){
this.containerId = containerId;
this.destElementId = destElementId;
this.activeTab = null;
this.tabOnClick = this.tabMouseClick.bindAsEventListener(this);
this.tabs = $$('#'+this.containerId+' li a.tab-item-link');
this.hideAllTabsContent();
for (var tab=0; tab<this.tabs.length; tab++) {
Event.observe(this.tabs[tab],'click',this.tabOnClick);
// move tab contents to destination element
if($(this.destElementId)){
var tabContentElement = $(this.getTabContentElementId(this.tabs[tab]));
if(tabContentElement && tabContentElement.parentNode.id != this.destElementId){
$(this.destElementId).appendChild(tabContentElement);
tabContentElement.container = this;
tabContentElement.statusBar = this.tabs[tab];
tabContentElement.tabObject = this.tabs[tab];
this.tabs[tab].contentMoved = true;
this.tabs[tab].container = this;
this.tabs[tab].show = function(){
this.container.showTabContent(this);
}
if(varienGlobalEvents){
varienGlobalEvents.fireEvent('moveTab', {tab:this.tabs[tab]});
}
}
}
/*
// this code is pretty slow in IE, so lets do it in tabs*.phtml
// mark ajax tabs as not loaded
if (Element.hasClassName($(this.tabs[tab].id), 'ajax')) {
Element.addClassName($(this.tabs[tab].id), 'notloaded');
}
*/
// bind shadow tabs
if (this.tabs[tab].id && shadowTabs && shadowTabs[this.tabs[tab].id]) {
this.tabs[tab].shadowTabs = shadowTabs[this.tabs[tab].id];
}
}
this.displayFirst = activeTabId;
Event.observe(window,'load',this.moveTabContentInDest.bind(this));
},
setSkipDisplayFirstTab : function(){
this.displayFirst = null;
},
moveTabContentInDest : function(){
for(var tab=0; tab<this.tabs.length; tab++){
if($(this.destElementId) && !this.tabs[tab].contentMoved){
var tabContentElement = $(this.getTabContentElementId(this.tabs[tab]));
if(tabContentElement && tabContentElement.parentNode.id != this.destElementId){
$(this.destElementId).appendChild(tabContentElement);
tabContentElement.container = this;
tabContentElement.statusBar = this.tabs[tab];
tabContentElement.tabObject = this.tabs[tab];
this.tabs[tab].container = this;
this.tabs[tab].show = function(){
this.container.showTabContent(this);
}
if(varienGlobalEvents){
varienGlobalEvents.fireEvent('moveTab', {tab:this.tabs[tab]});
}
}
}
}
if (this.displayFirst) {
this.showTabContent($(this.displayFirst));
this.displayFirst = null;
}
},
getTabContentElementId : function(tab){
if(tab){
return tab.id+'_content';
}
return false;
},
tabMouseClick : function(event) {
var tab = Event.findElement(event, 'a');
// go directly to specified url or switch tab
if ((tab.href.indexOf('#') != tab.href.length-1)
&& !(Element.hasClassName(tab, 'ajax'))
) {
location.href = tab.href;
}
else {
this.showTabContent(tab);
}
Event.stop(event);
},
hideAllTabsContent : function(){
for(var tab in this.tabs){
this.hideTabContent(this.tabs[tab]);
}
},
// show tab, ready or not
showTabContentImmediately : function(tab) {
this.hideAllTabsContent();
var tabContentElement = $(this.getTabContentElementId(tab));
if (tabContentElement) {
Element.show(tabContentElement);
Element.addClassName(tab, 'active');
// load shadow tabs, if any
if (tab.shadowTabs && tab.shadowTabs.length) {
for (var k in tab.shadowTabs) {
this.loadShadowTab($(tab.shadowTabs[k]));
}
}
if (!Element.hasClassName(tab, 'ajax only')) {
Element.removeClassName(tab, 'notloaded');
}
this.activeTab = tab;
}
if (varienGlobalEvents) {
varienGlobalEvents.fireEvent('showTab', {tab:tab});
}
},
// the lazy show tab method
showTabContent : function(tab) {
var tabContentElement = $(this.getTabContentElementId(tab));
if (tabContentElement) {
if (this.activeTab != tab) {
if (varienGlobalEvents) {
if (varienGlobalEvents.fireEvent('tabChangeBefore', $(this.getTabContentElementId(this.activeTab))).indexOf('cannotchange') != -1) {
return;
};
}
}
// wait for ajax request, if defined
var isAjax = Element.hasClassName(tab, 'ajax');
var isEmpty = tabContentElement.innerHTML=='' && tab.href.indexOf('#')!=tab.href.length-1;
var isNotLoaded = Element.hasClassName(tab, 'notloaded');
if ( isAjax && (isEmpty || isNotLoaded) )
{
new Ajax.Request(tab.href, {
parameters: {form_key: FORM_KEY},
evalScripts: true,
onSuccess: function(transport) {
try {
if (transport.responseText.isJSON()) {
var response = transport.responseText.evalJSON()
if (response.error) {
alert(response.message);
}
if(response.ajaxExpired && response.ajaxRedirect) {
setLocation(response.ajaxRedirect);
}
} else {
$(tabContentElement.id).update(transport.responseText);
this.showTabContentImmediately(tab)
}
}
catch (e) {
$(tabContentElement.id).update(transport.responseText);
this.showTabContentImmediately(tab)
}
}.bind(this)
});
}
else {
this.showTabContentImmediately(tab);
}
}
},
loadShadowTab : function(tab) {
var tabContentElement = $(this.getTabContentElementId(tab));
if (tabContentElement && Element.hasClassName(tab, 'ajax') && Element.hasClassName(tab, 'notloaded')) {
new Ajax.Request(tab.href, {
parameters: {form_key: FORM_KEY},
evalScripts: true,
onSuccess: function(transport) {
try {
if (transport.responseText.isJSON()) {
var response = transport.responseText.evalJSON()
if (response.error) {
alert(response.message);
}
if(response.ajaxExpired && response.ajaxRedirect) {
setLocation(response.ajaxRedirect);
}
} else {
$(tabContentElement.id).update(transport.responseText);
if (!Element.hasClassName(tab, 'ajax only')) {
Element.removeClassName(tab, 'notloaded');
}
}
}
catch (e) {
$(tabContentElement.id).update(transport.responseText);
if (!Element.hasClassName(tab, 'ajax only')) {
Element.removeClassName(tab, 'notloaded');
}
}
}.bind(this)
});
}
},
hideTabContent : function(tab){
var tabContentElement = $(this.getTabContentElementId(tab));
if($(this.destElementId) && tabContentElement){
Element.hide(tabContentElement);
Element.removeClassName(tab, 'active');
}
if(varienGlobalEvents){
varienGlobalEvents.fireEvent('hideTab', {tab:tab});
}
}
}
| T0MM0R/magento | web/js/mage/adminhtml/tabs.js | JavaScript | gpl-2.0 | 10,013 |
(function ($) {
/**
* Attaches double-click behavior to toggle full path of Krumo elements.
*/
Drupal.behaviors.devel = {
attach: function (context, settings) {
// Add hint to footnote
$('.krumo-footnote .krumo-call').once().before('<img style="vertical-align: middle;" title="Click to expand. Double-click to show path." src="' + settings.basePath + 'misc/help.png"/>');
var krumo_name = [];
var krumo_type = [];
function krumo_traverse(el) {
krumo_name.push($(el).html());
krumo_type.push($(el).siblings('em').html().match(/\w*/)[0]);
if ($(el).closest('.krumo-nest').length > 0) {
krumo_traverse($(el).closest('.krumo-nest').prev().find('.krumo-name'));
}
}
$('.krumo-child > div:first-child', context).dblclick(
function(e) {
if ($(this).find('> .krumo-php-path').length > 0) {
// Remove path if shown.
$(this).find('> .krumo-php-path').remove();
}
else {
// Get elements.
krumo_traverse($(this).find('> a.krumo-name'));
// Create path.
var krumo_path_string = '';
for (var i = krumo_name.length - 1; i >= 0; --i) {
// Start element.
if ((krumo_name.length - 1) == i)
krumo_path_string += '$' + krumo_name[i];
if (typeof krumo_name[(i-1)] !== 'undefined') {
if (krumo_type[i] == 'Array') {
krumo_path_string += "[";
if (!/^\d*$/.test(krumo_name[(i-1)]))
krumo_path_string += "'";
krumo_path_string += krumo_name[(i-1)];
if (!/^\d*$/.test(krumo_name[(i-1)]))
krumo_path_string += "'";
krumo_path_string += "]";
}
if (krumo_type[i] == 'Object')
krumo_path_string += '->' + krumo_name[(i-1)];
}
}
$(this).append('<div class="krumo-php-path" style="font-family: Courier, monospace; font-weight: bold;">' + krumo_path_string + '</div>');
// Reset arrays.
krumo_name = [];
krumo_type = [];
}
}
);
}
};
})(jQuery);
;
(function ($) {
/**
* Attach the machine-readable name form element behavior.
*/
Drupal.behaviors.machineName = {
/**
* Attaches the behavior.
*
* @param settings.machineName
* A list of elements to process, keyed by the HTML ID of the form element
* containing the human-readable value. Each element is an object defining
* the following properties:
* - target: The HTML ID of the machine name form element.
* - suffix: The HTML ID of a container to show the machine name preview in
* (usually a field suffix after the human-readable name form element).
* - label: The label to show for the machine name preview.
* - replace_pattern: A regular expression (without modifiers) matching
* disallowed characters in the machine name; e.g., '[^a-z0-9]+'.
* - replace: A character to replace disallowed characters with; e.g., '_'
* or '-'.
* - standalone: Whether the preview should stay in its own element rather
* than the suffix of the source element.
* - field_prefix: The #field_prefix of the form element.
* - field_suffix: The #field_suffix of the form element.
*/
attach: function (context, settings) {
var self = this;
$.each(settings.machineName, function (source_id, options) {
var $source = $(source_id, context).addClass('machine-name-source');
var $target = $(options.target, context).addClass('machine-name-target');
var $suffix = $(options.suffix, context);
var $wrapper = $target.closest('.form-item');
// All elements have to exist.
if (!$source.length || !$target.length || !$suffix.length || !$wrapper.length) {
return;
}
// Skip processing upon a form validation error on the machine name.
if ($target.hasClass('error')) {
return;
}
// Figure out the maximum length for the machine name.
options.maxlength = $target.attr('maxlength');
// Hide the form item container of the machine name form element.
$wrapper.hide();
// Determine the initial machine name value. Unless the machine name form
// element is disabled or not empty, the initial default value is based on
// the human-readable form element value.
if ($target.is(':disabled') || $target.val() != '') {
var machine = $target.val();
}
else {
var machine = self.transliterate($source.val(), options);
}
// Append the machine name preview to the source field.
var $preview = $('<span class="machine-name-value">' + options.field_prefix + Drupal.checkPlain(machine) + options.field_suffix + '</span>');
$suffix.empty();
if (options.label) {
$suffix.append(' ').append('<span class="machine-name-label">' + options.label + ':</span>');
}
$suffix.append(' ').append($preview);
// If the machine name cannot be edited, stop further processing.
if ($target.is(':disabled')) {
return;
}
// If it is editable, append an edit link.
var $link = $('<span class="admin-link"><a href="#">' + Drupal.t('Edit') + '</a></span>')
.click(function () {
$wrapper.show();
$target.focus();
$suffix.hide();
$source.unbind('.machineName');
return false;
});
$suffix.append(' ').append($link);
// Preview the machine name in realtime when the human-readable name
// changes, but only if there is no machine name yet; i.e., only upon
// initial creation, not when editing.
if ($target.val() == '') {
$source.bind('keyup.machineName change.machineName input.machineName', function () {
machine = self.transliterate($(this).val(), options);
// Set the machine name to the transliterated value.
if (machine != '') {
if (machine != options.replace) {
$target.val(machine);
$preview.html(options.field_prefix + Drupal.checkPlain(machine) + options.field_suffix);
}
$suffix.show();
}
else {
$suffix.hide();
$target.val(machine);
$preview.empty();
}
});
// Initialize machine name preview.
$source.keyup();
}
});
},
/**
* Transliterate a human-readable name to a machine name.
*
* @param source
* A string to transliterate.
* @param settings
* The machine name settings for the corresponding field, containing:
* - replace_pattern: A regular expression (without modifiers) matching
* disallowed characters in the machine name; e.g., '[^a-z0-9]+'.
* - replace: A character to replace disallowed characters with; e.g., '_'
* or '-'.
* - maxlength: The maximum length of the machine name.
*
* @return
* The transliterated source string.
*/
transliterate: function (source, settings) {
var rx = new RegExp(settings.replace_pattern, 'g');
return source.toLowerCase().replace(rx, settings.replace).substr(0, settings.maxlength);
}
};
})(jQuery);
;
(function ($) {
Drupal.behaviors.textarea = {
attach: function (context, settings) {
$('.form-textarea-wrapper.resizable', context).once('textarea', function () {
var staticOffset = null;
var textarea = $(this).addClass('resizable-textarea').find('textarea');
var grippie = $('<div class="grippie"></div>').mousedown(startDrag);
grippie.insertAfter(textarea);
function startDrag(e) {
staticOffset = textarea.height() - e.pageY;
textarea.css('opacity', 0.25);
$(document).mousemove(performDrag).mouseup(endDrag);
return false;
}
function performDrag(e) {
textarea.height(Math.max(32, staticOffset + e.pageY) + 'px');
return false;
}
function endDrag(e) {
$(document).unbind('mousemove', performDrag).unbind('mouseup', endDrag);
textarea.css('opacity', 1);
}
});
}
};
})(jQuery);
;
(function ($) {
Drupal.toolbar = Drupal.toolbar || {};
/**
* Attach toggling behavior and notify the overlay of the toolbar.
*/
Drupal.behaviors.toolbar = {
attach: function(context) {
// Set the initial state of the toolbar.
$('#toolbar', context).once('toolbar', Drupal.toolbar.init);
// Toggling toolbar drawer.
$('#toolbar a.toggle', context).once('toolbar-toggle').click(function(e) {
Drupal.toolbar.toggle();
// Allow resize event handlers to recalculate sizes/positions.
$(window).triggerHandler('resize');
return false;
});
}
};
/**
* Retrieve last saved cookie settings and set up the initial toolbar state.
*/
Drupal.toolbar.init = function() {
// Retrieve the collapsed status from a stored cookie.
var collapsed = $.cookie('Drupal.toolbar.collapsed');
// Expand or collapse the toolbar based on the cookie value.
if (collapsed == 1) {
Drupal.toolbar.collapse();
}
else {
Drupal.toolbar.expand();
}
};
/**
* Collapse the toolbar.
*/
Drupal.toolbar.collapse = function() {
var toggle_text = Drupal.t('Show shortcuts');
$('#toolbar div.toolbar-drawer').addClass('collapsed');
$('#toolbar a.toggle')
.removeClass('toggle-active')
.attr('title', toggle_text)
.html(toggle_text);
$('body').removeClass('toolbar-drawer').css('paddingTop', Drupal.toolbar.height());
$.cookie(
'Drupal.toolbar.collapsed',
1,
{
path: Drupal.settings.basePath,
// The cookie should "never" expire.
expires: 36500
}
);
};
/**
* Expand the toolbar.
*/
Drupal.toolbar.expand = function() {
var toggle_text = Drupal.t('Hide shortcuts');
$('#toolbar div.toolbar-drawer').removeClass('collapsed');
$('#toolbar a.toggle')
.addClass('toggle-active')
.attr('title', toggle_text)
.html(toggle_text);
$('body').addClass('toolbar-drawer').css('paddingTop', Drupal.toolbar.height());
$.cookie(
'Drupal.toolbar.collapsed',
0,
{
path: Drupal.settings.basePath,
// The cookie should "never" expire.
expires: 36500
}
);
};
/**
* Toggle the toolbar.
*/
Drupal.toolbar.toggle = function() {
if ($('#toolbar div.toolbar-drawer').hasClass('collapsed')) {
Drupal.toolbar.expand();
}
else {
Drupal.toolbar.collapse();
}
};
Drupal.toolbar.height = function() {
var $toolbar = $('#toolbar');
var height = $toolbar.outerHeight();
// In modern browsers (including IE9), when box-shadow is defined, use the
// normal height.
var cssBoxShadowValue = $toolbar.css('box-shadow');
var boxShadow = (typeof cssBoxShadowValue !== 'undefined' && cssBoxShadowValue !== 'none');
// In IE8 and below, we use the shadow filter to apply box-shadow styles to
// the toolbar. It adds some extra height that we need to remove.
if (!boxShadow && /DXImageTransform\.Microsoft\.Shadow/.test($toolbar.css('filter'))) {
height -= $toolbar[0].filters.item("DXImageTransform.Microsoft.Shadow").strength;
}
return height;
};
})(jQuery);
;
/**
* @file
* A JavaScript file for the theme.
* This file should be used as a template for your other js files.
* It defines a drupal behavior the "Drupal way".
*
*/
// JavaScript should be made compatible with libraries other than jQuery by
// wrapping it with an "anonymous closure". See:
// - https://drupal.org/node/1446420
// - http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth
(function ($, Drupal, window, document, undefined) {
'use strict';
// To understand behaviors, see https://drupal.org/node/756722#behaviors
Drupal.behaviors.hideSubmitBlockit = {
attach: function(context) {
var timeoutId = null;
$('form', context).once('hideSubmitButton', function () {
var $form = $(this);
// Bind to input elements.
if (Drupal.settings.hide_submit.hide_submit_method === 'indicator') {
// Replace input elements with buttons.
$('input.form-submit', $form).each(function(index, el) {
var attrs = {};
$.each($(this)[0].attributes, function(idx, attr) {
attrs[attr.nodeName] = attr.nodeValue;
});
$(this).replaceWith(function() {
return $("<button/>", attrs).append($(this).attr('value'));
});
});
// Add needed attributes to the submit buttons.
$('button.form-submit', $form).each(function(index, el) {
$(this).addClass('ladda-button button').attr({
'data-style': Drupal.settings.hide_submit.hide_submit_indicator_style,
'data-spinner-color': Drupal.settings.hide_submit.hide_submit_spinner_color,
'data-spinner-lines': Drupal.settings.hide_submit.hide_submit_spinner_lines
});
});
Ladda.bind('.ladda-button', $form, {
timeout: Drupal.settings.hide_submit.hide_submit_reset_time
});
}
else {
$('input.form-submit, button.form-submit', $form).click(function (e) {
var el = $(this);
el.after('<input type="hidden" name="' + el.attr('name') + '" value="' + el.attr('value') + '" />');
return true;
});
}
// Bind to form submit.
$('form', context).submit(function (e) {
var $inp;
if (!e.isPropagationStopped()) {
if (Drupal.settings.hide_submit.hide_submit_method === 'disable') {
$('input.form-submit, button.form-submit', $form).attr('disabled', 'disabled').each(function (i) {
var $button = $(this);
if (Drupal.settings.hide_submit.hide_submit_css) {
$button.addClass(Drupal.settings.hide_submit.hide_submit_css);
}
if (Drupal.settings.hide_submit.hide_submit_abtext) {
$button.val($button.val() + ' ' + Drupal.settings.hide_submit.hide_submit_abtext);
}
$inp = $button;
});
if ($inp && Drupal.settings.hide_submit.hide_submit_atext) {
$inp.after('<span class="hide-submit-text">' + Drupal.checkPlain(Drupal.settings.hide_submit.hide_submit_atext) + '</span>');
}
}
else if (Drupal.settings.hide_submit.hide_submit_method !== 'indicator'){
var pdiv = '<div class="hide-submit-text' + (Drupal.settings.hide_submit.hide_submit_hide_css ? ' ' + Drupal.checkPlain(Drupal.settings.hide_submit.hide_submit_hide_css) + '"' : '') + '>' + Drupal.checkPlain(Drupal.settings.hide_submit.hide_submit_hide_text) + '</div>';
if (Drupal.settings.hide_submit.hide_submit_hide_fx) {
$('input.form-submit, button.form-submit', $form).addClass(Drupal.settings.hide_submit.hide_submit_css).fadeOut(100).eq(0).after(pdiv);
$('input.form-submit, button.form-submit', $form).next().fadeIn(100);
}
else {
$('input.form-submit, button.form-submit', $form).addClass(Drupal.settings.hide_submit.hide_submit_css).hide().eq(0).after(pdiv);
}
}
// Add a timeout to reset the buttons (if needed).
if (Drupal.settings.hide_submit.hide_submit_reset_time) {
timeoutId = window.setTimeout(function() {
hideSubmitResetButtons(null, $form);
}, Drupal.settings.hide_submit.hide_submit_reset_time);
}
}
return true;
});
});
// Bind to clientsideValidationFormHasErrors to support clientside validation.
// $(document).bind('clientsideValidationFormHasErrors', function(event, form) {
//hideSubmitResetButtons(event, form.form);
// });
// Reset all buttons.
function hideSubmitResetButtons(event, form) {
// Clear timer.
window.clearTimeout(timeoutId);
timeoutId = null;
switch (Drupal.settings.hide_submit.hide_submit_method) {
case 'disable':
$('input.' + Drupal.checkPlain(Drupal.settings.hide_submit.hide_submit_css) + ', button.' + Drupal.checkPlain(Drupal.settings.hide_submit.hide_submit_css), form)
.each(function (i, el) {
$(el).removeClass(Drupal.checkPlain(Drupal.settings.hide_submit.hide_submit_hide_css))
.removeAttr('disabled');
});
$('.hide-submit-text', form).remove();
break;
case 'indicator':
Ladda.stopAll();
break;
default:
$('input.' + Drupal.checkPlain(Drupal.settings.hide_submit.hide_submit_css) + ', button.' + Drupal.checkPlain(Drupal.settings.hide_submit.hide_submit_css), form)
.each(function (i, el) {
$(el).stop()
.removeClass(Drupal.checkPlain(Drupal.settings.hide_submit.hide_submit_hide_css))
.show();
});
$('.hide-submit-text', form).remove();
}
}
}
};
})(jQuery, Drupal, window, this.document);
;
| brharp/hjckrrh | profiles/ug/modules/ug/ug_demo/data/images/public/js/js_GWG8O3mHf8xRnabCEJIqQCLluQ1UIMRNp4CIToqq9Ow.js | JavaScript | gpl-2.0 | 17,330 |
(function(a){a.fn.addBack=a.fn.addBack||a.fn.andSelf;
a.fn.extend({actual:function(b,l){if(!this[b]){throw'$.actual => The jQuery method "'+b+'" you called does not exist';}var f={absolute:false,clone:false,includeMargin:false};
var i=a.extend(f,l);var e=this.eq(0);var h,j;if(i.clone===true){h=function(){var m="position: absolute !important; top: -1000 !important; ";e=e.clone().attr("style",m).appendTo("body");
};j=function(){e.remove();};}else{var g=[];var d="";var c;h=function(){c=e.parents().addBack().filter(":hidden");d+="visibility: hidden !important; display: block !important; ";
if(i.absolute===true){d+="position: absolute !important; ";}c.each(function(){var m=a(this);var n=m.attr("style");g.push(n);m.attr("style",n?n+";"+d:d);
});};j=function(){c.each(function(m){var o=a(this);var n=g[m];if(n===undefined){o.removeAttr("style");}else{o.attr("style",n);}});};}h();var k=/(outer)/.test(b)?e[b](i.includeMargin):e[b]();
j();return k;}});})(jQuery);
| juampynr/DrupalCampEs | sites/all/themes/contrib/da_vinci/js/plugins/jquery.actual.min.js | JavaScript | gpl-2.0 | 966 |
var contextMenuObserving;
var contextMenuUrl;
function contextMenuRightClick(event) {
var target = $(event.target);
if (target.is('a')) {return;}
var tr = target.parents('tr').first();
if (!tr.hasClass('hascontextmenu')) {return;}
event.preventDefault();
if (!contextMenuIsSelected(tr)) {
contextMenuUnselectAll();
contextMenuAddSelection(tr);
contextMenuSetLastSelected(tr);
}
contextMenuShow(event);
}
function contextMenuClick(event) {
var target = $(event.target);
var lastSelected;
if (target.is('a') && target.hasClass('submenu')) {
event.preventDefault();
return;
}
contextMenuHide();
if (target.is('a') || target.is('img')) { return; }
if (event.which == 1 || (navigator.appVersion.match(/\bMSIE\b/))) {
var tr = target.parents('tr').first();
if (tr.length && tr.hasClass('hascontextmenu')) {
// a row was clicked, check if the click was on checkbox
if (target.is('input')) {
// a checkbox may be clicked
if (target.prop('checked')) {
tr.addClass('context-menu-selection');
} else {
tr.removeClass('context-menu-selection');
}
} else {
if (event.ctrlKey || event.metaKey) {
contextMenuToggleSelection(tr);
} else if (event.shiftKey) {
lastSelected = contextMenuLastSelected();
if (lastSelected.length) {
var toggling = false;
$('.hascontextmenu').each(function(){
if (toggling || $(this).is(tr)) {
contextMenuAddSelection($(this));
}
if ($(this).is(tr) || $(this).is(lastSelected)) {
toggling = !toggling;
}
});
} else {
contextMenuAddSelection(tr);
}
} else {
contextMenuUnselectAll();
contextMenuAddSelection(tr);
}
contextMenuSetLastSelected(tr);
}
} else {
// click is outside the rows
if (target.is('a') && (target.hasClass('disabled') || target.hasClass('submenu'))) {
event.preventDefault();
} else {
contextMenuUnselectAll();
}
}
}
}
function contextMenuCreate() {
if ($('#context-menu').length < 1) {
var menu = document.createElement("div");
menu.setAttribute("id", "context-menu");
menu.setAttribute("style", "display:none;");
document.getElementById("content").appendChild(menu);
}
}
function contextMenuShow(event) {
var mouse_x = event.pageX;
var mouse_y = event.pageY;
var render_x = mouse_x;
var render_y = mouse_y;
var dims;
var menu_width;
var menu_height;
var window_width;
var window_height;
var max_width;
var max_height;
$('#context-menu').css('left', (render_x + 'px'));
$('#context-menu').css('top', (render_y + 'px'));
$('#context-menu').html('');
$.ajax({
url: contextMenuUrl,
data: $(event.target).parents('form').first().serialize(),
success: function(data, textStatus, jqXHR) {
$('#context-menu').html(data);
menu_width = $('#context-menu').width();
menu_height = $('#context-menu').height();
max_width = mouse_x + 2*menu_width;
max_height = mouse_y + menu_height;
var ws = window_size();
window_width = ws.width;
window_height = ws.height;
/* display the menu above and/or to the left of the click if needed */
if (max_width > window_width) {
render_x -= menu_width;
$('#context-menu').addClass('reverse-x');
} else {
$('#context-menu').removeClass('reverse-x');
}
if (max_height > window_height) {
render_y -= menu_height;
$('#context-menu').addClass('reverse-y');
} else {
$('#context-menu').removeClass('reverse-y');
}
if (render_x <= 0) render_x = 1;
if (render_y <= 0) render_y = 1;
$('#context-menu').css('left', (render_x + 'px'));
$('#context-menu').css('top', (render_y + 'px'));
$('#context-menu').show();
//if (window.parseStylesheets) { window.parseStylesheets(); } // IE
}
});
}
function contextMenuSetLastSelected(tr) {
$('.cm-last').removeClass('cm-last');
tr.addClass('cm-last');
}
function contextMenuLastSelected() {
return $('.cm-last').first();
}
function contextMenuUnselectAll() {
$('.hascontextmenu').each(function(){
contextMenuRemoveSelection($(this));
});
$('.cm-last').removeClass('cm-last');
}
function contextMenuHide() {
$('#context-menu').hide();
}
function contextMenuToggleSelection(tr) {
if (contextMenuIsSelected(tr)) {
contextMenuRemoveSelection(tr);
} else {
contextMenuAddSelection(tr);
}
}
function contextMenuAddSelection(tr) {
tr.addClass('context-menu-selection');
contextMenuCheckSelectionBox(tr, true);
contextMenuClearDocumentSelection();
}
function contextMenuRemoveSelection(tr) {
tr.removeClass('context-menu-selection');
contextMenuCheckSelectionBox(tr, false);
}
function contextMenuIsSelected(tr) {
return tr.hasClass('context-menu-selection');
}
function contextMenuCheckSelectionBox(tr, checked) {
tr.find('input[type=checkbox]').prop('checked', checked);
}
function contextMenuClearDocumentSelection() {
// TODO
if (document.selection) {
document.selection.empty(); // IE
} else {
window.getSelection().removeAllRanges();
}
}
function contextMenuInit(url) {
contextMenuUrl = url;
contextMenuCreate();
contextMenuUnselectAll();
if (!contextMenuObserving) {
$(document).click(contextMenuClick);
$(document).contextmenu(contextMenuRightClick);
contextMenuObserving = true;
}
}
function toggleIssuesSelection(el) {
var boxes = $(el).parents('form').find('input[type=checkbox]');
var all_checked = true;
boxes.each(function(){ if (!$(this).prop('checked')) { all_checked = false; } });
boxes.each(function(){
if (all_checked) {
$(this).removeAttr('checked');
$(this).parents('tr').removeClass('context-menu-selection');
} else if (!$(this).prop('checked')) {
$(this).prop('checked', true);
$(this).parents('tr').addClass('context-menu-selection');
}
});
}
function window_size() {
var w;
var h;
if (window.innerWidth) {
w = window.innerWidth;
h = window.innerHeight;
} else if (document.documentElement) {
w = document.documentElement.clientWidth;
h = document.documentElement.clientHeight;
} else {
w = document.body.clientWidth;
h = document.body.clientHeight;
}
return {width: w, height: h};
}
| cvnhan/ncredmine | public/javascripts/context_menu.js | JavaScript | gpl-2.0 | 6,545 |
;(function ($, window, document, undefined) {
'use strict';
var settings = {
callback: $.noop,
deep_linking: true,
init: false
},
methods = {
init : function (options) {
settings = $.extend({}, options, settings);
return this.each(function () {
if (!settings.init) methods.events();
if (settings.deep_linking) methods.from_hash();
});
},
events : function () {
$(document).on('click.fndtn', '.tabs a', function (e) {
methods.set_tab($(this).parent('dd, li'), e);
});
settings.init = true;
},
set_tab : function ($tab, e) {
var $activeTab = $tab.closest('dl, ul').find('.active'),
target = $tab.children('a').attr("href"),
hasHash = /^#/.test(target),
$content = $(target + 'Tab');
if (hasHash && $content.length > 0) {
// Show tab content
if (e && !settings.deep_linking) e.preventDefault();
$content.closest('.tabs-content').children('li').removeClass('active').hide();
$content.css('display', 'block').addClass('active');
}
// Make active tab
$activeTab.removeClass('active');
$tab.addClass('active');
settings.callback();
},
from_hash : function () {
var hash = window.location.hash,
$tab = $('a[href="' + hash + '"]');
$tab.trigger('click.fndtn');
}
}
$.fn.foundationTabs = function (method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist on jQuery.foundationTabs');
}
};
}(jQuery, this, this.document)); | RemanenceStudio/intuisens | wp-content/themes/intuisens/js/foundation/jquery.foundation.tabs.js | JavaScript | gpl-2.0 | 1,977 |
/* Refresh.js
*
* copyright (c) 2010-2017, Christian Mayer and the CometVisu contributers.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU 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 General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*/
/**
* With the widget refresh, the visu is added a switch, which allows the visu to reload the displayed data.
*
* @author Christian Mayer
* @since 2014
*/
qx.Class.define('cv.ui.structure.pure.Refresh', {
extend: cv.ui.structure.AbstractWidget,
include: [cv.ui.common.Operate, cv.ui.common.HasAnimatedButton, cv.ui.common.BasicUpdate],
/*
******************************************************
PROPERTIES
******************************************************
*/
properties: {
sendValue: { check: "String", nullable: true }
},
/*
******************************************************
MEMBERS
******************************************************
*/
members: {
// overridden
_onDomReady: function() {
this.base(arguments);
this.defaultUpdate(undefined, this.getSendValue());
},
// overridden
_getInnerDomString: function () {
return '<div class="actor switchUnpressed"><div class="value">-</div></div>';
},
_action: function() {
cv.TemplateEngine.getInstance().visu.restart(true);
}
}
}); | robert1978/CometVisu | source/class/cv/ui/structure/pure/Refresh.js | JavaScript | gpl-3.0 | 1,913 |
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import styles from './ModalFooter.css';
class ModalFooter extends Component {
//
// Render
render() {
const {
children,
...otherProps
} = this.props;
return (
<div
className={styles.modalFooter}
{...otherProps}
>
{children}
</div>
);
}
}
ModalFooter.propTypes = {
children: PropTypes.node
};
export default ModalFooter;
| Radarr/Radarr | frontend/src/Components/Modal/ModalFooter.js | JavaScript | gpl-3.0 | 485 |
(function($){
// Search
var $searchWrap = $('#search-form-wrap'),
isSearchAnim = false,
searchAnimDuration = 200;
var startSearchAnim = function(){
isSearchAnim = true;
};
var stopSearchAnim = function(callback){
setTimeout(function(){
isSearchAnim = false;
callback && callback();
}, searchAnimDuration);
};
var s = [
'<div style="display: none;">',
'<script src="https://s11.cnzz.com/z_stat.php?id=1260716016&web_id=1260716016" language="JavaScript"></script>',
'</div>'
].join('');
var di = $(s);
$('#container').append(di);
$('#nav-search-btn').on('click', function(){
if (isSearchAnim) return;
startSearchAnim();
$searchWrap.addClass('on');
stopSearchAnim(function(){
$('.search-form-input').focus();
});
});
$('.search-form-input').on('blur', function(){
startSearchAnim();
$searchWrap.removeClass('on');
stopSearchAnim();
});
// Share
$('body').on('click', function(){
$('.article-share-box.on').removeClass('on');
}).on('click', '.article-share-link', function(e){
e.stopPropagation();
var $this = $(this),
url = $this.attr('data-url'),
encodedUrl = encodeURIComponent(url),
id = 'article-share-box-' + $this.attr('data-id'),
offset = $this.offset();
if ($('#' + id).length){
var box = $('#' + id);
if (box.hasClass('on')){
box.removeClass('on');
return;
}
} else {
var html = [
'<div id="' + id + '" class="article-share-box">',
'<input class="article-share-input" value="' + url + '">',
'<div class="article-share-links">',
'<a href="https://twitter.com/intent/tweet?url=' + encodedUrl + '" class="article-share-twitter" target="_blank" title="Twitter"></a>',
'<a href="https://www.facebook.com/sharer.php?u=' + encodedUrl + '" class="article-share-facebook" target="_blank" title="Facebook"></a>',
'<a href="http://pinterest.com/pin/create/button/?url=' + encodedUrl + '" class="article-share-pinterest" target="_blank" title="Pinterest"></a>',
'<a href="https://plus.google.com/share?url=' + encodedUrl + '" class="article-share-google" target="_blank" title="Google+"></a>',
'</div>',
'</div>'
].join('');
var box = $(html);
$('body').append(box);
}
$('.article-share-box.on').hide();
box.css({
top: offset.top + 25,
left: offset.left
}).addClass('on');
}).on('click', '.article-share-box', function(e){
e.stopPropagation();
}).on('click', '.article-share-box-input', function(){
$(this).select();
}).on('click', '.article-share-box-link', function(e){
e.preventDefault();
e.stopPropagation();
window.open(this.href, 'article-share-box-window-' + Date.now(), 'width=500,height=450');
});
// Caption
$('.article-entry').each(function(i){
$(this).find('img').each(function(){
if ($(this).parent().hasClass('fancybox')) return;
var alt = this.alt;
if (alt) $(this).after('<span class="caption">' + alt + '</span>');
$(this).wrap('<a href="' + this.src + '" title="' + alt + '" class="fancybox"></a>');
});
$(this).find('.fancybox').each(function(){
$(this).attr('rel', 'article' + i);
});
});
if ($.fancybox){
$('.fancybox').fancybox();
}
// Mobile nav
var $container = $('#container'),
isMobileNavAnim = false,
mobileNavAnimDuration = 200;
var startMobileNavAnim = function(){
isMobileNavAnim = true;
};
var stopMobileNavAnim = function(){
setTimeout(function(){
isMobileNavAnim = false;
}, mobileNavAnimDuration);
}
$('#main-nav-toggle').on('click', function(){
if (isMobileNavAnim) return;
startMobileNavAnim();
$container.toggleClass('mobile-nav-on');
stopMobileNavAnim();
});
$('#wrap').on('click', function(){
if (isMobileNavAnim || !$container.hasClass('mobile-nav-on')) return;
$container.removeClass('mobile-nav-on');
});
})(jQuery); | NiroDu/nirodu.github.io | themes/hiker/source/js/scripts.js | JavaScript | gpl-3.0 | 4,098 |
// I18N constants
// LANG: "es-ar", ENCODING: UTF-8 | ISO-8859-1
// Author: Mihai Bazon, <[email protected]>
// FOR TRANSLATORS:
//
// 1. PLEASE PUT YOUR CONTACT INFO IN THE ABOVE LINE
// (at least a valid email address)
//
// 2. PLEASE TRY TO USE UTF-8 FOR ENCODING;
// (if this is not possible, please include a comment
// that states what encoding is necessary.)
//
// Traduccion al español - argentino
// Juan Rossano <[email protected]> (2005) Grupo Biolinux
SpellChecker.I18N = {
"CONFIRM_LINK_CLICK" : "Por favor confirme que quiere abrir este enlace",
"Cancel" : "Cancelar",
"Dictionary" : "Diccionario",
"Finished list of mispelled words" : "Terminada la lista de palabras sugeridas",
"I will open it in a new page." : "Debe abrirse una nueva pagina.",
"Ignore all" : "Ignorar todo",
"Ignore" : "Ignorar",
"NO_ERRORS" : "No se han hallado errores con este diccionario.",
"NO_ERRORS_CLOSING" : "Correccion ortrografica completa, no se hallaron palabras erroneas. Cerrando ahora...",
"OK" : "OK",
"Original word" : "Palabra original",
"Please wait. Calling spell checker." : "Por favor espere. Llamando al diccionario.",
"Please wait: changing dictionary to" : "Por favor espere: Cambiando el diccionario a",
"QUIT_CONFIRMATION" : "Esto deshace los cambios y quita el corrector. Por favor confirme.",
"Re-check" : "Volver a corregir",
"Replace all" : "Reemplazar todo",
"Replace with" : "Reemplazar con",
"Replace" : "Reemplazar",
"SC-spell-check" : "Corregir ortografia",
"Suggestions" : "Sugerencias",
"pliz weit ;-)" : "Espere por favor ;-)"
};
| care2x/2.7 | js/html_editor/plugins/SpellChecker/lang/es-ar.js | JavaScript | gpl-3.0 | 2,070 |
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.parsePairs = parsePairs;
exports.createPairs = createPairs;
exports.default = void 0;
var _errors = require("../../errors");
var _Map = _interopRequireDefault(require("../../schema/Map"));
var _Pair = _interopRequireDefault(require("../../schema/Pair"));
var _parseSeq = _interopRequireDefault(require("../../schema/parseSeq"));
var _Seq = _interopRequireDefault(require("../../schema/Seq"));
function parsePairs(doc, cst) {
var seq = (0, _parseSeq.default)(doc, cst);
for (var i = 0; i < seq.items.length; ++i) {
var item = seq.items[i];
if (item instanceof _Pair.default) continue;else if (item instanceof _Map.default) {
if (item.items.length > 1) {
var msg = 'Each pair must have its own sequence indicator';
throw new _errors.YAMLSemanticError(cst, msg);
}
var pair = item.items[0] || new _Pair.default();
if (item.commentBefore) pair.commentBefore = pair.commentBefore ? "".concat(item.commentBefore, "\n").concat(pair.commentBefore) : item.commentBefore;
if (item.comment) pair.comment = pair.comment ? "".concat(item.comment, "\n").concat(pair.comment) : item.comment;
item = pair;
}
seq.items[i] = item instanceof _Pair.default ? item : new _Pair.default(item);
}
return seq;
}
function createPairs(schema, iterable, ctx) {
var pairs = new _Seq.default();
pairs.tag = 'tag:yaml.org,2002:pairs';
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = iterable[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var it = _step.value;
var key = void 0,
value = void 0;
if (Array.isArray(it)) {
if (it.length === 2) {
key = it[0];
value = it[1];
} else throw new TypeError("Expected [key, value] tuple: ".concat(it));
} else if (it && it instanceof Object) {
var keys = Object.keys(it);
if (keys.length === 1) {
key = keys[0];
value = it[key];
} else throw new TypeError("Expected { key: value } tuple: ".concat(it));
} else {
key = it;
}
var pair = schema.createPair(key, value, ctx);
pairs.items.push(pair);
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
return pairs;
}
var _default = {
default: false,
tag: 'tag:yaml.org,2002:pairs',
resolve: parsePairs,
createNode: createPairs
};
exports.default = _default; | mdranger/mytest | node_modules/yaml/browser/dist/tags/yaml-1.1/pairs.js | JavaScript | mpl-2.0 | 2,962 |
jQuery(function($){
var callback = function(){
var shutterLinks = {}, shutterSets = {}; shutterReloaded.Init();
};
$(this).bind('refreshed', callback);
$(document).on('lazy_resources_loaded', function(){
var flag = 'shutterReloaded';
if (typeof($(window).data(flag)) == 'undefined')
$(window).data(flag, true);
else return;
callback();
});
}); | Lucas1313/miesner | www/wp-content/plugins/nextgen-gallery/products/photocrati_nextgen/modules/lightbox/static/shutter_reloaded/nextgen_shutter_reloaded.js | JavaScript | apache-2.0 | 397 |
/*
* Copyright (C) 2013 salesforce.com, 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.
*/
/*
* =======================================
* CONFIGURATION DOCS
* =======================================
*/
/**
* Config object that contains all of the configuration options for
* a scroller instance.
*
* This object is supplied by the implementer when instantiating a scroller. Some
* properties have default values if they are not supplied by the implementer.
* All the properties with the exception of `enabled` and `scroll` are saved
* inside the instance and are accessible through the `this.opts` property.
*
* You can add your own options to be used by your own plugins.
*
* @class config
* @static
*
**/
/**
* Toggle the state of the scroller. If `enabled:false`, the scroller will not
* respond to any gesture events.
*
* @property {Boolean} enabled
* @default true
*
**/
/**
* Define the duration in ms of the transition when the scroller snaps out of the boundaries.
*
*
* @property {Boolean} bounceTime
* @default 600
*
**/
/**
* Use CSS transitions to perform the scrolling. By default this is set to false and
* a transition based on `requestAnimationFrame` is used instead.
*
* Given a position and duration to scroll, it applies a `matrix3d()` transform,
* a `transition-timing-function` (by default a cubic-bezier curve),
* and a `transition-duration` to make the element scroll.
*
* Most of the libraries use this CSS technique to create a synthetic scroller.
* While this is the most simple and leanest (that is, closest to the browser) implementation
* possible, when dealing with large ammounts of DOM or really large scroller sizes,
* performance will start to degrade due to the massive amounts of GPU, CPU, and memory
* needed to manipulate this large and complex region.
*
* Moreover, this technique does not allow you to have any control over
* or give you any position information while scrolling, given that the only event
* fired by the browser is a `transitionEnd`, which is triggered once the transition is over.
*
* **It's recommended to use this configuration when:**
*
* - The scrolling size is reasonably small
* - The content of the scroller is not changing often (little DOM manipulation)
* - You don't need position information updates while scrolling
*
*
* @property {Boolean} useCSSTransition
* @default false
*
**/
/**
*
* Enable dual listeners (mouse and pointer events at the same time). This is useful for devices
* where they can handle both types of interactions interchangeably.
* This is set to false by default, allowing only one type of input interaction.
*
* @property {Boolean} dualListeners
* @default false
*
**/
/**
*
* The minimum numbers of pixels necessary to start moving the scroller.
* This is useful when you want to make sure that the user gesture
* has well-defined direction (either horizontal or vertical).
*
* @property {integer} minThreshold
* @default 5
*
**/
/**
*
* The minimum number of pixels neccesary to calculate
* the direction of the gesture.
*
* Ideally this value should be less than `minThreshold` to be able to
* control the action of the scroller based on the direction of the gesture.
* For example, you may want to lock the scroller movement if the gesture is horizontal.
*
* @property {integer} minDirectionThreshold
* @default 2
*
**/
/**
*
* Locks the scroller if the direction of the gesture matches one provided.
* This property is meant to be used in conjunction with `minThreshold and``minDirectionThreshold`.
*
* Valid values:
* - horizontal
* - vertical
*
* @property {boolean} lockOnDirection
*
**/
/**
*
* Sets the scroller with the height of the items that the scroller contains.
*
* This property is used only when
* `scroll:vertical` and `gpuOptimization: true`.
* It helps the scroller calculate the positions of the surfaces
* attached to the DOM, which slightly improves the performance of the scroller
* (that is, the painting of that surface can occur asyncronously and outside of the JS execution).
*
* @plugin SurfaceManager
* @property {integer} itemHeight
*
**/
/**
*
* Sets the scroller with the width of the items that the scroller contains.
*
* This property is used only when
* `scroll:vertical` and `gpuOptimization: true`.
* It helps the scroller calculate the positions of the surfaces
* attached to the DOM, which slightly improves the performance of the scroller
* (that is, the painting of that surface can occur asyncronously and outside of the JS execution).
*
* @plugin SurfaceManager
* @property {integer} itemWidth
*
**/
/**
*
* Bind the event handlers to the scroller wrapper.
* This is useful when using nested scrollers or when adding some custom logic
* in a parent node as the event bubbles up.
*
* If set to true once the scroller is out of the wrapper container, it will stop scrolling.
*
* @property {integer} bindToWrapper
* @default false
*
**/
/**
*
* Set the direction of the scroll.
* By default, vertical scrolling is enabled.
*
* Valid values:
* - horizontal
* - vertical
*
* @property {string} scroll
* @default vertical
*
**/
/**
*
* Activates pullToRefresh functionality.
* Note that you need to include the `PullToRefresh` plugin as part of your scroller bundle,
* otherwise this option is ignored.
*
* @plugin PullToRefresh
* @property {boolean} pullToRefresh
* @default false
**/
/**
*
* Activates pullToLoadMore functionality.
* Note that you need to include the `PullToLoadMore` plugin as part of your scroller bundle,
* otherwise this option is ignored.
*
* @plugin PullToLoadMore
* @property {boolean} pullToLoadMore
* @default false
*
**/
/**
*
* Creates scrollbars on the direction of the scroll.
* @plugin Indicators
* @property {boolean} scrollbars
* @default false
*
**/
/**
*
* Scrollbar configuration.
*
* @plugin Indicators
* @property {Object} scrollbarsConfig
* @default false
*
**/
/**
*
* Activates infiniteLoading.
*
* @plugin InfiniteLoading
* @property {boolean} infiniteLoading
* @default false
*
**/
/**
*
* Sets the configuration for infiniteLoading.
* The `infiniteLoading` option must be set to true.
*
* @property {Object} infiniteLoadingConfig
*
**/
/**
*
* TODO: Debounce
*
* @property {boolean} debounce
*
**/
/**
*
* TODO: GPUOptimization
* @plugin SurfaceManager
* @property {boolean} gpuOptimization
*
**/ | forcedotcom/scrollerjs | src/config.js | JavaScript | apache-2.0 | 6,867 |
/**
* 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 '../amp-brightcove';
import * as consent from '../../../../src/consent';
import {BaseElement} from '../../../../src/base-element';
import {CONSENT_POLICY_STATE} from '../../../../src/consent-state';
import {CommonSignals} from '../../../../src/common-signals';
import {VideoEvents} from '../../../../src/video-interface';
import {
createElementWithAttributes,
whenUpgradedToCustomElement,
} from '../../../../src/dom';
import {listenOncePromise} from '../../../../src/event-helper';
import {macroTask} from '../../../../testing/yield';
import {parseUrlDeprecated} from '../../../../src/url';
import {user} from '../../../../src/log';
describes.realWin(
'amp-brightcove',
{
amp: {
extensions: ['amp-brightcove'],
runtimeOn: true,
},
},
(env) => {
let win, doc;
beforeEach(() => {
win = env.win;
doc = win.document;
// make sync
env.sandbox
.stub(BaseElement.prototype, 'mutateElement')
.callsFake((mutator) => {
mutator();
});
});
async function getBrightcoveBuild(attributes) {
const element = createElementWithAttributes(doc, 'amp-brightcove', {
width: '111',
height: '222',
...attributes,
});
doc.body.appendChild(element);
await whenUpgradedToCustomElement(element);
await element.whenBuilt();
return element;
}
async function getBrightcove(attributes) {
const element = await getBrightcoveBuild(attributes);
const impl = await element.getImpl(false);
await element.signals().whenSignal(CommonSignals.LOAD_START);
// Wait for the promise in layoutCallback() to resolve
await macroTask();
try {
fakePostMessage(impl, {event: 'ready'});
} catch (_) {
// This fails when the iframe is not available (after layoutCallback
// fails) in which case awaiting the LOAD_END sigal below will throw.
}
await element.signals().whenSignal(CommonSignals.LOAD_END);
return element;
}
function fakePostMessage(impl, info) {
impl.handlePlayerMessage_({
origin: 'https://players.brightcove.net',
source: impl.element.querySelector('iframe').contentWindow,
data: JSON.stringify(info),
});
}
// https://go.amp.dev/issue/32706
it('should remove `dock`', async () => {
const warn = env.sandbox.spy(user(), 'warn');
const element = await getBrightcoveBuild({
'data-account': '1290862519001',
'data-video-id': 'ref:amp-test-video',
'dock': '',
});
expect(element.hasAttribute('dock')).to.be.false;
expect(
warn.withArgs(
env.sandbox.match.any,
env.sandbox.match(/`dock` has been disabled/)
)
).to.have.been.calledOnce;
});
// https://go.amp.dev/issue/32706
it('should not warn without `dock`', async () => {
const warn = env.sandbox.spy(user(), 'warn');
const element = await getBrightcoveBuild({
'data-account': '1290862519001',
'data-video-id': 'ref:amp-test-video',
});
expect(element.hasAttribute('dock')).to.be.false;
expect(warn).to.not.have.been.called;
});
it('renders', () => {
return getBrightcove({
'data-account': '1290862519001',
'data-video-id': 'ref:amp-test-video',
}).then((bc) => {
const iframe = bc.querySelector('iframe');
expect(iframe).to.not.be.null;
expect(iframe.tagName).to.equal('IFRAME');
expect(iframe.src).to.equal(
'https://players.brightcove.net/1290862519001/default_default' +
'/index.html?videoId=ref:amp-test-video&playsinline=true'
);
});
});
it('removes iframe after unlayoutCallback', async () => {
const bc = await getBrightcove({
'data-account': '1290862519001',
'data-video-id': 'ref:amp-test-video',
});
const obj = await bc.getImpl();
const iframe = bc.querySelector('iframe');
expect(iframe).to.not.be.null;
obj.unlayoutCallback();
expect(bc.querySelector('iframe')).to.be.null;
expect(obj.iframe_).to.be.null;
});
it('should pass data-param-* attributes to the iframe src', () => {
return getBrightcove({
'data-account': '1290862519001',
'data-video-id': 'ref:amp-test-video',
'data-param-my-param': 'hello world',
}).then((bc) => {
const iframe = bc.querySelector('iframe');
const params = parseUrlDeprecated(iframe.src).search.split('&');
expect(params).to.contain('myParam=hello%20world');
});
});
it('should propagate mutated attributes', () => {
return getBrightcove({
'data-account': '1290862519001',
'data-video-id': 'ref:amp-test-video',
}).then((bc) => {
const iframe = bc.querySelector('iframe');
expect(iframe.src).to.equal(
'https://players.brightcove.net/1290862519001/default_default' +
'/index.html?videoId=ref:amp-test-video&playsinline=true'
);
bc.setAttribute('data-account', '12345');
bc.setAttribute('data-video-id', 'abcdef');
bc.mutatedAttributesCallback({
'data-account': '12345',
'data-video-id': 'abcdef',
});
expect(iframe.src).to.equal(
'https://players.brightcove.net/' +
'12345/default_default/index.html?videoId=abcdef&playsinline=true'
);
});
});
it('should give precedence to playlist id', () => {
return getBrightcove({
'data-account': '1290862519001',
'data-video-id': 'ref:amp-test-video',
'data-playlist-id': 'ref:test-playlist',
}).then((bc) => {
const iframe = bc.querySelector('iframe');
expect(iframe.src).to.contain('playlistId=ref:test-playlist');
expect(iframe.src).not.to.contain('videoId');
});
});
it('should allow both playlist and video id to be unset', () => {
return getBrightcove({
'data-account': '1290862519001',
}).then((bc) => {
const iframe = bc.querySelector('iframe');
expect(iframe.src).not.to.contain('&playlistId');
expect(iframe.src).not.to.contain('&videoId');
});
});
it('should pass referrer', () => {
return getBrightcove({
'data-account': '1290862519001',
'data-referrer': 'COUNTER',
}).then((bc) => {
const iframe = bc.querySelector('iframe');
expect(iframe.src).to.contain('referrer=1');
});
});
it('should force playsinline', () => {
return getBrightcove({
'data-account': '1290862519001',
'data-video-id': 'ref:amp-test-video',
'data-param-playsinline': 'false',
}).then((bc) => {
const iframe = bc.querySelector('iframe');
expect(iframe.src).to.contain('playsinline=true');
});
});
it('should forward events', async () => {
const bc = await getBrightcove({
'data-account': '1290862519001',
'data-video-id': 'ref:amp-test-video',
});
const impl = await bc.getImpl();
return Promise.resolve()
.then(() => {
const p = listenOncePromise(bc, VideoEvents.LOAD);
fakePostMessage(impl, {event: 'ready', muted: false, playing: false});
return p;
})
.then(() => {
const p = listenOncePromise(bc, VideoEvents.LOADEDMETADATA);
fakePostMessage(impl, {
event: 'loadedmetadata',
muted: false,
playing: false,
});
return p;
})
.then(() => {
const p = listenOncePromise(bc, VideoEvents.AD_START);
fakePostMessage(impl, {
event: 'ads-ad-started',
muted: false,
playing: false,
});
return p;
})
.then(() => {
const p = listenOncePromise(bc, VideoEvents.AD_END);
fakePostMessage(impl, {
event: 'ads-ad-ended',
muted: false,
playing: false,
});
return p;
})
.then(() => {
const p = listenOncePromise(bc, VideoEvents.PLAYING);
fakePostMessage(impl, {
event: 'playing',
muted: false,
playing: true,
});
return p;
})
.then(() => {
const p = listenOncePromise(bc, VideoEvents.MUTED);
fakePostMessage(impl, {
event: 'volumechange',
muted: true,
playing: true,
});
return p;
})
.then(() => {
const p = listenOncePromise(bc, VideoEvents.UNMUTED);
fakePostMessage(impl, {
event: 'volumechange',
muted: false,
playing: true,
});
return p;
})
.then(() => {
const p = listenOncePromise(bc, VideoEvents.PAUSE);
fakePostMessage(impl, {event: 'pause', muted: false, playing: false});
return p;
})
.then(() => {
const p = listenOncePromise(bc, VideoEvents.ENDED);
fakePostMessage(impl, {event: 'ended', muted: false, playing: false});
return p;
});
});
it('should propagate consent state to iframe', () => {
env.sandbox
.stub(consent, 'getConsentPolicyState')
.resolves(CONSENT_POLICY_STATE.SUFFICIENT);
env.sandbox
.stub(consent, 'getConsentPolicySharedData')
.resolves({a: 1, b: 2});
env.sandbox.stub(consent, 'getConsentPolicyInfo').resolves('abc');
return getBrightcove({
'data-account': '1290862519001',
'data-video-id': 'ref:amp-test-video',
'data-block-on-consent': '_till_accepted',
}).then((bc) => {
const iframe = bc.querySelector('iframe');
expect(iframe.src).to.contain(
`ampInitialConsentState=${CONSENT_POLICY_STATE.SUFFICIENT}`
);
expect(iframe.src).to.contain(
`ampConsentSharedData=${encodeURIComponent(
JSON.stringify({a: 1, b: 2})
)}`
);
expect(iframe.src).to.contain('ampInitialConsentValue=abc');
});
});
}
);
| lannka/amphtml | extensions/amp-brightcove/0.1/test/test-amp-brightcove.js | JavaScript | apache-2.0 | 10,948 |
//// [tests/cases/conformance/dynamicImport/importCallExpressionDeclarationEmit2.ts] ////
//// [0.ts]
export function foo() { return "foo"; }
//// [1.ts]
var p1 = import("./0");
//// [0.js]
export function foo() { return "foo"; }
//// [1.js]
var p1 = import("./0");
//// [0.d.ts]
export declare function foo(): string;
| synaptek/TypeScript | tests/baselines/reference/importCallExpressionDeclarationEmit2.js | JavaScript | apache-2.0 | 339 |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');
var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = require('babel-runtime/helpers/inherits');
var _inherits3 = _interopRequireDefault(_inherits2);
var _simpleAssign = require('simple-assign');
var _simpleAssign2 = _interopRequireDefault(_simpleAssign);
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _propTypes = require('prop-types');
var _propTypes2 = _interopRequireDefault(_propTypes);
var _keyboardArrowUp = require('../svg-icons/hardware/keyboard-arrow-up');
var _keyboardArrowUp2 = _interopRequireDefault(_keyboardArrowUp);
var _keyboardArrowDown = require('../svg-icons/hardware/keyboard-arrow-down');
var _keyboardArrowDown2 = _interopRequireDefault(_keyboardArrowDown);
var _IconButton = require('../IconButton');
var _IconButton2 = _interopRequireDefault(_IconButton);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function getStyles() {
return {
root: {
top: 0,
bottom: 0,
right: 4,
margin: 'auto',
position: 'absolute'
}
};
}
var CardExpandable = function (_Component) {
(0, _inherits3.default)(CardExpandable, _Component);
function CardExpandable() {
(0, _classCallCheck3.default)(this, CardExpandable);
return (0, _possibleConstructorReturn3.default)(this, (CardExpandable.__proto__ || (0, _getPrototypeOf2.default)(CardExpandable)).apply(this, arguments));
}
(0, _createClass3.default)(CardExpandable, [{
key: 'render',
value: function render() {
var styles = getStyles(this.props, this.context);
return _react2.default.createElement(
_IconButton2.default,
{
style: (0, _simpleAssign2.default)(styles.root, this.props.style),
onClick: this.props.onExpanding,
iconStyle: this.props.iconStyle
},
this.props.expanded ? this.props.openIcon : this.props.closeIcon
);
}
}]);
return CardExpandable;
}(_react.Component);
CardExpandable.contextTypes = {
muiTheme: _propTypes2.default.object.isRequired
};
CardExpandable.defaultProps = {
closeIcon: _react2.default.createElement(_keyboardArrowDown2.default, null),
openIcon: _react2.default.createElement(_keyboardArrowUp2.default, null)
};
CardExpandable.propTypes = process.env.NODE_ENV !== "production" ? {
closeIcon: _propTypes2.default.node,
expanded: _propTypes2.default.bool,
iconStyle: _propTypes2.default.object,
onExpanding: _propTypes2.default.func.isRequired,
openIcon: _propTypes2.default.node,
style: _propTypes2.default.object
} : {};
exports.default = CardExpandable; | yaolei/Samoyed | node_modules/material-ui/Card/CardExpandable.js | JavaScript | apache-2.0 | 3,257 |
/*
* 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 TypeService = function($http, ENV, locationUtils, messageModel) {
this.getTypes = function(queryParams) {
return $http.get(ENV.api['root'] + 'types', {params: queryParams}).then(
function (result) {
return result.data.response;
},
function (err) {
throw err;
}
)
};
this.getType = function(id) {
return $http.get(ENV.api['root'] + 'types', {params: {id: id}}).then(
function (result) {
return result.data.response[0];
},
function (err) {
throw err;
}
)
};
this.createType = function(type) {
return $http.post(ENV.api['root'] + 'types', type).then(
function(result) {
messageModel.setMessages([ { level: 'success', text: 'Type created' } ], true);
locationUtils.navigateToPath('/types');
return result;
},
function(err) {
messageModel.setMessages(err.data.alerts, false);
throw err;
}
);
};
// todo: change to use query param when it is supported
this.updateType = function(type) {
return $http.put(ENV.api['root'] + 'types/' + type.id, type).then(
function(result) {
messageModel.setMessages([ { level: 'success', text: 'Type updated' } ], false);
return result;
},
function(err) {
messageModel.setMessages(err.data.alerts, false);
throw err;
}
);
};
// todo: change to use query param when it is supported
this.deleteType = function(id) {
return $http.delete(ENV.api['root'] + "types/" + id).then(
function(result) {
messageModel.setMessages([ { level: 'success', text: 'Type deleted' } ], true);
return result;
},
function(err) {
messageModel.setMessages(err.data.alerts, true);
throw err;
}
);
};
};
TypeService.$inject = ['$http', 'ENV', 'locationUtils', 'messageModel'];
module.exports = TypeService;
| hbeatty/incubator-trafficcontrol | traffic_portal/app/src/common/api/TypeService.js | JavaScript | apache-2.0 | 3,066 |
// Copyright 2014 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.
goog.provide('goog.soy.dataTest');
goog.setTestOnly('goog.soy.dataTest');
goog.require('goog.html.SafeHtml');
goog.require('goog.html.SafeUrl');
/** @suppress {extraRequire} */
goog.require('goog.soy.testHelper');
goog.require('goog.testing.jsunit');
function testToSafeHtml() {
var html;
html = example.unsanitizedTextTemplate().toSafeHtml();
assertEquals(
'I <3 Puppies & Kittens', goog.html.SafeHtml.unwrap(html));
html = example.sanitizedHtmlTemplate().toSafeHtml();
assertEquals('Hello <b>World</b>', goog.html.SafeHtml.unwrap(html));
}
function testToSafeUrl() {
var url;
url = example.sanitizedSmsUrlTemplate().toSafeUrl();
assertEquals('sms:123456789', goog.html.SafeUrl.unwrap(url));
url = example.sanitizedHttpUrlTemplate().toSafeUrl();
assertEquals('https://google.com/foo?n=917', goog.html.SafeUrl.unwrap(url));
}
| redforks/closure-library | closure/goog/soy/data_test.js | JavaScript | apache-2.0 | 1,495 |
import Check from "./Check.js";
import defaultValue from "./defaultValue.js";
import defined from "./defined.js";
import DeveloperError from "./DeveloperError.js";
import CesiumMath from "./Math.js";
/**
* Creates a curve parameterized and evaluated by time. This type describes an interface
* and is not intended to be instantiated directly.
*
* @alias Spline
* @constructor
*
* @see CatmullRomSpline
* @see HermiteSpline
* @see LinearSpline
* @see QuaternionSpline
*/
function Spline() {
/**
* An array of times for the control points.
* @type {Number[]}
* @default undefined
*/
this.times = undefined;
/**
* An array of control points.
* @type {Cartesian3[]|Quaternion[]}
* @default undefined
*/
this.points = undefined;
DeveloperError.throwInstantiationError();
}
/**
* Evaluates the curve at a given time.
* @function
*
* @param {Number} time The time at which to evaluate the curve.
* @param {Cartesian3|Quaternion|Number[]} [result] The object onto which to store the result.
* @returns {Cartesian3|Quaternion|Number[]} The modified result parameter or a new instance of the point on the curve at the given time.
*
* @exception {DeveloperError} time must be in the range <code>[t<sub>0</sub>, t<sub>n</sub>]</code>, where <code>t<sub>0</sub></code>
* is the first element in the array <code>times</code> and <code>t<sub>n</sub></code> is the last element
* in the array <code>times</code>.
*/
Spline.prototype.evaluate = DeveloperError.throwInstantiationError;
/**
* Finds an index <code>i</code> in <code>times</code> such that the parameter
* <code>time</code> is in the interval <code>[times[i], times[i + 1]]</code>.
*
* @param {Number} time The time.
* @param {Number} startIndex The index from which to start the search.
* @returns {Number} The index for the element at the start of the interval.
*
* @exception {DeveloperError} time must be in the range <code>[t<sub>0</sub>, t<sub>n</sub>]</code>, where <code>t<sub>0</sub></code>
* is the first element in the array <code>times</code> and <code>t<sub>n</sub></code> is the last element
* in the array <code>times</code>.
*/
Spline.prototype.findTimeInterval = function (time, startIndex) {
var times = this.times;
var length = times.length;
//>>includeStart('debug', pragmas.debug);
if (!defined(time)) {
throw new DeveloperError("time is required.");
}
if (time < times[0] || time > times[length - 1]) {
throw new DeveloperError("time is out of range.");
}
//>>includeEnd('debug');
// Take advantage of temporal coherence by checking current, next and previous intervals
// for containment of time.
startIndex = defaultValue(startIndex, 0);
if (time >= times[startIndex]) {
if (startIndex + 1 < length && time < times[startIndex + 1]) {
return startIndex;
} else if (startIndex + 2 < length && time < times[startIndex + 2]) {
return startIndex + 1;
}
} else if (startIndex - 1 >= 0 && time >= times[startIndex - 1]) {
return startIndex - 1;
}
// The above failed so do a linear search. For the use cases so far, the
// length of the list is less than 10. In the future, if there is a bottle neck,
// it might be here.
var i;
if (time > times[startIndex]) {
for (i = startIndex; i < length - 1; ++i) {
if (time >= times[i] && time < times[i + 1]) {
break;
}
}
} else {
for (i = startIndex - 1; i >= 0; --i) {
if (time >= times[i] && time < times[i + 1]) {
break;
}
}
}
if (i === length - 1) {
i = length - 2;
}
return i;
};
/**
* Wraps the given time to the period covered by the spline.
* @function
*
* @param {Number} time The time.
* @return {Number} The time, wrapped around the animation period.
*/
Spline.prototype.wrapTime = function (time) {
//>>includeStart('debug', pragmas.debug);
Check.typeOf.number("time", time);
//>>includeEnd('debug');
var times = this.times;
var timeEnd = times[times.length - 1];
var timeStart = times[0];
var timeStretch = timeEnd - timeStart;
var divs;
if (time < timeStart) {
divs = Math.floor((timeStart - time) / timeStretch) + 1;
time += divs * timeStretch;
}
if (time > timeEnd) {
divs = Math.floor((time - timeEnd) / timeStretch) + 1;
time -= divs * timeStretch;
}
return time;
};
/**
* Clamps the given time to the period covered by the spline.
* @function
*
* @param {Number} time The time.
* @return {Number} The time, clamped to the animation period.
*/
Spline.prototype.clampTime = function (time) {
//>>includeStart('debug', pragmas.debug);
Check.typeOf.number("time", time);
//>>includeEnd('debug');
var times = this.times;
return CesiumMath.clamp(time, times[0], times[times.length - 1]);
};
export default Spline;
| progsung/cesium | Source/Core/Spline.js | JavaScript | apache-2.0 | 4,935 |
define(function(require, exports, module) {
var Notify = require('common/bootstrap-notify');
exports.run = function() {
var $table = $('#teacher-table');
$table.on('click', '.promote-user', function(){
$.post($(this).data('url'),function(response) {
window.location.reload();
});
});
$table.on('click', '.cancel-promote-user', function(){
$.post($(this).data('url'),function(response) {
window.location.reload();
});
});
};
}); | 18826252059/im | web/bundles/topxiaadmin/js/controller/user/teacher-list.js | JavaScript | apache-2.0 | 539 |
'use strict';
/* // [START classdefinition] */
export default class exampleClass {
/* // [END classdefinition] */
constructor () {
super();
console.log('Example Constructor');
}
exampleFunction () {
console.log('Example Function');
}
}
| beaufortfrancois/WebFundamentals | src/content/en/resources/jekyll/_code/example.js | JavaScript | apache-2.0 | 261 |
// This file was automatically generated. Do not modify.
'use strict';
goog.provide('Blockly.Msg.sv');
goog.require('Blockly.Msg');
Blockly.Msg.ADD_COMMENT = "Lägg till kommentar";
Blockly.Msg.AUTH = "Var god godkänn denna app för att du ska kunna spara och dela den.";
Blockly.Msg.CHANGE_VALUE_TITLE = "Ändra värde:";
Blockly.Msg.CHAT = "Chatta med din medarbetare genom att skriva i detta fält.";
Blockly.Msg.COLLAPSE_ALL = "Fäll ihop block";
Blockly.Msg.COLLAPSE_BLOCK = "Fäll ihop block";
Blockly.Msg.COLOUR_BLEND_COLOUR1 = "färg 1";
Blockly.Msg.COLOUR_BLEND_COLOUR2 = "färg 2";
Blockly.Msg.COLOUR_BLEND_HELPURL = "http://meyerweb.com/eric/tools/color-blend/";
Blockly.Msg.COLOUR_BLEND_RATIO = "förhållande";
Blockly.Msg.COLOUR_BLEND_TITLE = "blanda";
Blockly.Msg.COLOUR_BLEND_TOOLTIP = "Blandar ihop två färger med ett bestämt förhållande (0.0 - 1.0).";
Blockly.Msg.COLOUR_PICKER_HELPURL = "https://sv.wikipedia.org/wiki/Färg";
Blockly.Msg.COLOUR_PICKER_TOOLTIP = "Välj en färg från paletten.";
Blockly.Msg.COLOUR_RANDOM_HELPURL = "http://randomcolour.com"; // untranslated
Blockly.Msg.COLOUR_RANDOM_TITLE = "slumpfärg";
Blockly.Msg.COLOUR_RANDOM_TOOLTIP = "Slumpa fram en färg.";
Blockly.Msg.COLOUR_RGB_BLUE = "blå";
Blockly.Msg.COLOUR_RGB_GREEN = "grön";
Blockly.Msg.COLOUR_RGB_HELPURL = "http://www.december.com/html/spec/colorper.html";
Blockly.Msg.COLOUR_RGB_RED = "röd";
Blockly.Msg.COLOUR_RGB_TITLE = "färg med";
Blockly.Msg.COLOUR_RGB_TOOLTIP = "Skapa en färg med det angivna mängden röd, grön och blå. Alla värden måste vara mellan 0 och 100.";
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_HELPURL = "https://github.com/google/blockly/wiki/Loops#loop-termination-blocks"; // untranslated
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_OPERATOR_BREAK = "bryt ut ur loop";
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_OPERATOR_CONTINUE = "fortsätta med nästa upprepning av loop";
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_TOOLTIP_BREAK = "Bryta ut ur den innehållande upprepningen.";
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_TOOLTIP_CONTINUE = "Hoppa över resten av denna loop och fortsätt med nästa loop.";
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_WARNING = "Varning: Detta block kan endast användas i en loop.";
Blockly.Msg.CONTROLS_FOREACH_HELPURL = "https://github.com/google/blockly/wiki/Loops#for-each för varje-block";
Blockly.Msg.CONTROLS_FOREACH_INPUT_INLIST = "i listan";
Blockly.Msg.CONTROLS_FOREACH_INPUT_INLIST_TAIL = ""; // untranslated
Blockly.Msg.CONTROLS_FOREACH_INPUT_ITEM = "för varje föremål";
Blockly.Msg.CONTROLS_FOREACH_TOOLTIP = "För varje objekt i en lista, ange variabeln '%1' till objektet, och utför sedan några kommandon.";
Blockly.Msg.CONTROLS_FOR_HELPURL = "https://github.com/google/blockly/wiki/Loops#count-with"; // untranslated
Blockly.Msg.CONTROLS_FOR_INPUT_FROM_TO = "from %1 to %2"; // untranslated
Blockly.Msg.CONTROLS_FOR_INPUT_FROM_TO_BY = "från %1 till %2 med %3";
Blockly.Msg.CONTROLS_FOR_INPUT_WITH = "räkna med";
Blockly.Msg.CONTROLS_FOR_TOOLTIP = "Låt variabeln %1 ta värden från starttalet till sluttalet, beräknat med det angivna intervallet, och utför de angivna blocken.";
Blockly.Msg.CONTROLS_IF_ELSEIF_TOOLTIP = "Lägg till ett villkor blocket \"om\".";
Blockly.Msg.CONTROLS_IF_ELSE_TOOLTIP = "Lägg till ett sista villkor som täcker alla alternativ som är kvar för \"if\"-blocket.";
Blockly.Msg.CONTROLS_IF_HELPURL = "https://github.com/google/blockly/wiki/IfElse"; // untranslated
Blockly.Msg.CONTROLS_IF_IF_TOOLTIP = "Lägg till, ta bort eller ändra ordningen för sektioner för att omkonfigurera blocket \"om\".";
Blockly.Msg.CONTROLS_IF_MSG_ELSE = "annars";
Blockly.Msg.CONTROLS_IF_MSG_ELSEIF = "annars om";
Blockly.Msg.CONTROLS_IF_MSG_IF = "om";
Blockly.Msg.CONTROLS_IF_TOOLTIP_1 = "Om ett värde är sant, utför några kommandon.";
Blockly.Msg.CONTROLS_IF_TOOLTIP_2 = "Om värdet är sant, utför det första kommandoblocket. Annars utför det andra kommandoblocket.";
Blockly.Msg.CONTROLS_IF_TOOLTIP_3 = "Om det första värdet är sant, utför det första kommandoblocket. Annars, om det andra värdet är sant, utför det andra kommandoblocket.";
Blockly.Msg.CONTROLS_IF_TOOLTIP_4 = "Om det första värdet är sant, utför det första kommandoblocket. Annars, om det andra värdet är sant, utför det andra kommandoblocket. Om ingen av värdena är sanna, utför det sista kommandoblocket.";
Blockly.Msg.CONTROLS_REPEAT_HELPURL = "https://en.wikipedia.org/wiki/For_loop";
Blockly.Msg.CONTROLS_REPEAT_INPUT_DO = "utför";
Blockly.Msg.CONTROLS_REPEAT_TITLE = "upprepa %1 gånger";
Blockly.Msg.CONTROLS_REPEAT_TITLE_REPEAT = "upprepa";
Blockly.Msg.CONTROLS_REPEAT_TITLE_TIMES = "gånger";
Blockly.Msg.CONTROLS_REPEAT_TOOLTIP = "Utför några kommandon flera gånger.";
Blockly.Msg.CONTROLS_WHILEUNTIL_HELPURL = "https://github.com/google/blockly/wiki/Loops#repeat"; // untranslated
Blockly.Msg.CONTROLS_WHILEUNTIL_OPERATOR_UNTIL = "upprepa tills";
Blockly.Msg.CONTROLS_WHILEUNTIL_OPERATOR_WHILE = "upprepa medan";
Blockly.Msg.CONTROLS_WHILEUNTIL_TOOLTIP_UNTIL = "Medan ett värde är falskt, utför några kommandon.";
Blockly.Msg.CONTROLS_WHILEUNTIL_TOOLTIP_WHILE = "Medan ett värde är sant, utför några kommandon.";
Blockly.Msg.DELETE_BLOCK = "Radera block";
Blockly.Msg.DELETE_X_BLOCKS = "Radera %1 block";
Blockly.Msg.DISABLE_BLOCK = "Inaktivera block";
Blockly.Msg.DUPLICATE_BLOCK = "Duplicera";
Blockly.Msg.ENABLE_BLOCK = "Aktivera block";
Blockly.Msg.EXPAND_ALL = "Fäll ut block";
Blockly.Msg.EXPAND_BLOCK = "Fäll ut block";
Blockly.Msg.EXTERNAL_INPUTS = "Externa inmatningar";
Blockly.Msg.HELP = "Hjälp";
Blockly.Msg.INLINE_INPUTS = "Radinmatning";
Blockly.Msg.LISTS_CREATE_EMPTY_HELPURL = "https://en.wikipedia.org/wiki/Linked_list#Empty_lists";
Blockly.Msg.LISTS_CREATE_EMPTY_TITLE = "skapa tom lista";
Blockly.Msg.LISTS_CREATE_EMPTY_TOOLTIP = "Ger tillbaka en lista utan någon data, alltså med längden 0";
Blockly.Msg.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD = "lista";
Blockly.Msg.LISTS_CREATE_WITH_CONTAINER_TOOLTIP = "Lägg till, ta bort eller ändra ordningen på objekten för att göra om det här \"list\"-blocket.";
Blockly.Msg.LISTS_CREATE_WITH_HELPURL = "https://github.com/google/blockly/wiki/Lists#create-list-with";
Blockly.Msg.LISTS_CREATE_WITH_INPUT_WITH = "skapa lista med";
Blockly.Msg.LISTS_CREATE_WITH_ITEM_TOOLTIP = "Lägg till ett föremål till listan.";
Blockly.Msg.LISTS_CREATE_WITH_TOOLTIP = "Skapa en lista med valfritt antal föremål.";
Blockly.Msg.LISTS_GET_INDEX_FIRST = "första";
Blockly.Msg.LISTS_GET_INDEX_FROM_END = "# från slutet";
Blockly.Msg.LISTS_GET_INDEX_FROM_START = "#";
Blockly.Msg.LISTS_GET_INDEX_GET = "hämta";
Blockly.Msg.LISTS_GET_INDEX_GET_REMOVE = "hämta och ta bort";
Blockly.Msg.LISTS_GET_INDEX_LAST = "sista";
Blockly.Msg.LISTS_GET_INDEX_RANDOM = "slumpad";
Blockly.Msg.LISTS_GET_INDEX_REMOVE = "ta bort";
Blockly.Msg.LISTS_GET_INDEX_TAIL = ""; // untranslated
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FIRST = "Returnerar det första objektet i en lista.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FROM_END = "Ger tillbaka objektet på den efterfrågade positionen i en lista. #1 är det sista objektet.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FROM_START = "Ger tillbaka objektet på den efterfrågade positionen i en lista. #1 är det första objektet.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_LAST = "Returnerar det sista objektet i en lista.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_RANDOM = "Returnerar ett slumpmässigt objekt i en lista.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FIRST = "Tar bort och återställer det första objektet i en lista.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FROM_END = "Tar bort och återställer objektet på den specificerade positionen i en lista. #1 är det sista objektet.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FROM_START = "Tar bort och återställer objektet på den specificerade positionen i en lista. #1 är det första objektet.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_LAST = "Tar bort och återställer det sista objektet i en lista.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_RANDOM = "Tar bort och återställer ett slumpmässigt objekt i en lista.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FIRST = "Tar bort det första objektet i en lista.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FROM_END = "Tar bort objektet på den efterfrågade positionen i en lista. #1 är det sista objektet.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FROM_START = "Tar bort objektet på den specificerade positionen i en lista. #1 är det första objektet.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_LAST = "Tar bort det sista objektet i en lista.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_RANDOM = "Tar bort en slumpmässig post i en lista.";
Blockly.Msg.LISTS_GET_SUBLIST_END_FROM_END = "till # från slutet";
Blockly.Msg.LISTS_GET_SUBLIST_END_FROM_START = "till #";
Blockly.Msg.LISTS_GET_SUBLIST_END_LAST = "till sista";
Blockly.Msg.LISTS_GET_SUBLIST_HELPURL = "https://github.com/google/blockly/wiki/Lists#getting-a-sublist"; // untranslated
Blockly.Msg.LISTS_GET_SUBLIST_START_FIRST = "få underlista från första";
Blockly.Msg.LISTS_GET_SUBLIST_START_FROM_END = "få underlista från # från slutet";
Blockly.Msg.LISTS_GET_SUBLIST_START_FROM_START = "få underlista från #";
Blockly.Msg.LISTS_GET_SUBLIST_TAIL = ""; // untranslated
Blockly.Msg.LISTS_GET_SUBLIST_TOOLTIP = "Skapar en kopia av den specificerade delen av en lista.";
Blockly.Msg.LISTS_INDEX_OF_FIRST = "hitta första förekomsten av objektet";
Blockly.Msg.LISTS_INDEX_OF_HELPURL = "https://github.com/google/blockly/wiki/Lists#getting-items-from-a-list"; // untranslated
Blockly.Msg.LISTS_INDEX_OF_LAST = "hitta sista förekomsten av objektet";
Blockly.Msg.LISTS_INDEX_OF_TOOLTIP = "Ger tillbaka den första/sista förekomsten av objektet i listan. Ger tillbaka 0 om texten inte hittas.";
Blockly.Msg.LISTS_INLIST = "i listan";
Blockly.Msg.LISTS_IS_EMPTY_HELPURL = "https://github.com/google/blockly/wiki/Lists#is-empty"; // untranslated
Blockly.Msg.LISTS_IS_EMPTY_TITLE = "%1 är tom";
Blockly.Msg.LISTS_LENGTH_HELPURL = "https://github.com/google/blockly/wiki/Lists#length-of"; // untranslated
Blockly.Msg.LISTS_LENGTH_TITLE = "längden på %1";
Blockly.Msg.LISTS_LENGTH_TOOLTIP = "Returnerar längden på en lista.";
Blockly.Msg.LISTS_REPEAT_HELPURL = "https://github.com/google/blockly/wiki/Lists#create-list-with"; // untranslated
Blockly.Msg.LISTS_REPEAT_TITLE = "skapa lista med föremålet %1 upprepat %2 gånger";
Blockly.Msg.LISTS_REPEAT_TOOLTIP = "Skapar en lista som innehåller ett valt värde upprepat ett bestämt antalet gånger.";
Blockly.Msg.LISTS_SET_INDEX_HELPURL = "https://github.com/google/blockly/wiki/Lists#in-list--set"; // untranslated
Blockly.Msg.LISTS_SET_INDEX_INPUT_TO = "som";
Blockly.Msg.LISTS_SET_INDEX_INSERT = "Sätt in vid";
Blockly.Msg.LISTS_SET_INDEX_SET = "ange";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FIRST = "sätter in objektet i början av en lista.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FROM_END = "sätter in objektet vid en specificerad position i en lista. #1 är det sista objektet.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FROM_START = "Sätter in objektet vid en specificerad position i en lista. #1 är det första objektet.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_LAST = "Lägg till objektet i slutet av en lista.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_RANDOM = "sätter in objektet på en slumpad position i en lista.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FIRST = "Anger det första objektet i en lista.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FROM_END = "Sätter in objektet vid en specificerad position i en lista. #1 är det sista objektet.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FROM_START = "Sätter in objektet vid en specificerad position i en lista. #1 är det första objektet.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_LAST = "Anger det sista elementet i en lista.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_RANDOM = "Sätter in ett slumpat objekt i en lista.";
Blockly.Msg.LISTS_SPLIT_HELPURL = "https://github.com/google/blockly/wiki/Lists#splitting-strings-and-joining-lists";
Blockly.Msg.LISTS_SPLIT_LIST_FROM_TEXT = "skapa lista från text";
Blockly.Msg.LISTS_SPLIT_TEXT_FROM_LIST = "skapa text från lista";
Blockly.Msg.LISTS_SPLIT_TOOLTIP_JOIN = "Sammanfoga en textlista till en text, som separeras av en avgränsare.";
Blockly.Msg.LISTS_SPLIT_TOOLTIP_SPLIT = "Dela upp text till en textlista och bryt vid varje avgränsare.";
Blockly.Msg.LISTS_SPLIT_WITH_DELIMITER = "med avgränsare";
Blockly.Msg.LISTS_TOOLTIP = "Returnerar sant om listan är tom.";
Blockly.Msg.LOGIC_BOOLEAN_FALSE = "falskt";
Blockly.Msg.LOGIC_BOOLEAN_HELPURL = "https://github.com/google/blockly/wiki/Logic#values"; // untranslated
Blockly.Msg.LOGIC_BOOLEAN_TOOLTIP = "Returnerar antingen sant eller falskt.";
Blockly.Msg.LOGIC_BOOLEAN_TRUE = "sant";
Blockly.Msg.LOGIC_COMPARE_HELPURL = "https://sv.wikipedia.org/wiki/Olikhet";
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_EQ = "Ger tillbaka sant om båda värdena är lika med varandra.";
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_GT = "Ger tillbaka sant om det första värdet är större än det andra.";
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_GTE = "Ger tillbaka sant om det första värdet är större än eller lika med det andra.";
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_LT = "Ger tillbaka sant om det första värdet är mindre än det andra.";
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_LTE = "Ger tillbaka sant om det första värdet är mindre än eller lika med det andra.";
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_NEQ = "Ger tillbaka sant om båda värdena inte är lika med varandra.";
Blockly.Msg.LOGIC_NEGATE_HELPURL = "https://github.com/google/blockly/wiki/Logic#not"; // untranslated
Blockly.Msg.LOGIC_NEGATE_TITLE = "inte %1";
Blockly.Msg.LOGIC_NEGATE_TOOLTIP = "Ger tillbaka sant om inmatningen är falsk. Ger tillbaka falskt och inmatningen är sann.";
Blockly.Msg.LOGIC_NULL = "null";
Blockly.Msg.LOGIC_NULL_HELPURL = "https://sv.wikipedia.org/wiki/Null";
Blockly.Msg.LOGIC_NULL_TOOLTIP = "Returnerar null.";
Blockly.Msg.LOGIC_OPERATION_AND = "och";
Blockly.Msg.LOGIC_OPERATION_HELPURL = "https://github.com/google/blockly/wiki/Logic#logical-operations"; // untranslated
Blockly.Msg.LOGIC_OPERATION_OR = "eller";
Blockly.Msg.LOGIC_OPERATION_TOOLTIP_AND = "Ger tillbaka sant om båda värdena är sanna.";
Blockly.Msg.LOGIC_OPERATION_TOOLTIP_OR = "Ger tillbaka sant om minst ett av värdena är sant.";
Blockly.Msg.LOGIC_TERNARY_CONDITION = "test";
Blockly.Msg.LOGIC_TERNARY_HELPURL = "https://en.wikipedia.org/wiki/%3F:";
Blockly.Msg.LOGIC_TERNARY_IF_FALSE = "om falskt";
Blockly.Msg.LOGIC_TERNARY_IF_TRUE = "om sant";
Blockly.Msg.LOGIC_TERNARY_TOOLTIP = "Kontrollera villkoret i \"test\". Om villkoret är sant, ge tillbaka \"om sant\"-värdet; annars ge tillbaka \"om falskt\"-värdet.";
Blockly.Msg.MATH_ADDITION_SYMBOL = "+";
Blockly.Msg.MATH_ARITHMETIC_HELPURL = "https://sv.wikipedia.org/wiki/Aritmetik";
Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_ADD = "Returnerar summan av de två talen.";
Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_DIVIDE = "Returnerar kvoten av de två talen.";
Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_MINUS = "Returnerar differensen mellan de två talen.";
Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_MULTIPLY = "Returnerar produkten av de två talen.";
Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_POWER = "Ger tillbaka det första talet upphöjt till det andra talet.";
Blockly.Msg.MATH_CHANGE_HELPURL = "https://en.wikipedia.org/wiki/Programming_idiom#Incrementing_a_counter";
Blockly.Msg.MATH_CHANGE_INPUT_BY = "med";
Blockly.Msg.MATH_CHANGE_TITLE_CHANGE = "ändra";
Blockly.Msg.MATH_CHANGE_TOOLTIP = "Lägg till ett tal till variabeln '%1'.";
Blockly.Msg.MATH_CONSTANT_HELPURL = "https://sv.wikipedia.org/wiki/Matematisk_konstant";
Blockly.Msg.MATH_CONSTANT_TOOLTIP = "Returnerar en av de vanliga konstanterna: π (3.141…), e (2.718…), φ (1.618…), sqrt(2) (1.414…), sqrt(½) (0.707…) eller ∞ (oändligt).";
Blockly.Msg.MATH_CONSTRAIN_HELPURL = "https://en.wikipedia.org/wiki/Clamping_%28graphics%29";
Blockly.Msg.MATH_CONSTRAIN_TITLE = "begränsa %1 till mellan %2 och %3";
Blockly.Msg.MATH_CONSTRAIN_TOOLTIP = "Begränsa ett tal till att mellan de angivna gränsvärden (inklusive).";
Blockly.Msg.MATH_DIVISION_SYMBOL = "÷";
Blockly.Msg.MATH_IS_DIVISIBLE_BY = "är delbart med";
Blockly.Msg.MATH_IS_EVEN = "är jämnt";
Blockly.Msg.MATH_IS_NEGATIVE = "är negativt";
Blockly.Msg.MATH_IS_ODD = "är ojämnt";
Blockly.Msg.MATH_IS_POSITIVE = "är positivt";
Blockly.Msg.MATH_IS_PRIME = "är ett primtal";
Blockly.Msg.MATH_IS_TOOLTIP = "Kontrollera om ett tal är jämnt, ojämnt, helt, positivt, negativt eller det är delbart med ett bestämt tal. Returnerar med sant eller falskt.";
Blockly.Msg.MATH_IS_WHOLE = "är helt";
Blockly.Msg.MATH_MODULO_HELPURL = "https://en.wikipedia.org/wiki/Modulo_operation";
Blockly.Msg.MATH_MODULO_TITLE = "resten av %1 ÷ %2";
Blockly.Msg.MATH_MODULO_TOOLTIP = "Returnerar kvoten från divisionen av de två talen.";
Blockly.Msg.MATH_MULTIPLICATION_SYMBOL = "×";
Blockly.Msg.MATH_NUMBER_HELPURL = "https://sv.wikipedia.org/wiki/Tal";
Blockly.Msg.MATH_NUMBER_TOOLTIP = "Ett tal.";
Blockly.Msg.MATH_ONLIST_HELPURL = ""; // untranslated
Blockly.Msg.MATH_ONLIST_OPERATOR_AVERAGE = "medelvärdet av listan";
Blockly.Msg.MATH_ONLIST_OPERATOR_MAX = "högsta talet i listan";
Blockly.Msg.MATH_ONLIST_OPERATOR_MEDIAN = "medianen av listan";
Blockly.Msg.MATH_ONLIST_OPERATOR_MIN = "minsta talet i listan";
Blockly.Msg.MATH_ONLIST_OPERATOR_MODE = "typvärdet i listan";
Blockly.Msg.MATH_ONLIST_OPERATOR_RANDOM = "slumpmässigt objekt i listan";
Blockly.Msg.MATH_ONLIST_OPERATOR_STD_DEV = "standardavvikelsen i listan";
Blockly.Msg.MATH_ONLIST_OPERATOR_SUM = "summan av listan";
Blockly.Msg.MATH_ONLIST_TOOLTIP_AVERAGE = "Ger tillbaka medelvärdet (aritmetiskt) av de numeriska värdena i listan.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_MAX = "Ger tillbaka det största talet i listan.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_MEDIAN = "Returnerar medianen av talen i listan.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_MIN = "Ger tillbaka det minsta talet i listan.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_MODE = "Ger tillbaka en lista med de(t) vanligaste objekte(t/n) i listan.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_RANDOM = "Returnerar ett slumpmässigt element från listan.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_STD_DEV = "Ger tillbaka standardavvikelsen i listan.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_SUM = "Ger tillbaka summan av alla talen i listan.";
Blockly.Msg.MATH_POWER_SYMBOL = "^";
Blockly.Msg.MATH_RANDOM_FLOAT_HELPURL = "https://sv.wikipedia.org/wiki/Slumptalsgenerator";
Blockly.Msg.MATH_RANDOM_FLOAT_TITLE_RANDOM = "slumpat decimaltal";
Blockly.Msg.MATH_RANDOM_FLOAT_TOOLTIP = "Ger tillbaka ett slumpat decimaltal mellan 0.0 (inkluderat) och 1.0 (exkluderat).";
Blockly.Msg.MATH_RANDOM_INT_HELPURL = "https://sv.wikipedia.org/wiki/Slumptalsgenerator";
Blockly.Msg.MATH_RANDOM_INT_TITLE = "slumpartat heltal från %1 till %2";
Blockly.Msg.MATH_RANDOM_INT_TOOLTIP = "Ger tillbaka ett slumpat heltal mellan två värden (inklusive).";
Blockly.Msg.MATH_ROUND_HELPURL = "https://sv.wikipedia.org/wiki/Avrundning";
Blockly.Msg.MATH_ROUND_OPERATOR_ROUND = "avrunda";
Blockly.Msg.MATH_ROUND_OPERATOR_ROUNDDOWN = "avrunda nedåt";
Blockly.Msg.MATH_ROUND_OPERATOR_ROUNDUP = "avrunda uppåt";
Blockly.Msg.MATH_ROUND_TOOLTIP = "Avrunda ett tal uppåt eller nedåt.";
Blockly.Msg.MATH_SINGLE_HELPURL = "https://sv.wikipedia.org/wiki/Kvadratrot";
Blockly.Msg.MATH_SINGLE_OP_ABSOLUTE = "absolut";
Blockly.Msg.MATH_SINGLE_OP_ROOT = "kvadratrot";
Blockly.Msg.MATH_SINGLE_TOOLTIP_ABS = "Returnerar absolutvärdet av ett tal.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_EXP = "Ger tillbaka e upphöjt i ett tal.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_LN = "Returnera den naturliga logaritmen av ett tal.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_LOG10 = "Returnerar logaritmen för bas 10 av ett tal.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_NEG = "Returnerar negationen av ett tal.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_POW10 = "Ger tillbaka 10 upphöjt i ett tal.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_ROOT = "Returnerar kvadratroten av ett tal.";
Blockly.Msg.MATH_SUBTRACTION_SYMBOL = "-";
Blockly.Msg.MATH_TRIG_ACOS = "arccos";
Blockly.Msg.MATH_TRIG_ASIN = "arcsin";
Blockly.Msg.MATH_TRIG_ATAN = "arctan";
Blockly.Msg.MATH_TRIG_COS = "cos";
Blockly.Msg.MATH_TRIG_HELPURL = "https://sv.wikipedia.org/wiki/Trigonometrisk_funktion";
Blockly.Msg.MATH_TRIG_SIN = "sin";
Blockly.Msg.MATH_TRIG_TAN = "tan";
Blockly.Msg.MATH_TRIG_TOOLTIP_ACOS = "Ger tillbaka arcus cosinus (arccos) för ett tal.";
Blockly.Msg.MATH_TRIG_TOOLTIP_ASIN = "Ger tillbaka arcus sinus (arcsin) för ett tal.";
Blockly.Msg.MATH_TRIG_TOOLTIP_ATAN = "Ger tillbaka arcus tangens (arctan) av ett tal.";
Blockly.Msg.MATH_TRIG_TOOLTIP_COS = "Ger tillbaka cosinus för en grad (inte radian).";
Blockly.Msg.MATH_TRIG_TOOLTIP_SIN = "Ger tillbaka sinus för en grad (inte radian).";
Blockly.Msg.MATH_TRIG_TOOLTIP_TAN = "Ger tillbaka tangens för en grad (inte radian).";
Blockly.Msg.ME = "Jag";
Blockly.Msg.NEW_VARIABLE = "Ny variabel...";
Blockly.Msg.NEW_VARIABLE_TITLE = "Nytt variabelnamn:";
Blockly.Msg.ORDINAL_NUMBER_SUFFIX = ""; // untranslated
Blockly.Msg.PROCEDURES_ALLOW_STATEMENTS = "tillåta uttalanden";
Blockly.Msg.PROCEDURES_BEFORE_PARAMS = "med:";
Blockly.Msg.PROCEDURES_CALLNORETURN_CALL = ""; // untranslated
Blockly.Msg.PROCEDURES_CALLNORETURN_HELPURL = "https://sv.wikipedia.org/wiki/Funktion_%28programmering%29";
Blockly.Msg.PROCEDURES_CALLNORETURN_TOOLTIP = "Kör den användardefinierade funktionen \"%1\".";
Blockly.Msg.PROCEDURES_CALLRETURN_HELPURL = "https://sv.wikipedia.org/wiki/Funktion_%28programmering%29";
Blockly.Msg.PROCEDURES_CALLRETURN_TOOLTIP = "Kör den användardefinierade funktionen \"%1\" och använd resultatet av den.";
Blockly.Msg.PROCEDURES_CALL_BEFORE_PARAMS = "med:";
Blockly.Msg.PROCEDURES_CREATE_DO = "Skapa '%1'";
Blockly.Msg.PROCEDURES_DEFNORETURN_DO = ""; // untranslated
Blockly.Msg.PROCEDURES_DEFNORETURN_HELPURL = "https://sv.wikipedia.org/wiki/Funktion_%28programmering%29";
Blockly.Msg.PROCEDURES_DEFNORETURN_PROCEDURE = "göra något";
Blockly.Msg.PROCEDURES_DEFNORETURN_TITLE = "för att";
Blockly.Msg.PROCEDURES_DEFNORETURN_TOOLTIP = "Skapar en funktion utan output.";
Blockly.Msg.PROCEDURES_DEFRETURN_HELPURL = "https://sv.wikipedia.org/wiki/Funktion_%28programmering%29";
Blockly.Msg.PROCEDURES_DEFRETURN_RETURN = "returnera";
Blockly.Msg.PROCEDURES_DEFRETURN_TOOLTIP = "Skapar en funktion med output.";
Blockly.Msg.PROCEDURES_DEF_DUPLICATE_WARNING = "Varning: Denna funktion har dubbla parametrar.";
Blockly.Msg.PROCEDURES_HIGHLIGHT_DEF = "Markera funktionsdefinition";
Blockly.Msg.PROCEDURES_IFRETURN_TOOLTIP = "Om ett värde är sant returneras ett andra värde.";
Blockly.Msg.PROCEDURES_IFRETURN_WARNING = "Varning: Detta block får användas endast i en funktionsdefinition.";
Blockly.Msg.PROCEDURES_MUTATORARG_TITLE = "inmatningsnamn:";
Blockly.Msg.PROCEDURES_MUTATORARG_TOOLTIP = "Lägg till en inmatning till funktionen.";
Blockly.Msg.PROCEDURES_MUTATORCONTAINER_TITLE = "inmatningar";
Blockly.Msg.PROCEDURES_MUTATORCONTAINER_TOOLTIP = "Lägg till, ta bort och ändra ordningen för inmatningar till denna funktion.";
Blockly.Msg.REMOVE_COMMENT = "Radera kommentar";
Blockly.Msg.RENAME_VARIABLE = "Byt namn på variabel...";
Blockly.Msg.RENAME_VARIABLE_TITLE = "Byt namn på alla'%1'-variabler till:";
Blockly.Msg.TEXT_APPEND_APPENDTEXT = "lägg till text";
Blockly.Msg.TEXT_APPEND_HELPURL = "https://github.com/google/blockly/wiki/Text#text-modification"; // untranslated
Blockly.Msg.TEXT_APPEND_TO = "till";
Blockly.Msg.TEXT_APPEND_TOOLTIP = "Lägg till lite text till variabeln '%1'.";
Blockly.Msg.TEXT_CHANGECASE_HELPURL = "https://github.com/google/blockly/wiki/Text#adjusting-text-case"; // untranslated
Blockly.Msg.TEXT_CHANGECASE_OPERATOR_LOWERCASE = "till gemener";
Blockly.Msg.TEXT_CHANGECASE_OPERATOR_TITLECASE = "till Versala Initialer";
Blockly.Msg.TEXT_CHANGECASE_OPERATOR_UPPERCASE = "till VERSALER";
Blockly.Msg.TEXT_CHANGECASE_TOOLTIP = "Returnerar en kopia av texten i ett annat skiftläge.";
Blockly.Msg.TEXT_CHARAT_FIRST = "hämta första bokstaven";
Blockly.Msg.TEXT_CHARAT_FROM_END = "hämta bokstaven # från slutet";
Blockly.Msg.TEXT_CHARAT_FROM_START = "hämta bokstaven #";
Blockly.Msg.TEXT_CHARAT_HELPURL = "https://github.com/google/blockly/wiki/Text#extracting-text"; // untranslated
Blockly.Msg.TEXT_CHARAT_INPUT_INTEXT = "i texten";
Blockly.Msg.TEXT_CHARAT_LAST = "hämta sista bokstaven";
Blockly.Msg.TEXT_CHARAT_RANDOM = "hämta slumpad bokstav";
Blockly.Msg.TEXT_CHARAT_TAIL = ""; // untranslated
Blockly.Msg.TEXT_CHARAT_TOOLTIP = "Ger tillbaka bokstaven på den specificerade positionen.";
Blockly.Msg.TEXT_CREATE_JOIN_ITEM_TOOLTIP = "Lägg till ett föremål till texten.";
Blockly.Msg.TEXT_CREATE_JOIN_TITLE_JOIN = "sammanfoga";
Blockly.Msg.TEXT_CREATE_JOIN_TOOLTIP = "Lägg till, ta bort eller ändra ordningen för sektioner för att omkonfigurera detta textblock.";
Blockly.Msg.TEXT_GET_SUBSTRING_END_FROM_END = "till bokstav # från slutet";
Blockly.Msg.TEXT_GET_SUBSTRING_END_FROM_START = "till bokstav #";
Blockly.Msg.TEXT_GET_SUBSTRING_END_LAST = "till sista bokstaven";
Blockly.Msg.TEXT_GET_SUBSTRING_HELPURL = "https://github.com/google/blockly/wiki/Text#extracting-a-region-of-text"; // untranslated
Blockly.Msg.TEXT_GET_SUBSTRING_INPUT_IN_TEXT = "i texten";
Blockly.Msg.TEXT_GET_SUBSTRING_START_FIRST = "få textdel från första bokstaven";
Blockly.Msg.TEXT_GET_SUBSTRING_START_FROM_END = "få textdel från bokstav # från slutet";
Blockly.Msg.TEXT_GET_SUBSTRING_START_FROM_START = "få textdel från bokstav #";
Blockly.Msg.TEXT_GET_SUBSTRING_TAIL = ""; // untranslated
Blockly.Msg.TEXT_GET_SUBSTRING_TOOLTIP = "Ger tillbaka en viss del av texten.";
Blockly.Msg.TEXT_INDEXOF_HELPURL = "https://github.com/google/blockly/wiki/Text#finding-text"; // untranslated
Blockly.Msg.TEXT_INDEXOF_INPUT_INTEXT = "i texten";
Blockly.Msg.TEXT_INDEXOF_OPERATOR_FIRST = "hitta första förekomsten av texten";
Blockly.Msg.TEXT_INDEXOF_OPERATOR_LAST = "hitta sista förekomsten av texten";
Blockly.Msg.TEXT_INDEXOF_TAIL = ""; // untranslated
Blockly.Msg.TEXT_INDEXOF_TOOLTIP = "Ger tillbaka indexet för den första/sista förekomsten av första texten i den andra texten. Ger tillbaka 0 om texten inte hittas.";
Blockly.Msg.TEXT_ISEMPTY_HELPURL = "https://github.com/google/blockly/wiki/Text#checking-for-empty-text"; // untranslated
Blockly.Msg.TEXT_ISEMPTY_TITLE = "%1 är tom";
Blockly.Msg.TEXT_ISEMPTY_TOOLTIP = "Returnerar sant om den angivna texten är tom.";
Blockly.Msg.TEXT_JOIN_HELPURL = "https://github.com/google/blockly/wiki/Text#text-creation"; // untranslated
Blockly.Msg.TEXT_JOIN_TITLE_CREATEWITH = "skapa text med";
Blockly.Msg.TEXT_JOIN_TOOLTIP = "Skapa en textbit genom att sammanfoga ett valfritt antal föremål.";
Blockly.Msg.TEXT_LENGTH_HELPURL = "https://github.com/google/blockly/wiki/Text#text-modification"; // untranslated
Blockly.Msg.TEXT_LENGTH_TITLE = "längden på %1";
Blockly.Msg.TEXT_LENGTH_TOOLTIP = "Ger tillbaka antalet bokstäver (inklusive mellanslag) i den angivna texten.";
Blockly.Msg.TEXT_PRINT_HELPURL = "https://github.com/google/blockly/wiki/Text#printing-text"; // untranslated
Blockly.Msg.TEXT_PRINT_TITLE = "skriv %1";
Blockly.Msg.TEXT_PRINT_TOOLTIP = "Skriv den angivna texten, talet eller annat värde.";
Blockly.Msg.TEXT_PROMPT_HELPURL = "https://github.com/google/blockly/wiki/Text#getting-input-from-the-user"; // untranslated
Blockly.Msg.TEXT_PROMPT_TOOLTIP_NUMBER = "Fråga användaren efter ett tal.";
Blockly.Msg.TEXT_PROMPT_TOOLTIP_TEXT = "Fråga användaren efter lite text.";
Blockly.Msg.TEXT_PROMPT_TYPE_NUMBER = "fråga efter ett tal med meddelande";
Blockly.Msg.TEXT_PROMPT_TYPE_TEXT = "fråga efter text med meddelande";
Blockly.Msg.TEXT_TEXT_HELPURL = "https://sv.wikipedia.org/wiki/Str%C3%A4ng_%28data%29";
Blockly.Msg.TEXT_TEXT_TOOLTIP = "En bokstav, ord eller textrad.";
Blockly.Msg.TEXT_TRIM_HELPURL = "https://github.com/google/blockly/wiki/Text#trimming-removing-spaces"; // untranslated
Blockly.Msg.TEXT_TRIM_OPERATOR_BOTH = "ta bort mellanrum från båda sidorna av";
Blockly.Msg.TEXT_TRIM_OPERATOR_LEFT = "ta bort mellanrum från vänstra sidan av";
Blockly.Msg.TEXT_TRIM_OPERATOR_RIGHT = "ta bort mellanrum från högra sidan av";
Blockly.Msg.TEXT_TRIM_TOOLTIP = "Returnerar en kopia av texten med borttagna mellanrum från en eller båda ändar.";
Blockly.Msg.TODAY = "Today"; // untranslated
Blockly.Msg.VARIABLES_DEFAULT_NAME = "föremål";
Blockly.Msg.VARIABLES_GET_CREATE_SET = "Skapa \"välj %1\"";
Blockly.Msg.VARIABLES_GET_HELPURL = "https://github.com/google/blockly/wiki/Variables#get"; // untranslated
Blockly.Msg.VARIABLES_GET_TAIL = ""; // untranslated
Blockly.Msg.VARIABLES_GET_TITLE = ""; // untranslated
Blockly.Msg.VARIABLES_GET_TOOLTIP = "Returnerar värdet av denna variabel.";
Blockly.Msg.VARIABLES_SET_CREATE_GET = "Skapa 'hämta %1'";
Blockly.Msg.VARIABLES_SET_HELPURL = "https://github.com/google/blockly/wiki/Variables#set"; // untranslated
Blockly.Msg.VARIABLES_SET_TAIL = "till";
Blockly.Msg.VARIABLES_SET_TITLE = "välj";
Blockly.Msg.VARIABLES_SET_TOOLTIP = "Gör så att den här variabeln blir lika med inputen.";
Blockly.Msg.PROCEDURES_DEFRETURN_TITLE = Blockly.Msg.PROCEDURES_DEFNORETURN_TITLE;
Blockly.Msg.LISTS_GET_SUBLIST_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST;
Blockly.Msg.LISTS_SET_INDEX_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST;
Blockly.Msg.PROCEDURES_DEFRETURN_PROCEDURE = Blockly.Msg.PROCEDURES_DEFNORETURN_PROCEDURE;
Blockly.Msg.VARIABLES_SET_ITEM = Blockly.Msg.VARIABLES_DEFAULT_NAME;
Blockly.Msg.LISTS_CREATE_WITH_ITEM_TITLE = Blockly.Msg.VARIABLES_DEFAULT_NAME;
Blockly.Msg.MATH_CHANGE_TITLE_ITEM = Blockly.Msg.VARIABLES_DEFAULT_NAME;
Blockly.Msg.VARIABLES_GET_ITEM = Blockly.Msg.VARIABLES_DEFAULT_NAME;
Blockly.Msg.PROCEDURES_DEFRETURN_DO = Blockly.Msg.PROCEDURES_DEFNORETURN_DO;
Blockly.Msg.LISTS_GET_INDEX_HELPURL = Blockly.Msg.LISTS_INDEX_OF_HELPURL;
Blockly.Msg.TEXT_CREATE_JOIN_ITEM_TITLE_ITEM = Blockly.Msg.VARIABLES_DEFAULT_NAME;
Blockly.Msg.CONTROLS_IF_MSG_THEN = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO;
Blockly.Msg.LISTS_INDEX_OF_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST;
Blockly.Msg.PROCEDURES_CALLRETURN_CALL = Blockly.Msg.PROCEDURES_CALLNORETURN_CALL;
Blockly.Msg.LISTS_GET_INDEX_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST;
Blockly.Msg.CONTROLS_FOR_INPUT_DO = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO;
Blockly.Msg.CONTROLS_FOREACH_INPUT_DO = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO;
Blockly.Msg.CONTROLS_IF_IF_TITLE_IF = Blockly.Msg.CONTROLS_IF_MSG_IF;
Blockly.Msg.CONTROLS_WHILEUNTIL_INPUT_DO = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO;
Blockly.Msg.CONTROLS_IF_ELSEIF_TITLE_ELSEIF = Blockly.Msg.CONTROLS_IF_MSG_ELSEIF;
Blockly.Msg.TEXT_APPEND_VARIABLE = Blockly.Msg.VARIABLES_DEFAULT_NAME;
Blockly.Msg.CONTROLS_IF_ELSE_TITLE_ELSE = Blockly.Msg.CONTROLS_IF_MSG_ELSE; | radiumray/Mixly_Arduino | mixly_arduino/blockly/msg/js/sv.js | JavaScript | apache-2.0 | 31,095 |
// Copyright (C) 2015 the V8 project authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
es6id: 12.10.3
description: Invocation of `Symbol.toPrimitive` method during coercion
info: |
[...]
7. Return the result of performing Abstract Equality Comparison rval ==
lval.
ES6 Section 7.2.12 Abstract Equality Comparison
[...]
10. If Type(x) is either String, Number, or Symbol and Type(y) is Object,
then return the result of the comparison x == ToPrimitive(y).
ES6 Section 7.1.1 ToPrimitive ( input [, PreferredType] )
1. If PreferredType was not passed, let hint be "default".
[...]
4. Let exoticToPrim be GetMethod(input, @@toPrimitive).
5. ReturnIfAbrupt(exoticToPrim).
6. If exoticToPrim is not undefined, then
a. Let result be Call(exoticToPrim, input, «hint»).
[...]
features: [Symbol.toPrimitive]
---*/
var y = {};
var callCount = 0;
var thisVal, args;
y[Symbol.toPrimitive] = function() {
callCount += 1;
thisVal = this;
args = arguments;
};
0 == y;
assert.sameValue(callCount, 1, 'method invoked exactly once');
assert.sameValue(thisVal, y, '`this` value is the object being compared');
assert.sameValue(args.length, 1, 'method invoked with exactly one argument');
assert.sameValue(
args[0],
'default',
'method invoked with the string "default" as the first argument'
);
| sebastienros/jint | Jint.Tests.Test262/test/language/expressions/equals/coerce-symbol-to-prim-invocation.js | JavaScript | bsd-2-clause | 1,426 |
var loopback = require('loopback'),
boot = require('loopback-boot');
var app = loopback();
boot(app, __dirname);
module.exports = app;
| maschinenbau/freecodecamp | client/loopbackClient.js | JavaScript | bsd-3-clause | 142 |
/* @flow */
/* Flow declarations for express requests and responses */
/* eslint-disable no-unused-vars */
declare class Request {
method: String;
body: Object;
query: Object;
}
declare class Response {
status: (code: Number) => Response;
set: (field: String, value: String) => Response;
send: (body: String) => void;
}
| jamiehodge/express-graphql | resources/interfaces/express.js | JavaScript | bsd-3-clause | 333 |
if (this.importScripts) {
importScripts('../../../fast/js/resources/js-test-pre.js');
importScripts('shared.js');
}
description("Test transaction aborts send the proper onabort messages..");
indexedDBTest(prepareDatabase, startTest);
function prepareDatabase()
{
db = event.target.result;
store = evalAndLog("store = db.createObjectStore('storeName', null)");
request = evalAndLog("store.add({x: 'value', y: 'zzz'}, 'key')");
request.onerror = unexpectedErrorCallback;
}
function startTest()
{
trans = evalAndLog("trans = db.transaction(['storeName'], 'readwrite')");
evalAndLog("trans.onabort = transactionAborted");
evalAndLog("trans.oncomplete = unexpectedCompleteCallback");
store = evalAndLog("store = trans.objectStore('storeName')");
request = evalAndLog("store.add({x: 'value2', y: 'zzz2'}, 'key2')");
request.onerror = firstAdd;
request.onsuccess = unexpectedSuccessCallback;
request = evalAndLog("store.add({x: 'value3', y: 'zzz3'}, 'key3')");
request.onerror = secondAdd;
request.onsuccess = unexpectedSuccessCallback;
trans.abort();
firstError = false;
secondError = false;
abortFired = false;
}
function firstAdd()
{
shouldBe("event.target.error.name", "'AbortError'");
shouldBeNull("trans.error");
shouldBeFalse("firstError");
shouldBeFalse("secondError");
shouldBeFalse("abortFired");
firstError = true;
evalAndExpectException("store.add({x: 'value4', y: 'zzz4'}, 'key4')", "0", "'TransactionInactiveError'");
}
function secondAdd()
{
shouldBe("event.target.error.name", "'AbortError'");
shouldBeNull("trans.error");
shouldBeTrue("firstError");
shouldBeFalse("secondError");
shouldBeFalse("abortFired");
secondError = true;
}
function transactionAborted()
{
shouldBeTrue("firstError");
shouldBeTrue("secondError");
shouldBeFalse("abortFired");
shouldBeNull("trans.error");
abortFired = true;
evalAndExpectException("store.add({x: 'value5', y: 'zzz5'}, 'key5')", "0", "'TransactionInactiveError'");
evalAndExpectException("trans.abort()", "DOMException.INVALID_STATE_ERR", "'InvalidStateError'");
finishJSTest();
}
| leighpauls/k2cro4 | content/test/data/layout_tests/LayoutTests/storage/indexeddb/resources/transaction-abort.js | JavaScript | bsd-3-clause | 2,204 |
function config ($logProvider) {
'ngInject';
// Enable log
$logProvider.debugEnabled(true);
}
export default config;
| mike1808/godtracks | src/app/index.config.js | JavaScript | mit | 124 |
/*
Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang( 'colorbutton', 'bs', {
auto: 'Automatska',
bgColorTitle: 'Boja pozadine',
colors: {
'000': 'Black',
'800000': 'Maroon',
'8B4513': 'Saddle Brown',
'2F4F4F': 'Dark Slate Gray',
'008080': 'Teal',
'000080': 'Navy',
'4B0082': 'Indigo',
'696969': 'Dark Gray',
B22222: 'Fire Brick',
A52A2A: 'Brown',
DAA520: 'Golden Rod',
'006400': 'Dark Green',
'40E0D0': 'Turquoise',
'0000CD': 'Medium Blue',
'800080': 'Purple',
'808080': 'Gray',
F00: 'Red',
FF8C00: 'Dark Orange',
FFD700: 'Gold',
'008000': 'Green',
'0FF': 'Cyan',
'00F': 'Blue',
EE82EE: 'Violet',
A9A9A9: 'Dim Gray',
FFA07A: 'Light Salmon',
FFA500: 'Orange',
FFFF00: 'Yellow',
'00FF00': 'Lime',
AFEEEE: 'Pale Turquoise',
ADD8E6: 'Light Blue',
DDA0DD: 'Plum',
D3D3D3: 'Light Grey',
FFF0F5: 'Lavender Blush',
FAEBD7: 'Antique White',
FFFFE0: 'Light Yellow',
F0FFF0: 'Honeydew',
F0FFFF: 'Azure',
F0F8FF: 'Alice Blue',
E6E6FA: 'Lavender',
FFF: 'White',
'1ABC9C': 'Strong Cyan', // MISSING
'2ECC71': 'Emerald', // MISSING
'3498DB': 'Bright Blue', // MISSING
'9B59B6': 'Amethyst', // MISSING
'4E5F70': 'Grayish Blue', // MISSING
'F1C40F': 'Vivid Yellow', // MISSING
'16A085': 'Dark Cyan', // MISSING
'27AE60': 'Dark Emerald', // MISSING
'2980B9': 'Strong Blue', // MISSING
'8E44AD': 'Dark Violet', // MISSING
'2C3E50': 'Desaturated Blue', // MISSING
'F39C12': 'Orange', // MISSING
'E67E22': 'Carrot', // MISSING
'E74C3C': 'Pale Red', // MISSING
'ECF0F1': 'Bright Silver', // MISSING
'95A5A6': 'Light Grayish Cyan', // MISSING
'DDD': 'Light Gray', // MISSING
'D35400': 'Pumpkin', // MISSING
'C0392B': 'Strong Red', // MISSING
'BDC3C7': 'Silver', // MISSING
'7F8C8D': 'Grayish Cyan', // MISSING
'999': 'Dark Gray' // MISSING
},
more: 'Više boja...',
panelTitle: 'Colors',
textColorTitle: 'Boja teksta'
} );
| zweidner/hubzero-cms | core/plugins/editors/ckeditor/assets/plugins/colorbutton/lang/bs.js | JavaScript | mit | 2,069 |
var http = require("http");
var url = require("url");
var server;
// Diese Funktion reagiert auf HTTP Requests,
// hier wird also die Web Anwendung implementiert!
var simpleHTTPResponder = function(req, res) {
// Routing bedeutet, anhand der URL Adresse
// unterschiedliche Funktionen zu steuern.
// Dazu wird zunächst die URL Adresse benötigt
var url_parts = url.parse(req.url, true);
// Nun erfolgt die Fallunterscheidung,
// hier anhand des URL Pfads
if (url_parts.pathname == "/greetme") {
// HTTP Header müssen gesetzt werden
res.writeHead(200, {
"Content-Type": "text/html"
});
// Auch URL Query Parameter können abgefragt werden
var query = url_parts.query;
var name = "Anonymous";
if (query["name"] != undefined) {
name = query["name"];
}
// HTML im Script zu erzeugen ist mühselig...
res.end("<html><head><title>Greetme</title></head><body><H1>Greetings " +
name + "!</H1></body></html>");
// nun folgt der zweite Fall...
} else {
res.writeHead(404, {
"Content-Type": "text/html"
});
res.end(
"<html><head><title>Error</title></head><body><H1>Only /greetme is implemented.</H1></body></html>"
);
}
}
// Webserver erzeugen, an Endpunkt binden und starten
server = http.createServer(simpleHTTPResponder);
var port = process.argv[2];
server.listen(port);
| MaximilianKucher/vs1Lab | Beispiele/nodejs_webserver/web.js | JavaScript | mit | 1,328 |
goog.require('ol.Map');
goog.require('ol.View');
goog.require('ol.control');
goog.require('ol.layer.Tile');
goog.require('ol.layer.Vector');
goog.require('ol.source.GeoJSON');
goog.require('ol.source.OSM');
var map = new ol.Map({
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
}),
new ol.layer.Vector({
source: new ol.source.GeoJSON({
projection: 'EPSG:3857',
url: 'data/geojson/countries.geojson'
})
})
],
target: 'map',
controls: ol.control.defaults({
attributionOptions: /** @type {olx.control.AttributionOptions} */ ({
collapsible: false
})
}),
view: new ol.View({
center: [0, 0],
zoom: 2
})
});
var exportPNGElement = document.getElementById('export-png');
if ('download' in exportPNGElement) {
exportPNGElement.addEventListener('click', function(e) {
map.once('postcompose', function(event) {
var canvas = event.context.canvas;
exportPNGElement.href = canvas.toDataURL('image/png');
});
map.renderSync();
}, false);
} else {
var info = document.getElementById('no-download');
/**
* display error message
*/
info.style.display = '';
}
| buddebej/ol3-dem | ol3/examples/export-map.js | JavaScript | mit | 1,180 |
'use strict';
angular.module('sumaAnalysis')
.factory('actsLocs', function () {
function calculateDepthAndTooltip (item, list, root, depth) {
var parent;
depth = depth || {depth: 0, tooltipTitle: item.title, ancestors: []};
if (parseInt(item.parent, 10) === parseInt(root, 10)) {
return depth;
}
parent = _.find(list, {'id': item.parent});
depth.depth += 1;
depth.tooltipTitle = parent.title + ': ' + depth.tooltipTitle;
depth.ancestors.push(parent.id);
return calculateDepthAndTooltip(parent, list, root, depth);
}
function processActivities (activities, activityGroups) {
var activityList = [],
activityGroupsHash;
// Sort activities and activity groups
activities = _.sortBy(activities, 'rank');
activityGroups = _.sortBy(activityGroups, 'rank');
activityGroupsHash = _.object(_.map(activityGroups, function (aGrp) {
return [aGrp.id, aGrp.title];
}));
// For each activity group, build a list of activities
_.each(activityGroups, function (activityGroup) {
// Add activity group metadata to activityGroupList array
activityList.push({
'id' : activityGroup.id,
'rank' : activityGroup.rank,
'title' : activityGroup.title,
'type' : 'activityGroup',
'depth' : 0,
'filter' : 'allow',
'enabled': true
});
// Loop over activities and add the ones belonging to the current activityGroup
_.each(activities, function (activity) {
if (activity.activityGroup === activityGroup.id) {
// Add activities to activityList array behind proper activityGroup
activityList.push({
'id' : activity.id,
'rank' : activity.rank,
'title' : activity.title,
'type' : 'activity',
'depth' : 1,
'activityGroup' : activityGroup.id,
'activityGroupTitle': activityGroupsHash[activityGroup.id],
'tooltipTitle' : activityGroupsHash[activityGroup.id] + ': ' + activity.title,
'altName' : activityGroupsHash[activityGroup.id] + ': ' + activity.title,
'filter' : 'allow',
'enabled' : true
});
}
});
});
return activityList;
}
function processLocations (locations, root) {
return _.map(locations, function (loc, index, list) {
var depth = calculateDepthAndTooltip(loc, list, root);
loc.depth = depth.depth;
loc.tooltipTitle = depth.tooltipTitle;
loc.ancestors = depth.ancestors;
loc.filter = true;
loc.enabled = true;
return loc;
});
}
return {
get: function (init) {
return {
activities: processActivities(init.dictionary.activities, init.dictionary.activityGroups),
locations: processLocations(init.dictionary.locations, init.rootLocation)
};
}
};
});
| cazzerson/Suma | analysis/src/scripts/services/actsLocs.js | JavaScript | mit | 3,247 |
import Ember from 'ember';
import { module, test } from 'qunit';
import startApp from '../../tests/helpers/start-app';
module('Acceptance | navs', {
beforeEach() {
this.application = startApp();
},
afterEach() {
Ember.run(this.application, 'destroy');
}
});
test('visiting /navs', function(assert) {
visit('/navs');
andThen(function() {
assert.equal(currentURL(), '/navs');
});
});
| leoeuclids/ember-material-lite | tests/acceptance/navs-test.js | JavaScript | mit | 412 |
/*!
* screenfull
* v4.2.0 - 2019-04-01
* (c) Sindre Sorhus; MIT License
*/
(function () {
'use strict';
var document = typeof window !== 'undefined' && typeof window.document !== 'undefined' ? window.document : {};
var isCommonjs = typeof module !== 'undefined' && module.exports;
var keyboardAllowed = typeof Element !== 'undefined' && 'ALLOW_KEYBOARD_INPUT' in Element;
var fn = (function () {
var val;
var fnMap = [
[
'requestFullscreen',
'exitFullscreen',
'fullscreenElement',
'fullscreenEnabled',
'fullscreenchange',
'fullscreenerror'
],
// New WebKit
[
'webkitRequestFullscreen',
'webkitExitFullscreen',
'webkitFullscreenElement',
'webkitFullscreenEnabled',
'webkitfullscreenchange',
'webkitfullscreenerror'
],
// Old WebKit (Safari 5.1)
[
'webkitRequestFullScreen',
'webkitCancelFullScreen',
'webkitCurrentFullScreenElement',
'webkitCancelFullScreen',
'webkitfullscreenchange',
'webkitfullscreenerror'
],
[
'mozRequestFullScreen',
'mozCancelFullScreen',
'mozFullScreenElement',
'mozFullScreenEnabled',
'mozfullscreenchange',
'mozfullscreenerror'
],
[
'msRequestFullscreen',
'msExitFullscreen',
'msFullscreenElement',
'msFullscreenEnabled',
'MSFullscreenChange',
'MSFullscreenError'
]
];
var i = 0;
var l = fnMap.length;
var ret = {};
for (; i < l; i++) {
val = fnMap[i];
if (val && val[1] in document) {
for (i = 0; i < val.length; i++) {
ret[fnMap[0][i]] = val[i];
}
return ret;
}
}
return false;
})();
var eventNameMap = {
change: fn.fullscreenchange,
error: fn.fullscreenerror
};
var screenfull = {
request: function (elem) {
return new Promise(function (resolve) {
var request = fn.requestFullscreen;
var onFullScreenEntered = function () {
this.off('change', onFullScreenEntered);
resolve();
}.bind(this);
elem = elem || document.documentElement;
// Work around Safari 5.1 bug: reports support for
// keyboard in fullscreen even though it doesn't.
// Browser sniffing, since the alternative with
// setTimeout is even worse.
if (/ Version\/5\.1(?:\.\d+)? Safari\//.test(navigator.userAgent)) {
elem[request]();
} else {
elem[request](keyboardAllowed ? Element.ALLOW_KEYBOARD_INPUT : {});
}
this.on('change', onFullScreenEntered);
}.bind(this));
},
exit: function () {
return new Promise(function (resolve) {
if (!this.isFullscreen) {
resolve();
return;
}
var onFullScreenExit = function () {
this.off('change', onFullScreenExit);
resolve();
}.bind(this);
document[fn.exitFullscreen]();
this.on('change', onFullScreenExit);
}.bind(this));
},
toggle: function (elem) {
return this.isFullscreen ? this.exit() : this.request(elem);
},
onchange: function (callback) {
this.on('change', callback);
},
onerror: function (callback) {
this.on('error', callback);
},
on: function (event, callback) {
var eventName = eventNameMap[event];
if (eventName) {
document.addEventListener(eventName, callback, false);
}
},
off: function (event, callback) {
var eventName = eventNameMap[event];
if (eventName) {
document.removeEventListener(eventName, callback, false);
}
},
raw: fn
};
if (!fn) {
if (isCommonjs) {
module.exports = false;
} else {
window.screenfull = false;
}
return;
}
Object.defineProperties(screenfull, {
isFullscreen: {
get: function () {
return Boolean(document[fn.fullscreenElement]);
}
},
element: {
enumerable: true,
get: function () {
return document[fn.fullscreenElement];
}
},
enabled: {
enumerable: true,
get: function () {
// Coerce to boolean in case of old WebKit
return Boolean(document[fn.fullscreenEnabled]);
}
}
});
if (isCommonjs) {
module.exports = screenfull;
// TODO: remove this in the next major version
module.exports.default = screenfull;
} else {
window.screenfull = screenfull;
}
})();
| quindar/quindar-ux | public/scripts/screenfull.js | JavaScript | mit | 4,129 |
var stub = require('./fixtures/stub'),
constants = require('./../constants'),
Logger = require('./fixtures/stub_logger'),
utils = require('./../utils');
// huge hack here, but plugin tests need constants
constants.import(global);
function _set_up(callback) {
this.backup = {};
callback();
}
function _tear_down(callback) {
callback();
}
exports.utils = {
setUp : _set_up,
tearDown : _tear_down,
'plain ascii should not be encoded' : function (test) {
test.expect(1);
test.equals(utils.encode_qp('quoted printable'), 'quoted printable');
test.done();
},
'8-bit chars should be encoded' : function (test) {
test.expect(1);
test.equals(
utils.encode_qp(
'v\xe5re kj\xe6re norske tegn b\xf8r \xe6res'
),
'v=E5re kj=E6re norske tegn b=F8r =E6res');
test.done();
},
'trailing space should be encoded' : function (test) {
test.expect(5);
test.equals(utils.encode_qp(' '), '=20=20');
test.equals(utils.encode_qp('\tt\t'), '\tt=09');
test.equals(
utils.encode_qp('test \ntest\n\t \t \n'),
'test=20=20\ntest\n=09=20=09=20\n'
);
test.equals(utils.encode_qp("foo \t "), "foo=20=09=20");
test.equals(utils.encode_qp("foo\t \n \t"), "foo=09=20\n=20=09");
test.done();
},
'trailing space should be decoded unless newline' : function (test) {
test.expect(2);
test.deepEqual(utils.decode_qp("foo "), new Buffer("foo "));
test.deepEqual(utils.decode_qp("foo \n"), new Buffer("foo\n"));
test.done();
},
'"=" is special and should be decoded' : function (test) {
test.expect(2);
test.equals(utils.encode_qp("=30\n"), "=3D30\n");
test.equals(utils.encode_qp("\0\xff0"), "=00=FF0");
test.done();
},
'Very long lines should be broken' : function (test) {
test.expect(1);
test.equals(utils.encode_qp("The Quoted-Printable encoding is intended to represent data that largly consists of octets that correspond to printable characters in the ASCII character set."), "The Quoted-Printable encoding is intended to represent data that largly con=\nsists of octets that correspond to printable characters in the ASCII charac=\nter set.");
test.done();
},
'multiple long lines' : function (test) {
test.expect(1);
test.equals(utils.encode_qp("College football is a game which would be much more interesting if the faculty played instead of the students, and even more interesting if the\ntrustees played. There would be a great increase in broken arms, legs, and necks, and simultaneously an appreciable diminution in the loss to humanity. -- H. L. Mencken"), "College football is a game which would be much more interesting if the facu=\nlty played instead of the students, and even more interesting if the\ntrustees played. There would be a great increase in broken arms, legs, and=\n necks, and simultaneously an appreciable diminution in the loss to humanit=\ny. -- H. L. Mencken");
test.done();
},
"Don't break a line that's near but not over 76 chars" : function (test) {
var buffer = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" +
"xxxxxxxxxxxxxxxxxx";
test.equals(utils.encode_qp(buffer+"123"), buffer+"123");
test.equals(utils.encode_qp(buffer+"1234"), buffer+"1234");
test.equals(utils.encode_qp(buffer+"12345"), buffer+"12345");
test.equals(utils.encode_qp(buffer+"123456"), buffer+"123456");
test.equals(utils.encode_qp(buffer+"1234567"), buffer+"12345=\n67");
test.equals(utils.encode_qp(buffer+"123456="), buffer+"12345=\n6=3D");
test.equals(utils.encode_qp(buffer+"123\n"), buffer+"123\n");
test.equals(utils.encode_qp(buffer+"1234\n"), buffer+"1234\n");
test.equals(utils.encode_qp(buffer+"12345\n"), buffer+"12345\n");
test.equals(utils.encode_qp(buffer+"123456\n"), buffer+"123456\n");
test.equals(utils.encode_qp(buffer+"1234567\n"), buffer+"12345=\n67\n");
test.equals(
utils.encode_qp(buffer+"123456=\n"), buffer+"12345=\n6=3D\n"
);
test.done();
},
'Not allowed to break =XX escapes using soft line break' : function (test) {
test.expect(10);
var buffer = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" +
"xxxxxxxxxxxxxxxxxx";
test.equals(
utils.encode_qp(buffer+"===xxxxx"), buffer+"=3D=\n=3D=3Dxxxxx"
);
test.equals(
utils.encode_qp(buffer+"1===xxxx"), buffer+"1=3D=\n=3D=3Dxxxx"
);
test.equals(
utils.encode_qp(buffer+"12===xxx"), buffer+"12=3D=\n=3D=3Dxxx"
);
test.equals(
utils.encode_qp(buffer+"123===xx"), buffer+"123=\n=3D=3D=3Dxx"
);
test.equals(
utils.encode_qp(buffer+"1234===x"), buffer+"1234=\n=3D=3D=3Dx"
);
test.equals(utils.encode_qp(buffer+"12=\n"), buffer+"12=3D\n");
test.equals(utils.encode_qp(buffer+"123=\n"), buffer+"123=\n=3D\n");
test.equals(utils.encode_qp(buffer+"1234=\n"), buffer+"1234=\n=3D\n");
test.equals(utils.encode_qp(buffer+"12345=\n"), buffer+"12345=\n=3D\n");
test.equals(
utils.encode_qp(buffer+"123456=\n"), buffer+"12345=\n6=3D\n"
);
test.done();
},
'some extra special cases we have had problems with' : function (test) {
test.expect(2);
var buffer = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" +
"xxxxxxxxxxxxxxxxxx";
test.equals(utils.encode_qp(buffer+"12=x=x"), buffer+"12=3D=\nx=3Dx");
test.equals(
utils.encode_qp(buffer+"12345"+buffer+"12345"+buffer+"123456\n"),
buffer+"12345=\n"+buffer+"12345=\n"+buffer+"123456\n"
);
test.done();
},
'regression test 01' : function (test) {
test.expect(1);
test.deepEqual(
utils.decode_qp("foo \n\nfoo =\n\nfoo=20\n\n"),
new Buffer("foo\n\nfoo \nfoo \n\n")
);
test.done();
},
'regression test 01 with CRLF' : function (test) {
test.expect(1);
test.deepEqual(
utils.decode_qp("foo \r\n\r\nfoo =\r\n\r\nfoo=20\r\n\r\n"),
new Buffer("foo\n\nfoo \nfoo \n\n")
);
test.done();
},
'regression test 02' : function (test) {
test.expect(1);
test.deepEqual(
utils.decode_qp("foo = \t\x20\nbar\t\x20\n"),
new Buffer("foo bar\n")
);
test.done();
},
'regression test 02 with CRLF' : function (test) {
test.expect(1);
test.deepEqual(
utils.decode_qp("foo = \t\x20\r\nbar\t\x20\r\n"),
new Buffer("foo bar\n")
);
test.done();
},
'regression test 03' : function (test) {
test.expect(1);
test.deepEqual(
utils.decode_qp("foo = \t\x20\n"), new Buffer("foo ")
);
test.done();
},
'regression test 03 with CRLF' : function (test) {
test.expect(1);
test.deepEqual(
utils.decode_qp("foo = \t\x20\r\n"), new Buffer("foo ")
);
test.done();
},
'regression test 04 from CRLF to LF' : function (test) {
test.expect(1);
test.deepEqual(
utils.decode_qp("foo = \t\x20y\r\n"), new Buffer("foo = \t\x20y\n")
);
test.done();
},
'regression test 05 should be the same' : function (test) {
test.expect(1);
test.deepEqual(
utils.decode_qp("foo =xy\n"), new Buffer("foo =xy\n")
);
test.done();
},
'spin encode_qp()' : function (test) {
var spin = 10000;
test.expect(spin);
for (var i = 0; i < spin; i++) {
test.equals(
utils.encode_qp("quoted printable"), "quoted printable"
);
}
test.done();
}
};
exports.valid_regexes = {
setUp : _set_up,
tearDown : _tear_down,
'two valid': function (test) {
var re_list = ['.*\.exam.ple','.*\.example.com'];
test.expect(1);
test.deepEqual(re_list, utils.valid_regexes(re_list));
test.done();
},
'one valid, one invalid': function (test) {
var re_list = ['*\.exam.ple','.*\.example.com'];
test.expect(1);
test.deepEqual(['.*\.example.com'], utils.valid_regexes(re_list));
test.done();
},
'one valid, two invalid': function (test) {
var re_list = ['[', '*\.exam.ple','.*\.example.com'];
test.expect(1);
test.deepEqual(['.*\.example.com'], utils.valid_regexes(re_list));
test.done();
},
};
exports.base64 = {
setUp : _set_up,
tearDown : _tear_down,
'base64': function (test) {
test.expect(1);
test.equal(utils.base64('matt the tester'), 'bWF0dCB0aGUgdGVzdGVy');
test.done();
},
'unbase64': function (test) {
test.expect(1);
test.equal(utils.unbase64('bWF0dCB0aGUgdGVzdGVy'), 'matt the tester');
test.done();
}
};
exports.to_object = {
setUp : _set_up,
tearDown : _tear_down,
'string': function (test) {
test.expect(1);
test.deepEqual(utils.to_object('matt,test'),
{ matt: true, test: true }
);
test.done();
},
'array': function (test) {
test.expect(1);
test.deepEqual(utils.to_object(['matt','test']),
{ matt: true, test: true }
);
test.done();
},
};
exports.extend = {
'copies properties from one object': function (test) {
test.expect(1);
var both = utils.extend({first: 'boo'}, {second: 'ger'});
test.deepEqual({first: 'boo', second: 'ger'}, both);
test.done();
},
'copies properties from multiple objects': function (test) {
test.expect(1);
test.deepEqual(
utils.extend(
{first: 'boo'}, {second: 'ger'}, {third: 'eat'}
),
{first: 'boo', second: 'ger', third: 'eat'}
);
test.done();
},
};
exports.node_min = {
'node is new enough': function (test) {
test.expect(6);
test.ok(utils.node_min('0.8.0', '0.10.0'));
test.ok(utils.node_min('0.10.0', '0.10.0'));
test.ok(utils.node_min('0.10.0', '0.10.1'));
test.ok(utils.node_min('0.10.0', '0.12.0'));
test.ok(utils.node_min('0.10.0', '1.0.0'));
test.ok(utils.node_min('0.10', '1.0'));
test.done();
},
'node is too old': function (test) {
test.expect(4);
test.ok(!utils.node_min('0.12.0', '0.10.0'));
test.ok(!utils.node_min('1.0.0', '0.8.0'));
test.ok(!utils.node_min('1.0.0', '0.10.0'));
test.ok(!utils.node_min('1.0.0', '0.12.0'));
test.done();
},
};
exports.elapsed = {
'returns 0 decimal places': function (test) {
test.expect(1);
var start = new Date();
start.setTime(start.getTime() - 3517); // 3.517 seconds ago
test.strictEqual(utils.elapsed(start, 0), '4');
test.done();
},
'returns 1 decimal place': function (test) {
test.expect(1);
var start = new Date();
start.setTime(start.getTime() - 3517); // 3.517 seconds ago
test.strictEqual(utils.elapsed(start, 1), '3.5');
test.done();
},
'returns 2 decimal places': function (test) {
test.expect(1);
var start = new Date();
start.setTime(start.getTime() - 3517); // 3.517 seconds ago
test.strictEqual(utils.elapsed(start, 2), '3.52');
test.done();
},
'default N > 5 has 0 decimal places': function (test) {
test.expect(1);
var start = new Date();
start.setTime(start.getTime() - 13517); // 3.517 seconds ago
test.strictEqual(utils.elapsed(start), '14');
test.done();
},
'default N > 2 has 1 decimal places': function (test) {
test.expect(1);
var start = new Date();
start.setTime(start.getTime() - 3517); // 3.517 seconds ago
test.strictEqual(utils.elapsed(start), '3.5');
test.done();
},
'default has 2 decimal places': function (test) {
test.expect(1);
var start = new Date();
start.setTime(start.getTime() - 1517); // 3.517 seconds ago
test.strictEqual(utils.elapsed(start), '1.52');
test.done();
},
};
| jjz/Haraka | tests/utils.js | JavaScript | mit | 12,700 |
// Generated by LiveScript 1.5.0
var onmessage, this$ = this;
function addEventListener(event, cb){
return this.thread.on(event, cb);
}
function close(){
return this.thread.emit('close');
}
function importScripts(){
var i$, len$, p, results$ = [];
for (i$ = 0, len$ = (arguments).length; i$ < len$; ++i$) {
p = (arguments)[i$];
results$.push(self.eval(native_fs_.readFileSync(p, 'utf8')));
}
return results$;
}
onmessage = null;
thread.on('message', function(args){
return typeof onmessage == 'function' ? onmessage(args) : void 8;
});
| romainmnr/chatboteseo | node_modules/webworker-threads/src/load.js | JavaScript | mit | 558 |
module.exports = {
"env": {
"browser": true
},
"plugins": [
"callback-function"
],
"globals": {
"_": true,
"$": true,
"ActErr": true,
"async": true,
"config": true,
"logger": true,
"moment": true,
"respondWithError": true,
"sendJSONResponse": true,
"util": true,
"admiral": true
},
"extends": "airbnb-base/legacy",
"rules": {
// rules to override from airbnb/legacy
"object-curly-spacing": ["error", "never"],
"curly": ["error", "multi", "consistent"],
"no-param-reassign": ["error", { "props": false }],
"no-underscore-dangle": ["error", { "allow": ["_r", "_p"] }],
"quote-props": ["error", "consistent-as-needed"],
// rules from airbnb that we won't be using
"consistent-return": 0,
"default-case": 0,
"func-names": 0,
"no-plusplus": 0,
"no-use-before-define": 0,
"vars-on-top": 0,
"no-loop-func": 0,
"no-underscore-dangle": 0,
"no-param-reassign": 0,
"one-var-declaration-per-line": 0,
"one-var": 0,
"no-multi-assign": 0,
"global-require": 0,
// extra rules not present in airbnb
"max-len": ["error", 80],
}
};
| himanshu0503/admiral | .eslintrc.js | JavaScript | mit | 1,174 |
// textarea̳ðCu²ß·é
function adjustTextareaRows(obj, org, plus) {
var brlen = null;
if (obj.wrap) {
if (obj.wrap == 'virtual' || obj.wrap == 'soft') {
brlen = obj.cols;
}
}
var aLen = countLines(obj.value, brlen);
var aRows = aLen + plus;
var move = 0;
var scroll = 14;
if (org) {
if (Math.max(aRows, obj.rows) > org) {
move = Math.abs((aRows - obj.rows) * scroll);
if (move) {
obj.rows = Math.max(org, aRows);
window.scrollBy(0, move);
}
}
/*
if (aRows > org + plus) {
if (obj.rows < aRows) {
move = (aRows - obj.rows) * scroll;
} else if (obj.rows > aRows) {
move = (aRows - obj.rows) * -scroll;
}
if (move != 0) {
if (move < 0) {
window.scrollBy(0, move);
}
obj.rows = aRows;
if (move > 0) {
window.scrollBy(0, move);
}
}
}
*/
} else if (obj.rows < aRows) {
move = (aRows - obj.rows) * scroll;
obj.rows = aRows;
window.scrollBy(0, move);
}
}
/**
* \n ðüsƵÄsð¦é
*
* @param integer brlen üs·é¶B³wèÈç¶ÅüsµÈ¢
*/
function countLines(str, brlen) {
var lines = str.split("\n");
var count = lines.length;
var aLen = 0;
for (var i = 0; i < lines.length; i++) {
aLen = jstrlen(lines[i]);
if (brlen) {
var adjust = 1.15; // PêPÊÌÜèÔµÉεĢȢÌÅAoEg²®
if ((aLen * adjust) > brlen) {
count = count + Math.floor((aLen * adjust) / brlen);
}
}
}
return count;
}
// ¶ñðoCgŦé
function jstrlen(str) {
var len = 0;
str = escape(str);
for (var i = 0; i < str.length; i++, len++) {
if (str.charAt(i) == "%") {
if (str.charAt(++i) == "u") {
i += 3;
len++;
}
i++;
}
}
return len;
}
// (ÎÛªdisableÅȯêÎ) tH[JXðí¹é
function setFocus(ID){
var obj;
if (obj = document.getElementById(ID)) {
if (obj.disabled != true) {
obj.focus();
}
}
}
// sage`FbNÉí¹ÄA[Ìàeð«·¦é
function mailSage(){
var mailran, cbsage;
if (cbsage = document.getElementById('sage')) {
if (mailran = document.getElementById('mail')) {
if (cbsage.checked == true) {
mailran.value = "sage";
} else {
if (mailran.value == "sage") {
mailran.value = "";
}
}
}
}
}
// [ÌàeɶÄAsage`FbNðON OFF·é
function checkSage(){
var mailran, cbsage;
if (mailran = document.getElementById('mail')) {
if (cbsage = document.getElementById('sage')) {
if (mailran.value == "sage") {
cbsage.checked = true;
} else {
cbsage.checked = false;
}
}
}
}
/*
// ©®ÅÇÝÞ±Æɵ½ÌÅAgíÈ¢
// OñÌ«ÝàeðA·é
function loadLastPosted(from, mail, message){
if (fromran = document.getElementById('FROM')) {
fromran.value = from;
}
if (mailran = document.getElementById('mail')) {
mailran.value = mail;
}
if (messageran = document.getElementById('MESSAGE')) {
messageran.value = message;
}
checkSage();
}
*/
// «Ý{^ÌLøE³øðØèÖ¦é
function switchBlockSubmit(onoff) {
var kakiko_submit = document.getElementById('kakiko_submit');
if (kakiko_submit) {
kakiko_submit.disabled = onoff;
}
var submit_beres = document.getElementById('submit_beres');
if (submit_beres) {
submit_beres.disabled = onoff;
}
}
// è^¶ð}ü·é
function inputConstant(obj) {
var msg = document.getElementById('MESSAGE');
msg.value = msg.value + obj.options[obj.selectedIndex].value;
msg.focus();
obj.options[0].selected = true;
}
// «ÝàeðØ·é
function validateAll(doValidateMsg, doValidateSage) {
var block_submit = document.getElementById('block_submit');
if (block_submit && block_submit.checked) {
alert('«ÝubN');
return false;
}
if (doValidateMsg && !validateMsg()) {
return false;
}
if (doValidateSage && !validateSage()) {
return false;
}
return true;
}
// {¶ªóÅÈ¢©Ø·é
function validateMsg() {
if (document.getElementById('MESSAGE').value.length == 0) {
alert('{¶ª èܹñB');
return false;
}
return true;
}
// sageÄ¢é©Ø·é
function validateSage() {
if (document.getElementById('mail').value.indexOf('sage') == -1) {
if (window.confirm('sageÄܹñæH')) {
return true;
} else {
return false;
}
}
return true;
}
// øÉtrueðw赽缳µÅ·é©Ç¤©mF·é
function confirmNanashi(doconfirmNanashi) {
// øªtrueżOª0¶(¼³µ)ÈçÎ
if (doconfirmNanashi && document.getElementById('FROM').value.length == 0) {
if(window.confirm('±ÌÂͼ³µÉ fusianasan ªÜÜêĢܷB\n¼³µÅ«ÝÜ·©H')) {
return true;
} else {
return false;
}
}
return true;
}
//øÉtrueðw赽缳µÅoÈ¢
function blockNanashi(blockNanashi) {
// øªtrueżOª0¶(¼³µ)ÈçÎ
if (blockNanashi && document.getElementById('FROM').value.length == 0) {
alert('±ÌÂͼ³µÌ«Ýª§À³êÄ¢éÌż³µÅ«Þ±ÆªoܹñB');
return false;
}
return true;
} | okyada/p2-php | rep2/js/post_form.js | JavaScript | mit | 4,984 |
export * from './filterutils';
export * from './objectutils';
export * from './uniquecomponentid';
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoicHVibGljX2FwaS5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9hcHAvY29tcG9uZW50cy91dGlscy9wdWJsaWNfYXBpLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBLGNBQWMsZUFBZSxDQUFDO0FBQzlCLGNBQWMsZUFBZSxDQUFDO0FBQzlCLGNBQWMscUJBQXFCLENBQUMiLCJzb3VyY2VzQ29udGVudCI6WyJleHBvcnQgKiBmcm9tICcuL2ZpbHRlcnV0aWxzJztcbmV4cG9ydCAqIGZyb20gJy4vb2JqZWN0dXRpbHMnO1xuZXhwb3J0ICogZnJvbSAnLi91bmlxdWVjb21wb25lbnRpZCc7ICJdfQ== | cdnjs/cdnjs | ajax/libs/primeng/10.0.3/esm2015/utils/public_api.js | JavaScript | mit | 585 |
/**
* @author Moxiecode
* @copyright Copyright © 2004-2008, Moxiecode Systems AB, All rights reserved.
*
* @author ralf57
* @author luciorota ([email protected])
* @author dugris ([email protected])
*/
tinyMCEPopup.requireLangPack();
var XoopsimagemanagerDialog = {
preInit : function()
{
var url;
if (url = tinyMCEPopup.getParam("external_image_list_url"))
document.write('<script language="javascript" type="text/javascript" src="' + tinyMCEPopup.editor.documentBaseURI.toAbsolute(url) + '"></script>');
},
init : function(ed)
{
var f = document.forms[0], nl = f.elements, ed = tinyMCEPopup.editor, dom = ed.dom, n = ed.selection.getNode();
tinyMCEPopup.resizeToInnerSize();
this.fillClassList('class_list');
this.fillFileList('src_list', 'tinyMCEImageList');
this.fillFileList('over_list', 'tinyMCEImageList');
this.fillFileList('out_list', 'tinyMCEImageList');
if (n.nodeName == 'IMG') {
nl.src.value = dom.getAttrib(n, 'src');
nl.width.value = dom.getAttrib(n, 'width');
nl.height.value = dom.getAttrib(n, 'height');
nl.alt.value = dom.getAttrib(n, 'alt');
nl.title.value = dom.getAttrib(n, 'title');
nl.vspace.value = this.getAttrib(n, 'vspace');
nl.hspace.value = this.getAttrib(n, 'hspace');
nl.border.value = this.getAttrib(n, 'border');
selectByValue(f, 'align', this.getAttrib(n, 'align'));
selectByValue(f, 'class_list', dom.getAttrib(n, 'class'));
nl.style.value = dom.getAttrib(n, 'style');
nl.id.value = dom.getAttrib(n, 'id');
nl.dir.value = dom.getAttrib(n, 'dir');
nl.lang.value = dom.getAttrib(n, 'lang');
nl.usemap.value = dom.getAttrib(n, 'usemap');
nl.longdesc.value = dom.getAttrib(n, 'longdesc');
nl.insert.value = ed.getLang('update');
if (/^\s*this.src\s*=\s*\'([^\']+)\';?\s*$/.test(dom.getAttrib(n, 'onmouseover')))
nl.onmouseoversrc.value = dom.getAttrib(n, 'onmouseover').replace(/^\s*this.src\s*=\s*\'([^\']+)\';?\s*$/, '$1');
if (/^\s*this.src\s*=\s*\'([^\']+)\';?\s*$/.test(dom.getAttrib(n, 'onmouseout')))
nl.onmouseoutsrc.value = dom.getAttrib(n, 'onmouseout').replace(/^\s*this.src\s*=\s*\'([^\']+)\';?\s*$/, '$1');
if (ed.settings.inline_styles) {
// Move attribs to styles
if (dom.getAttrib(n, 'align'))
this.updateStyle('align');
if (dom.getAttrib(n, 'hspace'))
this.updateStyle('hspace');
if (dom.getAttrib(n, 'border'))
this.updateStyle('border');
if (dom.getAttrib(n, 'vspace'))
this.updateStyle('vspace');
}
}
// Setup browse button
document.getElementById('srcbrowsercontainer').innerHTML = getBrowserHTML('srcbrowser','src','image','theme_advanced_image');
if (isVisible('srcbrowser'))
document.getElementById('src').style.width = '260px';
// Setup browse button
document.getElementById('onmouseoversrccontainer').innerHTML = getBrowserHTML('overbrowser','onmouseoversrc','image','theme_advanced_image');
if (isVisible('overbrowser'))
document.getElementById('onmouseoversrc').style.width = '260px';
// Setup browse button
document.getElementById('onmouseoutsrccontainer').innerHTML = getBrowserHTML('outbrowser','onmouseoutsrc','image','theme_advanced_image');
if (isVisible('outbrowser'))
document.getElementById('onmouseoutsrc').style.width = '260px';
// If option enabled default contrain proportions to checked
if (ed.getParam("xoopsimagemanager_constrain_proportions", true))
f.constrain.checked = true;
// Check swap image if valid data
if (nl.onmouseoversrc.value || nl.onmouseoutsrc.value)
this.setSwapImage(true);
else
this.setSwapImage(false);
this.changeAppearance();
this.showPreviewImage(nl.src.value, 1);
},
insert : function(file, title)
{
var ed = tinyMCEPopup.editor, t = this, f = document.forms[0];
if (f.src.value === '') {
if (ed.selection.getNode().nodeName == 'IMG') {
ed.dom.remove(ed.selection.getNode());
ed.execCommand('mceRepaint');
}
tinyMCEPopup.close();
return;
}
if (tinyMCEPopup.getParam("accessibility_warnings", 1)) {
if (!f.alt.value) {
tinyMCEPopup.editor.windowManager.confirm(tinyMCEPopup.getLang('xoopsimagemanager_dlg.missing_alt'), function(s) {
if (s)
t.insertAndClose();
});
return;
}
}
t.insertAndClose();
},
insertAndClose : function()
{
var ed = tinyMCEPopup.editor, f = document.forms[0], nl = f.elements, v, args = {}, el;
tinyMCEPopup.restoreSelection();
// Fixes crash in Safari
if (tinymce.isWebKit)
ed.getWin().focus();
if (!ed.settings.inline_styles) {
args = {
vspace : nl.vspace.value,
hspace : nl.hspace.value,
border : nl.border.value,
align : getSelectValue(f, 'align')
};
} else {
// Remove deprecated values
args = {
vspace : '',
hspace : '',
border : '',
align : ''
};
}
tinymce.extend(args, {
src : nl.src.value,
width : nl.width.value,
height : nl.height.value,
alt : nl.alt.value,
title : nl.title.value,
'class' : getSelectValue(f, 'class_list'),
style : nl.style.value,
id : nl.id.value,
dir : nl.dir.value,
lang : nl.lang.value,
usemap : nl.usemap.value,
longdesc : nl.longdesc.value
});
args.onmouseover = args.onmouseout = '';
if (f.onmousemovecheck.checked) {
if (nl.onmouseoversrc.value)
args.onmouseover = "this.src='" + nl.onmouseoversrc.value + "';";
if (nl.onmouseoutsrc.value)
args.onmouseout = "this.src='" + nl.onmouseoutsrc.value + "';";
}
el = ed.selection.getNode();
if (el && el.nodeName == 'IMG') {
ed.dom.setAttribs(el, args);
} else {
ed.execCommand('mceInsertContent', false, '<img id="__mce_tmp" src="javascript:;" />', {skip_undo : 1});
ed.dom.setAttribs('__mce_tmp', args);
ed.dom.setAttrib('__mce_tmp', 'id', '');
ed.undoManager.add();
}
tinyMCEPopup.close();
},
getAttrib : function(e, at)
{
var ed = tinyMCEPopup.editor, dom = ed.dom, v, v2;
if (ed.settings.inline_styles) {
switch (at) {
case 'align':
if (v = dom.getStyle(e, 'float'))
return v;
if (v = dom.getStyle(e, 'vertical-align'))
return v;
break;
case 'hspace':
v = dom.getStyle(e, 'margin-left')
v2 = dom.getStyle(e, 'margin-right');
if (v && v == v2)
return parseInt(v.replace(/[^0-9]/g, ''));
break;
case 'vspace':
v = dom.getStyle(e, 'margin-top')
v2 = dom.getStyle(e, 'margin-bottom');
if (v && v == v2)
return parseInt(v.replace(/[^0-9]/g, ''));
break;
case 'border':
v = 0;
tinymce.each(['top', 'right', 'bottom', 'left'], function(sv) {
sv = dom.getStyle(e, 'border-' + sv + '-width');
// False or not the same as prev
if (!sv || (sv != v && v !== 0)) {
v = 0;
return false;
}
if (sv)
v = sv;
});
if (v)
return parseInt(v.replace(/[^0-9]/g, ''));
break;
}
}
if (v = dom.getAttrib(e, at))
return v;
return '';
},
setSwapImage : function(st)
{
var f = document.forms[0];
f.onmousemovecheck.checked = st;
setBrowserDisabled('overbrowser', !st);
setBrowserDisabled('outbrowser', !st);
if (f.over_list)
f.over_list.disabled = !st;
if (f.out_list)
f.out_list.disabled = !st;
f.onmouseoversrc.disabled = !st;
f.onmouseoutsrc.disabled = !st;
},
fillClassList : function(id)
{
var dom = tinyMCEPopup.dom, lst = dom.get(id), v, cl;
if (v = tinyMCEPopup.getParam('theme_advanced_styles')) {
cl = [];
tinymce.each(v.split(';'), function(v) {
var p = v.split('=');
cl.push({'title' : p[0], 'class' : p[1]});
});
} else
cl = tinyMCEPopup.editor.dom.getClasses();
if (cl.length > 0) {
lst.options[lst.options.length] = new Option(tinyMCEPopup.getLang('not_set'), '');
tinymce.each(cl, function(o) {
lst.options[lst.options.length] = new Option(o.title || o['class'], o['class']);
});
} else
dom.remove(dom.getParent(id, 'tr'));
},
fillFileList : function(id, l)
{
var dom = tinyMCEPopup.dom, lst = dom.get(id), v, cl;
l = window[l];
if (l && l.length > 0) {
lst.options[lst.options.length] = new Option('', '');
tinymce.each(l, function(o) {
lst.options[lst.options.length] = new Option(o[0], o[1]);
});
} else
dom.remove(dom.getParent(id, 'tr'));
},
resetImageData : function()
{
var f = document.forms[0];
f.elements.width.value = f.elements.height.value = '';
},
updateImageData : function(img, st)
{
var f = document.forms[0];
if (!st) {
f.elements.width.value = img.width;
f.elements.height.value = img.height;
}
this.preloadImg = img;
},
changeAppearance : function()
{
var ed = tinyMCEPopup.editor, f = document.forms[0], img = document.getElementById('alignSampleImg');
if (img) {
if (ed.getParam('inline_styles')) {
ed.dom.setAttrib(img, 'style', f.style.value);
} else {
img.align = f.align.value;
img.border = f.border.value;
img.hspace = f.hspace.value;
img.vspace = f.vspace.value;
}
}
},
changeHeight : function()
{
var f = document.forms[0], tp, t = this;
if (!f.constrain.checked || !t.preloadImg) {
return;
}
if (f.width.value == "" || f.height.value == "")
return;
tp = (parseInt(f.width.value) / parseInt(t.preloadImg.width)) * t.preloadImg.height;
f.height.value = tp.toFixed(0);
},
changeWidth : function()
{
var f = document.forms[0], tp, t = this;
if (!f.constrain.checked || !t.preloadImg) {
return;
}
if (f.width.value == "" || f.height.value == "")
return;
tp = (parseInt(f.height.value) / parseInt(t.preloadImg.height)) * t.preloadImg.width;
f.width.value = tp.toFixed(0);
},
updateStyle : function(ty)
{
var dom = tinyMCEPopup.dom, st, v, f = document.forms[0], img = dom.create('img', {style : dom.get('style').value});
if (tinyMCEPopup.editor.settings.inline_styles) {
// Handle align
if (ty == 'align') {
dom.setStyle(img, 'float', '');
dom.setStyle(img, 'vertical-align', '');
v = getSelectValue(f, 'align');
if (v) {
if (v == 'left' || v == 'right')
dom.setStyle(img, 'float', v);
else
img.style.verticalAlign = v;
}
}
// Handle border
if (ty == 'border') {
dom.setStyle(img, 'border', '');
v = f.border.value;
if (v || v == '0') {
if (v == '0')
img.style.border = '';
else
img.style.border = v + 'px solid black';
}
}
// Handle hspace
if (ty == 'hspace') {
dom.setStyle(img, 'marginLeft', '');
dom.setStyle(img, 'marginRight', '');
v = f.hspace.value;
if (v) {
img.style.marginLeft = v + 'px';
img.style.marginRight = v + 'px';
}
}
// Handle vspace
if (ty == 'vspace') {
dom.setStyle(img, 'marginTop', '');
dom.setStyle(img, 'marginBottom', '');
v = f.vspace.value;
if (v) {
img.style.marginTop = v + 'px';
img.style.marginBottom = v + 'px';
}
}
// Merge
dom.get('style').value = dom.serializeStyle(dom.parseStyle(img.style.cssText));
}
},
changeMouseMove : function()
{
},
showPreviewImage : function(u, st)
{
if (!u) {
tinyMCEPopup.dom.setHTML('prev', '');
return;
}
if (!st && tinyMCEPopup.getParam("xoopsimagemanager_update_dimensions_onchange", true))
this.resetImageData();
u = tinyMCEPopup.editor.documentBaseURI.toAbsolute(u);
if (!st)
tinyMCEPopup.dom.setHTML('prev', '<img id="previewImg" src="' + u + '" border="0" onload="XoopsimagemanagerDialog.updateImageData(this);" onerror="XoopsimagemanagerDialog.resetImageData();" />');
else
tinyMCEPopup.dom.setHTML('prev', '<img id="previewImg" src="' + u + '" border="0" onload="XoopsimagemanagerDialog.updateImageData(this, 1);" />');
}
};
XoopsimagemanagerDialog.preInit();
tinyMCEPopup.onInit.add(XoopsimagemanagerDialog.init, XoopsimagemanagerDialog);
function XoopsImageBrowser( input ) {
var url = "xoopsimagebrowser.php?target=src";
var type = "image";
var win = window.self;
var cmsURL = window.location.href; // script URL
var cmsURL = cmsURL.substring( 0, cmsURL.lastIndexOf("/") + 1 );
var searchString = window.location.search; // possible parameters
if (searchString.length < 1) {
// add "?" to the URL to include parameters (in other words: create a search string because there wasn't one before)
searchString = "?";
}
tinyMCE.activeEditor.windowManager.open({
file : cmsURL + url + searchString + "&type=" + type,
title : 'Xoops Image Manager',
width : 650,
height : 440,
resizable : "yes",
scrollbars : "yes",
inline : "yes", // This parameter only has an effect if you use the inlinepopups plugin!
close_previous : "no"
}, {
window : win,
input_src : input,
input_title : "title",
input_alt : "alt",
input_align : "align"
});
return false;
} | mambax7/XoopsCore25 | htdocs/class/xoopseditor/tinymce/tinymce/jscripts/tiny_mce/plugins/xoopsimagemanager/js/xoopsimagemanager.js | JavaScript | gpl-2.0 | 16,092 |
var express = require('express');
var leaderRouter = express.Router();
leaderRouter.route('/')
.all(function(req, res, next) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
next();
})
.get(function(req, res, next){
res.end('Will send all the leaders to you!');
})
.post(function(req, res, next){
res.end('Will add the leader: ' + req.body.name +
' with details: ' + req.body.description);
})
.delete(function(req, res, next){
res.end('Deleting all leaders');
});
leaderRouter.route('/:leaderId')
.all(function(req, res, next) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
next();
})
.get(function(req, res, next){
res.end('Will send details of the leader: ' + req.params.leaderId +' to you!');
})
.put(function(req, res, next){
res.write('Updating the leader: ' + req.params.leaderId + '\n');
res.end('Will update the leader: ' + req.body.name +
' with details: ' + req.body.description);
})
.delete(function(req, res, next){
res.end('Deleting the leader: ' + req.params.leaderId);
});
module.exports = leaderRouter;
| mikedanylov/full-stack-dev | NodeJS/week3/rest-server/routes/leaderRouter.js | JavaScript | gpl-2.0 | 1,220 |
//@tag dom,core
//@define Ext-more
//@require Ext.EventManager
/**
* @class Ext
*
* Ext is the global namespace for the whole Sencha Touch framework. Every class, function and configuration for the
* whole framework exists under this single global variable. The Ext singleton itself contains a set of useful helper
* functions (like {@link #apply}, {@link #min} and others), but most of the framework that you use day to day exists
* in specialized classes (for example {@link Ext.Panel}, {@link Ext.Carousel} and others).
*
* If you are new to Sencha Touch we recommend starting with the [Getting Started Guide][getting_started] to
* get a feel for how the framework operates. After that, use the more focused guides on subjects like panels, forms and data
* to broaden your understanding. The MVC guides take you through the process of building full applications using the
* framework, and detail how to deploy them to production.
*
* The functions listed below are mostly utility functions used internally by many of the classes shipped in the
* framework, but also often useful in your own apps.
*
* A method that is crucial to beginning your application is {@link #setup Ext.setup}. Please refer to it's documentation, or the
* [Getting Started Guide][getting_started] as a reference on beginning your application.
*
* Ext.setup({
* onReady: function() {
* Ext.Viewport.add({
* xtype: 'component',
* html: 'Hello world!'
* });
* }
* });
*
* [getting_started]: #!/guide/getting_started
*/
Ext.setVersion('touch', '2.1.0');
Ext.apply(Ext, {
/**
* The version of the framework
* @type String
*/
version: Ext.getVersion('touch'),
/**
* @private
*/
idSeed: 0,
/**
* Repaints the whole page. This fixes frequently encountered painting issues in mobile Safari.
*/
repaint: function() {
var mask = Ext.getBody().createChild({
cls: Ext.baseCSSPrefix + 'mask ' + Ext.baseCSSPrefix + 'mask-transparent'
});
setTimeout(function() {
mask.destroy();
}, 0);
},
/**
* Generates unique ids. If the element already has an `id`, it is unchanged.
* @param {Mixed} el (optional) The element to generate an id for.
* @param {String} [prefix=ext-gen] (optional) The `id` prefix.
* @return {String} The generated `id`.
*/
id: function(el, prefix) {
if (el && el.id) {
return el.id;
}
el = Ext.getDom(el) || {};
if (el === document || el === document.documentElement) {
el.id = 'ext-application';
}
else if (el === document.body) {
el.id = 'ext-viewport';
}
else if (el === window) {
el.id = 'ext-window';
}
el.id = el.id || ((prefix || 'ext-element-') + (++Ext.idSeed));
return el.id;
},
/**
* Returns the current document body as an {@link Ext.Element}.
* @return {Ext.Element} The document body.
*/
getBody: function() {
if (!Ext.documentBodyElement) {
if (!document.body) {
throw new Error("[Ext.getBody] document.body does not exist at this point");
}
Ext.documentBodyElement = Ext.get(document.body);
}
return Ext.documentBodyElement;
},
/**
* Returns the current document head as an {@link Ext.Element}.
* @return {Ext.Element} The document head.
*/
getHead: function() {
if (!Ext.documentHeadElement) {
Ext.documentHeadElement = Ext.get(document.head || document.getElementsByTagName('head')[0]);
}
return Ext.documentHeadElement;
},
/**
* Returns the current HTML document object as an {@link Ext.Element}.
* @return {Ext.Element} The document.
*/
getDoc: function() {
if (!Ext.documentElement) {
Ext.documentElement = Ext.get(document);
}
return Ext.documentElement;
},
/**
* This is shorthand reference to {@link Ext.ComponentMgr#get}.
* Looks up an existing {@link Ext.Component Component} by {@link Ext.Component#getId id}
* @param {String} id The component {@link Ext.Component#getId id}
* @return {Ext.Component} The Component, `undefined` if not found, or `null` if a
* Class was found.
*/
getCmp: function(id) {
return Ext.ComponentMgr.get(id);
},
/**
* Copies a set of named properties from the source object to the destination object.
*
* Example:
*
* ImageComponent = Ext.extend(Ext.Component, {
* initComponent: function() {
* this.autoEl = { tag: 'img' };
* MyComponent.superclass.initComponent.apply(this, arguments);
* this.initialBox = Ext.copyTo({}, this.initialConfig, 'x,y,width,height');
* }
* });
*
* Important note: To borrow class prototype methods, use {@link Ext.Base#borrow} instead.
*
* @param {Object} dest The destination object.
* @param {Object} source The source object.
* @param {String/String[]} names Either an Array of property names, or a comma-delimited list
* of property names to copy.
* @param {Boolean} [usePrototypeKeys=false] (optional) Pass `true` to copy keys off of the prototype as well as the instance.
* @return {Object} The modified object.
*/
copyTo : function(dest, source, names, usePrototypeKeys) {
if (typeof names == 'string') {
names = names.split(/[,;\s]/);
}
Ext.each (names, function(name) {
if (usePrototypeKeys || source.hasOwnProperty(name)) {
dest[name] = source[name];
}
}, this);
return dest;
},
/**
* Attempts to destroy any objects passed to it by removing all event listeners, removing them from the
* DOM (if applicable) and calling their destroy functions (if available). This method is primarily
* intended for arguments of type {@link Ext.Element} and {@link Ext.Component}.
* Any number of elements and/or components can be passed into this function in a single
* call as separate arguments.
* @param {Mixed...} args An {@link Ext.Element}, {@link Ext.Component}, or an Array of either of these to destroy.
*/
destroy: function() {
var args = arguments,
ln = args.length,
i, item;
for (i = 0; i < ln; i++) {
item = args[i];
if (item) {
if (Ext.isArray(item)) {
this.destroy.apply(this, item);
}
else if (Ext.isFunction(item.destroy)) {
item.destroy();
}
}
}
},
/**
* Return the dom node for the passed String (id), dom node, or Ext.Element.
* Here are some examples:
*
* // gets dom node based on id
* var elDom = Ext.getDom('elId');
*
* // gets dom node based on the dom node
* var elDom1 = Ext.getDom(elDom);
*
* // If we don't know if we are working with an
* // Ext.Element or a dom node use Ext.getDom
* function(el){
* var dom = Ext.getDom(el);
* // do something with the dom node
* }
*
* __Note:__ the dom node to be found actually needs to exist (be rendered, etc)
* when this method is called to be successful.
* @param {Mixed} el
* @return {HTMLElement}
*/
getDom: function(el) {
if (!el || !document) {
return null;
}
return el.dom ? el.dom : (typeof el == 'string' ? document.getElementById(el) : el);
},
/**
* Removes this element from the document, removes all DOM event listeners, and deletes the cache reference.
* All DOM event listeners are removed from this element.
* @param {HTMLElement} node The node to remove.
*/
removeNode: function(node) {
if (node && node.parentNode && node.tagName != 'BODY') {
Ext.get(node).clearListeners();
node.parentNode.removeChild(node);
delete Ext.cache[node.id];
}
},
/**
* @private
*/
defaultSetupConfig: {
eventPublishers: {
dom: {
xclass: 'Ext.event.publisher.Dom'
},
touchGesture: {
xclass: 'Ext.event.publisher.TouchGesture',
recognizers: {
drag: {
xclass: 'Ext.event.recognizer.Drag'
},
tap: {
xclass: 'Ext.event.recognizer.Tap'
},
doubleTap: {
xclass: 'Ext.event.recognizer.DoubleTap'
},
longPress: {
xclass: 'Ext.event.recognizer.LongPress'
},
swipe: {
xclass: 'Ext.event.recognizer.HorizontalSwipe'
},
pinch: {
xclass: 'Ext.event.recognizer.Pinch'
},
rotate: {
xclass: 'Ext.event.recognizer.Rotate'
}
}
},
componentDelegation: {
xclass: 'Ext.event.publisher.ComponentDelegation'
},
componentPaint: {
xclass: 'Ext.event.publisher.ComponentPaint'
},
// componentSize: {
// xclass: 'Ext.event.publisher.ComponentSize'
// },
elementPaint: {
xclass: 'Ext.event.publisher.ElementPaint'
},
elementSize: {
xclass: 'Ext.event.publisher.ElementSize'
}
},
//<feature logger>
logger: {
enabled: true,
xclass: 'Ext.log.Logger',
minPriority: 'deprecate',
writers: {
console: {
xclass: 'Ext.log.writer.Console',
throwOnErrors: true,
formatter: {
xclass: 'Ext.log.formatter.Default'
}
}
}
},
//</feature>
animator: {
xclass: 'Ext.fx.Runner'
},
viewport: {
xclass: 'Ext.viewport.Viewport'
}
},
/**
* @private
*/
isSetup: false,
/**
* This indicate the start timestamp of current cycle.
* It is only reliable during dom-event-initiated cycles and
* {@link Ext.draw.Animator} initiated cycles.
*/
frameStartTime: +new Date(),
/**
* @private
*/
setupListeners: [],
/**
* @private
*/
onSetup: function(fn, scope) {
if (Ext.isSetup) {
fn.call(scope);
}
else {
Ext.setupListeners.push({
fn: fn,
scope: scope
});
}
},
/**
* Ext.setup() is the entry-point to initialize a Sencha Touch application. Note that if your application makes
* use of MVC architecture, use {@link Ext#application} instead.
*
* This method accepts one single argument in object format. The most basic use of Ext.setup() is as follows:
*
* Ext.setup({
* onReady: function() {
* // ...
* }
* });
*
* This sets up the viewport, initializes the event system, instantiates a default animation runner, and a default
* logger (during development). When all of that is ready, it invokes the callback function given to the `onReady` key.
*
* The default scope (`this`) of `onReady` is the main viewport. By default the viewport instance is stored in
* {@link Ext.Viewport}. For example, this snippet adds a 'Hello World' button that is centered on the screen:
*
* Ext.setup({
* onReady: function() {
* this.add({
* xtype: 'button',
* centered: true,
* text: 'Hello world!'
* }); // Equivalent to Ext.Viewport.add(...)
* }
* });
*
* @param {Object} config An object with the following config options:
*
* @param {Function} config.onReady
* A function to be called when the application is ready. Your application logic should be here.
*
* @param {Object} config.viewport
* A custom config object to be used when creating the global {@link Ext.Viewport} instance. Please refer to the
* {@link Ext.Viewport} documentation for more information.
*
* Ext.setup({
* viewport: {
* width: 500,
* height: 500
* },
* onReady: function() {
* // ...
* }
* });
*
* @param {String/Object} config.icon
* Specifies a set of URLs to the application icon for different device form factors. This icon is displayed
* when the application is added to the device's Home Screen.
*
* Ext.setup({
* icon: {
* 57: 'resources/icons/Icon.png',
* 72: 'resources/icons/Icon~ipad.png',
* 114: 'resources/icons/[email protected]',
* 144: 'resources/icons/[email protected]'
* },
* onReady: function() {
* // ...
* }
* });
*
* Each key represents the dimension of the icon as a square shape. For example: '57' is the key for a 57 x 57
* icon image. Here is the breakdown of each dimension and its device target:
*
* - 57: Non-retina iPhone, iPod touch, and all Android devices
* - 72: Retina iPhone and iPod touch
* - 114: Non-retina iPad (first and second generation)
* - 144: Retina iPad (third generation)
*
* Note that the dimensions of the icon images must be exactly 57x57, 72x72, 114x114 and 144x144 respectively.
*
* It is highly recommended that you provide all these different sizes to accommodate a full range of
* devices currently available. However if you only have one icon in one size, make it 57x57 in size and
* specify it as a string value. This same icon will be used on all supported devices.
*
* Ext.setup({
* icon: 'resources/icons/Icon.png',
* onReady: function() {
* // ...
* }
* });
*
* @param {Object} config.startupImage
* Specifies a set of URLs to the application startup images for different device form factors. This image is
* displayed when the application is being launched from the Home Screen icon. Note that this currently only applies
* to iOS devices.
*
* Ext.setup({
* startupImage: {
* '320x460': 'resources/startup/320x460.jpg',
* '640x920': 'resources/startup/640x920.png',
* '640x1096': 'resources/startup/640x1096.png',
* '768x1004': 'resources/startup/768x1004.png',
* '748x1024': 'resources/startup/748x1024.png',
* '1536x2008': 'resources/startup/1536x2008.png',
* '1496x2048': 'resources/startup/1496x2048.png'
* },
* onReady: function() {
* // ...
* }
* });
*
* Each key represents the dimension of the image. For example: '320x460' is the key for a 320px x 460px image.
* Here is the breakdown of each dimension and its device target:
*
* - 320x460: Non-retina iPhone, iPod touch, and all Android devices
* - 640x920: Retina iPhone and iPod touch
* - 640x1096: iPhone 5 and iPod touch (fifth generation)
* - 768x1004: Non-retina iPad (first and second generation) in portrait orientation
* - 748x1024: Non-retina iPad (first and second generation) in landscape orientation
* - 1536x2008: Retina iPad (third generation) in portrait orientation
* - 1496x2048: Retina iPad (third generation) in landscape orientation
*
* Please note that there's no automatic fallback mechanism for the startup images. In other words, if you don't specify
* a valid image for a certain device, nothing will be displayed while the application is being launched on that device.
*
* @param {Boolean} isIconPrecomposed
* True to not having a glossy effect added to the icon by the OS, which will preserve its exact look. This currently
* only applies to iOS devices.
*
* @param {String} statusBarStyle
* The style of status bar to be shown on applications added to the iOS home screen. Valid options are:
*
* * `default`
* * `black`
* * `black-translucent`
*
* @param {String[]} config.requires
* An array of required classes for your application which will be automatically loaded before `onReady` is invoked.
* Please refer to {@link Ext.Loader} and {@link Ext.Loader#require} for more information.
*
* Ext.setup({
* requires: ['Ext.Button', 'Ext.tab.Panel'],
* onReady: function() {
* // ...
* }
* });
*
* @param {Object} config.eventPublishers
* Sencha Touch, by default, includes various {@link Ext.event.recognizer.Recognizer} subclasses to recognize events fired
* in your application. The list of default recognizers can be found in the documentation for
* {@link Ext.event.recognizer.Recognizer}.
*
* To change the default recognizers, you can use the following syntax:
*
* Ext.setup({
* eventPublishers: {
* touchGesture: {
* recognizers: {
* swipe: {
* // this will include both vertical and horizontal swipe recognizers
* xclass: 'Ext.event.recognizer.Swipe'
* }
* }
* }
* },
* onReady: function() {
* // ...
* }
* });
*
* You can also disable recognizers using this syntax:
*
* Ext.setup({
* eventPublishers: {
* touchGesture: {
* recognizers: {
* swipe: null,
* pinch: null,
* rotate: null
* }
* }
* },
* onReady: function() {
* // ...
* }
* });
*/
setup: function(config) {
var defaultSetupConfig = Ext.defaultSetupConfig,
emptyFn = Ext.emptyFn,
onReady = config.onReady || emptyFn,
onUpdated = config.onUpdated || emptyFn,
scope = config.scope,
requires = Ext.Array.from(config.requires),
extOnReady = Ext.onReady,
head = Ext.getHead(),
callback, viewport, precomposed;
Ext.setup = function() {
throw new Error("Ext.setup has already been called before");
};
delete config.requires;
delete config.onReady;
delete config.onUpdated;
delete config.scope;
Ext.require(['Ext.event.Dispatcher']);
callback = function() {
var listeners = Ext.setupListeners,
ln = listeners.length,
i, listener;
delete Ext.setupListeners;
Ext.isSetup = true;
for (i = 0; i < ln; i++) {
listener = listeners[i];
listener.fn.call(listener.scope);
}
Ext.onReady = extOnReady;
Ext.onReady(onReady, scope);
};
Ext.onUpdated = onUpdated;
Ext.onReady = function(fn, scope) {
var origin = onReady;
onReady = function() {
origin();
Ext.onReady(fn, scope);
};
};
config = Ext.merge({}, defaultSetupConfig, config);
Ext.onDocumentReady(function() {
Ext.factoryConfig(config, function(data) {
Ext.event.Dispatcher.getInstance().setPublishers(data.eventPublishers);
if (data.logger) {
Ext.Logger = data.logger;
}
if (data.animator) {
Ext.Animator = data.animator;
}
if (data.viewport) {
Ext.Viewport = viewport = data.viewport;
if (!scope) {
scope = viewport;
}
Ext.require(requires, function() {
Ext.Viewport.on('ready', callback, null, {single: true});
});
}
else {
Ext.require(requires, callback);
}
});
});
function addMeta(name, content) {
var meta = document.createElement('meta');
meta.setAttribute('name', name);
meta.setAttribute('content', content);
head.append(meta);
}
function addIcon(href, sizes, precomposed) {
var link = document.createElement('link');
link.setAttribute('rel', 'apple-touch-icon' + (precomposed ? '-precomposed' : ''));
link.setAttribute('href', href);
if (sizes) {
link.setAttribute('sizes', sizes);
}
head.append(link);
}
function addStartupImage(href, media) {
var link = document.createElement('link');
link.setAttribute('rel', 'apple-touch-startup-image');
link.setAttribute('href', href);
if (media) {
link.setAttribute('media', media);
}
head.append(link);
}
var icon = config.icon,
isIconPrecomposed = Boolean(config.isIconPrecomposed),
startupImage = config.startupImage || {},
statusBarStyle = config.statusBarStyle,
devicePixelRatio = window.devicePixelRatio || 1;
if (navigator.standalone) {
addMeta('viewport', 'width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0');
}
else {
addMeta('viewport', 'initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0');
}
addMeta('apple-mobile-web-app-capable', 'yes');
addMeta('apple-touch-fullscreen', 'yes');
// status bar style
if (statusBarStyle) {
addMeta('apple-mobile-web-app-status-bar-style', statusBarStyle);
}
if (Ext.isString(icon)) {
icon = {
57: icon,
72: icon,
114: icon,
144: icon
};
}
else if (!icon) {
icon = {};
}
//<deprecated product=touch since=2.0.1>
if ('phoneStartupScreen' in config) {
//<debug warn>
Ext.Logger.deprecate("[Ext.setup()] 'phoneStartupScreen' config is deprecated, please use 'startupImage' " +
"config instead. Refer to the latest API docs for more details");
//</debug>
config['320x460'] = config.phoneStartupScreen;
}
if ('tabletStartupScreen' in config) {
//<debug warn>
Ext.Logger.deprecate("[Ext.setup()] 'tabletStartupScreen' config is deprecated, please use 'startupImage' " +
"config instead. Refer to the latest API docs for more details");
//</debug>
config['768x1004'] = config.tabletStartupScreen;
}
if ('glossOnIcon' in config) {
//<debug warn>
Ext.Logger.deprecate("[Ext.setup()] 'glossOnIcon' config is deprecated, please use 'isIconPrecomposed' " +
"config instead. Refer to the latest API docs for more details");
//</debug>
isIconPrecomposed = Boolean(config.glossOnIcon);
}
//</deprecated>
if (Ext.os.is.iPad) {
if (devicePixelRatio >= 2) {
// Retina iPad - Landscape
if ('1496x2048' in startupImage) {
addStartupImage(startupImage['1496x2048'], '(orientation: landscape)');
}
// Retina iPad - Portrait
if ('1536x2008' in startupImage) {
addStartupImage(startupImage['1536x2008'], '(orientation: portrait)');
}
// Retina iPad
if ('144' in icon) {
addIcon(icon['144'], '144x144', isIconPrecomposed);
}
}
else {
// Non-Retina iPad - Landscape
if ('748x1024' in startupImage) {
addStartupImage(startupImage['748x1024'], '(orientation: landscape)');
}
// Non-Retina iPad - Portrait
if ('768x1004' in startupImage) {
addStartupImage(startupImage['768x1004'], '(orientation: portrait)');
}
// Non-Retina iPad
if ('72' in icon) {
addIcon(icon['72'], '72x72', isIconPrecomposed);
}
}
}
else {
// Retina iPhone, iPod touch with iOS version >= 4.3
if (devicePixelRatio >= 2 && Ext.os.version.gtEq('4.3')) {
if (Ext.os.is.iPhone5) {
addStartupImage(startupImage['640x1096']);
} else {
addStartupImage(startupImage['640x920']);
}
// Retina iPhone and iPod touch
if ('114' in icon) {
addIcon(icon['114'], '114x114', isIconPrecomposed);
}
}
else {
addStartupImage(startupImage['320x460']);
// Non-Retina iPhone, iPod touch, and Android devices
if ('57' in icon) {
addIcon(icon['57'], null, isIconPrecomposed);
}
}
}
},
/**
* @member Ext
* @method application
*
* Loads Ext.app.Application class and starts it up with given configuration after the page is ready.
*
* Ext.application({
* launch: function() {
* alert('Application launched!');
* }
* });
*
* See {@link Ext.app.Application} for details.
*
* @param {Object} config An object with the following config options:
*
* @param {Function} config.launch
* A function to be called when the application is ready. Your application logic should be here. Please see {@link Ext.app.Application}
* for details.
*
* @param {Object} config.viewport
* An object to be used when creating the global {@link Ext.Viewport} instance. Please refer to the {@link Ext.Viewport}
* documentation for more information.
*
* Ext.application({
* viewport: {
* layout: 'vbox'
* },
* launch: function() {
* Ext.Viewport.add({
* flex: 1,
* html: 'top (flex: 1)'
* });
*
* Ext.Viewport.add({
* flex: 4,
* html: 'bottom (flex: 4)'
* });
* }
* });
*
* @param {String/Object} config.icon
* Specifies a set of URLs to the application icon for different device form factors. This icon is displayed
* when the application is added to the device's Home Screen.
*
* Ext.application({
* icon: {
* 57: 'resources/icons/Icon.png',
* 72: 'resources/icons/Icon~ipad.png',
* 114: 'resources/icons/[email protected]',
* 144: 'resources/icons/[email protected]'
* },
* launch: function() {
* // ...
* }
* });
*
* Each key represents the dimension of the icon as a square shape. For example: '57' is the key for a 57 x 57
* icon image. Here is the breakdown of each dimension and its device target:
*
* - 57: Non-retina iPhone, iPod touch, and all Android devices
* - 72: Retina iPhone and iPod touch
* - 114: Non-retina iPad (first and second generation)
* - 144: Retina iPad (third generation)
*
* Note that the dimensions of the icon images must be exactly 57x57, 72x72, 114x114 and 144x144 respectively.
*
* It is highly recommended that you provide all these different sizes to accommodate a full range of
* devices currently available. However if you only have one icon in one size, make it 57x57 in size and
* specify it as a string value. This same icon will be used on all supported devices.
*
* Ext.setup({
* icon: 'resources/icons/Icon.png',
* onReady: function() {
* // ...
* }
* });
*
* @param {Object} config.startupImage
* Specifies a set of URLs to the application startup images for different device form factors. This image is
* displayed when the application is being launched from the Home Screen icon. Note that this currently only applies
* to iOS devices.
*
* Ext.application({
* startupImage: {
* '320x460': 'resources/startup/320x460.jpg',
* '640x920': 'resources/startup/640x920.png',
* '640x1096': 'resources/startup/640x1096.png',
* '768x1004': 'resources/startup/768x1004.png',
* '748x1024': 'resources/startup/748x1024.png',
* '1536x2008': 'resources/startup/1536x2008.png',
* '1496x2048': 'resources/startup/1496x2048.png'
* },
* launch: function() {
* // ...
* }
* });
*
* Each key represents the dimension of the image. For example: '320x460' is the key for a 320px x 460px image.
* Here is the breakdown of each dimension and its device target:
*
* - 320x460: Non-retina iPhone, iPod touch, and all Android devices
* - 640x920: Retina iPhone and iPod touch
* - 640x1096: iPhone 5 and iPod touch (fifth generation)
* - 768x1004: Non-retina iPad (first and second generation) in portrait orientation
* - 748x1024: Non-retina iPad (first and second generation) in landscape orientation
* - 1536x2008: Retina iPad (third generation) in portrait orientation
* - 1496x2048: Retina iPad (third generation) in landscape orientation
*
* Please note that there's no automatic fallback mechanism for the startup images. In other words, if you don't specify
* a valid image for a certain device, nothing will be displayed while the application is being launched on that device.
*
* @param {Boolean} config.isIconPrecomposed
* True to not having a glossy effect added to the icon by the OS, which will preserve its exact look. This currently
* only applies to iOS devices.
*
* @param {String} config.statusBarStyle
* The style of status bar to be shown on applications added to the iOS home screen. Valid options are:
*
* * `default`
* * `black`
* * `black-translucent`
*
* @param {String[]} config.requires
* An array of required classes for your application which will be automatically loaded if {@link Ext.Loader#enabled} is set
* to `true`. Please refer to {@link Ext.Loader} and {@link Ext.Loader#require} for more information.
*
* Ext.application({
* requires: ['Ext.Button', 'Ext.tab.Panel'],
* launch: function() {
* // ...
* }
* });
*
* @param {Object} config.eventPublishers
* Sencha Touch, by default, includes various {@link Ext.event.recognizer.Recognizer} subclasses to recognize events fired
* in your application. The list of default recognizers can be found in the documentation for {@link Ext.event.recognizer.Recognizer}.
*
* To change the default recognizers, you can use the following syntax:
*
* Ext.application({
* eventPublishers: {
* touchGesture: {
* recognizers: {
* swipe: {
* // this will include both vertical and horizontal swipe recognizers
* xclass: 'Ext.event.recognizer.Swipe'
* }
* }
* }
* },
* launch: function() {
* // ...
* }
* });
*
* You can also disable recognizers using this syntax:
*
* Ext.application({
* eventPublishers: {
* touchGesture: {
* recognizers: {
* swipe: null,
* pinch: null,
* rotate: null
* }
* }
* },
* launch: function() {
* // ...
* }
* });
*/
application: function(config) {
var appName = config.name,
onReady, scope, requires;
if (!config) {
config = {};
}
if (!Ext.Loader.config.paths[appName]) {
Ext.Loader.setPath(appName, config.appFolder || 'app');
}
requires = Ext.Array.from(config.requires);
config.requires = ['Ext.app.Application'];
onReady = config.onReady;
scope = config.scope;
config.onReady = function() {
config.requires = requires;
new Ext.app.Application(config);
if (onReady) {
onReady.call(scope);
}
};
Ext.setup(config);
},
/**
* @private
* @param config
* @param callback
* @member Ext
*/
factoryConfig: function(config, callback) {
var isSimpleObject = Ext.isSimpleObject(config);
if (isSimpleObject && config.xclass) {
var className = config.xclass;
delete config.xclass;
Ext.require(className, function() {
Ext.factoryConfig(config, function(cfg) {
callback(Ext.create(className, cfg));
});
});
return;
}
var isArray = Ext.isArray(config),
keys = [],
key, value, i, ln;
if (isSimpleObject || isArray) {
if (isSimpleObject) {
for (key in config) {
if (config.hasOwnProperty(key)) {
value = config[key];
if (Ext.isSimpleObject(value) || Ext.isArray(value)) {
keys.push(key);
}
}
}
}
else {
for (i = 0,ln = config.length; i < ln; i++) {
value = config[i];
if (Ext.isSimpleObject(value) || Ext.isArray(value)) {
keys.push(i);
}
}
}
i = 0;
ln = keys.length;
if (ln === 0) {
callback(config);
return;
}
function fn(value) {
config[key] = value;
i++;
factory();
}
function factory() {
if (i >= ln) {
callback(config);
return;
}
key = keys[i];
value = config[key];
Ext.factoryConfig(value, fn);
}
factory();
return;
}
callback(config);
},
/**
* A global factory method to instantiate a class from a config object. For example, these two calls are equivalent:
*
* Ext.factory({ text: 'My Button' }, 'Ext.Button');
* Ext.create('Ext.Button', { text: 'My Button' });
*
* If an existing instance is also specified, it will be updated with the supplied config object. This is useful
* if you need to either create or update an object, depending on if an instance already exists. For example:
*
* var button;
* button = Ext.factory({ text: 'New Button' }, 'Ext.Button', button); // Button created
* button = Ext.factory({ text: 'Updated Button' }, 'Ext.Button', button); // Button updated
*
* @param {Object} config The config object to instantiate or update an instance with.
* @param {String} classReference The class to instantiate from.
* @param {Object} [instance] The instance to update.
* @param [aliasNamespace]
* @member Ext
*/
factory: function(config, classReference, instance, aliasNamespace) {
var manager = Ext.ClassManager,
newInstance;
// If config is falsy or a valid instance, destroy the current instance
// (if it exists) and replace with the new one
if (!config || config.isInstance) {
if (instance && instance !== config) {
instance.destroy();
}
return config;
}
if (aliasNamespace) {
// If config is a string value, treat it as an alias
if (typeof config == 'string') {
return manager.instantiateByAlias(aliasNamespace + '.' + config);
}
// Same if 'type' is given in config
else if (Ext.isObject(config) && 'type' in config) {
return manager.instantiateByAlias(aliasNamespace + '.' + config.type, config);
}
}
if (config === true) {
return instance || manager.instantiate(classReference);
}
//<debug error>
if (!Ext.isObject(config)) {
Ext.Logger.error("Invalid config, must be a valid config object");
}
//</debug>
if ('xtype' in config) {
newInstance = manager.instantiateByAlias('widget.' + config.xtype, config);
}
else if ('xclass' in config) {
newInstance = manager.instantiate(config.xclass, config);
}
if (newInstance) {
if (instance) {
instance.destroy();
}
return newInstance;
}
if (instance) {
return instance.setConfig(config);
}
return manager.instantiate(classReference, config);
},
/**
* @private
* @member Ext
*/
deprecateClassMember: function(cls, oldName, newName, message) {
return this.deprecateProperty(cls.prototype, oldName, newName, message);
},
/**
* @private
* @member Ext
*/
deprecateClassMembers: function(cls, members) {
var prototype = cls.prototype,
oldName, newName;
for (oldName in members) {
if (members.hasOwnProperty(oldName)) {
newName = members[oldName];
this.deprecateProperty(prototype, oldName, newName);
}
}
},
/**
* @private
* @member Ext
*/
deprecateProperty: function(object, oldName, newName, message) {
if (!message) {
message = "'" + oldName + "' is deprecated";
}
if (newName) {
message += ", please use '" + newName + "' instead";
}
if (newName) {
Ext.Object.defineProperty(object, oldName, {
get: function() {
//<debug warn>
Ext.Logger.deprecate(message, 1);
//</debug>
return this[newName];
},
set: function(value) {
//<debug warn>
Ext.Logger.deprecate(message, 1);
//</debug>
this[newName] = value;
},
configurable: true
});
}
},
/**
* @private
* @member Ext
*/
deprecatePropertyValue: function(object, name, value, message) {
Ext.Object.defineProperty(object, name, {
get: function() {
//<debug warn>
Ext.Logger.deprecate(message, 1);
//</debug>
return value;
},
configurable: true
});
},
/**
* @private
* @member Ext
*/
deprecateMethod: function(object, name, method, message) {
object[name] = function() {
//<debug warn>
Ext.Logger.deprecate(message, 2);
//</debug>
if (method) {
return method.apply(this, arguments);
}
};
},
/**
* @private
* @member Ext
*/
deprecateClassMethod: function(cls, name, method, message) {
if (typeof name != 'string') {
var from, to;
for (from in name) {
if (name.hasOwnProperty(from)) {
to = name[from];
Ext.deprecateClassMethod(cls, from, to);
}
}
return;
}
var isLateBinding = typeof method == 'string',
member;
if (!message) {
message = "'" + name + "()' is deprecated, please use '" + (isLateBinding ? method : method.name) +
"()' instead";
}
if (isLateBinding) {
member = function() {
//<debug warn>
Ext.Logger.deprecate(message, this);
//</debug>
return this[method].apply(this, arguments);
};
}
else {
member = function() {
//<debug warn>
Ext.Logger.deprecate(message, this);
//</debug>
return method.apply(this, arguments);
};
}
if (name in cls.prototype) {
Ext.Object.defineProperty(cls.prototype, name, {
value: null,
writable: true,
configurable: true
});
}
cls.addMember(name, member);
},
//<debug>
/**
* Useful snippet to show an exact, narrowed-down list of top-level Components that are not yet destroyed.
* @private
*/
showLeaks: function() {
var map = Ext.ComponentManager.all.map,
leaks = [],
parent;
Ext.Object.each(map, function(id, component) {
while ((parent = component.getParent()) && map.hasOwnProperty(parent.getId())) {
component = parent;
}
if (leaks.indexOf(component) === -1) {
leaks.push(component);
}
});
console.log(leaks);
},
//</debug>
/**
* True when the document is fully initialized and ready for action
* @type Boolean
* @member Ext
* @private
*/
isReady : false,
/**
* @private
* @member Ext
*/
readyListeners: [],
/**
* @private
* @member Ext
*/
triggerReady: function() {
var listeners = Ext.readyListeners,
i, ln, listener;
if (!Ext.isReady) {
Ext.isReady = true;
for (i = 0,ln = listeners.length; i < ln; i++) {
listener = listeners[i];
listener.fn.call(listener.scope);
}
delete Ext.readyListeners;
}
},
/**
* @private
* @member Ext
*/
onDocumentReady: function(fn, scope) {
if (Ext.isReady) {
fn.call(scope);
}
else {
var triggerFn = Ext.triggerReady;
Ext.readyListeners.push({
fn: fn,
scope: scope
});
if (Ext.browser.is.PhoneGap && !Ext.os.is.Desktop) {
if (!Ext.readyListenerAttached) {
Ext.readyListenerAttached = true;
document.addEventListener('deviceready', triggerFn, false);
}
}
else {
if (document.readyState.match(/interactive|complete|loaded/) !== null) {
triggerFn();
}
else if (!Ext.readyListenerAttached) {
Ext.readyListenerAttached = true;
window.addEventListener('DOMContentLoaded', triggerFn, false);
}
}
}
},
/**
* Calls function after specified delay, or right away when delay == 0.
* @param {Function} callback The callback to execute.
* @param {Object} scope (optional) The scope to execute in.
* @param {Array} args (optional) The arguments to pass to the function.
* @param {Number} delay (optional) Pass a number to delay the call by a number of milliseconds.
* @member Ext
*/
callback: function(callback, scope, args, delay) {
if (Ext.isFunction(callback)) {
args = args || [];
scope = scope || window;
if (delay) {
Ext.defer(callback, delay, scope, args);
} else {
callback.apply(scope, args);
}
}
}
});
//<debug>
Ext.Object.defineProperty(Ext, 'Msg', {
get: function() {
Ext.Logger.error("Using Ext.Msg without requiring Ext.MessageBox");
return null;
},
set: function(value) {
Ext.Object.defineProperty(Ext, 'Msg', {
value: value
});
return value;
},
configurable: true
});
//</debug>
//<deprecated product=touch since=2.0>
Ext.deprecateMethod(Ext, 'getOrientation', function() {
return Ext.Viewport.getOrientation();
}, "Ext.getOrientation() is deprecated, use Ext.Viewport.getOrientation() instead");
Ext.deprecateMethod(Ext, 'log', function(message) {
return Ext.Logger.log(message);
}, "Ext.log() is deprecated, please use Ext.Logger.log() instead");
/**
* @member Ext.Function
* @method createDelegate
* @inheritdoc Ext.Function#bind
* @deprecated 2.0.0
* Please use {@link Ext.Function#bind bind} instead
*/
Ext.deprecateMethod(Ext.Function, 'createDelegate', Ext.Function.bind, "Ext.createDelegate() is deprecated, please use Ext.Function.bind() instead");
/**
* @member Ext
* @method createInterceptor
* @inheritdoc Ext.Function#createInterceptor
* @deprecated 2.0.0
* Please use {@link Ext.Function#createInterceptor createInterceptor} instead
*/
Ext.deprecateMethod(Ext, 'createInterceptor', Ext.Function.createInterceptor, "Ext.createInterceptor() is deprecated, " +
"please use Ext.Function.createInterceptor() instead");
/**
* @member Ext
* @property {Boolean} SSL_SECURE_URL
* URL to a blank file used by Ext JS when in secure mode for iframe src and onReady
* src to prevent the IE insecure content warning.
* @removed 2.0.0
*/
Ext.deprecateProperty(Ext, 'SSL_SECURE_URL', null, "Ext.SSL_SECURE_URL has been removed");
/**
* @member Ext
* @property {Boolean} enableGarbageCollector
* `true` to automatically un-cache orphaned Ext.Elements periodically.
* @removed 2.0.0
*/
Ext.deprecateProperty(Ext, 'enableGarbageCollector', null, "Ext.enableGarbageCollector has been removed");
/**
* @member Ext
* @property {Boolean} enableListenerCollection
* True to automatically purge event listeners during garbageCollection.
* @removed 2.0.0
*/
Ext.deprecateProperty(Ext, 'enableListenerCollection', null, "Ext.enableListenerCollection has been removed");
/**
* @member Ext
* @property {Boolean} isSecure
* True if the page is running over SSL.
* @removed 2.0.0 Please use {@link Ext.env.Browser#isSecure} instead
*/
Ext.deprecateProperty(Ext, 'isSecure', null, "Ext.enableListenerCollection has been removed, please use Ext.env.Browser.isSecure instead");
/**
* @member Ext
* @method dispatch
* Dispatches a request to a controller action.
* @removed 2.0.0 Please use {@link Ext.app.Application#dispatch} instead
*/
Ext.deprecateMethod(Ext, 'dispatch', null, "Ext.dispatch() is deprecated, please use Ext.app.Application.dispatch() instead");
/**
* @member Ext
* @method getOrientation
* Returns the current orientation of the mobile device.
* @removed 2.0.0
* Please use {@link Ext.Viewport#getOrientation getOrientation} instead
*/
Ext.deprecateMethod(Ext, 'getOrientation', null, "Ext.getOrientation() has been removed, " +
"please use Ext.Viewport.getOrientation() instead");
/**
* @member Ext
* @method reg
* Registers a new xtype.
* @removed 2.0.0
*/
Ext.deprecateMethod(Ext, 'reg', null, "Ext.reg() has been removed");
/**
* @member Ext
* @method preg
* Registers a new ptype.
* @removed 2.0.0
*/
Ext.deprecateMethod(Ext, 'preg', null, "Ext.preg() has been removed");
/**
* @member Ext
* @method redirect
* Dispatches a request to a controller action, adding to the History stack
* and updating the page url as necessary.
* @removed 2.0.0
*/
Ext.deprecateMethod(Ext, 'redirect', null, "Ext.redirect() has been removed");
/**
* @member Ext
* @method regApplication
* Creates a new Application class from the specified config object.
* @removed 2.0.0
*/
Ext.deprecateMethod(Ext, 'regApplication', null, "Ext.regApplication() has been removed");
/**
* @member Ext
* @method regController
* Creates a new Controller class from the specified config object.
* @removed 2.0.0
*/
Ext.deprecateMethod(Ext, 'regController', null, "Ext.regController() has been removed");
/**
* @member Ext
* @method regLayout
* Registers new layout type.
* @removed 2.0.0
*/
Ext.deprecateMethod(Ext, 'regLayout', null, "Ext.regLayout() has been removed");
//</deprecated>
| hackathon-3d/team-gryffindor-repo | www/touch/src/core/Ext-more.js | JavaScript | gpl-2.0 | 50,756 |
/**
* This file is part of OXID eShop Community Edition.
*
* OXID eShop Community Edition is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OXID eShop Community Edition 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OXID eShop Community Edition. If not, see <http://www.gnu.org/licenses/>.
*
* @link http://www.oxid-esales.com
* @package out
* @copyright (C) OXID eSales AG 2003-2013
* @version OXID eShop CE
* @version SVN: $Id: oxpromocategory.js 35529 2011-05-23 07:31:20Z vilma $
*/
( function( $ ) {
oxCenterElementOnHover = {
_create: function(){
var self = this;
var el = self.element;
el.hover(function(){
var targetObj = $(".viewAllHover", el);
var targetObjWidth = targetObj.outerWidth() / 2;
var parentObjWidth = el.width() / 2;
targetObj.css("left", parentObjWidth - targetObjWidth + "px");
targetObj.show();
}, function(){
$(".viewAllHover", el).hide();
});
}
}
$.widget( "ui.oxCenterElementOnHover", oxCenterElementOnHover );
} )( jQuery );
| apnfq/oxid_test | out/azure/src/js/widgets/oxcenterelementonhover.js | JavaScript | gpl-3.0 | 1,679 |
// Generated by CoffeeScript 1.5.0
var auth, changeDashboard, createGraph, dashboard, dataPoll, default_graphite_url, default_period, description, generateDataURL, generateEventsURL, generateGraphiteTargets, getTargetColor, graphScaffold, graphite_url, graphs, init, metrics, period, refresh, refreshSummary, refreshTimer, scheme, toggleCss, _avg, _formatBase1024KMGTP, _last, _max, _min, _sum;
graphite_url = graphite_url || 'demo';
default_graphite_url = graphite_url;
default_period = 1440;
if (scheme === void 0) {
scheme = 'classic9';
}
period = default_period;
dashboard = dashboards[0];
metrics = dashboard['metrics'];
description = dashboard['description'];
refresh = dashboard['refresh'];
refreshTimer = null;
auth = auth != null ? auth : false;
graphs = [];
dataPoll = function() {
var graph, _i, _len, _results;
_results = [];
for (_i = 0, _len = graphs.length; _i < _len; _i++) {
graph = graphs[_i];
_results.push(graph.refreshGraph(period));
}
return _results;
};
_sum = function(series) {
return _.reduce(series, (function(memo, val) {
return memo + val;
}), 0);
};
_avg = function(series) {
return _sum(series) / series.length;
};
_max = function(series) {
return _.reduce(series, (function(memo, val) {
if (memo === null) {
return val;
}
if (val > memo) {
return val;
}
return memo;
}), null);
};
_min = function(series) {
return _.reduce(series, (function(memo, val) {
if (memo === null) {
return val;
}
if (val < memo) {
return val;
}
return memo;
}), null);
};
_last = function(series) {
return _.reduce(series, (function(memo, val) {
if (val !== null) {
return val;
}
return memo;
}), null);
};
_formatBase1024KMGTP = function(y, formatter) {
var abs_y;
if (formatter == null) {
formatter = d3.format(".2r");
}
abs_y = Math.abs(y);
if (abs_y >= 1125899906842624) {
return formatter(y / 1125899906842624) + "P";
} else if (abs_y >= 1099511627776) {
return formatter(y / 1099511627776) + "T";
} else if (abs_y >= 1073741824) {
return formatter(y / 1073741824) + "G";
} else if (abs_y >= 1048576) {
return formatter(y / 1048576) + "M";
} else if (abs_y >= 1024) {
return formatter(y / 1024) + "K";
} else if (abs_y < 1 && y > 0) {
return formatter(y);
} else if (abs_y === 0) {
return 0;
} else {
return formatter(y);
}
};
refreshSummary = function(graph) {
var summary_func, y_data, _ref;
if (!((_ref = graph.args) != null ? _ref.summary : void 0)) {
return;
}
if (graph.args.summary === "sum") {
summary_func = _sum;
}
if (graph.args.summary === "avg") {
summary_func = _avg;
}
if (graph.args.summary === "min") {
summary_func = _min;
}
if (graph.args.summary === "max") {
summary_func = _max;
}
if (graph.args.summary === "last") {
summary_func = _last;
}
if (typeof graph.args.summary === "function") {
summary_func = graph.args.summary;
}
if (!summary_func) {
console.log("unknown summary function " + graph.args.summary);
}
y_data = _.map(_.flatten(_.pluck(graph.graph.series, 'data')), function(d) {
return d.y;
});
return $("" + graph.args.anchor + " .graph-summary").html(graph.args.summary_formatter(summary_func(y_data)));
};
graphScaffold = function() {
var colspan, context, converter, graph_template, i, metric, offset, _i, _len;
graph_template = "{{#dashboard_description}}\n <div class=\"well\">{{{dashboard_description}}}</div>\n{{/dashboard_description}}\n{{#metrics}}\n {{#start_row}}\n <div class=\"row-fluid\">\n {{/start_row}}\n <div class=\"{{span}}\" id=\"graph-{{graph_id}}\">\n <h2>{{metric_alias}} <span class=\"pull-right graph-summary\"><span></h2>\n <div class=\"chart\"></div>\n <div class=\"timeline\"></div>\n <p>{{metric_description}}</p>\n <div class=\"legend\"></div>\n </div>\n {{#end_row}}\n </div>\n {{/end_row}}\n{{/metrics}}";
$('#graphs').empty();
context = {
metrics: []
};
converter = new Markdown.Converter();
if (description) {
context['dashboard_description'] = converter.makeHtml(description);
}
offset = 0;
for (i = _i = 0, _len = metrics.length; _i < _len; i = ++_i) {
metric = metrics[i];
colspan = metric.colspan != null ? metric.colspan : 1;
context['metrics'].push({
start_row: offset % 3 === 0,
end_row: offset % 3 === 2,
graph_id: i,
span: 'span' + (4 * colspan),
metric_alias: metric.alias,
metric_description: metric.description
});
offset += colspan;
}
return $('#graphs').append(Mustache.render(graph_template, context));
};
init = function() {
var dash, i, metric, refreshInterval, _i, _j, _len, _len1;
$('.dropdown-menu').empty();
for (_i = 0, _len = dashboards.length; _i < _len; _i++) {
dash = dashboards[_i];
$('.dropdown-menu').append("<li><a href=\"#\">" + dash.name + "</a></li>");
}
graphScaffold();
graphs = [];
for (i = _j = 0, _len1 = metrics.length; _j < _len1; i = ++_j) {
metric = metrics[i];
graphs.push(createGraph("#graph-" + i, metric));
}
$('.page-header h1').empty().append(dashboard.name);
refreshInterval = refresh || 10000;
if (refreshTimer) {
clearInterval(refreshTimer);
}
return refreshTimer = setInterval(dataPoll, refreshInterval);
};
getTargetColor = function(targets, target) {
var t, _i, _len;
if (typeof targets !== 'object') {
return;
}
for (_i = 0, _len = targets.length; _i < _len; _i++) {
t = targets[_i];
if (!t.color) {
continue;
}
if (t.target === target || t.alias === target) {
return t.color;
}
}
};
generateGraphiteTargets = function(targets) {
var graphite_targets, target, _i, _len;
if (typeof targets === "string") {
return "&target=" + targets;
}
if (typeof targets === "function") {
return "&target=" + (targets());
}
graphite_targets = "";
for (_i = 0, _len = targets.length; _i < _len; _i++) {
target = targets[_i];
if (typeof target === "string") {
graphite_targets += "&target=" + target;
}
if (typeof target === "function") {
graphite_targets += "&target=" + (target());
}
if (typeof target === "object") {
graphite_targets += "&target=" + ((target != null ? target.target : void 0) || '');
}
}
return graphite_targets;
};
generateDataURL = function(targets, annotator_target, max_data_points) {
var data_targets;
annotator_target = annotator_target ? "&target=" + annotator_target : "";
data_targets = generateGraphiteTargets(targets);
return "" + graphite_url + "/render?from=-" + period + "minutes&" + data_targets + annotator_target + "&maxDataPoints=" + max_data_points + "&format=json&jsonp=?";
};
generateEventsURL = function(event_tags) {
var jsonp, tags;
tags = event_tags === '*' ? '' : "&tags=" + event_tags;
jsonp = window.json_fallback ? '' : "&jsonp=?";
return "" + graphite_url + "/events/get_data?from=-" + period + "minutes" + tags + jsonp;
};
createGraph = function(anchor, metric) {
var graph, graph_provider, _ref, _ref1;
if (graphite_url === 'demo') {
graph_provider = Rickshaw.Graph.Demo;
} else {
graph_provider = Rickshaw.Graph.JSONP.Graphite;
}
return graph = new graph_provider({
anchor: anchor,
targets: metric.target || metric.targets,
summary: metric.summary,
summary_formatter: metric.summary_formatter || _formatBase1024KMGTP,
scheme: metric.scheme || dashboard.scheme || scheme || 'classic9',
annotator_target: ((_ref = metric.annotator) != null ? _ref.target : void 0) || metric.annotator,
annotator_description: ((_ref1 = metric.annotator) != null ? _ref1.description : void 0) || 'deployment',
events: metric.events,
element: $("" + anchor + " .chart")[0],
width: $("" + anchor + " .chart").width(),
height: metric.height || 300,
min: metric.min || 0,
max: metric.max,
null_as: metric.null_as === void 0 ? null : metric.null_as,
renderer: metric.renderer || 'area',
interpolation: metric.interpolation || 'step-before',
unstack: metric.unstack,
stroke: metric.stroke === false ? false : true,
strokeWidth: metric.stroke_width,
dataURL: generateDataURL(metric.target || metric.targets),
onRefresh: function(transport) {
return refreshSummary(transport);
},
onComplete: function(transport) {
var detail, hover_formatter, shelving, xAxis, yAxis;
graph = transport.graph;
xAxis = new Rickshaw.Graph.Axis.Time({
graph: graph
});
xAxis.render();
yAxis = new Rickshaw.Graph.Axis.Y({
graph: graph,
tickFormat: function(y) {
return _formatBase1024KMGTP(y);
},
ticksTreatment: 'glow'
});
yAxis.render();
hover_formatter = metric.hover_formatter || _formatBase1024KMGTP;
detail = new Rickshaw.Graph.HoverDetail({
graph: graph,
yFormatter: function(y) {
return hover_formatter(y);
}
});
$("" + anchor + " .legend").empty();
this.legend = new Rickshaw.Graph.Legend({
graph: graph,
element: $("" + anchor + " .legend")[0]
});
shelving = new Rickshaw.Graph.Behavior.Series.Toggle({
graph: graph,
legend: this.legend
});
if (metric.annotator || metric.events) {
this.annotator = new GiraffeAnnotate({
graph: graph,
element: $("" + anchor + " .timeline")[0]
});
}
return refreshSummary(this);
}
});
};
Rickshaw.Graph.JSONP.Graphite = Rickshaw.Class.create(Rickshaw.Graph.JSONP, {
request: function() {
return this.refreshGraph(period);
},
refreshGraph: function(period) {
var deferred,
_this = this;
deferred = this.getAjaxData(period);
return deferred.done(function(result) {
var annotations, el, i, result_data, series, _i, _len;
if (result.length <= 0) {
return;
}
result_data = _.filter(result, function(el) {
var _ref;
return el.target !== ((_ref = _this.args.annotator_target) != null ? _ref.replace(/["']/g, '') : void 0);
});
result_data = _this.preProcess(result_data);
if (!_this.graph) {
_this.success(_this.parseGraphiteData(result_data, _this.args.null_as));
}
series = _this.parseGraphiteData(result_data, _this.args.null_as);
if (_this.args.annotator_target) {
annotations = _this.parseGraphiteData(_.filter(result, function(el) {
return el.target === _this.args.annotator_target.replace(/["']/g, '');
}), _this.args.null_as);
}
for (i = _i = 0, _len = series.length; _i < _len; i = ++_i) {
el = series[i];
_this.graph.series[i].data = el.data;
_this.addTotals(i);
}
_this.graph.renderer.unstack = _this.args.unstack;
_this.graph.render();
if (_this.args.events) {
deferred = _this.getEvents(period);
deferred.done(function(result) {
return _this.addEventAnnotations(result);
});
}
_this.addAnnotations(annotations, _this.args.annotator_description);
return _this.args.onRefresh(_this);
});
},
addTotals: function(i) {
var avg, label, max, min, series_data, sum;
label = $(this.legend.lines[i].element).find('span.label').text();
$(this.legend.lines[i].element).find('span.totals').remove();
series_data = _.map(this.legend.lines[i].series.data, function(d) {
return d.y;
});
sum = _formatBase1024KMGTP(_sum(series_data));
max = _formatBase1024KMGTP(_max(series_data));
min = _formatBase1024KMGTP(_min(series_data));
avg = _formatBase1024KMGTP(_avg(series_data));
return $(this.legend.lines[i].element).append("<span class='totals pull-right'> Σ: " + sum + " <i class='icon-caret-down'></i>: " + min + " <i class='icon-caret-up'></i>: " + max + " <i class='icon-sort'></i>: " + avg + "</span>");
},
preProcess: function(result) {
var item, _i, _len;
for (_i = 0, _len = result.length; _i < _len; _i++) {
item = result[_i];
if (item.datapoints.length === 1) {
item.datapoints[0][1] = 0;
if (this.args.unstack) {
item.datapoints.push([0, 1]);
} else {
item.datapoints.push([item.datapoints[0][0], 1]);
}
}
}
return result;
},
parseGraphiteData: function(d, null_as) {
var palette, rev_xy, targets;
if (null_as == null) {
null_as = null;
}
rev_xy = function(datapoints) {
return _.map(datapoints, function(point) {
return {
'x': point[1],
'y': point[0] !== null ? point[0] : null_as
};
});
};
palette = new Rickshaw.Color.Palette({
scheme: this.args.scheme
});
targets = this.args.target || this.args.targets;
d = _.map(d, function(el) {
var color, _ref;
if ((_ref = typeof targets) === "string" || _ref === "function") {
color = palette.color();
} else {
color = getTargetColor(targets, el.target) || palette.color();
}
return {
"color": color,
"name": el.target,
"data": rev_xy(el.datapoints)
};
});
Rickshaw.Series.zeroFill(d);
return d;
},
addEventAnnotations: function(events_json) {
var active_annotation, event, _i, _len, _ref, _ref1;
if (!events_json) {
return;
}
this.annotator || (this.annotator = new GiraffeAnnotate({
graph: this.graph,
element: $("" + this.args.anchor + " .timeline")[0]
}));
this.annotator.data = {};
$(this.annotator.elements.timeline).empty();
active_annotation = $(this.annotator.elements.timeline).parent().find('.annotation_line.active').size() > 0;
if ((_ref = $(this.annotator.elements.timeline).parent()) != null) {
_ref.find('.annotation_line').remove();
}
for (_i = 0, _len = events_json.length; _i < _len; _i++) {
event = events_json[_i];
this.annotator.add(event.when, "" + event.what + " " + (event.data || ''));
}
this.annotator.update();
if (active_annotation) {
return (_ref1 = $(this.annotator.elements.timeline).parent()) != null ? _ref1.find('.annotation_line').addClass('active') : void 0;
}
},
addAnnotations: function(annotations, description) {
var annotation_timestamps, _ref;
if (!annotations) {
return;
}
annotation_timestamps = _((_ref = annotations[0]) != null ? _ref.data : void 0).filter(function(el) {
return el.y !== 0 && el.y !== null;
});
return this.addEventAnnotations(_.map(annotation_timestamps, function(a) {
return {
when: a.x,
what: description
};
}));
},
getEvents: function(period) {
var deferred,
_this = this;
this.period = period;
return deferred = $.ajax({
dataType: 'json',
url: generateEventsURL(this.args.events),
error: function(xhr, textStatus, errorThrown) {
if (textStatus === 'parsererror' && /was not called/.test(errorThrown.message)) {
window.json_fallback = true;
return _this.refreshGraph(period);
} else {
return console.log("error loading eventsURL: " + generateEventsURL(_this.args.events));
}
}
});
},
getAjaxData: function(period) {
var deferred;
this.period = period;
return deferred = $.ajax({
dataType: 'json',
url: generateDataURL(this.args.targets, this.args.annotator_target, this.args.width),
error: this.error.bind(this)
});
}
});
Rickshaw.Graph.Demo = Rickshaw.Class.create(Rickshaw.Graph.JSONP.Graphite, {
success: function(data) {
var i, palette, _i;
palette = new Rickshaw.Color.Palette({
scheme: this.args.scheme
});
this.seriesData = [[], [], [], [], [], [], [], [], []];
this.random = new Rickshaw.Fixtures.RandomData(period / 60 + 10);
for (i = _i = 0; _i <= 60; i = ++_i) {
this.random.addData(this.seriesData);
}
this.graph = new Rickshaw.Graph({
element: this.args.element,
width: this.args.width,
height: this.args.height,
min: this.args.min,
max: this.args.max,
renderer: this.args.renderer,
interpolation: this.args.interpolation,
stroke: this.args.stroke,
strokeWidth: this.args.strokeWidth,
series: [
{
color: palette.color(),
data: this.seriesData[0],
name: 'Moscow'
}, {
color: palette.color(),
data: this.seriesData[1],
name: 'Shanghai'
}, {
color: palette.color(),
data: this.seriesData[2],
name: 'Amsterdam'
}, {
color: palette.color(),
data: this.seriesData[3],
name: 'Paris'
}, {
color: palette.color(),
data: this.seriesData[4],
name: 'Tokyo'
}, {
color: palette.color(),
data: this.seriesData[5],
name: 'London'
}, {
color: palette.color(),
data: this.seriesData[6],
name: 'New York'
}
]
});
this.graph.renderer.unstack = this.args.unstack;
this.graph.render();
return this.onComplete(this);
},
refreshGraph: function(period) {
var i, _i, _ref, _results;
if (!this.graph) {
return this.success();
} else {
this.random.addData(this.seriesData);
this.random.addData(this.seriesData);
_.each(this.seriesData, function(d) {
return d.shift();
});
this.args.onRefresh(this);
this.graph.render();
_results = [];
for (i = _i = 0, _ref = this.graph.series.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
_results.push(this.addTotals(i));
}
return _results;
}
}
});
/*
# Events and interaction
*/
$('.dropdown-menu').on('click', 'a', function() {
changeDashboard($(this).text());
$('.dropdown').removeClass('open');
return false;
});
changeDashboard = function(dash_name) {
dashboard = _.where(dashboards, {
name: dash_name
})[0] || dashboards[0];
graphite_url = dashboard['graphite_url'] || default_graphite_url;
description = dashboard['description'];
metrics = dashboard['metrics'];
refresh = dashboard['refresh'];
period || (period = default_period);
init();
return $.bbq.pushState({
dashboard: dashboard.name
});
};
$('.timepanel').on('click', 'a.range', function() {
var dash, timeFrame, _ref;
if (graphite_url === 'demo') {
changeDashboard(dashboard.name);
}
period = $(this).attr('data-timeframe') || default_period;
dataPoll();
timeFrame = $(this).attr('href').replace(/^#/, '');
dash = (_ref = $.bbq.getState()) != null ? _ref.dashboard : void 0;
$.bbq.pushState({
timeFrame: timeFrame,
dashboard: dash || dashboard.name
});
$(this).parent('.btn-group').find('a').removeClass('active');
$(this).addClass('active');
return false;
});
toggleCss = function(css_selector) {
if ($.rule(css_selector).text().match('display: ?none')) {
return $.rule(css_selector, 'style').remove();
} else {
return $.rule("" + css_selector + " {display:none;}").appendTo('style');
}
};
$('#legend-toggle').on('click', function() {
$(this).toggleClass('active');
$('.legend').toggle();
return false;
});
$('#axis-toggle').on('click', function() {
$(this).toggleClass('active');
toggleCss('.y_grid');
toggleCss('.y_ticks');
toggleCss('.x_tick');
return false;
});
$('#x-label-toggle').on('click', function() {
toggleCss('.rickshaw_graph .detail .x_label');
$(this).toggleClass('active');
return false;
});
$('#x-item-toggle').on('click', function() {
toggleCss('.rickshaw_graph .detail .item.active');
$(this).toggleClass('active');
return false;
});
$(window).bind('hashchange', function(e) {
var dash, timeFrame, _ref, _ref1;
timeFrame = ((_ref = e.getState()) != null ? _ref.timeFrame : void 0) || $(".timepanel a.range[data-timeframe='" + default_period + "']")[0].text || "1d";
dash = (_ref1 = e.getState()) != null ? _ref1.dashboard : void 0;
if (dash !== dashboard.name) {
changeDashboard(dash);
}
return $('.timepanel a.range[href="#' + timeFrame + '"]').click();
});
$(function() {
$(window).trigger('hashchange');
return init();
});
| Stub-O-Matic-BA/stubo-app | stubo/static/giraffe/js/giraffe.js | JavaScript | gpl-3.0 | 20,491 |
function rewriteTaskTitles(blockid) {
forEach(
getElementsByTagAndClassName('a', 'task-title', 'tasktable_' + blockid),
function(element) {
disconnectAll(element);
connect(element, 'onclick', function(e) {
e.stop();
var description = getFirstElementByTagAndClassName('div', 'task-desc', element.parentNode);
toggleElementClass('hidden', description);
});
}
);
}
function TaskPager(blockid) {
var self = this;
paginatorProxy.addObserver(self);
connect(self, 'pagechanged', partial(rewriteTaskTitles, blockid));
}
var taskPagers = [];
function initNewPlansBlock(blockid) {
if ($('plans_page_container_' + blockid)) {
new Paginator('block' + blockid + '_pagination', 'tasktable_' + blockid, 'artefact/plans/viewtasks.json.php', null);
taskPagers.push(new TaskPager(blockid));
}
rewriteTaskTitles(blockid);
}
| eireford/mahara | htdocs/artefact/plans/blocktype/plans/js/plansblock.js | JavaScript | gpl-3.0 | 963 |
var searchData=
[
['matrix_5fbase',['MATRIX_BASE',['../memorymap_8h.html#a096dcc80deb3676aeb5d5b8db13cfeba',1,'memorymap.h']]]
];
| Aghosh993/TARS_codebase | libopencm3/doc/sam3x/html/search/defines_7.js | JavaScript | gpl-3.0 | 132 |
/* eslint-disable jest/no-export, jest/no-disabled-tests */
/**
* Internal dependencies
*/
const {
shopper,
merchant,
createVariableProduct,
} = require( '@woocommerce/e2e-utils' );
let variablePostIdValue;
const cartDialogMessage = 'Please select some product options before adding this product to your cart.';
const runVariableProductUpdateTest = () => {
describe('Shopper > Update variable product',() => {
beforeAll(async () => {
await merchant.login();
variablePostIdValue = await createVariableProduct();
await merchant.logout();
});
it('shopper can change variable attributes to the same value', async () => {
await shopper.goToProduct(variablePostIdValue);
await expect(page).toSelect('#attr-1', 'val1');
await expect(page).toSelect('#attr-2', 'val1');
await expect(page).toSelect('#attr-3', 'val1');
await expect(page).toMatchElement('.woocommerce-variation-price', { text: '9.99' });
});
it('shopper can change attributes to combination with dimensions and weight', async () => {
await shopper.goToProduct(variablePostIdValue);
await expect(page).toSelect('#attr-1', 'val1');
await expect(page).toSelect('#attr-2', 'val2');
await expect(page).toSelect('#attr-3', 'val1');
await expect(page).toMatchElement('.woocommerce-variation-price', { text: '20.00' });
await expect(page).toMatchElement('.woocommerce-variation-availability', { text: 'Out of stock' });
await expect(page).toMatchElement('.woocommerce-product-attributes-item--weight', { text: '200 kg' });
await expect(page).toMatchElement('.woocommerce-product-attributes-item--dimensions', { text: '10 × 20 × 15 cm' });
});
it('shopper can change variable product attributes to variation with a different price', async () => {
await shopper.goToProduct(variablePostIdValue);
await expect(page).toSelect('#attr-1', 'val1');
await expect(page).toSelect('#attr-2', 'val1');
await expect(page).toSelect('#attr-3', 'val2');
await expect(page).toMatchElement('.woocommerce-variation-price', { text: '11.99' });
});
it('shopper can reset variations', async () => {
await shopper.goToProduct(variablePostIdValue);
await expect(page).toSelect('#attr-1', 'val1');
await expect(page).toSelect('#attr-2', 'val2');
await expect(page).toSelect('#attr-3', 'val1');
await expect(page).toClick('.reset_variations');
// Verify the reset by attempting to add the product to the cart
const couponDialog = await expect(page).toDisplayDialog(async () => {
await expect(page).toClick('.single_add_to_cart_button');
});
expect(couponDialog.message()).toMatch(cartDialogMessage);
// Accept the dialog
await couponDialog.accept();
});
});
};
module.exports = runVariableProductUpdateTest;
| Ninos/woocommerce | tests/e2e/core-tests/specs/shopper/front-end-variable-product-updates.test.js | JavaScript | gpl-3.0 | 2,776 |
/**
* AUTO-GENERATED - DO NOT EDIT. Source: https://github.com/gpuweb/cts
**/ export const description = '';
import { params, poptions } from '../../../../common/framework/params_builder.js';
import { makeTestGroup } from '../../../../common/framework/test_group.js';
import { kSizedTextureFormats, kSizedTextureFormatInfo } from '../../../capability_info.js';
import {
CopyBetweenLinearDataAndTextureTest,
kAllTestMethods,
texelBlockAlignmentTestExpanderForValueToCoordinate,
formatCopyableWithMethod,
} from './copyBetweenLinearDataAndTexture.js';
export const g = makeTestGroup(CopyBetweenLinearDataAndTextureTest);
g.test('texture_must_be_valid')
.params(
params()
.combine(poptions('method', kAllTestMethods))
.combine(poptions('textureState', ['valid', 'destroyed', 'error']))
)
.fn(async t => {
const { method, textureState } = t.params;
// A valid texture.
let texture = t.device.createTexture({
size: { width: 4, height: 4, depth: 1 },
format: 'rgba8unorm',
usage: GPUTextureUsage.COPY_SRC | GPUTextureUsage.COPY_DST,
});
switch (textureState) {
case 'destroyed': {
texture.destroy();
break;
}
case 'error': {
texture = t.getErrorTexture();
break;
}
}
const success = textureState === 'valid';
const submit = textureState === 'destroyed';
t.testRun(
{ texture },
{ bytesPerRow: 0 },
{ width: 0, height: 0, depth: 0 },
{ dataSize: 1, method, success, submit }
);
});
g.test('texture_usage_must_be_valid')
.params(
params()
.combine(poptions('method', kAllTestMethods))
.combine(
poptions('usage', [
GPUTextureUsage.COPY_SRC | GPUTextureUsage.SAMPLED,
GPUTextureUsage.COPY_DST | GPUTextureUsage.SAMPLED,
GPUTextureUsage.COPY_SRC | GPUTextureUsage.COPY_DST,
])
)
)
.fn(async t => {
const { usage, method } = t.params;
const texture = t.device.createTexture({
size: { width: 4, height: 4, depth: 1 },
format: 'rgba8unorm',
usage,
});
const success =
method === 'CopyTextureToBuffer'
? (usage & GPUTextureUsage.COPY_SRC) !== 0
: (usage & GPUTextureUsage.COPY_DST) !== 0;
t.testRun(
{ texture },
{ bytesPerRow: 0 },
{ width: 0, height: 0, depth: 0 },
{ dataSize: 1, method, success }
);
});
g.test('sample_count_must_be_1')
.params(
params()
.combine(poptions('method', kAllTestMethods))
.combine(poptions('sampleCount', [1, 4]))
)
.fn(async t => {
const { sampleCount, method } = t.params;
const texture = t.device.createTexture({
size: { width: 4, height: 4, depth: 1 },
sampleCount,
format: 'rgba8unorm',
usage: GPUTextureUsage.COPY_SRC | GPUTextureUsage.COPY_DST | GPUTextureUsage.SAMPLED,
});
const success = sampleCount === 1;
t.testRun(
{ texture },
{ bytesPerRow: 0 },
{ width: 0, height: 0, depth: 0 },
{ dataSize: 1, method, success }
);
});
g.test('mip_level_must_be_in_range')
.params(
params()
.combine(poptions('method', kAllTestMethods))
.combine(poptions('mipLevelCount', [3, 5]))
.combine(poptions('mipLevel', [3, 4]))
)
.fn(async t => {
const { mipLevelCount, mipLevel, method } = t.params;
const texture = t.device.createTexture({
size: { width: 32, height: 32, depth: 1 },
mipLevelCount,
format: 'rgba8unorm',
usage: GPUTextureUsage.COPY_SRC | GPUTextureUsage.COPY_DST,
});
const success = mipLevel < mipLevelCount;
t.testRun(
{ texture, mipLevel },
{ bytesPerRow: 0 },
{ width: 0, height: 0, depth: 0 },
{ dataSize: 1, method, success }
);
});
g.test('texel_block_alignments_on_origin')
.params(
params()
.combine(poptions('method', kAllTestMethods))
.combine(poptions('coordinateToTest', ['x', 'y', 'z']))
.combine(poptions('format', kSizedTextureFormats))
.filter(formatCopyableWithMethod)
.expand(texelBlockAlignmentTestExpanderForValueToCoordinate)
)
.fn(async t => {
const { valueToCoordinate, coordinateToTest, format, method } = t.params;
const info = kSizedTextureFormatInfo[format];
const origin = { x: 0, y: 0, z: 0 };
const size = { width: 0, height: 0, depth: 0 };
let success = true;
origin[coordinateToTest] = valueToCoordinate;
switch (coordinateToTest) {
case 'x': {
success = origin.x % info.blockWidth === 0;
break;
}
case 'y': {
success = origin.y % info.blockHeight === 0;
break;
}
}
const texture = t.createAlignedTexture(format, size, origin);
t.testRun({ texture, origin }, { bytesPerRow: 0 }, size, {
dataSize: 1,
method,
success,
});
});
g.test('1d_texture')
.params(
params()
.combine(poptions('method', kAllTestMethods))
.combine(poptions('width', [0, 1]))
.combine([
{ height: 1, depth: 1 },
{ height: 1, depth: 0 },
{ height: 1, depth: 2 },
{ height: 0, depth: 1 },
{ height: 2, depth: 1 },
])
)
.fn(async t => {
const { method, width, height, depth } = t.params;
const size = { width, height, depth };
const texture = t.device.createTexture({
size: { width: 2, height: 1, depth: 1 },
dimension: '1d',
format: 'rgba8unorm',
usage: GPUTextureUsage.COPY_SRC | GPUTextureUsage.COPY_DST,
});
// For 1d textures we require copyHeight and copyDepth to be 1,
// copyHeight or copyDepth being 0 should cause a validation error.
const success = size.height === 1 && size.depth === 1;
t.testRun({ texture }, { bytesPerRow: 256, rowsPerImage: 4 }, size, {
dataSize: 16,
method,
success,
});
});
g.test('texel_block_alignments_on_size')
.params(
params()
.combine(poptions('method', kAllTestMethods))
.combine(poptions('coordinateToTest', ['width', 'height', 'depth']))
.combine(poptions('format', kSizedTextureFormats))
.filter(formatCopyableWithMethod)
.expand(texelBlockAlignmentTestExpanderForValueToCoordinate)
)
.fn(async t => {
const { valueToCoordinate, coordinateToTest, format, method } = t.params;
const info = kSizedTextureFormatInfo[format];
const origin = { x: 0, y: 0, z: 0 };
const size = { width: 0, height: 0, depth: 0 };
let success = true;
size[coordinateToTest] = valueToCoordinate;
switch (coordinateToTest) {
case 'width': {
success = size.width % info.blockWidth === 0;
break;
}
case 'height': {
success = size.height % info.blockHeight === 0;
break;
}
}
const texture = t.createAlignedTexture(format, size, origin);
t.testRun({ texture, origin }, { bytesPerRow: 0 }, size, {
dataSize: 1,
method,
success,
});
});
g.test('texture_range_conditions')
.params(
params()
.combine(poptions('method', kAllTestMethods))
.combine(poptions('originValue', [7, 8]))
.combine(poptions('copySizeValue', [7, 8]))
.combine(poptions('textureSizeValue', [14, 15]))
.combine(poptions('mipLevel', [0, 2]))
.combine(poptions('coordinateToTest', [0, 1, 2]))
)
.fn(async t => {
const {
originValue,
copySizeValue,
textureSizeValue,
mipLevel,
coordinateToTest,
method,
} = t.params;
const origin = [0, 0, 0];
const copySize = [0, 0, 0];
const textureSize = { width: 16 << mipLevel, height: 16 << mipLevel, depth: 16 };
const success = originValue + copySizeValue <= textureSizeValue;
origin[coordinateToTest] = originValue;
copySize[coordinateToTest] = copySizeValue;
switch (coordinateToTest) {
case 0: {
textureSize.width = textureSizeValue << mipLevel;
break;
}
case 1: {
textureSize.height = textureSizeValue << mipLevel;
break;
}
case 2: {
textureSize.depth = textureSizeValue;
break;
}
}
const texture = t.device.createTexture({
size: textureSize,
mipLevelCount: 3,
format: 'rgba8unorm',
usage: GPUTextureUsage.COPY_SRC | GPUTextureUsage.COPY_DST,
});
t.testRun({ texture, origin, mipLevel }, { bytesPerRow: 0 }, copySize, {
dataSize: 1,
method,
success,
});
});
| CYBAI/servo | tests/wpt/webgpu/tests/webgpu/webgpu/api/validation/copy_between_linear_data_and_texture/copyBetweenLinearDataAndTexture_textureRelated.spec.js | JavaScript | mpl-2.0 | 8,523 |
/**
* <p>
* The scrollview module does not add any new classes. It simply plugs the ScrollViewScrollbars plugin into the
* base ScrollView class implementation provided by the scrollview-base module, so that all scrollview instances
* have scrollbars enabled.
* </p>
*
* <ul>
* <li><a href="../classes/ScrollView.html">ScrollView API documentation</a></li>
* <li><a href="scrollview-base.html">scrollview-base Module documentation</a></li>
* </ul>
*
* @module scrollview
*/
Y.Base.plug(Y.ScrollView, Y.Plugin.ScrollViewScrollbars);
| co-ment/comt | src/cm/media/js/lib/yui/yui3-3.15.0/src/scrollview/js/scrollview.js | JavaScript | agpl-3.0 | 556 |
/*
* 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/>.
*/
/*
* BrainBrowser v2.1.1
*
* Author: Tarek Sherif <[email protected]> (http://tareksherif.ca/)
* Author: Nicolas Kassis
* Author: Paul Mougel
*/
!function(){"use strict";function a(a){var b,c,d,e,f={};for(f.values=a.replace(/^\s+/,"").replace(/\s+$/,"").split(/\s+/).map(parseFloat),d=f.values[0],e=f.values[0],b=1,c=f.values.length;c>b;b++)d=Math.min(d,f.values[b]),e=Math.max(e,f.values[b]);return f.min=d,f.max=e,f}self.addEventListener("message",function(b){var c=b.data,d=c.data;self.postMessage(a(d))})}(); | rdvincent/brainbrowser | build/brainbrowser-2.1.1/workers/mniobj.intensity.worker.js | JavaScript | agpl-3.0 | 1,377 |
odoo.define('website_slides/static/src/tests/activity_tests.js', function (require) {
'use strict';
const components = {
Activity: require('mail/static/src/components/activity/activity.js'),
};
const {
afterEach,
beforeEach,
createRootComponent,
start,
} = require('mail/static/src/utils/test_utils.js');
QUnit.module('website_slides', {}, function () {
QUnit.module('components', {}, function () {
QUnit.module('activity', {}, function () {
QUnit.module('activity_tests.js', {
beforeEach() {
beforeEach(this);
this.createActivityComponent = async activity => {
await createRootComponent(this, components.Activity, {
props: { activityLocalId: activity.localId },
target: this.widget.el,
});
};
this.start = async params => {
const { env, widget } = await start(Object.assign({}, params, {
data: this.data,
}));
this.env = env;
this.widget = widget;
};
},
afterEach() {
afterEach(this);
},
});
QUnit.test('grant course access', async function (assert) {
assert.expect(8);
await this.start({
async mockRPC(route, args) {
if (args.method === 'action_grant_access') {
assert.strictEqual(args.args.length, 1);
assert.strictEqual(args.args[0].length, 1);
assert.strictEqual(args.args[0][0], 100);
assert.strictEqual(args.kwargs.partner_id, 5);
assert.step('access_grant');
}
return this._super(...arguments);
},
});
const activity = this.env.models['mail.activity'].create({
id: 100,
canWrite: true,
thread: [['insert', {
id: 100,
model: 'slide.channel',
}]],
requestingPartner: [['insert', {
id: 5,
displayName: "Pauvre pomme",
}]],
type: [['insert', {
id: 1,
displayName: "Access Request",
}]],
});
await this.createActivityComponent(activity);
assert.containsOnce(document.body, '.o_Activity', "should have activity component");
assert.containsOnce(document.body, '.o_Activity_grantAccessButton', "should have grant access button");
document.querySelector('.o_Activity_grantAccessButton').click();
assert.verifySteps(['access_grant'], "Grant button should trigger the right rpc call");
});
QUnit.test('refuse course access', async function (assert) {
assert.expect(8);
await this.start({
async mockRPC(route, args) {
if (args.method === 'action_refuse_access') {
assert.strictEqual(args.args.length, 1);
assert.strictEqual(args.args[0].length, 1);
assert.strictEqual(args.args[0][0], 100);
assert.strictEqual(args.kwargs.partner_id, 5);
assert.step('access_refuse');
}
return this._super(...arguments);
},
});
const activity = this.env.models['mail.activity'].create({
id: 100,
canWrite: true,
thread: [['insert', {
id: 100,
model: 'slide.channel',
}]],
requestingPartner: [['insert', {
id: 5,
displayName: "Pauvre pomme",
}]],
type: [['insert', {
id: 1,
displayName: "Access Request",
}]],
});
await this.createActivityComponent(activity);
assert.containsOnce(document.body, '.o_Activity', "should have activity component");
assert.containsOnce(document.body, '.o_Activity_refuseAccessButton', "should have refuse access button");
document.querySelector('.o_Activity_refuseAccessButton').click();
assert.verifySteps(['access_refuse'], "refuse button should trigger the right rpc call");
});
});
});
});
});
| rven/odoo | addons/website_slides/static/src/components/activity/activity_tests.js | JavaScript | agpl-3.0 | 3,940 |
/*
Copyright 2011, AUTHORS.txt (http://ui.operamasks.org/about)
Dual licensed under the MIT or LGPL Version 2 licenses.
*/
/**
* @file Spell checker
*/
// Register a plugin named "wsc".
OMEDITOR.plugins.add( 'wsc',
{
requires : [ 'dialog' ],
init : function( editor )
{
var commandName = 'checkspell';
var command = editor.addCommand( commandName, new OMEDITOR.dialogCommand( commandName ) );
// SpellChecker doesn't work in Opera and with custom domain
command.modes = { wysiwyg : ( !OMEDITOR.env.opera && !OMEDITOR.env.air && document.domain == window.location.hostname ) };
editor.ui.addButton( 'SpellChecker',
{
label : editor.lang.spellCheck.toolbar,
command : commandName
});
OMEDITOR.dialog.add( commandName, this.path + 'dialogs/wsc.js' );
}
});
OMEDITOR.config.wsc_customerId = OMEDITOR.config.wsc_customerId || '1:ua3xw1-2XyGJ3-GWruD3-6OFNT1-oXcuB1-nR6Bp4-hgQHc-EcYng3-sdRXG3-NOfFk' ;
OMEDITOR.config.wsc_customLoaderScript = OMEDITOR.config.wsc_customLoaderScript || null;
| yonghuang/fastui | samplecenter/basic/timeTest/operamasks-ui-2.0/development-bundle/ui/editor/_source/plugins/wsc/plugin.js | JavaScript | lgpl-3.0 | 1,027 |
/**
* @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
*/
export default [
[
[
'நள்.', 'நண்.', 'அதி.', 'கா.', 'மதி.', 'பிற்.', 'மா.',
'அந்தி மா.', 'இர.'
],
[
'நள்ளிரவு', 'நண்பகல்', 'அதிகாலை', 'காலை',
'மதியம்', 'பிற்பகல்', 'மாலை',
'அந்தி மாலை', 'இரவு'
],
],
[
[
'நள்.', 'நண்.', 'அதி.', 'கா.', 'மதி.', 'பிற்.', 'மா.',
'அந்தி மா.', 'இ.'
],
[
'நள்ளிரவு', 'நண்பகல்', 'அதிகாலை', 'காலை',
'மதியம்', 'பிற்பகல்', 'மாலை',
'அந்தி மாலை', 'இரவு'
],
],
[
'00:00', '12:00', ['03:00', '05:00'], ['05:00', '12:00'], ['12:00', '14:00'],
['14:00', '16:00'], ['16:00', '18:00'], ['18:00', '21:00'], ['21:00', '03:00']
]
];
//# sourceMappingURL=ta-MY.js.map | rospilot/rospilot | share/web_assets/nodejs_deps/node_modules/@angular/common/locales/extra/ta-MY.js | JavaScript | apache-2.0 | 1,346 |
/*
Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang("uicolor","et",{title:"Värvivalija kasutajaliides",preview:"Automaatne eelvaade",config:"Aseta see sõne oma config.js faili.",predefined:"Eelmääratud värvikomplektid"}); | viticm/pfadmin | vendor/frozennode/administrator/public/js/ckeditor/plugins/uicolor/lang/et.js | JavaScript | apache-2.0 | 344 |
/*
* Copyright 2016 The Closure Compiler Authors
*
* 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 Externs for Intersection Observer objects.
* @see https://wicg.github.io/IntersectionObserver/
* @externs
*/
// TODO(user): Once the Intersection Observer spec is adopted by W3C, add
// a w3c_ prefix to this file's name.
/**
* These contain the information provided from a change event.
* @see https://wicg.github.io/IntersectionObserver/#intersection-observer-entry
* @record
*/
function IntersectionObserverEntry() {}
/**
* The time the change was observed.
* @see https://wicg.github.io/IntersectionObserver/#dom-intersectionobserverentry-time
* @type {number}
* @const
*/
IntersectionObserverEntry.prototype.time;
/**
* The root intersection rectangle, if target belongs to the same unit of
* related similar-origin browsing contexts as the intersection root, null
* otherwise.
* @see https://wicg.github.io/IntersectionObserver/#dom-intersectionobserverentry-rootbounds
* @type {{top: number, right: number, bottom: number, left: number,
* height: number, width: number}}
* @const
*/
IntersectionObserverEntry.prototype.rootBounds;
/**
* The rectangle describing the element being observed.
* @see https://wicg.github.io/IntersectionObserver/#dom-intersectionobserverentry-boundingclientrect
* @type {!{top: number, right: number, bottom: number, left: number,
* height: number, width: number}}
* @const
*/
IntersectionObserverEntry.prototype.boundingClientRect;
/**
* The rectangle describing the intersection between the observed element and
* the viewport.
* @see https://wicg.github.io/IntersectionObserver/#dom-intersectionobserverentry-intersectionrect
* @type {!{top: number, right: number, bottom: number, left: number,
* height: number, width: number}}
* @const
*/
IntersectionObserverEntry.prototype.intersectionRect;
/**
* Ratio of intersectionRect area to boundingClientRect area.
* @see https://wicg.github.io/IntersectionObserver/#dom-intersectionobserverentry-intersectionratio
* @type {!number}
* @const
*/
IntersectionObserverEntry.prototype.intersectionRatio;
/**
* The Element whose intersection with the intersection root changed.
* @see https://wicg.github.io/IntersectionObserver/#dom-intersectionobserverentry-target
* @type {!Element}
* @const
*/
IntersectionObserverEntry.prototype.target;
/**
* Whether or not the target is intersecting with the root.
* @see https://wicg.github.io/IntersectionObserver/#dom-intersectionobserverentry-isintersecting
* @type {boolean}
* @const
*/
IntersectionObserverEntry.prototype.isIntersecting;
/**
* Callback for the IntersectionObserver.
* @see https://wicg.github.io/IntersectionObserver/#intersection-observer-callback
* @typedef {function(!Array<!IntersectionObserverEntry>,!IntersectionObserver)}
*/
var IntersectionObserverCallback;
/**
* Options for the IntersectionObserver.
* @see https://wicg.github.io/IntersectionObserver/#intersection-observer-init
* @typedef {{
* threshold: (!Array<number>|number|undefined),
* root: (!Element|undefined),
* rootMargin: (string|undefined)
* }}
*/
var IntersectionObserverInit;
/**
* This is the constructor for Intersection Observer objects.
* @see https://wicg.github.io/IntersectionObserver/#intersection-observer-interface
* @param {!IntersectionObserverCallback} handler The callback for the observer.
* @param {!IntersectionObserverInit=} opt_options The object defining the
* thresholds, etc.
* @constructor
*/
function IntersectionObserver(handler, opt_options) {};
/**
* The root Element to use for intersection, or null if the observer uses the
* implicit root.
* @see https://wicg.github.io/IntersectionObserver/#dom-intersectionobserver-root
* @type {?Element}
* @const
*/
IntersectionObserver.prototype.root;
/**
* Offsets applied to the intersection root’s bounding box, effectively growing
* or shrinking the box that is used to calculate intersections.
* @see https://wicg.github.io/IntersectionObserver/#dom-intersectionobserver-rootmargin
* @type {!string}
* @const
*/
IntersectionObserver.prototype.rootMargin;
/**
* A list of thresholds, sorted in increasing numeric order, where each
* threshold is a ratio of intersection area to bounding box area of an observed
* target.
* @see https://wicg.github.io/IntersectionObserver/#dom-intersectionobserver-thresholds
* @type {!Array.<!number>}
* @const
*/
IntersectionObserver.prototype.thresholds;
/**
* This is used to set which element to observe.
* @see https://wicg.github.io/IntersectionObserver/#dom-intersectionobserver-observe
* @param {!Element} element The element to observe.
* @return {undefined}
*/
IntersectionObserver.prototype.observe = function(element) {};
/**
* This is used to stop observing a given element.
* @see https://wicg.github.io/IntersectionObserver/#dom-intersectionobserver-unobserve
* @param {!Element} element The elmenent to stop observing.
* @return {undefined}
*/
IntersectionObserver.prototype.unobserve = function(element) {};
/**
* Disconnect.
* @see https://wicg.github.io/IntersectionObserver/#dom-intersectionobserver-disconnect
*/
IntersectionObserver.prototype.disconnect = function() {};
/**
* Take records.
* @see https://wicg.github.io/IntersectionObserver/#dom-intersectionobserver-takerecords
* @return {!Array.<!IntersectionObserverEntry>}
*/
IntersectionObserver.prototype.takeRecords = function() {};
| MatrixFrog/closure-compiler | externs/browser/intersection_observer.js | JavaScript | apache-2.0 | 6,017 |
/*
* 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';
/**
* Additional information of DPM Protected item.
*
*/
class DPMProtectedItemExtendedInfo {
/**
* Create a DPMProtectedItemExtendedInfo.
* @member {object} [protectableObjectLoadPath] Attribute to provide
* information on various DBs.
* @member {boolean} [protectedProperty] To check if backup item is disk
* protected.
* @member {boolean} [isPresentOnCloud] To check if backup item is cloud
* protected.
* @member {string} [lastBackupStatus] Last backup status information on
* backup item.
* @member {date} [lastRefreshedAt] Last refresh time on backup item.
* @member {date} [oldestRecoveryPoint] Oldest cloud recovery point time.
* @member {number} [recoveryPointCount] cloud recovery point count.
* @member {date} [onPremiseOldestRecoveryPoint] Oldest disk recovery point
* time.
* @member {date} [onPremiseLatestRecoveryPoint] latest disk recovery point
* time.
* @member {number} [onPremiseRecoveryPointCount] disk recovery point count.
* @member {boolean} [isCollocated] To check if backup item is collocated.
* @member {string} [protectionGroupName] Protection group name of the backup
* item.
* @member {string} [diskStorageUsedInBytes] Used Disk storage in bytes.
* @member {string} [totalDiskStorageSizeInBytes] total Disk storage in
* bytes.
*/
constructor() {
}
/**
* Defines the metadata of DPMProtectedItemExtendedInfo
*
* @returns {object} metadata of DPMProtectedItemExtendedInfo
*
*/
mapper() {
return {
required: false,
serializedName: 'DPMProtectedItemExtendedInfo',
type: {
name: 'Composite',
className: 'DPMProtectedItemExtendedInfo',
modelProperties: {
protectableObjectLoadPath: {
required: false,
serializedName: 'protectableObjectLoadPath',
type: {
name: 'Dictionary',
value: {
required: false,
serializedName: 'StringElementType',
type: {
name: 'String'
}
}
}
},
protectedProperty: {
required: false,
serializedName: 'protected',
type: {
name: 'Boolean'
}
},
isPresentOnCloud: {
required: false,
serializedName: 'isPresentOnCloud',
type: {
name: 'Boolean'
}
},
lastBackupStatus: {
required: false,
serializedName: 'lastBackupStatus',
type: {
name: 'String'
}
},
lastRefreshedAt: {
required: false,
serializedName: 'lastRefreshedAt',
type: {
name: 'DateTime'
}
},
oldestRecoveryPoint: {
required: false,
serializedName: 'oldestRecoveryPoint',
type: {
name: 'DateTime'
}
},
recoveryPointCount: {
required: false,
serializedName: 'recoveryPointCount',
type: {
name: 'Number'
}
},
onPremiseOldestRecoveryPoint: {
required: false,
serializedName: 'onPremiseOldestRecoveryPoint',
type: {
name: 'DateTime'
}
},
onPremiseLatestRecoveryPoint: {
required: false,
serializedName: 'onPremiseLatestRecoveryPoint',
type: {
name: 'DateTime'
}
},
onPremiseRecoveryPointCount: {
required: false,
serializedName: 'onPremiseRecoveryPointCount',
type: {
name: 'Number'
}
},
isCollocated: {
required: false,
serializedName: 'isCollocated',
type: {
name: 'Boolean'
}
},
protectionGroupName: {
required: false,
serializedName: 'protectionGroupName',
type: {
name: 'String'
}
},
diskStorageUsedInBytes: {
required: false,
serializedName: 'diskStorageUsedInBytes',
type: {
name: 'String'
}
},
totalDiskStorageSizeInBytes: {
required: false,
serializedName: 'totalDiskStorageSizeInBytes',
type: {
name: 'String'
}
}
}
}
};
}
}
module.exports = DPMProtectedItemExtendedInfo;
| xingwu1/azure-sdk-for-node | lib/services/recoveryServicesBackupManagement/lib/models/dPMProtectedItemExtendedInfo.js | JavaScript | apache-2.0 | 5,048 |
define([
"dojo/_base/declare", // declare
"dojo/dom-construct", // domConstruct.destroy domConstruct.place
"dojo/keys", // keys.ENTER
"dojo/_base/lang",
"dojo/on",
"dojo/sniff", // has("ie") has("mozilla") has("webkit")
"dojo/_base/window", // win.withGlobal
"dojo/window", // winUtils.scrollIntoView
"../_Plugin",
"../RichText",
"../range",
"../../_base/focus"
], function(declare, domConstruct, keys, lang, on, has, win, winUtils, _Plugin, RichText, rangeapi, baseFocus){
// module:
// dijit/_editor/plugins/EnterKeyHandling
return declare("dijit._editor.plugins.EnterKeyHandling", _Plugin, {
// summary:
// This plugin tries to make all browsers behave consistently with regard to
// how ENTER behaves in the editor window. It traps the ENTER key and alters
// the way DOM is constructed in certain cases to try to commonize the generated
// DOM and behaviors across browsers.
//
// description:
// This plugin has three modes:
//
// - blockNodeForEnter=BR
// - blockNodeForEnter=DIV
// - blockNodeForEnter=P
//
// In blockNodeForEnter=P, the ENTER key starts a new
// paragraph, and shift-ENTER starts a new line in the current paragraph.
// For example, the input:
//
// | first paragraph <shift-ENTER>
// | second line of first paragraph <ENTER>
// | second paragraph
//
// will generate:
//
// | <p>
// | first paragraph
// | <br/>
// | second line of first paragraph
// | </p>
// | <p>
// | second paragraph
// | </p>
//
// In BR and DIV mode, the ENTER key conceptually goes to a new line in the
// current paragraph, and users conceptually create a new paragraph by pressing ENTER twice.
// For example, if the user enters text into an editor like this:
//
// | one <ENTER>
// | two <ENTER>
// | three <ENTER>
// | <ENTER>
// | four <ENTER>
// | five <ENTER>
// | six <ENTER>
//
// It will appear on the screen as two 'paragraphs' of three lines each. Markupwise, this generates:
//
// BR:
// | one<br/>
// | two<br/>
// | three<br/>
// | <br/>
// | four<br/>
// | five<br/>
// | six<br/>
//
// DIV:
// | <div>one</div>
// | <div>two</div>
// | <div>three</div>
// | <div> </div>
// | <div>four</div>
// | <div>five</div>
// | <div>six</div>
// blockNodeForEnter: String
// This property decides the behavior of Enter key. It can be either P,
// DIV, BR, or empty (which means disable this feature). Anything else
// will trigger errors. The default is 'BR'
//
// See class description for more details.
blockNodeForEnter: 'BR',
constructor: function(args){
if(args){
if("blockNodeForEnter" in args){
args.blockNodeForEnter = args.blockNodeForEnter.toUpperCase();
}
lang.mixin(this, args);
}
},
setEditor: function(editor){
// Overrides _Plugin.setEditor().
if(this.editor === editor){
return;
}
this.editor = editor;
if(this.blockNodeForEnter == 'BR'){
// While Moz has a mode tht mostly works, it's still a little different,
// So, try to just have a common mode and be consistent. Which means
// we need to enable customUndo, if not already enabled.
this.editor.customUndo = true;
editor.onLoadDeferred.then(lang.hitch(this, function(d){
this.own(on(editor.document, "keydown", lang.hitch(this, function(e){
if(e.keyCode == keys.ENTER){
// Just do it manually. The handleEnterKey has a shift mode that
// Always acts like <br>, so just use it.
var ne = lang.mixin({}, e);
ne.shiftKey = true;
if(!this.handleEnterKey(ne)){
e.stopPropagation();
e.preventDefault();
}
}
})));
if(has("ie") >= 9 && has("ie") <= 10){
this.own(on(editor.document, "paste", lang.hitch(this, function(e){
setTimeout(lang.hitch(this, function(){
// Use the old range/selection code to kick IE 9 into updating
// its range by moving it back, then forward, one 'character'.
var r = this.editor.document.selection.createRange();
r.move('character', -1);
r.select();
r.move('character', 1);
r.select();
}), 0);
})));
}
return d;
}));
}else if(this.blockNodeForEnter){
// add enter key handler
var h = lang.hitch(this, "handleEnterKey");
editor.addKeyHandler(13, 0, 0, h); //enter
editor.addKeyHandler(13, 0, 1, h); //shift+enter
this.own(this.editor.on('KeyPressed', lang.hitch(this, 'onKeyPressed')));
}
},
onKeyPressed: function(){
// summary:
// Handler for after the user has pressed a key, and the display has been updated.
// Connected to RichText's onKeyPressed() method.
// tags:
// private
if(this._checkListLater){
if(win.withGlobal(this.editor.window, 'isCollapsed', baseFocus)){ // TODO: stop using withGlobal(), and baseFocus
var liparent = this.editor.selection.getAncestorElement('LI');
if(!liparent){
// circulate the undo detection code by calling RichText::execCommand directly
RichText.prototype.execCommand.call(this.editor, 'formatblock', this.blockNodeForEnter);
// set the innerHTML of the new block node
var block = this.editor.selection.getAncestorElement(this.blockNodeForEnter);
if(block){
block.innerHTML = this.bogusHtmlContent;
if(has("ie") <= 9){
// move to the start by moving backwards one char
var r = this.editor.document.selection.createRange();
r.move('character', -1);
r.select();
}
}else{
console.error('onKeyPressed: Cannot find the new block node'); // FIXME
}
}else{
if(has("mozilla")){
if(liparent.parentNode.parentNode.nodeName == 'LI'){
liparent = liparent.parentNode.parentNode;
}
}
var fc = liparent.firstChild;
if(fc && fc.nodeType == 1 && (fc.nodeName == 'UL' || fc.nodeName == 'OL')){
liparent.insertBefore(fc.ownerDocument.createTextNode('\xA0'), fc);
var newrange = rangeapi.create(this.editor.window);
newrange.setStart(liparent.firstChild, 0);
var selection = rangeapi.getSelection(this.editor.window, true);
selection.removeAllRanges();
selection.addRange(newrange);
}
}
}
this._checkListLater = false;
}
if(this._pressedEnterInBlock){
// the new created is the original current P, so we have previousSibling below
if(this._pressedEnterInBlock.previousSibling){
this.removeTrailingBr(this._pressedEnterInBlock.previousSibling);
}
delete this._pressedEnterInBlock;
}
},
// bogusHtmlContent: [private] String
// HTML to stick into a new empty block
bogusHtmlContent: ' ', //
// blockNodes: [private] Regex
// Regex for testing if a given tag is a block level (display:block) tag
blockNodes: /^(?:P|H1|H2|H3|H4|H5|H6|LI)$/,
handleEnterKey: function(e){
// summary:
// Handler for enter key events when blockNodeForEnter is DIV or P.
// description:
// Manually handle enter key event to make the behavior consistent across
// all supported browsers. See class description for details.
// tags:
// private
var selection, range, newrange, startNode, endNode, brNode, doc = this.editor.document, br, rs, txt;
if(e.shiftKey){ // shift+enter always generates <br>
var parent = this.editor.selection.getParentElement();
var header = rangeapi.getAncestor(parent, this.blockNodes);
if(header){
if(header.tagName == 'LI'){
return true; // let browser handle
}
selection = rangeapi.getSelection(this.editor.window);
range = selection.getRangeAt(0);
if(!range.collapsed){
range.deleteContents();
selection = rangeapi.getSelection(this.editor.window);
range = selection.getRangeAt(0);
}
if(rangeapi.atBeginningOfContainer(header, range.startContainer, range.startOffset)){
br = doc.createElement('br');
newrange = rangeapi.create(this.editor.window);
header.insertBefore(br, header.firstChild);
newrange.setStartAfter(br);
selection.removeAllRanges();
selection.addRange(newrange);
}else if(rangeapi.atEndOfContainer(header, range.startContainer, range.startOffset)){
newrange = rangeapi.create(this.editor.window);
br = doc.createElement('br');
header.appendChild(br);
header.appendChild(doc.createTextNode('\xA0'));
newrange.setStart(header.lastChild, 0);
selection.removeAllRanges();
selection.addRange(newrange);
}else{
rs = range.startContainer;
if(rs && rs.nodeType == 3){
// Text node, we have to split it.
txt = rs.nodeValue;
startNode = doc.createTextNode(txt.substring(0, range.startOffset));
endNode = doc.createTextNode(txt.substring(range.startOffset));
brNode = doc.createElement("br");
if(endNode.nodeValue == "" && has("webkit")){
endNode = doc.createTextNode('\xA0')
}
domConstruct.place(startNode, rs, "after");
domConstruct.place(brNode, startNode, "after");
domConstruct.place(endNode, brNode, "after");
domConstruct.destroy(rs);
newrange = rangeapi.create(this.editor.window);
newrange.setStart(endNode, 0);
selection.removeAllRanges();
selection.addRange(newrange);
return false;
}
return true; // let browser handle
}
}else{
selection = rangeapi.getSelection(this.editor.window);
if(selection.rangeCount){
range = selection.getRangeAt(0);
if(range && range.startContainer){
if(!range.collapsed){
range.deleteContents();
selection = rangeapi.getSelection(this.editor.window);
range = selection.getRangeAt(0);
}
rs = range.startContainer;
if(rs && rs.nodeType == 3){
// Text node, we have to split it.
var endEmpty = false;
var offset = range.startOffset;
if(rs.length < offset){
//We are not splitting the right node, try to locate the correct one
ret = this._adjustNodeAndOffset(rs, offset);
rs = ret.node;
offset = ret.offset;
}
txt = rs.nodeValue;
startNode = doc.createTextNode(txt.substring(0, offset));
endNode = doc.createTextNode(txt.substring(offset));
brNode = doc.createElement("br");
if(!endNode.length){
endNode = doc.createTextNode('\xA0');
endEmpty = true;
}
if(startNode.length){
domConstruct.place(startNode, rs, "after");
}else{
startNode = rs;
}
domConstruct.place(brNode, startNode, "after");
domConstruct.place(endNode, brNode, "after");
domConstruct.destroy(rs);
newrange = rangeapi.create(this.editor.window);
newrange.setStart(endNode, 0);
newrange.setEnd(endNode, endNode.length);
selection.removeAllRanges();
selection.addRange(newrange);
if(endEmpty && !has("webkit")){
this.editor.selection.remove();
}else{
this.editor.selection.collapse(true);
}
}else{
var targetNode;
if(range.startOffset >= 0){
targetNode = rs.childNodes[range.startOffset];
}
var brNode = doc.createElement("br");
var endNode = doc.createTextNode('\xA0');
if(!targetNode){
rs.appendChild(brNode);
rs.appendChild(endNode);
}else{
domConstruct.place(brNode, targetNode, "before");
domConstruct.place(endNode, brNode, "after");
}
newrange = rangeapi.create(this.editor.window);
newrange.setStart(endNode, 0);
newrange.setEnd(endNode, endNode.length);
selection.removeAllRanges();
selection.addRange(newrange);
this.editor.selection.collapse(true);
}
}
}else{
// don't change this: do not call this.execCommand, as that may have other logic in subclass
RichText.prototype.execCommand.call(this.editor, 'inserthtml', '<br>');
}
}
return false;
}
var _letBrowserHandle = true;
// first remove selection
selection = rangeapi.getSelection(this.editor.window);
range = selection.getRangeAt(0);
if(!range.collapsed){
range.deleteContents();
selection = rangeapi.getSelection(this.editor.window);
range = selection.getRangeAt(0);
}
var block = rangeapi.getBlockAncestor(range.endContainer, null, this.editor.editNode);
var blockNode = block.blockNode;
// if this is under a LI or the parent of the blockNode is LI, just let browser to handle it
if((this._checkListLater = (blockNode && (blockNode.nodeName == 'LI' || blockNode.parentNode.nodeName == 'LI')))){
if(has("mozilla")){
// press enter in middle of P may leave a trailing <br/>, let's remove it later
this._pressedEnterInBlock = blockNode;
}
// if this li only contains spaces, set the content to empty so the browser will outdent this item
if(/^(\s| | |\xA0|<span\b[^>]*\bclass=['"]Apple-style-span['"][^>]*>(\s| | |\xA0)<\/span>)?(<br>)?$/.test(blockNode.innerHTML)){
// empty LI node
blockNode.innerHTML = '';
if(has("webkit")){ // WebKit tosses the range when innerHTML is reset
newrange = rangeapi.create(this.editor.window);
newrange.setStart(blockNode, 0);
selection.removeAllRanges();
selection.addRange(newrange);
}
this._checkListLater = false; // nothing to check since the browser handles outdent
}
return true;
}
// text node directly under body, let's wrap them in a node
if(!block.blockNode || block.blockNode === this.editor.editNode){
try{
RichText.prototype.execCommand.call(this.editor, 'formatblock', this.blockNodeForEnter);
}catch(e2){ /*squelch FF3 exception bug when editor content is a single BR*/
}
// get the newly created block node
// FIXME
block = {blockNode: this.editor.selection.getAncestorElement(this.blockNodeForEnter),
blockContainer: this.editor.editNode};
if(block.blockNode){
if(block.blockNode != this.editor.editNode &&
(!(block.blockNode.textContent || block.blockNode.innerHTML).replace(/^\s+|\s+$/g, "").length)){
this.removeTrailingBr(block.blockNode);
return false;
}
}else{ // we shouldn't be here if formatblock worked
block.blockNode = this.editor.editNode;
}
selection = rangeapi.getSelection(this.editor.window);
range = selection.getRangeAt(0);
}
var newblock = doc.createElement(this.blockNodeForEnter);
newblock.innerHTML = this.bogusHtmlContent;
this.removeTrailingBr(block.blockNode);
var endOffset = range.endOffset;
var node = range.endContainer;
if(node.length < endOffset){
//We are not checking the right node, try to locate the correct one
var ret = this._adjustNodeAndOffset(node, endOffset);
node = ret.node;
endOffset = ret.offset;
}
if(rangeapi.atEndOfContainer(block.blockNode, node, endOffset)){
if(block.blockNode === block.blockContainer){
block.blockNode.appendChild(newblock);
}else{
domConstruct.place(newblock, block.blockNode, "after");
}
_letBrowserHandle = false;
// lets move caret to the newly created block
newrange = rangeapi.create(this.editor.window);
newrange.setStart(newblock, 0);
selection.removeAllRanges();
selection.addRange(newrange);
if(this.editor.height){
winUtils.scrollIntoView(newblock);
}
}else if(rangeapi.atBeginningOfContainer(block.blockNode,
range.startContainer, range.startOffset)){
domConstruct.place(newblock, block.blockNode, block.blockNode === block.blockContainer ? "first" : "before");
if(newblock.nextSibling && this.editor.height){
// position input caret - mostly WebKit needs this
newrange = rangeapi.create(this.editor.window);
newrange.setStart(newblock.nextSibling, 0);
selection.removeAllRanges();
selection.addRange(newrange);
// browser does not scroll the caret position into view, do it manually
winUtils.scrollIntoView(newblock.nextSibling);
}
_letBrowserHandle = false;
}else{ //press enter in the middle of P/DIV/Whatever/
if(block.blockNode === block.blockContainer){
block.blockNode.appendChild(newblock);
}else{
domConstruct.place(newblock, block.blockNode, "after");
}
_letBrowserHandle = false;
// Clone any block level styles.
if(block.blockNode.style){
if(newblock.style){
if(block.blockNode.style.cssText){
newblock.style.cssText = block.blockNode.style.cssText;
}
}
}
// Okay, we probably have to split.
rs = range.startContainer;
var firstNodeMoved;
if(rs && rs.nodeType == 3){
// Text node, we have to split it.
var nodeToMove, tNode;
endOffset = range.endOffset;
if(rs.length < endOffset){
//We are not splitting the right node, try to locate the correct one
ret = this._adjustNodeAndOffset(rs, endOffset);
rs = ret.node;
endOffset = ret.offset;
}
txt = rs.nodeValue;
startNode = doc.createTextNode(txt.substring(0, endOffset));
endNode = doc.createTextNode(txt.substring(endOffset, txt.length));
// Place the split, then remove original nodes.
domConstruct.place(startNode, rs, "before");
domConstruct.place(endNode, rs, "after");
domConstruct.destroy(rs);
// Okay, we split the text. Now we need to see if we're
// parented to the block element we're splitting and if
// not, we have to split all the way up. Ugh.
var parentC = startNode.parentNode;
while(parentC !== block.blockNode){
var tg = parentC.tagName;
var newTg = doc.createElement(tg);
// Clone over any 'style' data.
if(parentC.style){
if(newTg.style){
if(parentC.style.cssText){
newTg.style.cssText = parentC.style.cssText;
}
}
}
// If font also need to clone over any font data.
if(parentC.tagName === "FONT"){
if(parentC.color){
newTg.color = parentC.color;
}
if(parentC.face){
newTg.face = parentC.face;
}
if(parentC.size){ // this check was necessary on IE
newTg.size = parentC.size;
}
}
nodeToMove = endNode;
while(nodeToMove){
tNode = nodeToMove.nextSibling;
newTg.appendChild(nodeToMove);
nodeToMove = tNode;
}
domConstruct.place(newTg, parentC, "after");
startNode = parentC;
endNode = newTg;
parentC = parentC.parentNode;
}
// Lastly, move the split out tags to the new block.
// as they should now be split properly.
nodeToMove = endNode;
if(nodeToMove.nodeType == 1 || (nodeToMove.nodeType == 3 && nodeToMove.nodeValue)){
// Non-blank text and non-text nodes need to clear out that blank space
// before moving the contents.
newblock.innerHTML = "";
}
firstNodeMoved = nodeToMove;
while(nodeToMove){
tNode = nodeToMove.nextSibling;
newblock.appendChild(nodeToMove);
nodeToMove = tNode;
}
}
//lets move caret to the newly created block
newrange = rangeapi.create(this.editor.window);
var nodeForCursor;
var innerMostFirstNodeMoved = firstNodeMoved;
if(this.blockNodeForEnter !== 'BR'){
while(innerMostFirstNodeMoved){
nodeForCursor = innerMostFirstNodeMoved;
tNode = innerMostFirstNodeMoved.firstChild;
innerMostFirstNodeMoved = tNode;
}
if(nodeForCursor && nodeForCursor.parentNode){
newblock = nodeForCursor.parentNode;
newrange.setStart(newblock, 0);
selection.removeAllRanges();
selection.addRange(newrange);
if(this.editor.height){
winUtils.scrollIntoView(newblock);
}
if(has("mozilla")){
// press enter in middle of P may leave a trailing <br/>, let's remove it later
this._pressedEnterInBlock = block.blockNode;
}
}else{
_letBrowserHandle = true;
}
}else{
newrange.setStart(newblock, 0);
selection.removeAllRanges();
selection.addRange(newrange);
if(this.editor.height){
winUtils.scrollIntoView(newblock);
}
if(has("mozilla")){
// press enter in middle of P may leave a trailing <br/>, let's remove it later
this._pressedEnterInBlock = block.blockNode;
}
}
}
return _letBrowserHandle;
},
_adjustNodeAndOffset: function(/*DomNode*/node, /*Int*/offset){
// summary:
// In the case there are multiple text nodes in a row the offset may not be within the node. If the offset is larger than the node length, it will attempt to find
// the next text sibling until it locates the text node in which the offset refers to
// node:
// The node to check.
// offset:
// The position to find within the text node
// tags:
// private.
while(node.length < offset && node.nextSibling && node.nextSibling.nodeType == 3){
//Adjust the offset and node in the case of multiple text nodes in a row
offset = offset - node.length;
node = node.nextSibling;
}
return {"node": node, "offset": offset};
},
removeTrailingBr: function(container){
// summary:
// If last child of container is a `<br>`, then remove it.
// tags:
// private
var para = /P|DIV|LI/i.test(container.tagName) ?
container : this.editor.selection.getParentOfType(container, ['P', 'DIV', 'LI']);
if(!para){
return;
}
if(para.lastChild){
if((para.childNodes.length > 1 && para.lastChild.nodeType == 3 && /^[\s\xAD]*$/.test(para.lastChild.nodeValue)) ||
para.lastChild.tagName == 'BR'){
domConstruct.destroy(para.lastChild);
}
}
if(!para.childNodes.length){
para.innerHTML = this.bogusHtmlContent;
}
}
});
});
| denov/dojo-demo | src/main/webapp/js/dijit/_editor/plugins/EnterKeyHandling.js | JavaScript | apache-2.0 | 22,062 |
/* jshint globalstrict:false, strict:false, unused : false */
/* global assertEqual */
// //////////////////////////////////////////////////////////////////////////////
// / @brief tests for dump/reload
// /
// / @file
// /
// / DISCLAIMER
// /
// / Copyright 2010-2012 triagens GmbH, Cologne, Germany
// /
// / Licensed under the Apache License, Version 2.0 (the "License")
// / you may not use this file except in compliance with the License.
// / You may obtain a copy of the License at
// /
// / http://www.apache.org/licenses/LICENSE-2.0
// /
// / Unless required by applicable law or agreed to in writing, software
// / distributed under the License is distributed on an "AS IS" BASIS,
// / WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// / See the License for the specific language governing permissions and
// / limitations under the License.
// /
// / Copyright holder is triAGENS GmbH, Cologne, Germany
// /
// / @author Jan Steemann
// / @author Copyright 2012, triAGENS GmbH, Cologne, Germany
// //////////////////////////////////////////////////////////////////////////////
var db = require('@arangodb').db;
var internal = require('internal');
var jsunity = require('jsunity');
function runSetup () {
'use strict';
internal.debugClearFailAt();
db._drop('UnitTestsRecovery');
var c = db._create('UnitTestsRecovery');
// try to re-create collection with the same name
try {
db._create('UnitTestsRecovery');
} catch (err) {
}
c.save({ _key: 'foo' }, true);
internal.debugTerminate('crashing server');
}
// //////////////////////////////////////////////////////////////////////////////
// / @brief test suite
// //////////////////////////////////////////////////////////////////////////////
function recoverySuite () {
'use strict';
jsunity.jsUnity.attachAssertions();
return {
setUp: function () {},
tearDown: function () {},
// //////////////////////////////////////////////////////////////////////////////
// / @brief test whether we can restore the trx data
// //////////////////////////////////////////////////////////////////////////////
testCollectionDuplicate: function () {
var c = db._collection('UnitTestsRecovery');
assertEqual(1, c.count());
}
};
}
// //////////////////////////////////////////////////////////////////////////////
// / @brief executes the test suite
// //////////////////////////////////////////////////////////////////////////////
function main (argv) {
'use strict';
if (argv[1] === 'setup') {
runSetup();
return 0;
} else {
jsunity.run(recoverySuite);
return jsunity.writeDone().status ? 0 : 1;
}
}
| wiltonlazary/arangodb | tests/js/server/recovery/collection-duplicate.js | JavaScript | apache-2.0 | 2,684 |
'use strict';
(function (scope) {
/**
* Shape erased
*
* @class ShapeErased
* @extends ShapeCandidate
* @param {Object} [obj]
* @constructor
*/
function ShapeErased(obj) {
scope.ShapeCandidate.call(this, obj);
}
/**
* Inheritance property
*/
ShapeErased.prototype = new scope.ShapeCandidate();
/**
* Constructor property
*/
ShapeErased.prototype.constructor = ShapeErased;
// Export
scope.ShapeErased = ShapeErased;
})(MyScript); | countshadow/MyScriptJS | src/output/shape/shapeErased.js | JavaScript | apache-2.0 | 532 |
"use strict";
const HTMLElementImpl = require("./HTMLElement-impl").implementation;
const Document = require("../generated/Document");
const DocumentFragment = require("../generated/DocumentFragment");
const { cloningSteps, domSymbolTree } = require("../helpers/internal-constants");
const { clone } = require("../node");
class HTMLTemplateElementImpl extends HTMLElementImpl {
constructor(globalObject, args, privateData) {
super(globalObject, args, privateData);
const doc = this._appropriateTemplateContentsOwnerDocument(this._ownerDocument);
this._templateContents = DocumentFragment.createImpl(this._globalObject, [], {
ownerDocument: doc,
host: this
});
}
// https://html.spec.whatwg.org/multipage/scripting.html#appropriate-template-contents-owner-document
_appropriateTemplateContentsOwnerDocument(doc) {
if (!doc._isInertTemplateDocument) {
if (doc._associatedInertTemplateDocument === undefined) {
const newDoc = Document.createImpl(this._globalObject, [], {
options: {
parsingMode: doc._parsingMode,
encoding: doc._encoding
}
});
newDoc._isInertTemplateDocument = true;
doc._associatedInertTemplateDocument = newDoc;
}
doc = doc._associatedInertTemplateDocument;
}
return doc;
}
// https://html.spec.whatwg.org/multipage/scripting.html#template-adopting-steps
_adoptingSteps() {
const doc = this._appropriateTemplateContentsOwnerDocument(this._ownerDocument);
doc._adoptNode(this._templateContents);
}
get content() {
return this._templateContents;
}
[cloningSteps](copy, node, document, cloneChildren) {
if (!cloneChildren) {
return;
}
for (const child of domSymbolTree.childrenIterator(node._templateContents)) {
const childCopy = clone(child, copy._templateContents._ownerDocument, true);
copy._templateContents.appendChild(childCopy);
}
}
}
module.exports = {
implementation: HTMLTemplateElementImpl
};
| GoogleCloudPlatform/prometheus-engine | third_party/prometheus_ui/base/web/ui/react-app/node_modules/jsdom/lib/jsdom/living/nodes/HTMLTemplateElement-impl.js | JavaScript | apache-2.0 | 2,038 |
/*
* Copyright 2017 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.
*/
Aria.classDefinition({
$classpath : "test.aria.widgets.container.tab.focusTab.FocusTabTestCase",
$extends : "aria.jsunit.TemplateTestCase",
$prototype : {
runTemplateTest : function () {
this.templateCtxt._tpl.$focus("summaryTab");
var domElt = this.getElementById("summaryTab");
var anchor = domElt.getElementsByTagName("a")[0];
this.waitForDomEltFocus(anchor, function () {
this.templateCtxt._tpl.$focus("mapTab");
var span = this.getElementById("mapTab");
this.waitForDomEltFocus(span, this.end());
});
}
}
});
| fbasso/ariatemplates | test/aria/widgets/container/tab/focusTab/FocusTabTestCase.js | JavaScript | apache-2.0 | 1,249 |
({
L_MENU_GRID: "Valikkoruudukko",
L_MENU_ITEM_DISABLED: "%1 ei ole k\u00e4ytett\u00e4viss\u00e4",
L_MENU_ITEM_SUBMENU: "%1 (alivalikko)",
L_MENU_SUBMENU: "alivalikko",
L_MENU_CHECK: "valinta"
})
| iharkhukhrakou/XPagesExtensionLibrary | extlib/lwp/product/runtime/eclipse/plugins/com.ibm.xsp.extlib.domino/resources/web/dwa/common/nls/fi/menu.js | JavaScript | apache-2.0 | 196 |
require('should');
var option = require('..').sdk.option;
describe('option', function() {
it('can get default values', function() {
option.get('encoding').should.equal('utf8');
});
it('can set values', function() {
option.set('encoding', 'unicode');
option.get('encoding').should.equal('unicode');
option.clean();
option.get('encoding').should.equal('utf8');
option.option('encoding').should.equal('utf8');
option.option('encoding', 'unicode');
option.get('encoding').should.equal('unicode');
option.clean();
});
it('will init with some values', function() {
var o = new option.Option({foo: 'bar'});
o.get('foo').should.equal('bar');
});
it('can clean a key', function() {
var o = new option.Option({foo: 'bar'});
o.clean('foo');
o._cache.should.eql({});
});
it('can set defaults', function() {
option.defaults({
foo: {
foo: 'bar'
}
});
option.set('foo', {bar: 'foo'});
option.get('foo').should.have.ownProperty('foo');
option.get('foo').should.have.ownProperty('bar');
});
});
| thcode/nico | tests/sdk.option.test.js | JavaScript | bsd-3-clause | 1,096 |
function setSearchTextField(paramname, field) {
var passed = location.search.substring(1);
var query = getParm(passed,paramname);
var query = getParm(passed,paramname);
query = query.replace(/\+/g," ");
var loc = document.location;
if(/.*search.html/.test(loc)) {
document.title = decodeURIComponent(query) + ' - Wolfram Search';
}
field.value = decodeURIComponent(query);
}
function getParm(string,parm) {
// returns value of parm from string
var startPos = string.indexOf(parm + "=");
if (startPos > -1) {
startPos = startPos + parm.length + 1;
var endPos = string.indexOf("&",startPos);
if (endPos == -1)
endPos = string.length;
return string.substring(startPos,endPos);
}
return '';
}
| mfroeling/DTITools | docs/htmldoc/standard/javascript/search.js | JavaScript | bsd-3-clause | 723 |
'use strict';
const hljs = require('highlight.js');
const languages = hljs.listLanguages();
const fs = require('fs');
const result = {
languages: languages,
aliases: {}
};
languages.forEach(lang => {
result.aliases[lang] = lang;
const def = require('highlight.js/lib/languages/' + lang)(hljs);
const aliases = def.aliases;
if (aliases) {
aliases.forEach(alias => {
result.aliases[alias] = lang;
});
}
});
const stream = fs.createWriteStream('highlight_alias.json');
stream.write(JSON.stringify(result));
stream.on('end', () => {
stream.end();
});
| hexojs/hexo-util | scripts/build_highlight_alias.js | JavaScript | mit | 583 |
'use strict';
/*
jQuery UI Sortable plugin wrapper
@param [ui-sortable] {object} Options to pass to $.fn.sortable() merged onto ui.config
*/
angular.module('mpk').value('uiSortableConfig',{}).directive('uiSortable', [
'uiSortableConfig', '$timeout', '$log',
function(uiSortableConfig, $timeout, $log) {
return {
require: '?ngModel',
link: function(scope, element, attrs, ngModel) {
var savedNodes;
function combineCallbacks(first,second){
if(second && (typeof second === 'function')) {
return function(e, ui) {
first(e, ui);
second(e, ui);
};
}
return first;
}
var opts = {};
var callbacks = {
receive: null,
remove:null,
start:null,
stop:null,
update:null
};
angular.extend(opts, uiSortableConfig);
if (ngModel) {
// When we add or remove elements, we need the sortable to 'refresh'
// so it can find the new/removed elements.
scope.$watch(attrs.ngModel+'.length', function() {
// Timeout to let ng-repeat modify the DOM
$timeout(function() {
element.sortable('refresh');
});
});
callbacks.start = function(e, ui) {
// Save the starting position of dragged item
ui.item.sortable = {
index: ui.item.index(),
cancel: function () {
ui.item.sortable._isCanceled = true;
},
isCanceled: function () {
return ui.item.sortable._isCanceled;
},
_isCanceled: false
};
};
callbacks.activate = function(/*e, ui*/) {
// We need to make a copy of the current element's contents so
// we can restore it after sortable has messed it up.
// This is inside activate (instead of start) in order to save
// both lists when dragging between connected lists.
savedNodes = element.contents();
// If this list has a placeholder (the connected lists won't),
// don't inlcude it in saved nodes.
var placeholder = element.sortable('option','placeholder');
// placeholder.element will be a function if the placeholder, has
// been created (placeholder will be an object). If it hasn't
// been created, either placeholder will be false if no
// placeholder class was given or placeholder.element will be
// undefined if a class was given (placeholder will be a string)
if (placeholder && placeholder.element && typeof placeholder.element === 'function') {
var phElement = placeholder.element();
// workaround for jquery ui 1.9.x,
// not returning jquery collection
if (!phElement.jquery) {
phElement = angular.element(phElement);
}
// exact match with the placeholder's class attribute to handle
// the case that multiple connected sortables exist and
// the placehoilder option equals the class of sortable items
var excludes = element.find('[class="' + phElement.attr('class') + '"]');
savedNodes = savedNodes.not(excludes);
}
};
callbacks.update = function(e, ui) {
// Save current drop position but only if this is not a second
// update that happens when moving between lists because then
// the value will be overwritten with the old value
if(!ui.item.sortable.received) {
ui.item.sortable.dropindex = ui.item.index();
ui.item.sortable.droptarget = ui.item.parent();
// Cancel the sort (let ng-repeat do the sort for us)
// Don't cancel if this is the received list because it has
// already been canceled in the other list, and trying to cancel
// here will mess up the DOM.
element.sortable('cancel');
}
// Put the nodes back exactly the way they started (this is very
// important because ng-repeat uses comment elements to delineate
// the start and stop of repeat sections and sortable doesn't
// respect their order (even if we cancel, the order of the
// comments are still messed up).
savedNodes.detach();
if (element.sortable('option','helper') === 'clone') {
// first detach all the savedNodes and then restore all of them
// except .ui-sortable-helper element (which is placed last).
// That way it will be garbage collected.
savedNodes = savedNodes.not(savedNodes.last());
}
savedNodes.appendTo(element);
// If received is true (an item was dropped in from another list)
// then we add the new item to this list otherwise wait until the
// stop event where we will know if it was a sort or item was
// moved here from another list
if(ui.item.sortable.received && !ui.item.sortable.isCanceled()) {
scope.$apply(function () {
ngModel.$modelValue.splice(ui.item.sortable.dropindex, 0,
ui.item.sortable.moved);
});
}
};
callbacks.stop = function(e, ui) {
// If the received flag hasn't be set on the item, this is a
// normal sort, if dropindex is set, the item was moved, so move
// the items in the list.
if(!ui.item.sortable.received &&
('dropindex' in ui.item.sortable) &&
!ui.item.sortable.isCanceled()) {
scope.$apply(function () {
ngModel.$modelValue.splice(
ui.item.sortable.dropindex, 0,
ngModel.$modelValue.splice(ui.item.sortable.index, 1)[0]);
});
} else {
// if the item was not moved, then restore the elements
// so that the ngRepeat's comment are correct.
if((!('dropindex' in ui.item.sortable) || ui.item.sortable.isCanceled()) && element.sortable('option','helper') !== 'clone') {
savedNodes.detach().appendTo(element);
}
}
};
callbacks.receive = function(e, ui) {
// An item was dropped here from another list, set a flag on the
// item.
ui.item.sortable.received = true;
};
callbacks.remove = function(e, ui) {
// Remove the item from this list's model and copy data into item,
// so the next list can retrive it
if (!ui.item.sortable.isCanceled()) {
scope.$apply(function () {
ui.item.sortable.moved = ngModel.$modelValue.splice(
ui.item.sortable.index, 1)[0];
});
}
};
scope.$watch(attrs.uiSortable, function(newVal /*, oldVal*/) {
angular.forEach(newVal, function(value, key) {
if(callbacks[key]) {
if( key === 'stop' ){
// call apply after stop
value = combineCallbacks(
value, function() { scope.$apply(); });
}
// wrap the callback
value = combineCallbacks(callbacks[key], value);
}
element.sortable('option', key, value);
});
}, true);
angular.forEach(callbacks, function(value, key) {
opts[key] = combineCallbacks(value, opts[key]);
});
} else {
$log.info('ui.sortable: ngModel not provided!', element);
}
// Create sortable
element.sortable(opts);
}
};
}
]);
| mabotech/maboss-admin | public/kanban/scripts/directives/sortable.js | JavaScript | mit | 8,434 |
$(document).ready(function() {
var a, b, c, d, e, col, otherCol;
module("Backbone.Collection", {
setup: function() {
a = new Backbone.Model({id: 3, label: 'a'});
b = new Backbone.Model({id: 2, label: 'b'});
c = new Backbone.Model({id: 1, label: 'c'});
d = new Backbone.Model({id: 0, label: 'd'});
e = null;
col = new Backbone.Collection([a,b,c,d]);
otherCol = new Backbone.Collection();
}
});
test("new and sort", 9, function() {
var counter = 0;
col.on('sort', function(){ counter++; });
equal(col.first(), a, "a should be first");
equal(col.last(), d, "d should be last");
col.comparator = function(a, b) {
return a.id > b.id ? -1 : 1;
};
col.sort();
equal(counter, 1);
equal(col.first(), a, "a should be first");
equal(col.last(), d, "d should be last");
col.comparator = function(model) { return model.id; };
col.sort();
equal(counter, 2);
equal(col.first(), d, "d should be first");
equal(col.last(), a, "a should be last");
equal(col.length, 4);
});
test("String comparator.", 1, function() {
var collection = new Backbone.Collection([
{id: 3},
{id: 1},
{id: 2}
], {comparator: 'id'});
deepEqual(collection.pluck('id'), [1, 2, 3]);
});
test("new and parse", 3, function() {
var Collection = Backbone.Collection.extend({
parse : function(data) {
return _.filter(data, function(datum) {
return datum.a % 2 === 0;
});
}
});
var models = [{a: 1}, {a: 2}, {a: 3}, {a: 4}];
var collection = new Collection(models, {parse: true});
strictEqual(collection.length, 2);
strictEqual(collection.first().get('a'), 2);
strictEqual(collection.last().get('a'), 4);
});
test("get", 6, function() {
equal(col.get(0), d);
equal(col.get(d.clone()), d);
equal(col.get(2), b);
equal(col.get({id: 1}), c);
equal(col.get(c.clone()), c);
equal(col.get(col.first().cid), col.first());
});
test("get with non-default ids", 5, function() {
var col = new Backbone.Collection();
var MongoModel = Backbone.Model.extend({idAttribute: '_id'});
var model = new MongoModel({_id: 100});
col.add(model);
equal(col.get(100), model);
equal(col.get(model.cid), model);
equal(col.get(model), model);
equal(col.get(101), void 0);
var col2 = new Backbone.Collection();
col2.model = MongoModel;
col2.add(model.attributes);
equal(col2.get(model.clone()), col2.first());
});
test("update index when id changes", 4, function() {
var col = new Backbone.Collection();
col.add([
{id : 0, name : 'one'},
{id : 1, name : 'two'}
]);
var one = col.get(0);
equal(one.get('name'), 'one');
col.on('change:name', function (model) { ok(this.get(model)); });
one.set({name: 'dalmatians', id : 101});
equal(col.get(0), null);
equal(col.get(101).get('name'), 'dalmatians');
});
test("at", 1, function() {
equal(col.at(2), c);
});
test("pluck", 1, function() {
equal(col.pluck('label').join(' '), 'a b c d');
});
test("add", 10, function() {
var added, opts, secondAdded;
added = opts = secondAdded = null;
e = new Backbone.Model({id: 10, label : 'e'});
otherCol.add(e);
otherCol.on('add', function() {
secondAdded = true;
});
col.on('add', function(model, collection, options){
added = model.get('label');
opts = options;
});
col.add(e, {amazing: true});
equal(added, 'e');
equal(col.length, 5);
equal(col.last(), e);
equal(otherCol.length, 1);
equal(secondAdded, null);
ok(opts.amazing);
var f = new Backbone.Model({id: 20, label : 'f'});
var g = new Backbone.Model({id: 21, label : 'g'});
var h = new Backbone.Model({id: 22, label : 'h'});
var atCol = new Backbone.Collection([f, g, h]);
equal(atCol.length, 3);
atCol.add(e, {at: 1});
equal(atCol.length, 4);
equal(atCol.at(1), e);
equal(atCol.last(), h);
});
test("add multiple models", 6, function() {
var col = new Backbone.Collection([{at: 0}, {at: 1}, {at: 9}]);
col.add([{at: 2}, {at: 3}, {at: 4}, {at: 5}, {at: 6}, {at: 7}, {at: 8}], {at: 2});
for (var i = 0; i <= 5; i++) {
equal(col.at(i).get('at'), i);
}
});
test("add; at should have preference over comparator", 1, function() {
var Col = Backbone.Collection.extend({
comparator: function(a,b) {
return a.id > b.id ? -1 : 1;
}
});
var col = new Col([{id: 2}, {id: 3}]);
col.add(new Backbone.Model({id: 1}), {at: 1});
equal(col.pluck('id').join(' '), '3 1 2');
});
test("can't add model to collection twice", function() {
var col = new Backbone.Collection([{id: 1}, {id: 2}, {id: 1}, {id: 2}, {id: 3}]);
equal(col.pluck('id').join(' '), '1 2 3');
});
test("can't add different model with same id to collection twice", 1, function() {
var col = new Backbone.Collection;
col.unshift({id: 101});
col.add({id: 101});
equal(col.length, 1);
});
test("merge in duplicate models with {merge: true}", 3, function() {
var col = new Backbone.Collection;
col.add([{id: 1, name: 'Moe'}, {id: 2, name: 'Curly'}, {id: 3, name: 'Larry'}]);
col.add({id: 1, name: 'Moses'});
equal(col.first().get('name'), 'Moe');
col.add({id: 1, name: 'Moses'}, {merge: true});
equal(col.first().get('name'), 'Moses');
col.add({id: 1, name: 'Tim'}, {merge: true, silent: true});
equal(col.first().get('name'), 'Tim');
});
test("add model to multiple collections", 10, function() {
var counter = 0;
var e = new Backbone.Model({id: 10, label : 'e'});
e.on('add', function(model, collection) {
counter++;
equal(e, model);
if (counter > 1) {
equal(collection, colF);
} else {
equal(collection, colE);
}
});
var colE = new Backbone.Collection([]);
colE.on('add', function(model, collection) {
equal(e, model);
equal(colE, collection);
});
var colF = new Backbone.Collection([]);
colF.on('add', function(model, collection) {
equal(e, model);
equal(colF, collection);
});
colE.add(e);
equal(e.collection, colE);
colF.add(e);
equal(e.collection, colE);
});
test("add model with parse", 1, function() {
var Model = Backbone.Model.extend({
parse: function(obj) {
obj.value += 1;
return obj;
}
});
var Col = Backbone.Collection.extend({model: Model});
var col = new Col;
col.add({value: 1}, {parse: true});
equal(col.at(0).get('value'), 2);
});
test("add with parse and merge", function() {
var Model = Backbone.Model.extend({
parse: function (data) {
return data.model;
}
});
var collection = new Backbone.Collection();
collection.model = Model;
collection.add({id: 1});
collection.add({model: {id: 1, name: 'Alf'}}, {parse: true, merge: true});
equal(collection.first().get('name'), 'Alf');
});
test("add model to collection with sort()-style comparator", 3, function() {
var col = new Backbone.Collection;
col.comparator = function(a, b) {
return a.get('name') < b.get('name') ? -1 : 1;
};
var tom = new Backbone.Model({name: 'Tom'});
var rob = new Backbone.Model({name: 'Rob'});
var tim = new Backbone.Model({name: 'Tim'});
col.add(tom);
col.add(rob);
col.add(tim);
equal(col.indexOf(rob), 0);
equal(col.indexOf(tim), 1);
equal(col.indexOf(tom), 2);
});
test("comparator that depends on `this`", 2, function() {
var col = new Backbone.Collection;
col.negative = function(num) {
return -num;
};
col.comparator = function(a) {
return this.negative(a.id);
};
col.add([{id: 1}, {id: 2}, {id: 3}]);
deepEqual(col.pluck('id'), [3, 2, 1]);
col.comparator = function(a, b) {
return this.negative(b.id) - this.negative(a.id);
};
col.sort();
deepEqual(col.pluck('id'), [1, 2, 3]);
});
test("remove", 5, function() {
var removed = null;
var otherRemoved = null;
col.on('remove', function(model, col, options) {
removed = model.get('label');
equal(options.index, 3);
});
otherCol.on('remove', function(model, col, options) {
otherRemoved = true;
});
col.remove(d);
equal(removed, 'd');
equal(col.length, 3);
equal(col.first(), a);
equal(otherRemoved, null);
});
test("shift and pop", 2, function() {
var col = new Backbone.Collection([{a: 'a'}, {b: 'b'}, {c: 'c'}]);
equal(col.shift().get('a'), 'a');
equal(col.pop().get('c'), 'c');
});
test("slice", 2, function() {
var col = new Backbone.Collection([{a: 'a'}, {b: 'b'}, {c: 'c'}]);
var array = col.slice(1, 3);
equal(array.length, 2);
equal(array[0].get('b'), 'b');
});
test("events are unbound on remove", 3, function() {
var counter = 0;
var dj = new Backbone.Model();
var emcees = new Backbone.Collection([dj]);
emcees.on('change', function(){ counter++; });
dj.set({name : 'Kool'});
equal(counter, 1);
emcees.reset([]);
equal(dj.collection, undefined);
dj.set({name : 'Shadow'});
equal(counter, 1);
});
test("remove in multiple collections", 7, function() {
var modelData = {
id : 5,
title : 'Othello'
};
var passed = false;
var e = new Backbone.Model(modelData);
var f = new Backbone.Model(modelData);
f.on('remove', function() {
passed = true;
});
var colE = new Backbone.Collection([e]);
var colF = new Backbone.Collection([f]);
ok(e != f);
ok(colE.length === 1);
ok(colF.length === 1);
colE.remove(e);
equal(passed, false);
ok(colE.length === 0);
colF.remove(e);
ok(colF.length === 0);
equal(passed, true);
});
test("remove same model in multiple collection", 16, function() {
var counter = 0;
var e = new Backbone.Model({id: 5, title: 'Othello'});
e.on('remove', function(model, collection) {
counter++;
equal(e, model);
if (counter > 1) {
equal(collection, colE);
} else {
equal(collection, colF);
}
});
var colE = new Backbone.Collection([e]);
colE.on('remove', function(model, collection) {
equal(e, model);
equal(colE, collection);
});
var colF = new Backbone.Collection([e]);
colF.on('remove', function(model, collection) {
equal(e, model);
equal(colF, collection);
});
equal(colE, e.collection);
colF.remove(e);
ok(colF.length === 0);
ok(colE.length === 1);
equal(counter, 1);
equal(colE, e.collection);
colE.remove(e);
equal(null, e.collection);
ok(colE.length === 0);
equal(counter, 2);
});
test("model destroy removes from all collections", 3, function() {
var e = new Backbone.Model({id: 5, title: 'Othello'});
e.sync = function(method, model, options) { options.success(); };
var colE = new Backbone.Collection([e]);
var colF = new Backbone.Collection([e]);
e.destroy();
ok(colE.length === 0);
ok(colF.length === 0);
equal(undefined, e.collection);
});
test("Colllection: non-persisted model destroy removes from all collections", 3, function() {
var e = new Backbone.Model({title: 'Othello'});
e.sync = function(method, model, options) { throw "should not be called"; };
var colE = new Backbone.Collection([e]);
var colF = new Backbone.Collection([e]);
e.destroy();
ok(colE.length === 0);
ok(colF.length === 0);
equal(undefined, e.collection);
});
test("fetch", 4, function() {
var collection = new Backbone.Collection;
collection.url = '/test';
collection.fetch();
equal(this.syncArgs.method, 'read');
equal(this.syncArgs.model, collection);
equal(this.syncArgs.options.parse, true);
collection.fetch({parse: false});
equal(this.syncArgs.options.parse, false);
});
test("fetch with an error response triggers an error event", 1, function () {
var collection = new Backbone.Collection();
collection.on('error', function () {
ok(true);
});
collection.sync = function (method, model, options) { options.error(); };
collection.fetch();
});
test("ensure fetch only parses once", 1, function() {
var collection = new Backbone.Collection;
var counter = 0;
collection.parse = function(models) {
counter++;
return models;
};
collection.url = '/test';
collection.fetch();
this.syncArgs.options.success();
equal(counter, 1);
});
test("create", 4, function() {
var collection = new Backbone.Collection;
collection.url = '/test';
var model = collection.create({label: 'f'}, {wait: true});
equal(this.syncArgs.method, 'create');
equal(this.syncArgs.model, model);
equal(model.get('label'), 'f');
equal(model.collection, collection);
});
test("create with validate:true enforces validation", 2, function() {
var ValidatingModel = Backbone.Model.extend({
validate: function(attrs) {
return "fail";
}
});
var ValidatingCollection = Backbone.Collection.extend({
model: ValidatingModel
});
var col = new ValidatingCollection();
col.on('invalid', function (collection, attrs, options) {
equal(options.validationError, 'fail');
});
equal(col.create({"foo":"bar"}, {validate:true}), false);
});
test("a failing create returns model with errors", function() {
var ValidatingModel = Backbone.Model.extend({
validate: function(attrs) {
return "fail";
}
});
var ValidatingCollection = Backbone.Collection.extend({
model: ValidatingModel
});
var col = new ValidatingCollection();
var m = col.create({"foo":"bar"});
equal(m.validationError, 'fail');
equal(col.length, 1);
});
test("initialize", 1, function() {
var Collection = Backbone.Collection.extend({
initialize: function() {
this.one = 1;
}
});
var coll = new Collection;
equal(coll.one, 1);
});
test("toJSON", 1, function() {
equal(JSON.stringify(col), '[{"id":3,"label":"a"},{"id":2,"label":"b"},{"id":1,"label":"c"},{"id":0,"label":"d"}]');
});
test("where and findWhere", 8, function() {
var model = new Backbone.Model({a: 1});
var coll = new Backbone.Collection([
model,
{a: 1},
{a: 1, b: 2},
{a: 2, b: 2},
{a: 3}
]);
equal(coll.where({a: 1}).length, 3);
equal(coll.where({a: 2}).length, 1);
equal(coll.where({a: 3}).length, 1);
equal(coll.where({b: 1}).length, 0);
equal(coll.where({b: 2}).length, 2);
equal(coll.where({a: 1, b: 2}).length, 1);
equal(coll.findWhere({a: 1}), model);
equal(coll.findWhere({a: 4}), void 0);
});
test("Underscore methods", 14, function() {
equal(col.map(function(model){ return model.get('label'); }).join(' '), 'a b c d');
equal(col.any(function(model){ return model.id === 100; }), false);
equal(col.any(function(model){ return model.id === 0; }), true);
equal(col.indexOf(b), 1);
equal(col.size(), 4);
equal(col.rest().length, 3);
ok(!_.include(col.rest(), a));
ok(_.include(col.rest(), d));
ok(!col.isEmpty());
ok(!_.include(col.without(d), d));
equal(col.max(function(model){ return model.id; }).id, 3);
equal(col.min(function(model){ return model.id; }).id, 0);
deepEqual(col.chain()
.filter(function(o){ return o.id % 2 === 0; })
.map(function(o){ return o.id * 2; })
.value(),
[4, 0]);
deepEqual(col.difference([c, d]), [a, b]);
});
test("sortedIndex", function () {
var model = new Backbone.Model({key: 2});
var collection = new (Backbone.Collection.extend({
comparator: 'key'
}))([model, {key: 1}]);
equal(collection.sortedIndex(model), 1);
equal(collection.sortedIndex(model, 'key'), 1);
equal(collection.sortedIndex(model, function (model) {
return model.get('key');
}), 1);
});
test("reset", 12, function() {
var resetCount = 0;
var models = col.models;
col.on('reset', function() { resetCount += 1; });
col.reset([]);
equal(resetCount, 1);
equal(col.length, 0);
equal(col.last(), null);
col.reset(models);
equal(resetCount, 2);
equal(col.length, 4);
equal(col.last(), d);
col.reset(_.map(models, function(m){ return m.attributes; }));
equal(resetCount, 3);
equal(col.length, 4);
ok(col.last() !== d);
ok(_.isEqual(col.last().attributes, d.attributes));
col.reset();
equal(col.length, 0);
equal(resetCount, 4);
});
test ("reset with different values", function(){
var col = new Backbone.Collection({id: 1});
col.reset({id: 1, a: 1});
equal(col.get(1).get('a'), 1);
});
test("same references in reset", function() {
var model = new Backbone.Model({id: 1});
var collection = new Backbone.Collection({id: 1});
collection.reset(model);
equal(collection.get(1), model);
});
test("reset passes caller options", 3, function() {
var Model = Backbone.Model.extend({
initialize: function(attrs, options) {
this.model_parameter = options.model_parameter;
}
});
var col = new (Backbone.Collection.extend({ model: Model }))();
col.reset([{ astring: "green", anumber: 1 }, { astring: "blue", anumber: 2 }], { model_parameter: 'model parameter' });
equal(col.length, 2);
col.each(function(model) {
equal(model.model_parameter, 'model parameter');
});
});
test("trigger custom events on models", 1, function() {
var fired = null;
a.on("custom", function() { fired = true; });
a.trigger("custom");
equal(fired, true);
});
test("add does not alter arguments", 2, function(){
var attrs = {};
var models = [attrs];
new Backbone.Collection().add(models);
equal(models.length, 1);
ok(attrs === models[0]);
});
test("#714: access `model.collection` in a brand new model.", 2, function() {
var collection = new Backbone.Collection;
collection.url = '/test';
var Model = Backbone.Model.extend({
set: function(attrs) {
equal(attrs.prop, 'value');
equal(this.collection, collection);
return this;
}
});
collection.model = Model;
collection.create({prop: 'value'});
});
test("#574, remove its own reference to the .models array.", 2, function() {
var col = new Backbone.Collection([
{id: 1}, {id: 2}, {id: 3}, {id: 4}, {id: 5}, {id: 6}
]);
equal(col.length, 6);
col.remove(col.models);
equal(col.length, 0);
});
test("#861, adding models to a collection which do not pass validation, with validate:true", function() {
var Model = Backbone.Model.extend({
validate: function(attrs) {
if (attrs.id == 3) return "id can't be 3";
}
});
var Collection = Backbone.Collection.extend({
model: Model
});
var collection = new Collection;
collection.on("error", function() { ok(true); });
collection.add([{id: 1}, {id: 2}, {id: 3}, {id: 4}, {id: 5}, {id: 6}], {validate:true});
deepEqual(collection.pluck('id'), [1, 2, 4, 5, 6]);
});
test("Invalid models are discarded with validate:true.", 5, function() {
var collection = new Backbone.Collection;
collection.on('test', function() { ok(true); });
collection.model = Backbone.Model.extend({
validate: function(attrs){ if (!attrs.valid) return 'invalid'; }
});
var model = new collection.model({id: 1, valid: true});
collection.add([model, {id: 2}], {validate:true});
model.trigger('test');
ok(collection.get(model.cid));
ok(collection.get(1));
ok(!collection.get(2));
equal(collection.length, 1);
});
test("multiple copies of the same model", 3, function() {
var col = new Backbone.Collection();
var model = new Backbone.Model();
col.add([model, model]);
equal(col.length, 1);
col.add([{id: 1}, {id: 1}]);
equal(col.length, 2);
equal(col.last().id, 1);
});
test("#964 - collection.get return inconsistent", 2, function() {
var c = new Backbone.Collection();
ok(c.get(null) === undefined);
ok(c.get() === undefined);
});
test("#1112 - passing options.model sets collection.model", 2, function() {
var Model = Backbone.Model.extend({});
var c = new Backbone.Collection([{id: 1}], {model: Model});
ok(c.model === Model);
ok(c.at(0) instanceof Model);
});
test("null and undefined are invalid ids.", 2, function() {
var model = new Backbone.Model({id: 1});
var collection = new Backbone.Collection([model]);
model.set({id: null});
ok(!collection.get('null'));
model.set({id: 1});
model.set({id: undefined});
ok(!collection.get('undefined'));
});
test("falsy comparator", 4, function(){
var Col = Backbone.Collection.extend({
comparator: function(model){ return model.id; }
});
var col = new Col();
var colFalse = new Col(null, {comparator: false});
var colNull = new Col(null, {comparator: null});
var colUndefined = new Col(null, {comparator: undefined});
ok(col.comparator);
ok(!colFalse.comparator);
ok(!colNull.comparator);
ok(colUndefined.comparator);
});
test("#1355 - `options` is passed to success callbacks", 2, function(){
var m = new Backbone.Model({x:1});
var col = new Backbone.Collection();
var opts = {
success: function(collection, resp, options){
ok(options);
}
};
col.sync = m.sync = function( method, collection, options ){
options.success(collection, [], options);
};
col.fetch(opts);
col.create(m, opts);
});
test("#1412 - Trigger 'request' and 'sync' events.", 4, function() {
var collection = new Backbone.Collection;
collection.url = '/test';
Backbone.ajax = function(settings){ settings.success(); };
collection.on('request', function(obj, xhr, options) {
ok(obj === collection, "collection has correct 'request' event after fetching");
});
collection.on('sync', function(obj, response, options) {
ok(obj === collection, "collection has correct 'sync' event after fetching");
});
collection.fetch();
collection.off();
collection.on('request', function(obj, xhr, options) {
ok(obj === collection.get(1), "collection has correct 'request' event after one of its models save");
});
collection.on('sync', function(obj, response, options) {
ok(obj === collection.get(1), "collection has correct 'sync' event after one of its models save");
});
collection.create({id: 1});
collection.off();
});
test("#1447 - create with wait adds model.", 1, function() {
var collection = new Backbone.Collection;
var model = new Backbone.Model;
model.sync = function(method, model, options){ options.success(); };
collection.on('add', function(){ ok(true); });
collection.create(model, {wait: true});
});
test("#1448 - add sorts collection after merge.", 1, function() {
var collection = new Backbone.Collection([
{id: 1, x: 1},
{id: 2, x: 2}
]);
collection.comparator = function(model){ return model.get('x'); };
collection.add({id: 1, x: 3}, {merge: true});
deepEqual(collection.pluck('id'), [2, 1]);
});
test("#1655 - groupBy can be used with a string argument.", 3, function() {
var collection = new Backbone.Collection([{x: 1}, {x: 2}]);
var grouped = collection.groupBy('x');
strictEqual(_.keys(grouped).length, 2);
strictEqual(grouped[1][0].get('x'), 1);
strictEqual(grouped[2][0].get('x'), 2);
});
test("#1655 - sortBy can be used with a string argument.", 1, function() {
var collection = new Backbone.Collection([{x: 3}, {x: 1}, {x: 2}]);
var values = _.map(collection.sortBy('x'), function(model) {
return model.get('x');
});
deepEqual(values, [1, 2, 3]);
});
test("#1604 - Removal during iteration.", 0, function() {
var collection = new Backbone.Collection([{}, {}]);
collection.on('add', function() {
collection.at(0).destroy();
});
collection.add({}, {at: 0});
});
test("#1638 - `sort` during `add` triggers correctly.", function() {
var collection = new Backbone.Collection;
collection.comparator = function(model) { return model.get('x'); };
var added = [];
collection.on('add', function(model) {
model.set({x: 3});
collection.sort();
added.push(model.id);
});
collection.add([{id: 1, x: 1}, {id: 2, x: 2}]);
deepEqual(added, [1, 2]);
});
test("fetch parses models by default", 1, function() {
var model = {};
var Collection = Backbone.Collection.extend({
url: 'test',
model: Backbone.Model.extend({
parse: function(resp) {
strictEqual(resp, model);
}
})
});
new Collection().fetch();
this.ajaxSettings.success([model]);
});
test("`sort` shouldn't always fire on `add`", 1, function() {
var c = new Backbone.Collection([{id: 1}, {id: 2}, {id: 3}], {
comparator: 'id'
});
c.sort = function(){ ok(true); };
c.add([]);
c.add({id: 1});
c.add([{id: 2}, {id: 3}]);
c.add({id: 4});
});
test("#1407 parse option on constructor parses collection and models", 2, function() {
var model = {
namespace : [{id: 1}, {id:2}]
};
var Collection = Backbone.Collection.extend({
model: Backbone.Model.extend({
parse: function(model) {
model.name = 'test';
return model;
}
}),
parse: function(model) {
return model.namespace;
}
});
var c = new Collection(model, {parse:true});
equal(c.length, 2);
equal(c.at(0).get('name'), 'test');
});
test("#1407 parse option on reset parses collection and models", 2, function() {
var model = {
namespace : [{id: 1}, {id:2}]
};
var Collection = Backbone.Collection.extend({
model: Backbone.Model.extend({
parse: function(model) {
model.name = 'test';
return model;
}
}),
parse: function(model) {
return model.namespace;
}
});
var c = new Collection();
c.reset(model, {parse:true});
equal(c.length, 2);
equal(c.at(0).get('name'), 'test');
});
test("Reset includes previous models in triggered event.", 1, function() {
var model = new Backbone.Model();
var collection = new Backbone.Collection([model])
.on('reset', function(collection, options) {
deepEqual(options.previousModels, [model]);
});
collection.reset([]);
});
test("set", function() {
var m1 = new Backbone.Model();
var m2 = new Backbone.Model({id: 2});
var m3 = new Backbone.Model();
var c = new Backbone.Collection([m1, m2]);
// Test add/change/remove events
c.on('add', function(model) {
strictEqual(model, m3);
});
c.on('change', function(model) {
strictEqual(model, m2);
});
c.on('remove', function(model) {
strictEqual(model, m1);
});
// remove: false doesn't remove any models
c.set([], {remove: false});
strictEqual(c.length, 2);
// add: false doesn't add any models
c.set([m1, m2, m3], {add: false});
strictEqual(c.length, 2);
// merge: false doesn't change any models
c.set([m1, {id: 2, a: 1}], {merge: false});
strictEqual(m2.get('a'), void 0);
// add: false, remove: false only merges existing models
c.set([m1, {id: 2, a: 0}, m3, {id: 4}], {add: false, remove: false});
strictEqual(c.length, 2);
strictEqual(m2.get('a'), 0);
// default options add/remove/merge as appropriate
c.set([{id: 2, a: 1}, m3]);
strictEqual(c.length, 2);
strictEqual(m2.get('a'), 1);
// Test removing models not passing an argument
c.off('remove').on('remove', function(model) {
ok(model === m2 || model === m3);
});
c.set([]);
strictEqual(c.length, 0);
});
test("set with only cids", 3, function() {
var m1 = new Backbone.Model;
var m2 = new Backbone.Model;
var c = new Backbone.Collection;
c.set([m1, m2]);
equal(c.length, 2);
c.set([m1]);
equal(c.length, 1);
c.set([m1, m1, m1, m2, m2], {remove: false});
equal(c.length, 2);
});
test("set with only idAttribute", 3, function() {
var m1 = { _id: 1 };
var m2 = { _id: 2 };
var col = Backbone.Collection.extend({
model: Backbone.Model.extend({
idAttribute: '_id'
})
});
var c = new col;
c.set([m1, m2]);
equal(c.length, 2);
c.set([m1]);
equal(c.length, 1);
c.set([m1, m1, m1, m2, m2], {remove: false});
equal(c.length, 2);
});
test("set + merge with default values defined", function() {
var Model = Backbone.Model.extend({
defaults: {
key: 'value'
}
});
var m = new Model({id: 1});
var col = new Backbone.Collection([m], {model: Model});
equal(col.first().get('key'), 'value');
col.set({id: 1, key: 'other'});
equal(col.first().get('key'), 'other');
col.set({id: 1, other: 'value'});
equal(col.first().get('key'), 'other');
equal(col.length, 1);
});
test('merge without mutation', function () {
var Model = Backbone.Model.extend({
initialize: function (attrs, options) {
if (attrs.child) {
this.set('child', new Model(attrs.child, options), options);
}
}
});
var Collection = Backbone.Collection.extend({model: Model});
var data = [{id: 1, child: {id: 2}}];
var collection = new Collection(data);
equal(collection.first().id, 1);
collection.set(data);
equal(collection.first().id, 1);
collection.set([{id: 2, child: {id: 2}}].concat(data));
deepEqual(collection.pluck('id'), [2, 1]);
});
test("`set` and model level `parse`", function() {
var Model = Backbone.Model.extend({
parse: function (res) { return res.model; }
});
var Collection = Backbone.Collection.extend({
model: Model,
parse: function (res) { return res.models; }
});
var model = new Model({id: 1});
var collection = new Collection(model);
collection.set({models: [
{model: {id: 1}},
{model: {id: 2}}
]}, {parse: true});
equal(collection.first(), model);
});
test("`set` data is only parsed once", function() {
var collection = new Backbone.Collection();
collection.model = Backbone.Model.extend({
parse: function (data) {
equal(data.parsed, void 0);
data.parsed = true;
return data;
}
});
collection.set({}, {parse: true});
});
test('`set` matches input order in the absence of a comparator', function () {
var one = new Backbone.Model({id: 1});
var two = new Backbone.Model({id: 2});
var three = new Backbone.Model({id: 3});
var collection = new Backbone.Collection([one, two, three]);
collection.set([{id: 3}, {id: 2}, {id: 1}]);
deepEqual(collection.models, [three, two, one]);
collection.set([{id: 1}, {id: 2}]);
deepEqual(collection.models, [one, two]);
collection.set([two, three, one]);
deepEqual(collection.models, [two, three, one]);
collection.set([{id: 1}, {id: 2}], {remove: false});
deepEqual(collection.models, [two, three, one]);
collection.set([{id: 1}, {id: 2}, {id: 3}], {merge: false});
deepEqual(collection.models, [one, two, three]);
collection.set([three, two, one, {id: 4}], {add: false});
deepEqual(collection.models, [one, two, three]);
});
test("#1894 - Push should not trigger a sort", 0, function() {
var Collection = Backbone.Collection.extend({
comparator: 'id',
sort: function() {
ok(false);
}
});
new Collection().push({id: 1});
});
test("`set` with non-normal id", function() {
var Collection = Backbone.Collection.extend({
model: Backbone.Model.extend({idAttribute: '_id'})
});
var collection = new Collection({_id: 1});
collection.set([{_id: 1, a: 1}], {add: false});
equal(collection.first().get('a'), 1);
});
test("#1894 - `sort` can optionally be turned off", 0, function() {
var Collection = Backbone.Collection.extend({
comparator: 'id',
sort: function() { ok(true); }
});
new Collection().add({id: 1}, {sort: false});
});
test("#1915 - `parse` data in the right order in `set`", function() {
var collection = new (Backbone.Collection.extend({
parse: function (data) {
strictEqual(data.status, 'ok');
return data.data;
}
}));
var res = {status: 'ok', data:[{id: 1}]};
collection.set(res, {parse: true});
});
asyncTest("#1939 - `parse` is passed `options`", 1, function () {
var collection = new (Backbone.Collection.extend({
url: '/',
parse: function (data, options) {
strictEqual(options.xhr.someHeader, 'headerValue');
return data;
}
}));
var ajax = Backbone.ajax;
Backbone.ajax = function (params) {
_.defer(params.success);
return {someHeader: 'headerValue'};
};
collection.fetch({
success: function () { start(); }
});
Backbone.ajax = ajax;
});
test("`add` only `sort`s when necessary", 2, function () {
var collection = new (Backbone.Collection.extend({
comparator: 'a'
}))([{id: 1}, {id: 2}, {id: 3}]);
collection.on('sort', function () { ok(true); });
collection.add({id: 4}); // do sort, new model
collection.add({id: 1, a: 1}, {merge: true}); // do sort, comparator change
collection.add({id: 1, b: 1}, {merge: true}); // don't sort, no comparator change
collection.add({id: 1, a: 1}, {merge: true}); // don't sort, no comparator change
collection.add(collection.models); // don't sort, nothing new
collection.add(collection.models, {merge: true}); // don't sort
});
test("`add` only `sort`s when necessary with comparator function", 3, function () {
var collection = new (Backbone.Collection.extend({
comparator: function(a, b) {
return a.get('a') > b.get('a') ? 1 : (a.get('a') < b.get('a') ? -1 : 0);
}
}))([{id: 1}, {id: 2}, {id: 3}]);
collection.on('sort', function () { ok(true); });
collection.add({id: 4}); // do sort, new model
collection.add({id: 1, a: 1}, {merge: true}); // do sort, model change
collection.add({id: 1, b: 1}, {merge: true}); // do sort, model change
collection.add({id: 1, a: 1}, {merge: true}); // don't sort, no model change
collection.add(collection.models); // don't sort, nothing new
collection.add(collection.models, {merge: true}); // don't sort
});
test("Attach options to collection.", 2, function() {
var model = new Backbone.Model;
var comparator = function(){};
var collection = new Backbone.Collection([], {
model: model,
comparator: comparator
});
ok(collection.model === model);
ok(collection.comparator === comparator);
});
test("`add` overrides `set` flags", function () {
var collection = new Backbone.Collection();
collection.once('add', function (model, collection, options) {
collection.add({id: 2}, options);
});
collection.set({id: 1});
equal(collection.length, 2);
});
test("#2606 - Collection#create, success arguments", 1, function() {
var collection = new Backbone.Collection;
collection.url = 'test';
collection.create({}, {
success: function(model, resp, options) {
strictEqual(resp, 'response');
}
});
this.ajaxSettings.success('response');
});
});
| wakanpaladin/mybackbone | test/collection.js | JavaScript | mit | 35,957 |
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const app_utils_1 = require("../../utilities/app-utils");
const dynamic_path_parser_1 = require("../../utilities/dynamic-path-parser");
const config_1 = require("../../models/config");
const stringUtils = require('ember-cli-string-utils');
const Blueprint = require('../../ember-cli/lib/models/blueprint');
const getFiles = Blueprint.prototype.files;
exports.default = Blueprint.extend({
name: 'class',
description: '',
aliases: ['cl'],
availableOptions: [
{
name: 'spec',
type: Boolean,
description: 'Specifies if a spec file is generated.'
},
{
name: 'app',
type: String,
aliases: ['a'],
description: 'Specifies app name to use.'
}
],
normalizeEntityName: function (entityName) {
const appConfig = app_utils_1.getAppFromConfig(this.options.app);
const parsedPath = dynamic_path_parser_1.dynamicPathParser(this.project, entityName.split('.')[0], appConfig);
this.dynamicPath = parsedPath;
return parsedPath.name;
},
locals: function (options) {
const rawName = options.args[1];
const nameParts = rawName.split('.')
.filter(part => part.length !== 0);
const classType = nameParts[1];
this.fileName = stringUtils.dasherize(options.entity.name);
if (classType) {
this.fileName += '.' + classType.toLowerCase();
}
options.spec = options.spec !== undefined ?
options.spec : config_1.CliConfig.getValue('defaults.class.spec');
return {
dynamicPath: this.dynamicPath.dir,
flat: options.flat,
fileName: this.fileName
};
},
files: function () {
let fileList = getFiles.call(this);
if (this.options && !this.options.spec) {
fileList = fileList.filter(p => p.indexOf('__name__.spec.ts') < 0);
}
return fileList;
},
fileMapTokens: function () {
// Return custom template variables here.
return {
__path__: () => {
this.generatePath = this.dynamicPath.dir;
return this.generatePath;
},
__name__: () => {
return this.fileName;
}
};
}
});
//# sourceMappingURL=/users/hans/sources/angular-cli/blueprints/class/index.js.map | raymonddavis/Angular-SailsJs-SocketIo | web/node_modules/@angular/cli/blueprints/class/index.js | JavaScript | mit | 2,492 |
'use strict';
var path = require('path');
var fixtures = require('haraka-test-fixtures');
var Connection = fixtures.connection;
var Plugin = fixtures.plugin;
var _set_up = function(done) {
this.backup = {};
// needed for tests
this.plugin = new Plugin('auth/auth_vpopmaild');
this.plugin.inherits('auth/auth_base');
// reset the config/root_path
this.plugin.config.root_path = path.resolve(__dirname, '../../../config');
this.plugin.cfg = this.plugin.config.get('auth_vpopmaild.ini');
this.connection = Connection.createConnection();
this.connection.capabilities=null;
done();
};
exports.hook_capabilities = {
setUp : _set_up,
'no TLS': function (test) {
var cb = function (rc, msg) {
test.expect(3);
test.equal(undefined, rc);
test.equal(undefined, msg);
test.equal(null, this.connection.capabilities);
test.done();
}.bind(this);
this.plugin.hook_capabilities(cb, this.connection);
},
'with TLS': function (test) {
var cb = function (rc, msg) {
test.expect(3);
test.equal(undefined, rc);
test.equal(undefined, msg);
test.ok(this.connection.capabilities.length);
// console.log(this.connection.capabilities);
test.done();
}.bind(this);
this.connection.using_tls=true;
this.connection.capabilities=[];
this.plugin.hook_capabilities(cb, this.connection);
},
'with TLS, sysadmin': function (test) {
var cb = function (rc, msg) {
test.expect(3);
test.equal(undefined, rc);
test.equal(undefined, msg);
test.ok(this.connection.capabilities.length);
// console.log(this.connection.capabilities);
test.done();
}.bind(this);
this.connection.using_tls=true;
this.connection.capabilities=[];
this.plugin.hook_capabilities(cb, this.connection);
},
};
exports.get_vpopmaild_socket = {
setUp : _set_up,
'any': function (test) {
test.expect(1);
var socket = this.plugin.get_vpopmaild_socket('[email protected]');
// console.log(socket);
test.ok(socket);
socket.end();
test.done();
}
};
exports.get_plain_passwd = {
setUp : _set_up,
'[email protected]': function (test) {
var cb = function (pass) {
test.expect(1);
test.ok(pass);
test.done();
};
if (this.plugin.cfg['example.com'].sysadmin) {
this.plugin.get_plain_passwd('[email protected]', cb);
}
else {
test.expect(0);
test.done();
}
}
};
| slattery/Haraka | tests/plugins/auth/auth_vpopmaild.js | JavaScript | mit | 2,773 |
//= require locastyle/templates/_popover.jst.eco
//= require locastyle/templates/_dropdown.jst.eco
| diegoeis/locawebstyle | source/assets/javascripts/templates.js | JavaScript | mit | 99 |
// # Mail API
// API for sending Mail
var Promise = require('bluebird'),
pipeline = require('../utils/pipeline'),
errors = require('../errors'),
mail = require('../mail'),
Models = require('../models'),
utils = require('./utils'),
notifications = require('./notifications'),
i18n = require('../i18n'),
docName = 'mail',
mailer,
apiMail;
/**
* Send mail helper
*/
function sendMail(object) {
if (!(mailer instanceof mail.GhostMailer)) {
mailer = new mail.GhostMailer();
}
return mailer.send(object.mail[0].message).catch(function (err) {
if (mailer.state.usingDirect) {
notifications.add(
{notifications: [{
type: 'warn',
message: [
i18n.t('warnings.index.unableToSendEmail'),
i18n.t('common.seeLinkForInstructions',
{link: '<a href=\'https://docs.ghost.org/v1.0.0/docs/mail-config\' target=\'_blank\'>Checkout our mail configuration docs!</a>'})
].join(' ')
}]},
{context: {internal: true}}
);
}
return Promise.reject(new errors.EmailError({err: err}));
});
}
/**
* ## Mail API Methods
*
* **See:** [API Methods](index.js.html#api%20methods)
* @typedef Mail
* @param mail
*/
apiMail = {
/**
* ### Send
* Send an email
*
* @public
* @param {Mail} object details of the email to send
* @returns {Promise}
*/
send: function (object, options) {
var tasks;
/**
* ### Format Response
* @returns {Mail} mail
*/
function formatResponse(data) {
delete object.mail[0].options;
// Sendmail returns extra details we don't need and that don't convert to JSON
delete object.mail[0].message.transport;
object.mail[0].status = {
message: data.message
};
return object;
}
/**
* ### Send Mail
*/
function send() {
return sendMail(object, options);
}
tasks = [
utils.handlePermissions(docName, 'send'),
send,
formatResponse
];
return pipeline(tasks, options || {});
},
/**
* ### SendTest
* Send a test email
*
* @public
* @param {Object} options required property 'to' which contains the recipient address
* @returns {Promise}
*/
sendTest: function (options) {
var tasks;
/**
* ### Model Query
*/
function modelQuery() {
return Models.User.findOne({id: options.context.user});
}
/**
* ### Generate content
*/
function generateContent(result) {
return mail.utils.generateContent({template: 'test'}).then(function (content) {
var payload = {
mail: [{
message: {
to: result.get('email'),
subject: i18n.t('common.api.mail.testGhostEmail'),
html: content.html,
text: content.text
}
}]
};
return payload;
});
}
/**
* ### Send mail
*/
function send(payload) {
return sendMail(payload, options);
}
tasks = [
modelQuery,
generateContent,
send
];
return pipeline(tasks);
}
};
module.exports = apiMail;
| jordanwalsh23/jordanwalsh23.github.io | core/server/api/mail.js | JavaScript | mit | 3,802 |
/**
* Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
* Build: `lodash modularize exports="amd" -o ./compat/`
* 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/baseEach', '../functions/createCallback', '../objects/isArray'], function(baseEach, createCallback, isArray) {
/**
* Creates an array of values by running each element in the collection
* through the callback. The callback is bound to `thisArg` and invoked with
* three arguments; (value, index|key, collection).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @alias collect
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Array} Returns a new array of the results of each `callback` execution.
* @example
*
* _.map([1, 2, 3], function(num) { return num * 3; });
* // => [3, 6, 9]
*
* _.map({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { return num * 3; });
* // => [3, 6, 9] (property order is not guaranteed across environments)
*
* var characters = [
* { 'name': 'barney', 'age': 36 },
* { 'name': 'fred', 'age': 40 }
* ];
*
* // using "_.pluck" callback shorthand
* _.map(characters, 'name');
* // => ['barney', 'fred']
*/
function map(collection, callback, thisArg) {
var index = -1,
length = collection ? collection.length : 0,
result = Array(typeof length == 'number' ? length : 0);
callback = createCallback(callback, thisArg, 3);
if (isArray(collection)) {
while (++index < length) {
result[index] = callback(collection[index], index, collection);
}
} else {
baseEach(collection, function(value, key, collection) {
result[++index] = callback(value, key, collection);
});
}
return result;
}
return map;
});
| john-bixly/Morsel | app/vendor/lodash-amd/compat/collections/map.js | JavaScript | mit | 2,696 |
window.Reactable = require('../build/reactable.common');
| wemcdonald/reactable | src/reactable.global.js | JavaScript | mit | 57 |
/**
* ag-grid-community - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v20.2.0
* @link http://www.ag-grid.com/
* @license MIT
*/
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
var context_1 = require("../context/context");
var logger_1 = require("../logger");
var eventService_1 = require("../eventService");
var events_1 = require("../events");
var gridOptionsWrapper_1 = require("../gridOptionsWrapper");
var columnApi_1 = require("../columnController/columnApi");
var gridApi_1 = require("../gridApi");
var utils_1 = require("../utils");
/** Adds drag listening onto an element. In ag-Grid this is used twice, first is resizing columns,
* second is moving the columns and column groups around (ie the 'drag' part of Drag and Drop. */
var DragService = /** @class */ (function () {
function DragService() {
this.onMouseUpListener = this.onMouseUp.bind(this);
this.onMouseMoveListener = this.onMouseMove.bind(this);
this.onTouchEndListener = this.onTouchUp.bind(this);
this.onTouchMoveListener = this.onTouchMove.bind(this);
this.dragEndFunctions = [];
this.dragSources = [];
}
DragService.prototype.init = function () {
this.logger = this.loggerFactory.create('DragService');
};
DragService.prototype.destroy = function () {
this.dragSources.forEach(this.removeListener.bind(this));
this.dragSources.length = 0;
};
DragService.prototype.removeListener = function (dragSourceAndListener) {
var element = dragSourceAndListener.dragSource.eElement;
var mouseDownListener = dragSourceAndListener.mouseDownListener;
element.removeEventListener('mousedown', mouseDownListener);
// remove touch listener only if it exists
if (dragSourceAndListener.touchEnabled) {
var touchStartListener = dragSourceAndListener.touchStartListener;
element.removeEventListener('touchstart', touchStartListener, { passive: true });
}
};
DragService.prototype.removeDragSource = function (params) {
var dragSourceAndListener = utils_1._.find(this.dragSources, function (item) { return item.dragSource === params; });
if (!dragSourceAndListener) {
return;
}
this.removeListener(dragSourceAndListener);
utils_1._.removeFromArray(this.dragSources, dragSourceAndListener);
};
DragService.prototype.setNoSelectToBody = function (noSelect) {
var eDocument = this.gridOptionsWrapper.getDocument();
var eBody = eDocument.querySelector('body');
if (utils_1._.exists(eBody)) {
// when we drag the mouse in ag-Grid, this class gets added / removed from the body, so that
// the mouse isn't selecting text when dragging.
utils_1._.addOrRemoveCssClass(eBody, 'ag-unselectable', noSelect);
}
};
DragService.prototype.addDragSource = function (params, includeTouch) {
if (includeTouch === void 0) { includeTouch = false; }
var mouseListener = this.onMouseDown.bind(this, params);
params.eElement.addEventListener('mousedown', mouseListener);
var touchListener = null;
var suppressTouch = this.gridOptionsWrapper.isSuppressTouch();
if (includeTouch && !suppressTouch) {
touchListener = this.onTouchStart.bind(this, params);
params.eElement.addEventListener('touchstart', touchListener, { passive: false });
}
this.dragSources.push({
dragSource: params,
mouseDownListener: mouseListener,
touchStartListener: touchListener,
touchEnabled: includeTouch
});
};
// gets called whenever mouse down on any drag source
DragService.prototype.onTouchStart = function (params, touchEvent) {
var _this = this;
this.currentDragParams = params;
this.dragging = false;
var touch = touchEvent.touches[0];
this.touchLastTime = touch;
this.touchStart = touch;
touchEvent.preventDefault();
// we temporally add these listeners, for the duration of the drag, they
// are removed in touch end handling.
params.eElement.addEventListener('touchmove', this.onTouchMoveListener, { passive: true });
params.eElement.addEventListener('touchend', this.onTouchEndListener, { passive: true });
params.eElement.addEventListener('touchcancel', this.onTouchEndListener, { passive: true });
this.dragEndFunctions.push(function () {
params.eElement.removeEventListener('touchmove', _this.onTouchMoveListener, { passive: true });
params.eElement.removeEventListener('touchend', _this.onTouchEndListener, { passive: true });
params.eElement.removeEventListener('touchcancel', _this.onTouchEndListener, { passive: true });
});
// see if we want to start dragging straight away
if (params.dragStartPixels === 0) {
this.onCommonMove(touch, this.touchStart);
}
};
// gets called whenever mouse down on any drag source
DragService.prototype.onMouseDown = function (params, mouseEvent) {
var _this = this;
// we ignore when shift key is pressed. this is for the range selection, as when
// user shift-clicks a cell, this should not be interpreted as the start of a drag.
// if (mouseEvent.shiftKey) { return; }
if (params.skipMouseEvent) {
if (params.skipMouseEvent(mouseEvent)) {
return;
}
}
// if there are two elements with parent / child relationship, and both are draggable,
// when we drag the child, we should NOT drag the parent. an example of this is row moving
// and range selection - row moving should get preference when use drags the rowDrag component.
if (mouseEvent._alreadyProcessedByDragService) {
return;
}
mouseEvent._alreadyProcessedByDragService = true;
// only interested in left button clicks
if (mouseEvent.button !== 0) {
return;
}
this.currentDragParams = params;
this.dragging = false;
this.mouseEventLastTime = mouseEvent;
this.mouseStartEvent = mouseEvent;
var eDocument = this.gridOptionsWrapper.getDocument();
// we temporally add these listeners, for the duration of the drag, they
// are removed in mouseup handling.
eDocument.addEventListener('mousemove', this.onMouseMoveListener);
eDocument.addEventListener('mouseup', this.onMouseUpListener);
this.dragEndFunctions.push(function () {
eDocument.removeEventListener('mousemove', _this.onMouseMoveListener);
eDocument.removeEventListener('mouseup', _this.onMouseUpListener);
});
//see if we want to start dragging straight away
if (params.dragStartPixels === 0) {
this.onMouseMove(mouseEvent);
}
};
// returns true if the event is close to the original event by X pixels either vertically or horizontally.
// we only start dragging after X pixels so this allows us to know if we should start dragging yet.
DragService.prototype.isEventNearStartEvent = function (currentEvent, startEvent) {
// by default, we wait 4 pixels before starting the drag
var dragStartPixels = this.currentDragParams.dragStartPixels;
var requiredPixelDiff = utils_1._.exists(dragStartPixels) ? dragStartPixels : 4;
return utils_1._.areEventsNear(currentEvent, startEvent, requiredPixelDiff);
};
DragService.prototype.getFirstActiveTouch = function (touchList) {
for (var i = 0; i < touchList.length; i++) {
if (touchList[i].identifier === this.touchStart.identifier) {
return touchList[i];
}
}
return null;
};
DragService.prototype.onCommonMove = function (currentEvent, startEvent) {
if (!this.dragging) {
// if mouse hasn't travelled from the start position enough, do nothing
if (!this.dragging && this.isEventNearStartEvent(currentEvent, startEvent)) {
return;
}
this.dragging = true;
var event_1 = {
type: events_1.Events.EVENT_DRAG_STARTED,
api: this.gridApi,
columnApi: this.columnApi
};
this.eventService.dispatchEvent(event_1);
this.currentDragParams.onDragStart(startEvent);
this.setNoSelectToBody(true);
}
this.currentDragParams.onDragging(currentEvent);
};
DragService.prototype.onTouchMove = function (touchEvent) {
var touch = this.getFirstActiveTouch(touchEvent.touches);
if (!touch) {
return;
}
// this.___statusPanel.setInfoText(Math.random() + ' onTouchMove preventDefault stopPropagation');
// if we don't preview default, then the browser will try and do it's own touch stuff,
// like do 'back button' (chrome does this) or scroll the page (eg drag column could be confused
// with scroll page in the app)
// touchEvent.preventDefault();
this.onCommonMove(touch, this.touchStart);
};
// only gets called after a mouse down - as this is only added after mouseDown
// and is removed when mouseUp happens
DragService.prototype.onMouseMove = function (mouseEvent) {
this.onCommonMove(mouseEvent, this.mouseStartEvent);
};
DragService.prototype.onTouchUp = function (touchEvent) {
var touch = this.getFirstActiveTouch(touchEvent.changedTouches);
// i haven't worked this out yet, but there is no matching touch
// when we get the touch up event. to get around this, we swap in
// the last touch. this is a hack to 'get it working' while we
// figure out what's going on, why we are not getting a touch in
// current event.
if (!touch) {
touch = this.touchLastTime;
}
// if mouse was left up before we started to move, then this is a tap.
// we check this before onUpCommon as onUpCommon resets the dragging
// let tap = !this.dragging;
// let tapTarget = this.currentDragParams.eElement;
this.onUpCommon(touch);
// if tap, tell user
// console.log(`${Math.random()} tap = ${tap}`);
// if (tap) {
// tapTarget.click();
// }
};
DragService.prototype.onMouseUp = function (mouseEvent) {
this.onUpCommon(mouseEvent);
};
DragService.prototype.onUpCommon = function (eventOrTouch) {
if (this.dragging) {
this.dragging = false;
this.currentDragParams.onDragStop(eventOrTouch);
var event_2 = {
type: events_1.Events.EVENT_DRAG_STOPPED,
api: this.gridApi,
columnApi: this.columnApi
};
this.eventService.dispatchEvent(event_2);
}
this.setNoSelectToBody(false);
this.mouseStartEvent = null;
this.mouseEventLastTime = null;
this.touchStart = null;
this.touchLastTime = null;
this.currentDragParams = null;
this.dragEndFunctions.forEach(function (func) { return func(); });
this.dragEndFunctions.length = 0;
};
__decorate([
context_1.Autowired('loggerFactory'),
__metadata("design:type", logger_1.LoggerFactory)
], DragService.prototype, "loggerFactory", void 0);
__decorate([
context_1.Autowired('eventService'),
__metadata("design:type", eventService_1.EventService)
], DragService.prototype, "eventService", void 0);
__decorate([
context_1.Autowired('gridOptionsWrapper'),
__metadata("design:type", gridOptionsWrapper_1.GridOptionsWrapper)
], DragService.prototype, "gridOptionsWrapper", void 0);
__decorate([
context_1.Autowired('columnApi'),
__metadata("design:type", columnApi_1.ColumnApi)
], DragService.prototype, "columnApi", void 0);
__decorate([
context_1.Autowired('gridApi'),
__metadata("design:type", gridApi_1.GridApi)
], DragService.prototype, "gridApi", void 0);
__decorate([
context_1.PostConstruct,
__metadata("design:type", Function),
__metadata("design:paramtypes", []),
__metadata("design:returntype", void 0)
], DragService.prototype, "init", null);
__decorate([
context_1.PreDestroy,
__metadata("design:type", Function),
__metadata("design:paramtypes", []),
__metadata("design:returntype", void 0)
], DragService.prototype, "destroy", null);
DragService = __decorate([
context_1.Bean('dragService')
], DragService);
return DragService;
}());
exports.DragService = DragService;
| sufuf3/cdnjs | ajax/libs/ag-grid/21.0.0/lib/dragAndDrop/dragService.js | JavaScript | mit | 13,765 |
/* http://keith-wood.name/calculator.html
Catalan initialisation for the jQuery calculator extension
Written by Esteve Camps (ecamps at google dot com) June 2010. */
(function($) { // hide the namespace
$.calculator.regionalOptions['ca'] = {
decimalChar: ',',
buttonText: '...', buttonStatus: 'Obrir la calculadora',
closeText: 'Tancar', closeStatus: 'Tancar la calculadora',
useText: 'Usar', useStatus: 'Usar el valor actual',
eraseText: 'Esborrar', eraseStatus: 'Esborrar el valor actual',
backspaceText: 'BS', backspaceStatus: 'Esborrar el darrer dígit',
clearErrorText: 'CE', clearErrorStatus: 'Esborrar el darrer número',
clearText: 'CA', clearStatus: 'Reiniciar el càlcul',
memClearText: 'MC', memClearStatus: 'Esborrar la memòria',
memRecallText: 'MR', memRecallStatus: 'Recuperar el valor de la memòria',
memStoreText: 'MS', memStoreStatus: 'Guardar el valor a la memòria',
memAddText: 'M+', memAddStatus: 'Afegir a la memòria',
memSubtractText: 'M-', memSubtractStatus: 'Treure de la memòria',
base2Text: 'Bin', base2Status: 'Canviar al mode Binari',
base8Text: 'Oct', base8Status: 'Canviar al mode Octal',
base10Text: 'Dec', base10Status: 'Canviar al mode Decimal',
base16Text: 'Hex', base16Status: 'Canviar al mode Hexadecimal',
degreesText: 'Deg', degreesStatus: 'Canviar al mode Graus',
radiansText: 'Rad', radiansStatus: 'Canviar al mode Radians',
isRTL: false};
$.calculator.setDefaults($.calculator.regionalOptions['ca']);
})(jQuery); | rsantellan/ventanas-html-proyecto | ventanas/src/AppBundle/Resources/public/admin/vendor/calculator/jquery.calculator-ca.js | JavaScript | mit | 1,535 |
/**
* EditorCommands.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
*/
/**
* This class enables you to add custom editor commands and it contains
* overrides for native browser commands to address various bugs and issues.
*
* @class tinymce.EditorCommands
*/
define("tinymce/EditorCommands", [
"tinymce/html/Serializer",
"tinymce/Env",
"tinymce/util/Tools",
"tinymce/dom/ElementUtils",
"tinymce/dom/RangeUtils",
"tinymce/dom/TreeWalker"
], function(Serializer, Env, Tools, ElementUtils, RangeUtils, TreeWalker) {
// Added for compression purposes
var each = Tools.each, extend = Tools.extend;
var map = Tools.map, inArray = Tools.inArray, explode = Tools.explode;
var isIE = Env.ie, isOldIE = Env.ie && Env.ie < 11;
var TRUE = true, FALSE = false;
return function(editor) {
var dom, selection, formatter,
commands = {state: {}, exec: {}, value: {}},
settings = editor.settings,
bookmark;
editor.on('PreInit', function() {
dom = editor.dom;
selection = editor.selection;
settings = editor.settings;
formatter = editor.formatter;
});
/**
* Executes the specified command.
*
* @method execCommand
* @param {String} command Command to execute.
* @param {Boolean} ui Optional user interface state.
* @param {Object} value Optional value for command.
* @param {Object} args Optional extra arguments to the execCommand.
* @return {Boolean} true/false if the command was found or not.
*/
function execCommand(command, ui, value, args) {
var func, customCommand, state = 0;
if (!/^(mceAddUndoLevel|mceEndUndoLevel|mceBeginUndoLevel|mceRepaint)$/.test(command) && (!args || !args.skip_focus)) {
editor.focus();
}
args = editor.fire('BeforeExecCommand', {command: command, ui: ui, value: value});
if (args.isDefaultPrevented()) {
return false;
}
customCommand = command.toLowerCase();
if ((func = commands.exec[customCommand])) {
func(customCommand, ui, value);
editor.fire('ExecCommand', {command: command, ui: ui, value: value});
return true;
}
// Plugin commands
each(editor.plugins, function(p) {
if (p.execCommand && p.execCommand(command, ui, value)) {
editor.fire('ExecCommand', {command: command, ui: ui, value: value});
state = true;
return false;
}
});
if (state) {
return state;
}
// Theme commands
if (editor.theme && editor.theme.execCommand && editor.theme.execCommand(command, ui, value)) {
editor.fire('ExecCommand', {command: command, ui: ui, value: value});
return true;
}
// Browser commands
try {
state = editor.getDoc().execCommand(command, ui, value);
} catch (ex) {
// Ignore old IE errors
}
if (state) {
editor.fire('ExecCommand', {command: command, ui: ui, value: value});
return true;
}
return false;
}
/**
* Queries the current state for a command for example if the current selection is "bold".
*
* @method queryCommandState
* @param {String} command Command to check the state of.
* @return {Boolean/Number} true/false if the selected contents is bold or not, -1 if it's not found.
*/
function queryCommandState(command) {
var func;
// Is hidden then return undefined
if (editor._isHidden()) {
return;
}
command = command.toLowerCase();
if ((func = commands.state[command])) {
return func(command);
}
// Browser commands
try {
return editor.getDoc().queryCommandState(command);
} catch (ex) {
// Fails sometimes see bug: 1896577
}
return false;
}
/**
* Queries the command value for example the current fontsize.
*
* @method queryCommandValue
* @param {String} command Command to check the value of.
* @return {Object} Command value of false if it's not found.
*/
function queryCommandValue(command) {
var func;
// Is hidden then return undefined
if (editor._isHidden()) {
return;
}
command = command.toLowerCase();
if ((func = commands.value[command])) {
return func(command);
}
// Browser commands
try {
return editor.getDoc().queryCommandValue(command);
} catch (ex) {
// Fails sometimes see bug: 1896577
}
}
/**
* Adds commands to the command collection.
*
* @method addCommands
* @param {Object} command_list Name/value collection with commands to add, the names can also be comma separated.
* @param {String} type Optional type to add, defaults to exec. Can be value or state as well.
*/
function addCommands(command_list, type) {
type = type || 'exec';
each(command_list, function(callback, command) {
each(command.toLowerCase().split(','), function(command) {
commands[type][command] = callback;
});
});
}
function addCommand(command, callback, scope) {
command = command.toLowerCase();
commands.exec[command] = function(command, ui, value, args) {
return callback.call(scope || editor, ui, value, args);
};
}
/**
* Returns true/false if the command is supported or not.
*
* @method queryCommandSupported
* @param {String} command Command that we check support for.
* @return {Boolean} true/false if the command is supported or not.
*/
function queryCommandSupported(command) {
command = command.toLowerCase();
if (commands.exec[command]) {
return true;
}
// Browser commands
try {
return editor.getDoc().queryCommandSupported(command);
} catch (ex) {
// Fails sometimes see bug: 1896577
}
return false;
}
function addQueryStateHandler(command, callback, scope) {
command = command.toLowerCase();
commands.state[command] = function() {
return callback.call(scope || editor);
};
}
function addQueryValueHandler(command, callback, scope) {
command = command.toLowerCase();
commands.value[command] = function() {
return callback.call(scope || editor);
};
}
function hasCustomCommand(command) {
command = command.toLowerCase();
return !!commands.exec[command];
}
// Expose public methods
extend(this, {
execCommand: execCommand,
queryCommandState: queryCommandState,
queryCommandValue: queryCommandValue,
queryCommandSupported: queryCommandSupported,
addCommands: addCommands,
addCommand: addCommand,
addQueryStateHandler: addQueryStateHandler,
addQueryValueHandler: addQueryValueHandler,
hasCustomCommand: hasCustomCommand
});
// Private methods
function execNativeCommand(command, ui, value) {
if (ui === undefined) {
ui = FALSE;
}
if (value === undefined) {
value = null;
}
return editor.getDoc().execCommand(command, ui, value);
}
function isFormatMatch(name) {
return formatter.match(name);
}
function toggleFormat(name, value) {
formatter.toggle(name, value ? {value: value} : undefined);
editor.nodeChanged();
}
function storeSelection(type) {
bookmark = selection.getBookmark(type);
}
function restoreSelection() {
selection.moveToBookmark(bookmark);
}
// Add execCommand overrides
addCommands({
// Ignore these, added for compatibility
'mceResetDesignMode,mceBeginUndoLevel': function() {},
// Add undo manager logic
'mceEndUndoLevel,mceAddUndoLevel': function() {
editor.undoManager.add();
},
'Cut,Copy,Paste': function(command) {
var doc = editor.getDoc(), failed;
// Try executing the native command
try {
execNativeCommand(command);
} catch (ex) {
// Command failed
failed = TRUE;
}
// Present alert message about clipboard access not being available
if (failed || !doc.queryCommandSupported(command)) {
var msg = editor.translate(
"Your browser doesn't support direct access to the clipboard. " +
"Please use the Ctrl+X/C/V keyboard shortcuts instead."
);
if (Env.mac) {
msg = msg.replace(/Ctrl\+/g, '\u2318+');
}
editor.notificationManager.open({text: msg, type: 'error'});
}
},
// Override unlink command
unlink: function() {
if (selection.isCollapsed()) {
var elm = selection.getNode();
if (elm.tagName == 'A') {
editor.dom.remove(elm, true);
}
return;
}
formatter.remove("link");
},
// Override justify commands to use the text formatter engine
'JustifyLeft,JustifyCenter,JustifyRight,JustifyFull,JustifyNone': function(command) {
var align = command.substring(7);
if (align == 'full') {
align = 'justify';
}
// Remove all other alignments first
each('left,center,right,justify'.split(','), function(name) {
if (align != name) {
formatter.remove('align' + name);
}
});
if (align != 'none') {
toggleFormat('align' + align);
}
},
// Override list commands to fix WebKit bug
'InsertUnorderedList,InsertOrderedList': function(command) {
var listElm, listParent;
execNativeCommand(command);
// WebKit produces lists within block elements so we need to split them
// we will replace the native list creation logic to custom logic later on
// TODO: Remove this when the list creation logic is removed
listElm = dom.getParent(selection.getNode(), 'ol,ul');
if (listElm) {
listParent = listElm.parentNode;
// If list is within a text block then split that block
if (/^(H[1-6]|P|ADDRESS|PRE)$/.test(listParent.nodeName)) {
storeSelection();
dom.split(listParent, listElm);
restoreSelection();
}
}
},
// Override commands to use the text formatter engine
'Bold,Italic,Underline,Strikethrough,Superscript,Subscript': function(command) {
toggleFormat(command);
},
// Override commands to use the text formatter engine
'ForeColor,HiliteColor,FontName': function(command, ui, value) {
toggleFormat(command, value);
},
FontSize: function(command, ui, value) {
var fontClasses, fontSizes;
// Convert font size 1-7 to styles
if (value >= 1 && value <= 7) {
fontSizes = explode(settings.font_size_style_values);
fontClasses = explode(settings.font_size_classes);
if (fontClasses) {
value = fontClasses[value - 1] || value;
} else {
value = fontSizes[value - 1] || value;
}
}
toggleFormat(command, value);
},
RemoveFormat: function(command) {
formatter.remove(command);
},
mceBlockQuote: function() {
toggleFormat('blockquote');
},
FormatBlock: function(command, ui, value) {
return toggleFormat(value || 'p');
},
mceCleanup: function() {
var bookmark = selection.getBookmark();
editor.setContent(editor.getContent({cleanup: TRUE}), {cleanup: TRUE});
selection.moveToBookmark(bookmark);
},
mceRemoveNode: function(command, ui, value) {
var node = value || selection.getNode();
// Make sure that the body node isn't removed
if (node != editor.getBody()) {
storeSelection();
editor.dom.remove(node, TRUE);
restoreSelection();
}
},
mceSelectNodeDepth: function(command, ui, value) {
var counter = 0;
dom.getParent(selection.getNode(), function(node) {
if (node.nodeType == 1 && counter++ == value) {
selection.select(node);
return FALSE;
}
}, editor.getBody());
},
mceSelectNode: function(command, ui, value) {
selection.select(value);
},
mceInsertContent: function(command, ui, value) {
var parser, serializer, parentNode, rootNode, fragment, args;
var marker, rng, node, node2, bookmarkHtml, merge, data;
var textInlineElements = editor.schema.getTextInlineElements();
function trimOrPaddLeftRight(html) {
var rng, container, offset;
rng = selection.getRng(true);
container = rng.startContainer;
offset = rng.startOffset;
function hasSiblingText(siblingName) {
return container[siblingName] && container[siblingName].nodeType == 3;
}
if (container.nodeType == 3) {
if (offset > 0) {
html = html.replace(/^ /, ' ');
} else if (!hasSiblingText('previousSibling')) {
html = html.replace(/^ /, ' ');
}
if (offset < container.length) {
html = html.replace(/ (<br>|)$/, ' ');
} else if (!hasSiblingText('nextSibling')) {
html = html.replace(/( | )(<br>|)$/, ' ');
}
}
return html;
}
// Removes from a [b] c -> a c -> a c
function trimNbspAfterDeleteAndPaddValue() {
var rng, container, offset;
rng = selection.getRng(true);
container = rng.startContainer;
offset = rng.startOffset;
if (container.nodeType == 3 && rng.collapsed) {
if (container.data[offset] === '\u00a0') {
container.deleteData(offset, 1);
if (!/[\u00a0| ]$/.test(value)) {
value += ' ';
}
} else if (container.data[offset - 1] === '\u00a0') {
container.deleteData(offset - 1, 1);
if (!/[\u00a0| ]$/.test(value)) {
value = ' ' + value;
}
}
}
}
function markInlineFormatElements(fragment) {
if (merge) {
for (node = fragment.firstChild; node; node = node.walk(true)) {
if (textInlineElements[node.name]) {
node.attr('data-mce-new', "true");
}
}
}
}
function reduceInlineTextElements() {
if (merge) {
var root = editor.getBody(), elementUtils = new ElementUtils(dom);
each(dom.select('*[data-mce-new]'), function(node) {
node.removeAttribute('data-mce-new');
for (var testNode = node.parentNode; testNode && testNode != root; testNode = testNode.parentNode) {
if (elementUtils.compare(testNode, node)) {
dom.remove(node, true);
}
}
});
}
}
function moveSelectionToMarker(marker) {
var parentEditableFalseElm;
function getContentEditableFalseParent(node) {
var root = editor.getBody();
for (; node && node !== root; node = node.parentNode) {
if (editor.dom.getContentEditable(node) === 'false') {
return node;
}
}
return null;
}
if (!marker) {
return;
}
selection.scrollIntoView(marker);
// If marker is in cE=false then move selection to that element instead
parentEditableFalseElm = getContentEditableFalseParent(marker);
if (parentEditableFalseElm) {
dom.remove(marker);
selection.select(parentEditableFalseElm);
return;
}
// Move selection before marker and remove it
rng = dom.createRng();
// If previous sibling is a text node set the selection to the end of that node
node = marker.previousSibling;
if (node && node.nodeType == 3) {
rng.setStart(node, node.nodeValue.length);
// TODO: Why can't we normalize on IE
if (!isIE) {
node2 = marker.nextSibling;
if (node2 && node2.nodeType == 3) {
node.appendData(node2.data);
node2.parentNode.removeChild(node2);
}
}
} else {
// If the previous sibling isn't a text node or doesn't exist set the selection before the marker node
rng.setStartBefore(marker);
rng.setEndBefore(marker);
}
// Remove the marker node and set the new range
dom.remove(marker);
selection.setRng(rng);
}
if (typeof value != 'string') {
merge = value.merge;
data = value.data;
value = value.content;
}
// Check for whitespace before/after value
if (/^ | $/.test(value)) {
value = trimOrPaddLeftRight(value);
}
// Setup parser and serializer
parser = editor.parser;
serializer = new Serializer({
validate: settings.validate
}, editor.schema);
bookmarkHtml = '<span id="mce_marker" data-mce-type="bookmark">​</span>';
// Run beforeSetContent handlers on the HTML to be inserted
args = {content: value, format: 'html', selection: true};
editor.fire('BeforeSetContent', args);
value = args.content;
// Add caret at end of contents if it's missing
if (value.indexOf('{$caret}') == -1) {
value += '{$caret}';
}
// Replace the caret marker with a span bookmark element
value = value.replace(/\{\$caret\}/, bookmarkHtml);
// If selection is at <body>|<p></p> then move it into <body><p>|</p>
rng = selection.getRng();
var caretElement = rng.startContainer || (rng.parentElement ? rng.parentElement() : null);
var body = editor.getBody();
if (caretElement === body && selection.isCollapsed()) {
if (dom.isBlock(body.firstChild) && dom.isEmpty(body.firstChild)) {
rng = dom.createRng();
rng.setStart(body.firstChild, 0);
rng.setEnd(body.firstChild, 0);
selection.setRng(rng);
}
}
// Insert node maker where we will insert the new HTML and get it's parent
if (!selection.isCollapsed()) {
editor.getDoc().execCommand('Delete', false, null);
trimNbspAfterDeleteAndPaddValue();
}
parentNode = selection.getNode();
// Parse the fragment within the context of the parent node
var parserArgs = {context: parentNode.nodeName.toLowerCase(), data: data};
fragment = parser.parse(value, parserArgs);
markInlineFormatElements(fragment);
// Move the caret to a more suitable location
node = fragment.lastChild;
if (node.attr('id') == 'mce_marker') {
marker = node;
for (node = node.prev; node; node = node.walk(true)) {
if (node.type == 3 || !dom.isBlock(node.name)) {
if (editor.schema.isValidChild(node.parent.name, 'span')) {
node.parent.insert(marker, node, node.name === 'br');
}
break;
}
}
}
editor._selectionOverrides.showBlockCaretContainer(parentNode);
// If parser says valid we can insert the contents into that parent
if (!parserArgs.invalid) {
value = serializer.serialize(fragment);
// Check if parent is empty or only has one BR element then set the innerHTML of that parent
node = parentNode.firstChild;
node2 = parentNode.lastChild;
if (!node || (node === node2 && node.nodeName === 'BR')) {
dom.setHTML(parentNode, value);
} else {
selection.setContent(value);
}
} else {
// If the fragment was invalid within that context then we need
// to parse and process the parent it's inserted into
// Insert bookmark node and get the parent
selection.setContent(bookmarkHtml);
parentNode = selection.getNode();
rootNode = editor.getBody();
// Opera will return the document node when selection is in root
if (parentNode.nodeType == 9) {
parentNode = node = rootNode;
} else {
node = parentNode;
}
// Find the ancestor just before the root element
while (node !== rootNode) {
parentNode = node;
node = node.parentNode;
}
// Get the outer/inner HTML depending on if we are in the root and parser and serialize that
value = parentNode == rootNode ? rootNode.innerHTML : dom.getOuterHTML(parentNode);
value = serializer.serialize(
parser.parse(
// Need to replace by using a function since $ in the contents would otherwise be a problem
value.replace(/<span (id="mce_marker"|id=mce_marker).+?<\/span>/i, function() {
return serializer.serialize(fragment);
})
)
);
// Set the inner/outer HTML depending on if we are in the root or not
if (parentNode == rootNode) {
dom.setHTML(rootNode, value);
} else {
dom.setOuterHTML(parentNode, value);
}
}
reduceInlineTextElements();
moveSelectionToMarker(dom.get('mce_marker'));
editor.fire('SetContent', args);
editor.addVisual();
},
mceInsertRawHTML: function(command, ui, value) {
selection.setContent('tiny_mce_marker');
editor.setContent(
editor.getContent().replace(/tiny_mce_marker/g, function() {
return value;
})
);
},
mceToggleFormat: function(command, ui, value) {
toggleFormat(value);
},
mceSetContent: function(command, ui, value) {
editor.setContent(value);
},
'Indent,Outdent': function(command) {
var intentValue, indentUnit, value;
// Setup indent level
intentValue = settings.indentation;
indentUnit = /[a-z%]+$/i.exec(intentValue);
intentValue = parseInt(intentValue, 10);
if (!queryCommandState('InsertUnorderedList') && !queryCommandState('InsertOrderedList')) {
// If forced_root_blocks is set to false we don't have a block to indent so lets create a div
if (!settings.forced_root_block && !dom.getParent(selection.getNode(), dom.isBlock)) {
formatter.apply('div');
}
each(selection.getSelectedBlocks(), function(element) {
if (dom.getContentEditable(element) === "false") {
return;
}
if (element.nodeName != "LI") {
var indentStyleName = editor.getParam('indent_use_margin', false) ? 'margin' : 'padding';
indentStyleName += dom.getStyle(element, 'direction', true) == 'rtl' ? 'Right' : 'Left';
if (command == 'outdent') {
value = Math.max(0, parseInt(element.style[indentStyleName] || 0, 10) - intentValue);
dom.setStyle(element, indentStyleName, value ? value + indentUnit : '');
} else {
value = (parseInt(element.style[indentStyleName] || 0, 10) + intentValue) + indentUnit;
dom.setStyle(element, indentStyleName, value);
}
}
});
} else {
execNativeCommand(command);
}
},
mceRepaint: function() {
},
InsertHorizontalRule: function() {
editor.execCommand('mceInsertContent', false, '<hr />');
},
mceToggleVisualAid: function() {
editor.hasVisual = !editor.hasVisual;
editor.addVisual();
},
mceReplaceContent: function(command, ui, value) {
editor.execCommand('mceInsertContent', false, value.replace(/\{\$selection\}/g, selection.getContent({format: 'text'})));
},
mceInsertLink: function(command, ui, value) {
var anchor;
if (typeof value == 'string') {
value = {href: value};
}
anchor = dom.getParent(selection.getNode(), 'a');
// Spaces are never valid in URLs and it's a very common mistake for people to make so we fix it here.
value.href = value.href.replace(' ', '%20');
// Remove existing links if there could be child links or that the href isn't specified
if (!anchor || !value.href) {
formatter.remove('link');
}
// Apply new link to selection
if (value.href) {
formatter.apply('link', value, anchor);
}
},
selectAll: function() {
var root = dom.getRoot(), rng;
if (selection.getRng().setStart) {
rng = dom.createRng();
rng.setStart(root, 0);
rng.setEnd(root, root.childNodes.length);
selection.setRng(rng);
} else {
// IE will render it's own root level block elements and sometimes
// even put font elements in them when the user starts typing. So we need to
// move the selection to a more suitable element from this:
// <body>|<p></p></body> to this: <body><p>|</p></body>
rng = selection.getRng();
if (!rng.item) {
rng.moveToElementText(root);
rng.select();
}
}
},
"delete": function() {
execNativeCommand("Delete");
// Check if body is empty after the delete call if so then set the contents
// to an empty string and move the caret to any block produced by that operation
// this fixes the issue with root blocks not being properly produced after a delete call on IE
var body = editor.getBody();
if (dom.isEmpty(body)) {
editor.setContent('');
if (body.firstChild && dom.isBlock(body.firstChild)) {
editor.selection.setCursorLocation(body.firstChild, 0);
} else {
editor.selection.setCursorLocation(body, 0);
}
}
},
mceNewDocument: function() {
editor.setContent('');
},
InsertLineBreak: function(command, ui, value) {
// We load the current event in from EnterKey.js when appropriate to heed
// certain event-specific variations such as ctrl-enter in a list
var evt = value;
var brElm, extraBr, marker;
var rng = selection.getRng(true);
new RangeUtils(dom).normalize(rng);
var offset = rng.startOffset;
var container = rng.startContainer;
// Resolve node index
if (container.nodeType == 1 && container.hasChildNodes()) {
var isAfterLastNodeInContainer = offset > container.childNodes.length - 1;
container = container.childNodes[Math.min(offset, container.childNodes.length - 1)] || container;
if (isAfterLastNodeInContainer && container.nodeType == 3) {
offset = container.nodeValue.length;
} else {
offset = 0;
}
}
var parentBlock = dom.getParent(container, dom.isBlock);
var parentBlockName = parentBlock ? parentBlock.nodeName.toUpperCase() : ''; // IE < 9 & HTML5
var containerBlock = parentBlock ? dom.getParent(parentBlock.parentNode, dom.isBlock) : null;
var containerBlockName = containerBlock ? containerBlock.nodeName.toUpperCase() : ''; // IE < 9 & HTML5
// Enter inside block contained within a LI then split or insert before/after LI
var isControlKey = evt && evt.ctrlKey;
if (containerBlockName == 'LI' && !isControlKey) {
parentBlock = containerBlock;
parentBlockName = containerBlockName;
}
// Walks the parent block to the right and look for BR elements
function hasRightSideContent() {
var walker = new TreeWalker(container, parentBlock), node;
var nonEmptyElementsMap = editor.schema.getNonEmptyElements();
while ((node = walker.next())) {
if (nonEmptyElementsMap[node.nodeName.toLowerCase()] || node.length > 0) {
return true;
}
}
}
if (container && container.nodeType == 3 && offset >= container.nodeValue.length) {
// Insert extra BR element at the end block elements
if (!isOldIE && !hasRightSideContent()) {
brElm = dom.create('br');
rng.insertNode(brElm);
rng.setStartAfter(brElm);
rng.setEndAfter(brElm);
extraBr = true;
}
}
brElm = dom.create('br');
rng.insertNode(brElm);
// Rendering modes below IE8 doesn't display BR elements in PRE unless we have a \n before it
var documentMode = dom.doc.documentMode;
if (isOldIE && parentBlockName == 'PRE' && (!documentMode || documentMode < 8)) {
brElm.parentNode.insertBefore(dom.doc.createTextNode('\r'), brElm);
}
// Insert temp marker and scroll to that
marker = dom.create('span', {}, ' ');
brElm.parentNode.insertBefore(marker, brElm);
selection.scrollIntoView(marker);
dom.remove(marker);
if (!extraBr) {
rng.setStartAfter(brElm);
rng.setEndAfter(brElm);
} else {
rng.setStartBefore(brElm);
rng.setEndBefore(brElm);
}
selection.setRng(rng);
editor.undoManager.add();
return TRUE;
}
});
// Add queryCommandState overrides
addCommands({
// Override justify commands
'JustifyLeft,JustifyCenter,JustifyRight,JustifyFull': function(command) {
var name = 'align' + command.substring(7);
var nodes = selection.isCollapsed() ? [dom.getParent(selection.getNode(), dom.isBlock)] : selection.getSelectedBlocks();
var matches = map(nodes, function(node) {
return !!formatter.matchNode(node, name);
});
return inArray(matches, TRUE) !== -1;
},
'Bold,Italic,Underline,Strikethrough,Superscript,Subscript': function(command) {
return isFormatMatch(command);
},
mceBlockQuote: function() {
return isFormatMatch('blockquote');
},
Outdent: function() {
var node;
if (settings.inline_styles) {
if ((node = dom.getParent(selection.getStart(), dom.isBlock)) && parseInt(node.style.paddingLeft, 10) > 0) {
return TRUE;
}
if ((node = dom.getParent(selection.getEnd(), dom.isBlock)) && parseInt(node.style.paddingLeft, 10) > 0) {
return TRUE;
}
}
return (
queryCommandState('InsertUnorderedList') ||
queryCommandState('InsertOrderedList') ||
(!settings.inline_styles && !!dom.getParent(selection.getNode(), 'BLOCKQUOTE'))
);
},
'InsertUnorderedList,InsertOrderedList': function(command) {
var list = dom.getParent(selection.getNode(), 'ul,ol');
return list &&
(
command === 'insertunorderedlist' && list.tagName === 'UL' ||
command === 'insertorderedlist' && list.tagName === 'OL'
);
}
}, 'state');
// Add queryCommandValue overrides
addCommands({
'FontSize,FontName': function(command) {
var value = 0, parent;
if ((parent = dom.getParent(selection.getNode(), 'span'))) {
if (command == 'fontsize') {
value = parent.style.fontSize;
} else {
value = parent.style.fontFamily.replace(/, /g, ',').replace(/[\'\"]/g, '').toLowerCase();
}
}
return value;
}
}, 'value');
// Add undo manager logic
addCommands({
Undo: function() {
editor.undoManager.undo();
},
Redo: function() {
editor.undoManager.redo();
}
});
};
});
| michalgraczyk/calculus | web/js/tiny_mce/js/tinymce/classes/EditorCommands.js | JavaScript | mit | 29,362 |
define([
'angular'
, './view-rubberband-controller'
, './view-rubberband-directive'
], function(
angular
, Controller
, directive
) {
"use strict";
return angular.module('mtk.viewRubberband', [])
.controller('ViewRubberbandController', Controller)
.directive('mtkViewRubberband', directive)
;
});
| jeroenbreen/metapolator | app/lib/ui/metapolator/view-rubberband/view-rubberband.js | JavaScript | gpl-3.0 | 354 |
// UK lang variables
tinyMCE.addI18n('pt.codehighlighting',{
codehighlighting_desc : "Code Highlighting",
codehighlighting_title : "Code Highlighting",
codehighlighting_langaugepicker : "Choose the language",
codehighlighting_pagecode : "Paste your code here",
codehighlighting_button_desc: "Insert code",
codehighlighting_nogutter : "No Gutter",
codehighlighting_collapse : "Collapse",
codehighlighting_nocontrols : "No Controls",
codehighlighting_showcolumns : "Show Columns"
});
| ahilles107/Newscoop | newscoop/js/tinymce/plugins/codehighlighting/langs/pt.js | JavaScript | gpl-3.0 | 494 |
Subsets and Splits