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
|
---|---|---|---|---|---|
// { "framework": "Vue" }
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ({
/***/ 0:
/***/ function(module, exports, __webpack_require__) {
var __vue_exports__, __vue_options__
var __vue_styles__ = []
/* styles */
__vue_styles__.push(__webpack_require__(571)
)
/* script */
__vue_exports__ = __webpack_require__(572)
/* template */
var __vue_template__ = __webpack_require__(573)
__vue_options__ = __vue_exports__ = __vue_exports__ || {}
if (
typeof __vue_exports__.default === "object" ||
typeof __vue_exports__.default === "function"
) {
if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")}
__vue_options__ = __vue_exports__ = __vue_exports__.default
}
if (typeof __vue_options__ === "function") {
__vue_options__ = __vue_options__.options
}
__vue_options__.__file = "/Users/bobning/work/source/apache-incubator-weex/examples/vue/style/style-item.vue"
__vue_options__.render = __vue_template__.render
__vue_options__.staticRenderFns = __vue_template__.staticRenderFns
__vue_options__._scopeId = "data-v-768350d6"
__vue_options__.style = __vue_options__.style || {}
__vue_styles__.forEach(function (module) {
for (var name in module) {
__vue_options__.style[name] = module[name]
}
})
if (typeof __register_static_styles__ === "function") {
__register_static_styles__(__vue_options__._scopeId, __vue_styles__)
}
module.exports = __vue_exports__
module.exports.el = 'true'
new Vue(module.exports)
/***/ },
/***/ 571:
/***/ function(module, exports) {
module.exports = {
"item": {
"marginRight": 10,
"width": 160,
"height": 75,
"paddingLeft": 8,
"paddingRight": 8,
"paddingTop": 8,
"paddingBottom": 8
},
"txt": {
"color": "#eeeeee"
}
}
/***/ },
/***/ 572:
/***/ function(module, exports) {
'use strict';
//
//
//
//
//
//
//
module.exports = {
props: {
value: { default: '' },
type: { default: '0' } // 0, 1
},
computed: {
bgColor: function bgColor() {
return this.type == '1' ? '#7BA3A8' : '#BEAD92';
}
}
};
/***/ },
/***/ 573:
/***/ function(module, exports) {
module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;
return _c('text', {
staticClass: ["item", "txt"],
style: {
backgroundColor: _vm.bgColor
},
attrs: {
"value": _vm.value
}
})
},staticRenderFns: []}
module.exports.render._withStripped = true
/***/ }
/******/ }); | MrRaindrop/incubator-weex | ios/playground/bundlejs/vue/style/style-item.js | JavaScript | apache-2.0 | 3,888 |
//// [inheritanceMemberAccessorOverridingAccessor.ts]
class a {
get x() {
return "20";
}
set x(aValue: string) {
}
}
class b extends a {
get x() {
return "20";
}
set x(aValue: string) {
}
}
//// [inheritanceMemberAccessorOverridingAccessor.js]
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var a = (function () {
function a() {
}
Object.defineProperty(a.prototype, "x", {
get: function () {
return "20";
},
set: function (aValue) {
},
enumerable: true,
configurable: true
});
return a;
}());
var b = (function (_super) {
__extends(b, _super);
function b() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(b.prototype, "x", {
get: function () {
return "20";
},
set: function (aValue) {
},
enumerable: true,
configurable: true
});
return b;
}(a));
| mihailik/TypeScript | tests/baselines/reference/inheritanceMemberAccessorOverridingAccessor.js | JavaScript | apache-2.0 | 1,503 |
import Feature from '../src/ol/Feature.js';
import Map from '../src/ol/Map.js';
import Point from '../src/ol/geom/Point.js';
import VectorLayer from '../src/ol/layer/Vector.js';
import VectorSource from '../src/ol/source/Vector.js';
import View from '../src/ol/View.js';
import {Fill, RegularShape, Stroke, Style} from '../src/ol/style.js';
const stroke = new Stroke({color: 'black', width: 2});
const fill = new Fill({color: 'red'});
const styles = {
'square': new Style({
image: new RegularShape({
fill: fill,
stroke: stroke,
points: 4,
radius: 10,
angle: Math.PI / 4,
}),
}),
'rectangle': new Style({
image: new RegularShape({
fill: fill,
stroke: stroke,
radius: 10 / Math.SQRT2,
radius2: 10,
points: 4,
angle: 0,
scale: [1, 0.5],
}),
}),
'triangle': new Style({
image: new RegularShape({
fill: fill,
stroke: stroke,
points: 3,
radius: 10,
rotation: Math.PI / 4,
angle: 0,
}),
}),
'star': new Style({
image: new RegularShape({
fill: fill,
stroke: stroke,
points: 5,
radius: 10,
radius2: 4,
angle: 0,
}),
}),
'cross': new Style({
image: new RegularShape({
fill: fill,
stroke: stroke,
points: 4,
radius: 10,
radius2: 0,
angle: 0,
}),
}),
'x': new Style({
image: new RegularShape({
fill: fill,
stroke: stroke,
points: 4,
radius: 10,
radius2: 0,
angle: Math.PI / 4,
}),
}),
'stacked': [
new Style({
image: new RegularShape({
fill: fill,
stroke: stroke,
points: 4,
radius: 5,
angle: Math.PI / 4,
displacement: [0, 10],
}),
}),
new Style({
image: new RegularShape({
fill: fill,
stroke: stroke,
points: 4,
radius: 10,
angle: Math.PI / 4,
}),
}),
],
};
const styleKeys = [
'x',
'cross',
'star',
'triangle',
'square',
'rectangle',
'stacked',
];
const count = 250;
const features = new Array(count);
const e = 4500000;
for (let i = 0; i < count; ++i) {
const coordinates = [2 * e * Math.random() - e, 2 * e * Math.random() - e];
features[i] = new Feature(new Point(coordinates));
features[i].setStyle(
styles[styleKeys[Math.floor(Math.random() * styleKeys.length)]]
);
}
const source = new VectorSource({
features: features,
});
const vectorLayer = new VectorLayer({
source: source,
});
const map = new Map({
layers: [vectorLayer],
target: 'map',
view: new View({
center: [0, 0],
zoom: 2,
}),
});
| adube/ol3 | examples/regularshape.js | JavaScript | bsd-2-clause | 2,662 |
module.exports.middleware = function(req, res, next) {
req.rootUrl = function() {
var port = req.app.settings.port;
res.locals.requested_url = req.protocol + '://' + req.hostname + (port == 80 || port == 443 ? '' : ':' + port);
return req.protocol + "://" + req.get('host');
};
req.fullPath = function() {
return req.rootUrl() + req.path;
};
return next();
};
| andrewvy/slack-pongbot | lib/url.js | JavaScript | isc | 387 |
// add_test.js
/* globals add */
describe('Addition', function () {
it('should add numbers', function () {
expect(add(2, 4)).toBe(6)
expect(add(2, 4)).not.toBe(2)
})
})
| dmitriz/baseline-utils | demo/min-karma-function_test.js | JavaScript | mit | 182 |
const common = require('../../../../lib/common');
const commands = require('../../../schema').commands;
const table = 'actions';
const message1 = `Adding table: ${table}`;
const message2 = `Dropping table: ${table}`;
module.exports.up = (options) => {
const connection = options.connection;
return connection.schema.hasTable(table)
.then(function (exists) {
if (exists) {
common.logging.warn(message1);
return;
}
common.logging.info(message1);
return commands.createTable(table, connection);
});
};
module.exports.down = (options) => {
const connection = options.connection;
return connection.schema.hasTable(table)
.then(function (exists) {
if (!exists) {
common.logging.warn(message2);
return;
}
common.logging.info(message2);
return commands.deleteTable(table, connection);
});
};
| dingotiles/ghost-for-cloudfoundry | versions/3.3.0/core/server/data/migrations/versions/2.14/1-add-actions-table.js | JavaScript | mit | 998 |
/*! jQuery UI - v1.10.4 - 2014-06-22
* http://jqueryui.com
* Copyright 2014 jQuery Foundation and other contributors; Licensed MIT */
(function(t){t.effects.effect.explode=function(e,i){function s(){b.push(this),b.length===u*d&&n()}function n(){p.css({visibility:"visible"}),t(b).remove(),g||p.hide(),i()}var a,o,r,l,h,c,u=e.pieces?Math.round(Math.sqrt(e.pieces)):3,d=u,p=t(this),f=t.effects.setMode(p,e.mode||"hide"),g="show"===f,m=p.show().css("visibility","hidden").offset(),v=Math.ceil(p.outerWidth()/d),_=Math.ceil(p.outerHeight()/u),b=[];for(a=0;u>a;a++)for(l=m.top+a*_,c=a-(u-1)/2,o=0;d>o;o++)r=m.left+o*v,h=o-(d-1)/2,p.clone().appendTo("body").wrap("<div></div>").css({position:"absolute",visibility:"visible",left:-o*v,top:-a*_}).parent().addClass("ui-effects-explode").css({position:"absolute",overflow:"hidden",width:v,height:_,left:r+(g?h*v:0),top:l+(g?c*_:0),opacity:g?0:1}).animate({left:r+(g?0:h*v),top:l+(g?0:c*_),opacity:g?1:0},e.duration||500,e.easing,s)}})(jQuery); | camperjz/trident | plugins_public/jquery-ui/jquery.ui.effect-explode.min.js | JavaScript | mit | 985 |
var WOLF_WIDTH = 55;
var WOLF_HEIGHT = 37;
var WOLF_Y_OFFSET = 5;
function Wolf(x, y, direction) {
LandEnemy.call(this, x, y, direction, 'wolf', [0, 1], [2, 3], 150);
this.sprite.body.setSize(WOLF_WIDTH, WOLF_HEIGHT, 0, WOLF_Y_OFFSET);
}
Wolf.spawn = function(spawnSettings, group) {
spawnSettings.forEach(function(settings) {
group.add(new Wolf(settings.x * TILE_SIZE, settings.y * TILE_SIZE - (WOLF_HEIGHT + WOLF_Y_OFFSET - TILE_SIZE), settings.direction).sprite);
}, this);
};
$.extend(Wolf.prototype, LandEnemy.prototype)
module.exports = Wolf; | nickchulani99/ITE-445 | final/alien/js/LandEnemy.js | JavaScript | mit | 561 |
/**
* @author mrdoob / http://mrdoob.com/
*/
function WebGLBufferRenderer( gl, extensions, info, capabilities ) {
var isWebGL2 = capabilities.isWebGL2;
var mode;
function setMode( value ) {
mode = value;
}
function render( start, count ) {
gl.drawArrays( mode, start, count );
info.update( count, mode );
}
function renderInstances( geometry, start, count, primcount ) {
if ( primcount === 0 ) return;
var extension, methodName;
if ( isWebGL2 ) {
extension = gl;
methodName = 'drawArraysInstanced';
} else {
extension = extensions.get( 'ANGLE_instanced_arrays' );
methodName = 'drawArraysInstancedANGLE';
if ( extension === null ) {
console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
return;
}
}
extension[ methodName ]( mode, start, count, primcount );
info.update( count, mode, primcount );
}
//
this.setMode = setMode;
this.render = render;
this.renderInstances = renderInstances;
}
export { WebGLBufferRenderer };
| SpinVR/three.js | src/renderers/webgl/WebGLBufferRenderer.js | JavaScript | mit | 1,103 |
import Ember from 'ember';
import { module, test } from 'qunit';
import startApp from '../helpers/start-app';
import destroyModal from '../helpers/destroy-modal';
import getToastMessage from '../helpers/toast-message';
var application;
module('Acceptance: Account Activation', {
beforeEach: function() {
application = startApp();
},
afterEach: function() {
Ember.$('#hidden-login-form').off('submit.stopInTest');
destroyModal();
Ember.run(application, 'destroy');
Ember.$.mockjax.clear();
}
});
test('visiting /activation', function(assert) {
assert.expect(1);
visit('/activation');
andThen(function() {
assert.equal(currentPath(), 'activation.index');
});
});
test('request activation link without entering e-mail', function(assert) {
assert.expect(2);
visit('/activation');
click('.activation-page form .btn-primary');
andThen(function() {
assert.equal(currentPath(), 'activation.index');
assert.equal(getToastMessage(), 'Enter e-mail address.');
});
});
test('request activation link with invalid e-mail', function(assert) {
assert.expect(2);
var message = 'Entered e-mail is invalid.';
Ember.$.mockjax({
url: '/api/auth/send-activation/',
status: 400,
responseText: {
'detail': message,
'code': 'invalid_email'
}
});
visit('/activation');
fillIn('.activation-page form input', 'not-valid-email');
click('.activation-page form .btn-primary');
andThen(function() {
assert.equal(currentPath(), 'activation.index');
assert.equal(getToastMessage(), message);
});
});
test('request activation link with non-existing e-mail', function(assert) {
assert.expect(2);
var message = 'No user with this e-mail exists.';
Ember.$.mockjax({
url: '/api/auth/send-activation/',
status: 400,
responseText: {
'detail': message,
'code': 'not_found'
}
});
visit('/activation');
fillIn('.activation-page form input', 'not-valid-email');
click('.activation-page form .btn-primary');
andThen(function() {
assert.equal(currentPath(), 'activation.index');
assert.equal(getToastMessage(), message);
});
});
test('request activation link with user-activated account', function(assert) {
assert.expect(2);
var message = 'You have to activate your account before you will be able to sign in.';
Ember.$.mockjax({
url: '/api/auth/send-activation/',
status: 400,
responseText: {
'detail': message,
'code': 'inactive_user'
}
});
visit('/activation');
fillIn('.activation-page form input', '[email protected]');
click('.activation-page form .btn-primary');
andThen(function() {
assert.equal(currentPath(), 'activation.index');
assert.equal(getToastMessage(), message);
});
});
test('request activation link with admin-activated account', function(assert) {
assert.expect(2);
var message = 'Your account has to be activated by Administrator before you will be able to sign in.';
Ember.$.mockjax({
url: '/api/auth/send-activation/',
status: 400,
responseText: {
'detail': message,
'code': 'inactive_admin'
}
});
visit('/activation');
fillIn('.activation-page form input', '[email protected]');
click('.activation-page form .btn-primary');
andThen(function() {
assert.equal(currentPath(), 'activation.index');
assert.equal(getToastMessage(), message);
});
});
test('request activation link with banned account', function(assert) {
assert.expect(2);
Ember.$.mockjax({
url: '/api/auth/send-activation/',
status: 400,
responseText: {
'detail': {
'expires_on': null,
'message': {
'plain': 'You are banned for trolling.',
'html': '<p>You are banned for trolling.</p>',
}
},
'code': 'banned'
}
});
visit('/activation');
fillIn('.activation-page form input', '[email protected]');
click('.activation-page form .btn-primary');
andThen(function() {
var errorMessage = find('.error-page .lead p').text();
assert.equal(errorMessage, 'You are banned for trolling.');
var expirationMessage = Ember.$.trim(find('.error-message>p').text());
assert.equal(expirationMessage, 'This ban is permanent.');
});
});
test('request activation link', function(assert) {
assert.expect(1);
Ember.$.mockjax({
url: '/api/auth/send-activation/',
status: 200,
responseText: {
'username': 'BobBoberson',
'email': '[email protected]'
}
});
visit('/activation');
fillIn('.activation-page form input', '[email protected]');
click('.activation-page form .btn-primary');
andThen(function() {
var pageHeader = Ember.$.trim(find('.page-header h1').text());
assert.equal(pageHeader, 'Activation link sent');
});
});
test('invalid token is handled', function(assert) {
assert.expect(2);
var message = 'Token was rejected.';
Ember.$.mockjax({
url: '/api/auth/activate-account/1/token/',
status: 400,
responseText: {
'detail': message
}
});
visit('/activation/1/token/');
andThen(function() {
assert.equal(currentPath(), 'activation.index');
assert.equal(getToastMessage(), message);
});
});
test('permission denied is handled', function(assert) {
assert.expect(2);
var message = 'Token was rejected.';
Ember.$.mockjax({
url: '/api/auth/activate-account/1/token/',
status: 403,
responseText: {
'detail': message
}
});
visit('/activation/1/token/');
andThen(function() {
assert.equal(currentPath(), 'error-403');
var errorMessage = Ember.$.trim(find('.error-page .lead').text());
assert.equal(errorMessage, message);
});
});
test('account is activated', function(assert) {
assert.expect(2);
var message = 'Yur account has been activated!';
Ember.$.mockjax({
url: '/api/auth/activate-account/1/token/',
status: 200,
responseText: {
'detail': message
}
});
visit('/activation/1/token/');
andThen(function() {
assert.equal(currentPath(), 'index');
assert.equal(getToastMessage(), message);
});
});
| leture/Misago | misago/emberapp/tests/acceptance/activate-test.js | JavaScript | gpl-2.0 | 6,118 |
'use strict';
var async = require('async'),
db = require('./database'),
topics = require('./topics'),
categories = require('./categories'),
posts = require('./posts'),
plugins = require('./plugins'),
batch = require('./batch');
(function(ThreadTools) {
ThreadTools.delete = function(tid, uid, callback) {
toggleDelete(tid, uid, true, callback);
};
ThreadTools.restore = function(tid, uid, callback) {
toggleDelete(tid, uid, false, callback);
};
function toggleDelete(tid, uid, isDelete, callback) {
topics.getTopicFields(tid, ['tid', 'cid', 'uid', 'deleted', 'title', 'mainPid'], function(err, topicData) {
if (err) {
return callback(err);
}
if (parseInt(topicData.deleted, 10) === 1 && isDelete) {
return callback(new Error('[[error:topic-already-deleted]]'));
} else if(parseInt(topicData.deleted, 10) !== 1 && !isDelete) {
return callback(new Error('[[error:topic-already-restored]]'));
}
topics[isDelete ? 'delete' : 'restore'](tid, function(err) {
if (err) {
return callback(err);
}
topicData.deleted = isDelete ? 1 : 0;
if (isDelete) {
plugins.fireHook('action:topic.delete', tid);
} else {
plugins.fireHook('action:topic.restore', topicData);
}
var data = {
tid: tid,
cid: topicData.cid,
isDelete: isDelete,
uid: uid
};
callback(null, data);
});
});
}
ThreadTools.purge = function(tid, uid, callback) {
var topic;
async.waterfall([
function(next) {
topics.exists(tid, next);
},
function(exists, next) {
if (!exists) {
return callback();
}
batch.processSortedSet('tid:' + tid + ':posts', function(pids, next) {
async.eachLimit(pids, 10, posts.purge, next);
}, {alwaysStartAt: 0}, next);
},
function(next) {
topics.getTopicFields(tid, ['mainPid', 'cid'], next);
},
function(_topic, next) {
topic = _topic;
posts.purge(topic.mainPid, next);
},
function(next) {
topics.purge(tid, next);
},
function(next) {
next(null, {tid: tid, cid: topic.cid, uid: uid});
}
], callback);
};
ThreadTools.lock = function(tid, uid, callback) {
toggleLock(tid, uid, true, callback);
};
ThreadTools.unlock = function(tid, uid, callback) {
toggleLock(tid, uid, false, callback);
};
function toggleLock(tid, uid, lock, callback) {
callback = callback || function() {};
topics.getTopicField(tid, 'cid', function(err, cid) {
if (err) {
return callback(err);
}
topics.setTopicField(tid, 'locked', lock ? 1 : 0);
var data = {
tid: tid,
isLocked: lock,
uid: uid,
cid: cid
};
plugins.fireHook('action:topic.lock', data);
callback(null, data);
});
}
ThreadTools.pin = function(tid, uid, callback) {
togglePin(tid, uid, true, callback);
};
ThreadTools.unpin = function(tid, uid, callback) {
togglePin(tid, uid, false, callback);
};
function togglePin(tid, uid, pin, callback) {
topics.getTopicFields(tid, ['cid', 'lastposttime'], function(err, topicData) {
if (err) {
return callback(err);
}
topics.setTopicField(tid, 'pinned', pin ? 1 : 0);
db.sortedSetAdd('cid:' + topicData.cid + ':tids', pin ? Math.pow(2, 53) : topicData.lastposttime, tid);
var data = {
tid: tid,
isPinned: pin,
uid: uid,
cid: topicData.cid
};
plugins.fireHook('action:topic.pin', data);
callback(null, data);
});
}
ThreadTools.move = function(tid, cid, uid, callback) {
var topic;
async.waterfall([
function(next) {
topics.getTopicFields(tid, ['cid', 'lastposttime', 'pinned', 'deleted', 'postcount'], next);
},
function(topicData, next) {
topic = topicData;
db.sortedSetsRemove([
'cid:' + topicData.cid + ':tids',
'cid:' + topicData.cid + ':tids:posts'
], tid, next);
},
function(next) {
var timestamp = parseInt(topic.pinned, 10) ? Math.pow(2, 53) : topic.lastposttime;
async.parallel([
function(next) {
db.sortedSetAdd('cid:' + cid + ':tids', timestamp, tid, next);
},
function(next) {
topic.postcount = topic.postcount || 0;
db.sortedSetAdd('cid:' + cid + ':tids:posts', topic.postcount, tid, next);
}
], next);
}
], function(err) {
if (err) {
return callback(err);
}
var oldCid = topic.cid;
if(!parseInt(topic.deleted, 10)) {
categories.incrementCategoryFieldBy(oldCid, 'topic_count', -1);
categories.incrementCategoryFieldBy(cid, 'topic_count', 1);
}
categories.moveRecentReplies(tid, oldCid, cid);
topics.setTopicField(tid, 'cid', cid, function(err) {
if (err) {
return callback(err);
}
plugins.fireHook('action:topic.move', {
tid: tid,
fromCid: oldCid,
toCid: cid,
uid: uid
});
callback();
});
});
};
}(exports));
| mario56/nodebb-cn-mongo | src/threadTools.js | JavaScript | gpl-3.0 | 4,819 |
/*!
*
* Super simple wysiwyg editor v0.8.16
* https://summernote.org
*
*
* Copyright 2013- Alan Hong. and other contributors
* summernote may be freely distributed under the MIT license.
*
* Date: 2020-02-19T09:12Z
*
*/
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else {
var a = factory();
for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];
}
})(window, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 10);
/******/ })
/************************************************************************/
/******/ ({
/***/ 10:
/***/ (function(module, exports) {
(function ($) {
$.extend($.summernote.lang, {
'ca-ES': {
font: {
bold: 'Negreta',
italic: 'Cursiva',
underline: 'Subratllat',
clear: 'Treure estil de lletra',
height: 'Alçada de línia',
name: 'Font',
strikethrough: 'Ratllat',
subscript: 'Subíndex',
superscript: 'Superíndex',
size: 'Mida de lletra'
},
image: {
image: 'Imatge',
insert: 'Inserir imatge',
resizeFull: 'Redimensionar a mida completa',
resizeHalf: 'Redimensionar a la meitat',
resizeQuarter: 'Redimensionar a un quart',
floatLeft: 'Alinear a l\'esquerra',
floatRight: 'Alinear a la dreta',
floatNone: 'No alinear',
shapeRounded: 'Forma: Arrodonit',
shapeCircle: 'Forma: Cercle',
shapeThumbnail: 'Forma: Marc',
shapeNone: 'Forma: Cap',
dragImageHere: 'Arrossegueu una imatge o text aquí',
dropImage: 'Deixa anar aquí una imatge o un text',
selectFromFiles: 'Seleccioneu des dels arxius',
maximumFileSize: 'Mida màxima de l\'arxiu',
maximumFileSizeError: 'La mida màxima de l\'arxiu s\'ha superat.',
url: 'URL de la imatge',
remove: 'Eliminar imatge',
original: 'Original'
},
video: {
video: 'Vídeo',
videoLink: 'Enllaç del vídeo',
insert: 'Inserir vídeo',
url: 'URL del vídeo?',
providers: '(YouTube, Vimeo, Vine, Instagram, DailyMotion o Youku)'
},
link: {
link: 'Enllaç',
insert: 'Inserir enllaç',
unlink: 'Treure enllaç',
edit: 'Editar',
textToDisplay: 'Text per mostrar',
url: 'Cap a quina URL porta l\'enllaç?',
openInNewWindow: 'Obrir en una finestra nova'
},
table: {
table: 'Taula',
addRowAbove: 'Add row above',
addRowBelow: 'Add row below',
addColLeft: 'Add column left',
addColRight: 'Add column right',
delRow: 'Delete row',
delCol: 'Delete column',
delTable: 'Delete table'
},
hr: {
insert: 'Inserir línia horitzontal'
},
style: {
style: 'Estil',
p: 'p',
blockquote: 'Cita',
pre: 'Codi',
h1: 'Títol 1',
h2: 'Títol 2',
h3: 'Títol 3',
h4: 'Títol 4',
h5: 'Títol 5',
h6: 'Títol 6'
},
lists: {
unordered: 'Llista desendreçada',
ordered: 'Llista endreçada'
},
options: {
help: 'Ajut',
fullscreen: 'Pantalla sencera',
codeview: 'Veure codi font'
},
paragraph: {
paragraph: 'Paràgraf',
outdent: 'Menys tabulació',
indent: 'Més tabulació',
left: 'Alinear a l\'esquerra',
center: 'Alinear al mig',
right: 'Alinear a la dreta',
justify: 'Justificar'
},
color: {
recent: 'Últim color',
more: 'Més colors',
background: 'Color de fons',
foreground: 'Color de lletra',
transparent: 'Transparent',
setTransparent: 'Establir transparent',
reset: 'Restablir',
resetToDefault: 'Restablir per defecte'
},
shortcut: {
shortcuts: 'Dreceres de teclat',
close: 'Tancar',
textFormatting: 'Format de text',
action: 'Acció',
paragraphFormatting: 'Format de paràgraf',
documentStyle: 'Estil del document',
extraKeys: 'Tecles adicionals'
},
help: {
'insertParagraph': 'Inserir paràgraf',
'undo': 'Desfer l\'última acció',
'redo': 'Refer l\'última acció',
'tab': 'Tabular',
'untab': 'Eliminar tabulació',
'bold': 'Establir estil negreta',
'italic': 'Establir estil cursiva',
'underline': 'Establir estil subratllat',
'strikethrough': 'Establir estil ratllat',
'removeFormat': 'Netejar estil',
'justifyLeft': 'Alinear a l\'esquerra',
'justifyCenter': 'Alinear al centre',
'justifyRight': 'Alinear a la dreta',
'justifyFull': 'Justificar',
'insertUnorderedList': 'Inserir llista desendreçada',
'insertOrderedList': 'Inserir llista endreçada',
'outdent': 'Reduïr tabulació del paràgraf',
'indent': 'Augmentar tabulació del paràgraf',
'formatPara': 'Canviar l\'estil del bloc com a un paràgraf (etiqueta P)',
'formatH1': 'Canviar l\'estil del bloc com a un H1',
'formatH2': 'Canviar l\'estil del bloc com a un H2',
'formatH3': 'Canviar l\'estil del bloc com a un H3',
'formatH4': 'Canviar l\'estil del bloc com a un H4',
'formatH5': 'Canviar l\'estil del bloc com a un H5',
'formatH6': 'Canviar l\'estil del bloc com a un H6',
'insertHorizontalRule': 'Inserir una línia horitzontal',
'linkDialog.show': 'Mostrar panel d\'enllaços'
},
history: {
undo: 'Desfer',
redo: 'Refer'
},
specialChar: {
specialChar: 'CARÀCTERS ESPECIALS',
select: 'Selecciona caràcters especials'
}
}
});
})(jQuery);
/***/ })
/******/ });
}); | rhomicom-systems-tech-gh/Rhomicom-ERP-Web | self/cs/plugins/summernote/lang/summernote-ca-ES.js | JavaScript | gpl-3.0 | 9,499 |
(function() {var implementors = {};
implementors["dbus"] = [];
if (window.register_implementors) {
window.register_implementors(implementors);
} else {
window.pending_implementors = implementors;
}
})()
| servo/doc.servo.org | implementors/dbus/objpath/trait.PropertyROHandler.js | JavaScript | mpl-2.0 | 281 |
/*
Built by: build_media_element_js.rake
from https://github.com/johndyer/mediaelement.git
revision: ceeb1a7f41b2557c4f6a865cee5564c82039201d
YOU SHOULDN'T EDIT ME DIRECTLY
*/
define(['jquery'], function (jQuery){
/*!
*
* MediaElement.js
* HTML5 <video> and <audio> shim and player
* http://mediaelementjs.com/
*
* Creates a JavaScript object that mimics HTML5 MediaElement API
* for browsers that don't understand HTML5 or can't play the provided codec
* Can play MP4 (H.264), Ogg, WebM, FLV, WMV, WMA, ACC, and MP3
*
* Copyright 2010-2014, John Dyer (http://j.hn)
* License: MIT
*
*/
// Namespace
var mejs = mejs || {};
// version number
mejs.version = '2.16.4';
// player number (for missing, same id attr)
mejs.meIndex = 0;
// media types accepted by plugins
mejs.plugins = {
silverlight: [
{version: [3,0], types: ['video/mp4','video/m4v','video/mov','video/wmv','audio/wma','audio/m4a','audio/mp3','audio/wav','audio/mpeg']}
],
flash: [
{version: [9,0,124], types: ['video/mp4','video/m4v','video/mov','video/flv','video/rtmp','video/x-flv','audio/flv','audio/x-flv','audio/mp3','audio/m4a','audio/mpeg', 'video/youtube', 'video/x-youtube', 'application/x-mpegURL']}
//,{version: [12,0], types: ['video/webm']} // for future reference (hopefully!)
],
youtube: [
{version: null, types: ['video/youtube', 'video/x-youtube', 'audio/youtube', 'audio/x-youtube']}
],
vimeo: [
{version: null, types: ['video/vimeo', 'video/x-vimeo']}
]
};
/*
Utility methods
*/
mejs.Utility = {
encodeUrl: function(url) {
return encodeURIComponent(url); //.replace(/\?/gi,'%3F').replace(/=/gi,'%3D').replace(/&/gi,'%26');
},
escapeHTML: function(s) {
return s.toString().split('&').join('&').split('<').join('<').split('"').join('"');
},
absolutizeUrl: function(url) {
var el = document.createElement('div');
el.innerHTML = '<a href="' + this.escapeHTML(url) + '">x</a>';
return el.firstChild.href;
},
getScriptPath: function(scriptNames) {
var
i = 0,
j,
codePath = '',
testname = '',
slashPos,
filenamePos,
scriptUrl,
scriptPath,
scriptFilename,
scripts = document.getElementsByTagName('script'),
il = scripts.length,
jl = scriptNames.length;
// go through all <script> tags
for (; i < il; i++) {
scriptUrl = scripts[i].src;
slashPos = scriptUrl.lastIndexOf('/');
if (slashPos > -1) {
scriptFilename = scriptUrl.substring(slashPos + 1);
scriptPath = scriptUrl.substring(0, slashPos + 1);
} else {
scriptFilename = scriptUrl;
scriptPath = '';
}
// see if any <script> tags have a file name that matches the
for (j = 0; j < jl; j++) {
testname = scriptNames[j];
filenamePos = scriptFilename.indexOf(testname);
if (filenamePos > -1) {
codePath = scriptPath;
break;
}
}
// if we found a path, then break and return it
if (codePath !== '') {
break;
}
}
// send the best path back
return codePath;
},
secondsToTimeCode: function(time, forceHours, showFrameCount, fps) {
//add framecount
if (typeof showFrameCount == 'undefined') {
showFrameCount=false;
} else if(typeof fps == 'undefined') {
fps = 25;
}
var hours = Math.floor(time / 3600) % 24,
minutes = Math.floor(time / 60) % 60,
seconds = Math.floor(time % 60),
frames = Math.floor(((time % 1)*fps).toFixed(3)),
result =
( (forceHours || hours > 0) ? (hours < 10 ? '0' + hours : hours) + ':' : '')
+ (minutes < 10 ? '0' + minutes : minutes) + ':'
+ (seconds < 10 ? '0' + seconds : seconds)
+ ((showFrameCount) ? ':' + (frames < 10 ? '0' + frames : frames) : '');
return result;
},
timeCodeToSeconds: function(hh_mm_ss_ff, forceHours, showFrameCount, fps){
if (typeof showFrameCount == 'undefined') {
showFrameCount=false;
} else if(typeof fps == 'undefined') {
fps = 25;
}
var tc_array = hh_mm_ss_ff.split(":"),
tc_hh = parseInt(tc_array[0], 10),
tc_mm = parseInt(tc_array[1], 10),
tc_ss = parseInt(tc_array[2], 10),
tc_ff = 0,
tc_in_seconds = 0;
if (showFrameCount) {
tc_ff = parseInt(tc_array[3])/fps;
}
tc_in_seconds = ( tc_hh * 3600 ) + ( tc_mm * 60 ) + tc_ss + tc_ff;
return tc_in_seconds;
},
convertSMPTEtoSeconds: function (SMPTE) {
if (typeof SMPTE != 'string')
return false;
SMPTE = SMPTE.replace(',', '.');
var secs = 0,
decimalLen = (SMPTE.indexOf('.') != -1) ? SMPTE.split('.')[1].length : 0,
multiplier = 1;
SMPTE = SMPTE.split(':').reverse();
for (var i = 0; i < SMPTE.length; i++) {
multiplier = 1;
if (i > 0) {
multiplier = Math.pow(60, i);
}
secs += Number(SMPTE[i]) * multiplier;
}
return Number(secs.toFixed(decimalLen));
},
/* borrowed from SWFObject: http://code.google.com/p/swfobject/source/browse/trunk/swfobject/src/swfobject.js#474 */
removeSwf: function(id) {
var obj = document.getElementById(id);
if (obj && /object|embed/i.test(obj.nodeName)) {
if (mejs.MediaFeatures.isIE) {
obj.style.display = "none";
(function(){
if (obj.readyState == 4) {
mejs.Utility.removeObjectInIE(id);
} else {
setTimeout(arguments.callee, 10);
}
})();
} else {
obj.parentNode.removeChild(obj);
}
}
},
removeObjectInIE: function(id) {
var obj = document.getElementById(id);
if (obj) {
for (var i in obj) {
if (typeof obj[i] == "function") {
obj[i] = null;
}
}
obj.parentNode.removeChild(obj);
}
}
};
// Core detector, plugins are added below
mejs.PluginDetector = {
// main public function to test a plug version number PluginDetector.hasPluginVersion('flash',[9,0,125]);
hasPluginVersion: function(plugin, v) {
var pv = this.plugins[plugin];
v[1] = v[1] || 0;
v[2] = v[2] || 0;
return (pv[0] > v[0] || (pv[0] == v[0] && pv[1] > v[1]) || (pv[0] == v[0] && pv[1] == v[1] && pv[2] >= v[2])) ? true : false;
},
// cached values
nav: window.navigator,
ua: window.navigator.userAgent.toLowerCase(),
// stored version numbers
plugins: [],
// runs detectPlugin() and stores the version number
addPlugin: function(p, pluginName, mimeType, activeX, axDetect) {
this.plugins[p] = this.detectPlugin(pluginName, mimeType, activeX, axDetect);
},
// get the version number from the mimetype (all but IE) or ActiveX (IE)
detectPlugin: function(pluginName, mimeType, activeX, axDetect) {
var version = [0,0,0],
description,
i,
ax;
// Firefox, Webkit, Opera
if (typeof(this.nav.plugins) != 'undefined' && typeof this.nav.plugins[pluginName] == 'object') {
description = this.nav.plugins[pluginName].description;
if (description && !(typeof this.nav.mimeTypes != 'undefined' && this.nav.mimeTypes[mimeType] && !this.nav.mimeTypes[mimeType].enabledPlugin)) {
version = description.replace(pluginName, '').replace(/^\s+/,'').replace(/\sr/gi,'.').split('.');
for (i=0; i<version.length; i++) {
version[i] = parseInt(version[i].match(/\d+/), 10);
}
}
// Internet Explorer / ActiveX
} else if (typeof(window.ActiveXObject) != 'undefined') {
try {
ax = new ActiveXObject(activeX);
if (ax) {
version = axDetect(ax);
}
}
catch (e) { }
}
return version;
}
};
// Add Flash detection
mejs.PluginDetector.addPlugin('flash','Shockwave Flash','application/x-shockwave-flash','ShockwaveFlash.ShockwaveFlash', function(ax) {
// adapted from SWFObject
var version = [],
d = ax.GetVariable("$version");
if (d) {
d = d.split(" ")[1].split(",");
version = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
}
return version;
});
// Add Silverlight detection
mejs.PluginDetector.addPlugin('silverlight','Silverlight Plug-In','application/x-silverlight-2','AgControl.AgControl', function (ax) {
// Silverlight cannot report its version number to IE
// but it does have a isVersionSupported function, so we have to loop through it to get a version number.
// adapted from http://www.silverlightversion.com/
var v = [0,0,0,0],
loopMatch = function(ax, v, i, n) {
while(ax.isVersionSupported(v[0]+ "."+ v[1] + "." + v[2] + "." + v[3])){
v[i]+=n;
}
v[i] -= n;
};
loopMatch(ax, v, 0, 1);
loopMatch(ax, v, 1, 1);
loopMatch(ax, v, 2, 10000); // the third place in the version number is usually 5 digits (4.0.xxxxx)
loopMatch(ax, v, 2, 1000);
loopMatch(ax, v, 2, 100);
loopMatch(ax, v, 2, 10);
loopMatch(ax, v, 2, 1);
loopMatch(ax, v, 3, 1);
return v;
});
// add adobe acrobat
/*
PluginDetector.addPlugin('acrobat','Adobe Acrobat','application/pdf','AcroPDF.PDF', function (ax) {
var version = [],
d = ax.GetVersions().split(',')[0].split('=')[1].split('.');
if (d) {
version = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
}
return version;
});
*/
// necessary detection (fixes for <IE9)
mejs.MediaFeatures = {
init: function() {
var
t = this,
d = document,
nav = mejs.PluginDetector.nav,
ua = mejs.PluginDetector.ua.toLowerCase(),
i,
v,
html5Elements = ['source','track','audio','video'];
// detect browsers (only the ones that have some kind of quirk we need to work around)
t.isiPad = (ua.match(/ipad/i) !== null);
t.isiPhone = (ua.match(/iphone/i) !== null);
t.isiOS = t.isiPhone || t.isiPad;
t.isAndroid = (ua.match(/android/i) !== null);
t.isBustedAndroid = (ua.match(/android 2\.[12]/) !== null);
t.isBustedNativeHTTPS = (location.protocol === 'https:' && (ua.match(/android [12]\./) !== null || ua.match(/macintosh.* version.* safari/) !== null));
t.isIE = (nav.appName.toLowerCase().indexOf("microsoft") != -1 || nav.appName.toLowerCase().match(/trident/gi) !== null);
t.isChrome = (ua.match(/chrome/gi) !== null);
t.isChromium = (ua.match(/chromium/gi) !== null);
t.isFirefox = (ua.match(/firefox/gi) !== null);
t.isWebkit = (ua.match(/webkit/gi) !== null);
t.isGecko = (ua.match(/gecko/gi) !== null) && !t.isWebkit && !t.isIE;
t.isOpera = (ua.match(/opera/gi) !== null);
t.hasTouch = ('ontouchstart' in window); // && window.ontouchstart != null); // this breaks iOS 7
// borrowed from Modernizr
t.svg = !! document.createElementNS &&
!! document.createElementNS('http://www.w3.org/2000/svg','svg').createSVGRect;
// create HTML5 media elements for IE before 9, get a <video> element for fullscreen detection
for (i=0; i<html5Elements.length; i++) {
v = document.createElement(html5Elements[i]);
}
t.supportsMediaTag = (typeof v.canPlayType !== 'undefined' || t.isBustedAndroid);
// Fix for IE9 on Windows 7N / Windows 7KN (Media Player not installer)
try{
v.canPlayType("video/mp4");
}catch(e){
t.supportsMediaTag = false;
}
// detect native JavaScript fullscreen (Safari/Firefox only, Chrome still fails)
// iOS
t.hasSemiNativeFullScreen = (typeof v.webkitEnterFullscreen !== 'undefined');
// W3C
t.hasNativeFullscreen = (typeof v.requestFullscreen !== 'undefined');
// webkit/firefox/IE11+
t.hasWebkitNativeFullScreen = (typeof v.webkitRequestFullScreen !== 'undefined');
t.hasMozNativeFullScreen = (typeof v.mozRequestFullScreen !== 'undefined');
t.hasMsNativeFullScreen = (typeof v.msRequestFullscreen !== 'undefined');
t.hasTrueNativeFullScreen = (t.hasWebkitNativeFullScreen || t.hasMozNativeFullScreen || t.hasMsNativeFullScreen);
t.nativeFullScreenEnabled = t.hasTrueNativeFullScreen;
// Enabled?
if (t.hasMozNativeFullScreen) {
t.nativeFullScreenEnabled = document.mozFullScreenEnabled;
} else if (t.hasMsNativeFullScreen) {
t.nativeFullScreenEnabled = document.msFullscreenEnabled;
}
if (t.isChrome) {
t.hasSemiNativeFullScreen = false;
}
if (t.hasTrueNativeFullScreen) {
t.fullScreenEventName = '';
if (t.hasWebkitNativeFullScreen) {
t.fullScreenEventName = 'webkitfullscreenchange';
} else if (t.hasMozNativeFullScreen) {
t.fullScreenEventName = 'mozfullscreenchange';
} else if (t.hasMsNativeFullScreen) {
t.fullScreenEventName = 'MSFullscreenChange';
}
t.isFullScreen = function() {
if (t.hasMozNativeFullScreen) {
return d.mozFullScreen;
} else if (t.hasWebkitNativeFullScreen) {
return d.webkitIsFullScreen;
} else if (t.hasMsNativeFullScreen) {
return d.msFullscreenElement !== null;
}
}
t.requestFullScreen = function(el) {
if (t.hasWebkitNativeFullScreen) {
el.webkitRequestFullScreen();
} else if (t.hasMozNativeFullScreen) {
el.mozRequestFullScreen();
} else if (t.hasMsNativeFullScreen) {
el.msRequestFullscreen();
}
}
t.cancelFullScreen = function() {
if (t.hasWebkitNativeFullScreen) {
document.webkitCancelFullScreen();
} else if (t.hasMozNativeFullScreen) {
document.mozCancelFullScreen();
} else if (t.hasMsNativeFullScreen) {
document.msExitFullscreen();
}
}
}
// OS X 10.5 can't do this even if it says it can :(
if (t.hasSemiNativeFullScreen && ua.match(/mac os x 10_5/i)) {
t.hasNativeFullScreen = false;
t.hasSemiNativeFullScreen = false;
}
}
};
mejs.MediaFeatures.init();
/*
extension methods to <video> or <audio> object to bring it into parity with PluginMediaElement (see below)
*/
mejs.HtmlMediaElement = {
pluginType: 'native',
isFullScreen: false,
setCurrentTime: function (time) {
this.currentTime = time;
},
setMuted: function (muted) {
this.muted = muted;
},
setVolume: function (volume) {
this.volume = volume;
},
// for parity with the plugin versions
stop: function () {
this.pause();
},
// This can be a url string
// or an array [{src:'file.mp4',type:'video/mp4'},{src:'file.webm',type:'video/webm'}]
setSrc: function (url) {
// Fix for IE9 which can't set .src when there are <source> elements. Awesome, right?
var
existingSources = this.getElementsByTagName('source');
while (existingSources.length > 0){
this.removeChild(existingSources[0]);
}
if (typeof url == 'string') {
this.src = url;
} else {
var i, media;
for (i=0; i<url.length; i++) {
media = url[i];
if (this.canPlayType(media.type)) {
this.src = media.src;
break;
}
}
}
},
setVideoSize: function (width, height) {
this.width = width;
this.height = height;
}
};
/*
Mimics the <video/audio> element by calling Flash's External Interface or Silverlights [ScriptableMember]
*/
mejs.PluginMediaElement = function (pluginid, pluginType, mediaUrl) {
this.id = pluginid;
this.pluginType = pluginType;
this.src = mediaUrl;
this.events = {};
this.attributes = {};
};
// JavaScript values and ExternalInterface methods that match HTML5 video properties methods
// http://www.adobe.com/livedocs/flash/9.0/ActionScriptLangRefV3/fl/video/FLVPlayback.html
// http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html
mejs.PluginMediaElement.prototype = {
// special
pluginElement: null,
pluginType: '',
isFullScreen: false,
// not implemented :(
playbackRate: -1,
defaultPlaybackRate: -1,
seekable: [],
played: [],
// HTML5 read-only properties
paused: true,
ended: false,
seeking: false,
duration: 0,
error: null,
tagName: '',
// HTML5 get/set properties, but only set (updated by event handlers)
muted: false,
volume: 1,
currentTime: 0,
// HTML5 methods
play: function () {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube' || this.pluginType == 'vimeo') {
this.pluginApi.playVideo();
} else {
this.pluginApi.playMedia();
}
this.paused = false;
}
},
load: function () {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube' || this.pluginType == 'vimeo') {
} else {
this.pluginApi.loadMedia();
}
this.paused = false;
}
},
pause: function () {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube' || this.pluginType == 'vimeo') {
this.pluginApi.pauseVideo();
} else {
this.pluginApi.pauseMedia();
}
this.paused = true;
}
},
stop: function () {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube' || this.pluginType == 'vimeo') {
this.pluginApi.stopVideo();
} else {
this.pluginApi.stopMedia();
}
this.paused = true;
}
},
canPlayType: function(type) {
var i,
j,
pluginInfo,
pluginVersions = mejs.plugins[this.pluginType];
for (i=0; i<pluginVersions.length; i++) {
pluginInfo = pluginVersions[i];
// test if user has the correct plugin version
if (mejs.PluginDetector.hasPluginVersion(this.pluginType, pluginInfo.version)) {
// test for plugin playback types
for (j=0; j<pluginInfo.types.length; j++) {
// find plugin that can play the type
if (type == pluginInfo.types[j]) {
return 'probably';
}
}
}
}
return '';
},
positionFullscreenButton: function(x,y,visibleAndAbove) {
if (this.pluginApi != null && this.pluginApi.positionFullscreenButton) {
this.pluginApi.positionFullscreenButton(Math.floor(x),Math.floor(y),visibleAndAbove);
}
},
hideFullscreenButton: function() {
if (this.pluginApi != null && this.pluginApi.hideFullscreenButton) {
this.pluginApi.hideFullscreenButton();
}
},
// custom methods since not all JavaScript implementations support get/set
// This can be a url string
// or an array [{src:'file.mp4',type:'video/mp4'},{src:'file.webm',type:'video/webm'}]
setSrc: function (url) {
if (typeof url == 'string') {
this.pluginApi.setSrc(mejs.Utility.absolutizeUrl(url));
this.src = mejs.Utility.absolutizeUrl(url);
} else {
var i, media;
for (i=0; i<url.length; i++) {
media = url[i];
if (this.canPlayType(media.type)) {
this.pluginApi.setSrc(mejs.Utility.absolutizeUrl(media.src));
this.src = mejs.Utility.absolutizeUrl(url);
break;
}
}
}
},
setCurrentTime: function (time) {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube' || this.pluginType == 'vimeo') {
this.pluginApi.seekTo(time);
} else {
this.pluginApi.setCurrentTime(time);
}
this.currentTime = time;
}
},
setVolume: function (volume) {
if (this.pluginApi != null) {
// same on YouTube and MEjs
if (this.pluginType == 'youtube') {
this.pluginApi.setVolume(volume * 100);
} else {
this.pluginApi.setVolume(volume);
}
this.volume = volume;
}
},
setMuted: function (muted) {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
if (muted) {
this.pluginApi.mute();
} else {
this.pluginApi.unMute();
}
this.muted = muted;
this.dispatchEvent('volumechange');
} else {
this.pluginApi.setMuted(muted);
}
this.muted = muted;
}
},
// additional non-HTML5 methods
setVideoSize: function (width, height) {
//if (this.pluginType == 'flash' || this.pluginType == 'silverlight') {
if (this.pluginElement && this.pluginElement.style) {
this.pluginElement.style.width = width + 'px';
this.pluginElement.style.height = height + 'px';
}
if (this.pluginApi != null && this.pluginApi.setVideoSize) {
this.pluginApi.setVideoSize(width, height);
}
//}
},
setFullscreen: function (fullscreen) {
if (this.pluginApi != null && this.pluginApi.setFullscreen) {
this.pluginApi.setFullscreen(fullscreen);
}
},
enterFullScreen: function() {
if (this.pluginApi != null && this.pluginApi.setFullscreen) {
this.setFullscreen(true);
}
},
exitFullScreen: function() {
if (this.pluginApi != null && this.pluginApi.setFullscreen) {
this.setFullscreen(false);
}
},
// start: fake events
addEventListener: function (eventName, callback, bubble) {
this.events[eventName] = this.events[eventName] || [];
this.events[eventName].push(callback);
},
removeEventListener: function (eventName, callback) {
if (!eventName) { this.events = {}; return true; }
var callbacks = this.events[eventName];
if (!callbacks) return true;
if (!callback) { this.events[eventName] = []; return true; }
for (var i = 0; i < callbacks.length; i++) {
if (callbacks[i] === callback) {
this.events[eventName].splice(i, 1);
return true;
}
}
return false;
},
dispatchEvent: function (eventName) {
var i,
args,
callbacks = this.events[eventName];
if (callbacks) {
args = Array.prototype.slice.call(arguments, 1);
for (i = 0; i < callbacks.length; i++) {
callbacks[i].apply(this, args);
}
}
},
// end: fake events
// fake DOM attribute methods
hasAttribute: function(name){
return (name in this.attributes);
},
removeAttribute: function(name){
delete this.attributes[name];
},
getAttribute: function(name){
if (this.hasAttribute(name)) {
return this.attributes[name];
}
return '';
},
setAttribute: function(name, value){
this.attributes[name] = value;
},
remove: function() {
mejs.Utility.removeSwf(this.pluginElement.id);
mejs.MediaPluginBridge.unregisterPluginElement(this.pluginElement.id);
}
};
// Handles calls from Flash/Silverlight and reports them as native <video/audio> events and properties
mejs.MediaPluginBridge = {
pluginMediaElements:{},
htmlMediaElements:{},
registerPluginElement: function (id, pluginMediaElement, htmlMediaElement) {
this.pluginMediaElements[id] = pluginMediaElement;
this.htmlMediaElements[id] = htmlMediaElement;
},
unregisterPluginElement: function (id) {
delete this.pluginMediaElements[id];
delete this.htmlMediaElements[id];
},
// when Flash/Silverlight is ready, it calls out to this method
initPlugin: function (id) {
var pluginMediaElement = this.pluginMediaElements[id],
htmlMediaElement = this.htmlMediaElements[id];
if (pluginMediaElement) {
// find the javascript bridge
switch (pluginMediaElement.pluginType) {
case "flash":
pluginMediaElement.pluginElement = pluginMediaElement.pluginApi = document.getElementById(id);
break;
case "silverlight":
pluginMediaElement.pluginElement = document.getElementById(pluginMediaElement.id);
pluginMediaElement.pluginApi = pluginMediaElement.pluginElement.Content.MediaElementJS;
break;
}
if (pluginMediaElement.pluginApi != null && pluginMediaElement.success) {
pluginMediaElement.success(pluginMediaElement, htmlMediaElement);
}
}
},
// receives events from Flash/Silverlight and sends them out as HTML5 media events
// http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html
fireEvent: function (id, eventName, values) {
var
e,
i,
bufferedTime,
pluginMediaElement = this.pluginMediaElements[id];
if(!pluginMediaElement){
return;
}
// fake event object to mimic real HTML media event.
e = {
type: eventName,
target: pluginMediaElement
};
// attach all values to element and event object
for (i in values) {
pluginMediaElement[i] = values[i];
e[i] = values[i];
}
// fake the newer W3C buffered TimeRange (loaded and total have been removed)
bufferedTime = values.bufferedTime || 0;
e.target.buffered = e.buffered = {
start: function(index) {
return 0;
},
end: function (index) {
return bufferedTime;
},
length: 1
};
pluginMediaElement.dispatchEvent(e.type, e);
}
};
/*
Default options
*/
mejs.MediaElementDefaults = {
// allows testing on HTML5, flash, silverlight
// auto: attempts to detect what the browser can do
// auto_plugin: prefer plugins and then attempt native HTML5
// native: forces HTML5 playback
// shim: disallows HTML5, will attempt either Flash or Silverlight
// none: forces fallback view
mode: 'auto',
// remove or reorder to change plugin priority and availability
plugins: ['flash','silverlight','youtube','vimeo'],
// shows debug errors on screen
enablePluginDebug: false,
// use plugin for browsers that have trouble with Basic Authentication on HTTPS sites
httpsBasicAuthSite: false,
// overrides the type specified, useful for dynamic instantiation
type: '',
// path to Flash and Silverlight plugins
pluginPath: mejs.Utility.getScriptPath(['mediaelement.js','mediaelement.min.js','mediaelement-and-player.js','mediaelement-and-player.min.js']),
// name of flash file
flashName: 'flashmediaelement.swf',
// streamer for RTMP streaming
flashStreamer: '',
// turns on the smoothing filter in Flash
enablePluginSmoothing: false,
// enabled pseudo-streaming (seek) on .mp4 files
enablePseudoStreaming: false,
// start query parameter sent to server for pseudo-streaming
pseudoStreamingStartQueryParam: 'start',
// name of silverlight file
silverlightName: 'silverlightmediaelement.xap',
// default if the <video width> is not specified
defaultVideoWidth: 480,
// default if the <video height> is not specified
defaultVideoHeight: 270,
// overrides <video width>
pluginWidth: -1,
// overrides <video height>
pluginHeight: -1,
// additional plugin variables in 'key=value' form
pluginVars: [],
// rate in milliseconds for Flash and Silverlight to fire the timeupdate event
// larger number is less accurate, but less strain on plugin->JavaScript bridge
timerRate: 250,
// initial volume for player
startVolume: 0.8,
success: function () { },
error: function () { }
};
/*
Determines if a browser supports the <video> or <audio> element
and returns either the native element or a Flash/Silverlight version that
mimics HTML5 MediaElement
*/
mejs.MediaElement = function (el, o) {
return mejs.HtmlMediaElementShim.create(el,o);
};
mejs.HtmlMediaElementShim = {
create: function(el, o) {
var
options = mejs.MediaElementDefaults,
htmlMediaElement = (typeof(el) == 'string') ? document.getElementById(el) : el,
tagName = htmlMediaElement.tagName.toLowerCase(),
isMediaTag = (tagName === 'audio' || tagName === 'video'),
src = (isMediaTag) ? htmlMediaElement.getAttribute('src') : htmlMediaElement.getAttribute('href'),
poster = htmlMediaElement.getAttribute('poster'),
autoplay = htmlMediaElement.getAttribute('autoplay'),
preload = htmlMediaElement.getAttribute('preload'),
controls = htmlMediaElement.getAttribute('controls'),
playback,
prop;
// extend options
for (prop in o) {
options[prop] = o[prop];
}
// clean up attributes
src = (typeof src == 'undefined' || src === null || src == '') ? null : src;
poster = (typeof poster == 'undefined' || poster === null) ? '' : poster;
preload = (typeof preload == 'undefined' || preload === null || preload === 'false') ? 'none' : preload;
autoplay = !(typeof autoplay == 'undefined' || autoplay === null || autoplay === 'false');
controls = !(typeof controls == 'undefined' || controls === null || controls === 'false');
// test for HTML5 and plugin capabilities
playback = this.determinePlayback(htmlMediaElement, options, mejs.MediaFeatures.supportsMediaTag, isMediaTag, src);
playback.url = (playback.url !== null) ? mejs.Utility.absolutizeUrl(playback.url) : '';
if (playback.method == 'native') {
// second fix for android
if (mejs.MediaFeatures.isBustedAndroid) {
htmlMediaElement.src = playback.url;
htmlMediaElement.addEventListener('click', function() {
htmlMediaElement.play();
}, false);
}
// add methods to native HTMLMediaElement
return this.updateNative(playback, options, autoplay, preload);
} else if (playback.method !== '') {
// create plugin to mimic HTMLMediaElement
return this.createPlugin( playback, options, poster, autoplay, preload, controls);
} else {
// boo, no HTML5, no Flash, no Silverlight.
this.createErrorMessage( playback, options, poster );
return this;
}
},
determinePlayback: function(htmlMediaElement, options, supportsMediaTag, isMediaTag, src) {
var
mediaFiles = [],
i,
j,
k,
l,
n,
type,
result = { method: '', url: '', htmlMediaElement: htmlMediaElement, isVideo: (htmlMediaElement.tagName.toLowerCase() != 'audio')},
pluginName,
pluginVersions,
pluginInfo,
dummy,
media;
// STEP 1: Get URL and type from <video src> or <source src>
// supplied type overrides <video type> and <source type>
if (typeof options.type != 'undefined' && options.type !== '') {
// accept either string or array of types
if (typeof options.type == 'string') {
mediaFiles.push({type:options.type, url:src});
} else {
for (i=0; i<options.type.length; i++) {
mediaFiles.push({type:options.type[i], url:src});
}
}
// test for src attribute first
} else if (src !== null) {
type = this.formatType(src, htmlMediaElement.getAttribute('type'));
mediaFiles.push({type:type, url:src});
// then test for <source> elements
} else {
// test <source> types to see if they are usable
for (i = 0; i < htmlMediaElement.childNodes.length; i++) {
n = htmlMediaElement.childNodes[i];
if (n.nodeType == 1 && n.tagName.toLowerCase() == 'source') {
src = n.getAttribute('src');
type = this.formatType(src, n.getAttribute('type'));
media = n.getAttribute('media');
if (!media || !window.matchMedia || (window.matchMedia && window.matchMedia(media).matches)) {
mediaFiles.push({type:type, url:src});
}
}
}
}
// in the case of dynamicly created players
// check for audio types
if (!isMediaTag && mediaFiles.length > 0 && mediaFiles[0].url !== null && this.getTypeFromFile(mediaFiles[0].url).indexOf('audio') > -1) {
result.isVideo = false;
}
// STEP 2: Test for playback method
// special case for Android which sadly doesn't implement the canPlayType function (always returns '')
if (mejs.MediaFeatures.isBustedAndroid) {
htmlMediaElement.canPlayType = function(type) {
return (type.match(/video\/(mp4|m4v)/gi) !== null) ? 'maybe' : '';
};
}
// special case for Chromium to specify natively supported video codecs (i.e. WebM and Theora)
if (mejs.MediaFeatures.isChromium) {
htmlMediaElement.canPlayType = function(type) {
return (type.match(/video\/(webm|ogv|ogg)/gi) !== null) ? 'maybe' : '';
};
}
// test for native playback first
if (supportsMediaTag && (options.mode === 'auto' || options.mode === 'auto_plugin' || options.mode === 'native') && !(mejs.MediaFeatures.isBustedNativeHTTPS && options.httpsBasicAuthSite === true)) {
if (!isMediaTag) {
// create a real HTML5 Media Element
dummy = document.createElement( result.isVideo ? 'video' : 'audio');
htmlMediaElement.parentNode.insertBefore(dummy, htmlMediaElement);
htmlMediaElement.style.display = 'none';
// use this one from now on
result.htmlMediaElement = htmlMediaElement = dummy;
}
for (i=0; i<mediaFiles.length; i++) {
// normal check
if (mediaFiles[i].type == "video/m3u8" || htmlMediaElement.canPlayType(mediaFiles[i].type).replace(/no/, '') !== ''
// special case for Mac/Safari 5.0.3 which answers '' to canPlayType('audio/mp3') but 'maybe' to canPlayType('audio/mpeg')
|| htmlMediaElement.canPlayType(mediaFiles[i].type.replace(/mp3/,'mpeg')).replace(/no/, '') !== ''
// special case for m4a supported by detecting mp4 support
|| htmlMediaElement.canPlayType(mediaFiles[i].type.replace(/m4a/,'mp4')).replace(/no/, '') !== '') {
result.method = 'native';
result.url = mediaFiles[i].url;
break;
}
}
if (result.method === 'native') {
if (result.url !== null) {
htmlMediaElement.src = result.url;
}
// if `auto_plugin` mode, then cache the native result but try plugins.
if (options.mode !== 'auto_plugin') {
return result;
}
}
}
// if native playback didn't work, then test plugins
if (options.mode === 'auto' || options.mode === 'auto_plugin' || options.mode === 'shim') {
for (i=0; i<mediaFiles.length; i++) {
type = mediaFiles[i].type;
// test all plugins in order of preference [silverlight, flash]
for (j=0; j<options.plugins.length; j++) {
pluginName = options.plugins[j];
// test version of plugin (for future features)
pluginVersions = mejs.plugins[pluginName];
for (k=0; k<pluginVersions.length; k++) {
pluginInfo = pluginVersions[k];
// test if user has the correct plugin version
// for youtube/vimeo
if (pluginInfo.version == null ||
mejs.PluginDetector.hasPluginVersion(pluginName, pluginInfo.version)) {
// test for plugin playback types
for (l=0; l<pluginInfo.types.length; l++) {
// find plugin that can play the type
if (type == pluginInfo.types[l]) {
result.method = pluginName;
result.url = mediaFiles[i].url;
return result;
}
}
}
}
}
}
}
// at this point, being in 'auto_plugin' mode implies that we tried plugins but failed.
// if we have native support then return that.
if (options.mode === 'auto_plugin' && result.method === 'native') {
return result;
}
// what if there's nothing to play? just grab the first available
if (result.method === '' && mediaFiles.length > 0) {
result.url = mediaFiles[0].url;
}
return result;
},
formatType: function(url, type) {
var ext;
// if no type is supplied, fake it with the extension
if (url && !type) {
return this.getTypeFromFile(url);
} else {
// only return the mime part of the type in case the attribute contains the codec
// see http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html#the-source-element
// `video/mp4; codecs="avc1.42E01E, mp4a.40.2"` becomes `video/mp4`
if (type && ~type.indexOf(';')) {
return type.substr(0, type.indexOf(';'));
} else {
return type;
}
}
},
getTypeFromFile: function(url) {
url = url.split('?')[0];
var ext = url.substring(url.lastIndexOf('.') + 1).toLowerCase();
return (/(mp4|m4v|ogg|ogv|m3u8|webm|webmv|flv|wmv|mpeg|mov)/gi.test(ext) ? 'video' : 'audio') + '/' + this.getTypeFromExtension(ext);
},
getTypeFromExtension: function(ext) {
switch (ext) {
case 'mp4':
case 'm4v':
case 'm4a':
return 'mp4';
case 'webm':
case 'webma':
case 'webmv':
return 'webm';
case 'ogg':
case 'oga':
case 'ogv':
return 'ogg';
default:
return ext;
}
},
createErrorMessage: function(playback, options, poster) {
var
htmlMediaElement = playback.htmlMediaElement,
errorContainer = document.createElement('div');
errorContainer.className = 'me-cannotplay';
try {
errorContainer.style.width = htmlMediaElement.width + 'px';
errorContainer.style.height = htmlMediaElement.height + 'px';
} catch (e) {}
if (options.customError) {
errorContainer.innerHTML = options.customError;
} else {
errorContainer.innerHTML = (poster !== '') ?
'<a href="' + playback.url + '"><img src="' + poster + '" width="100%" height="100%" /></a>' :
'<a href="' + playback.url + '"><span>' + mejs.i18n.t('Download File') + '</span></a>';
}
htmlMediaElement.parentNode.insertBefore(errorContainer, htmlMediaElement);
htmlMediaElement.style.display = 'none';
options.error(htmlMediaElement);
},
createPlugin:function(playback, options, poster, autoplay, preload, controls) {
var
htmlMediaElement = playback.htmlMediaElement,
width = 1,
height = 1,
pluginid = 'me_' + playback.method + '_' + (mejs.meIndex++),
pluginMediaElement = new mejs.PluginMediaElement(pluginid, playback.method, playback.url),
container = document.createElement('div'),
specialIEContainer,
node,
initVars;
// copy tagName from html media element
pluginMediaElement.tagName = htmlMediaElement.tagName
// copy attributes from html media element to plugin media element
for (var i = 0; i < htmlMediaElement.attributes.length; i++) {
var attribute = htmlMediaElement.attributes[i];
if (attribute.specified == true) {
pluginMediaElement.setAttribute(attribute.name, attribute.value);
}
}
// check for placement inside a <p> tag (sometimes WYSIWYG editors do this)
node = htmlMediaElement.parentNode;
while (node !== null && node.tagName.toLowerCase() !== 'body' && node.parentNode != null) {
if (node.parentNode.tagName.toLowerCase() === 'p') {
node.parentNode.parentNode.insertBefore(node, node.parentNode);
break;
}
node = node.parentNode;
}
if (playback.isVideo) {
width = (options.pluginWidth > 0) ? options.pluginWidth : (options.videoWidth > 0) ? options.videoWidth : (htmlMediaElement.getAttribute('width') !== null) ? htmlMediaElement.getAttribute('width') : options.defaultVideoWidth;
height = (options.pluginHeight > 0) ? options.pluginHeight : (options.videoHeight > 0) ? options.videoHeight : (htmlMediaElement.getAttribute('height') !== null) ? htmlMediaElement.getAttribute('height') : options.defaultVideoHeight;
// in case of '%' make sure it's encoded
width = mejs.Utility.encodeUrl(width);
height = mejs.Utility.encodeUrl(height);
} else {
if (options.enablePluginDebug) {
width = 320;
height = 240;
}
}
// register plugin
pluginMediaElement.success = options.success;
mejs.MediaPluginBridge.registerPluginElement(pluginid, pluginMediaElement, htmlMediaElement);
// add container (must be added to DOM before inserting HTML for IE)
container.className = 'me-plugin';
container.id = pluginid + '_container';
if (playback.isVideo) {
htmlMediaElement.parentNode.insertBefore(container, htmlMediaElement);
} else {
document.body.insertBefore(container, document.body.childNodes[0]);
}
// flash/silverlight vars
initVars = [
'id=' + pluginid,
'jsinitfunction=' + "mejs.MediaPluginBridge.initPlugin",
'jscallbackfunction=' + "mejs.MediaPluginBridge.fireEvent",
'isvideo=' + ((playback.isVideo) ? "true" : "false"),
'autoplay=' + ((autoplay) ? "true" : "false"),
'preload=' + preload,
'width=' + width,
'startvolume=' + options.startVolume,
'timerrate=' + options.timerRate,
'flashstreamer=' + options.flashStreamer,
'height=' + height,
'pseudostreamstart=' + options.pseudoStreamingStartQueryParam];
if (playback.url !== null) {
if (playback.method == 'flash') {
initVars.push('file=' + mejs.Utility.encodeUrl(playback.url));
} else {
initVars.push('file=' + playback.url);
}
}
if (options.enablePluginDebug) {
initVars.push('debug=true');
}
if (options.enablePluginSmoothing) {
initVars.push('smoothing=true');
}
if (options.enablePseudoStreaming) {
initVars.push('pseudostreaming=true');
}
if (controls) {
initVars.push('controls=true'); // shows controls in the plugin if desired
}
if (options.pluginVars) {
initVars = initVars.concat(options.pluginVars);
}
switch (playback.method) {
case 'silverlight':
container.innerHTML =
'<object data="data:application/x-silverlight-2," type="application/x-silverlight-2" id="' + pluginid + '" name="' + pluginid + '" width="' + width + '" height="' + height + '" class="mejs-shim">' +
'<param name="initParams" value="' + initVars.join(',') + '" />' +
'<param name="windowless" value="true" />' +
'<param name="background" value="black" />' +
'<param name="minRuntimeVersion" value="3.0.0.0" />' +
'<param name="autoUpgrade" value="true" />' +
'<param name="source" value="' + options.pluginPath + options.silverlightName + '" />' +
'</object>';
break;
case 'flash':
if (mejs.MediaFeatures.isIE) {
specialIEContainer = document.createElement('div');
container.appendChild(specialIEContainer);
specialIEContainer.outerHTML =
'<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="//download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" ' +
'id="' + pluginid + '" width="' + width + '" height="' + height + '" class="mejs-shim">' +
'<param name="movie" value="' + options.pluginPath + options.flashName + '?x=' + (new Date()) + '" />' +
'<param name="flashvars" value="' + initVars.join('&') + '" />' +
'<param name="quality" value="high" />' +
'<param name="bgcolor" value="#000000" />' +
'<param name="wmode" value="transparent" />' +
'<param name="allowScriptAccess" value="always" />' +
'<param name="allowFullScreen" value="true" />' +
'<param name="scale" value="default" />' +
'</object>';
} else {
container.innerHTML =
'<embed id="' + pluginid + '" name="' + pluginid + '" ' +
'play="true" ' +
'loop="false" ' +
'quality="high" ' +
'bgcolor="#000000" ' +
'wmode="transparent" ' +
'allowScriptAccess="always" ' +
'allowFullScreen="true" ' +
'type="application/x-shockwave-flash" pluginspage="//www.macromedia.com/go/getflashplayer" ' +
'src="' + options.pluginPath + options.flashName + '" ' +
'flashvars="' + initVars.join('&') + '" ' +
'width="' + width + '" ' +
'height="' + height + '" ' +
'scale="default"' +
'class="mejs-shim"></embed>';
}
break;
case 'youtube':
var videoId;
// youtu.be url from share button
if (playback.url.lastIndexOf("youtu.be") != -1) {
videoId = playback.url.substr(playback.url.lastIndexOf('/')+1);
if (videoId.indexOf('?') != -1) {
videoId = videoId.substr(0, videoId.indexOf('?'));
}
}
else {
videoId = playback.url.substr(playback.url.lastIndexOf('=')+1);
}
youtubeSettings = {
container: container,
containerId: container.id,
pluginMediaElement: pluginMediaElement,
pluginId: pluginid,
videoId: videoId,
height: height,
width: width
};
if (mejs.PluginDetector.hasPluginVersion('flash', [10,0,0]) ) {
mejs.YouTubeApi.createFlash(youtubeSettings);
} else {
mejs.YouTubeApi.enqueueIframe(youtubeSettings);
}
break;
// DEMO Code. Does NOT work.
case 'vimeo':
var player_id = pluginid + "_player";
pluginMediaElement.vimeoid = playback.url.substr(playback.url.lastIndexOf('/')+1);
container.innerHTML ='<iframe src="//player.vimeo.com/video/' + pluginMediaElement.vimeoid + '?api=1&portrait=0&byline=0&title=0&player_id=' + player_id + '" width="' + width +'" height="' + height +'" frameborder="0" class="mejs-shim" id="' + player_id + '" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>';
if (typeof($f) == 'function') { // froogaloop available
var player = $f(container.childNodes[0]);
player.addEvent('ready', function() {
player.playVideo = function() {
player.api( 'play' );
}
player.stopVideo = function() {
player.api( 'unload' );
}
player.pauseVideo = function() {
player.api( 'pause' );
}
player.seekTo = function( seconds ) {
player.api( 'seekTo', seconds );
}
player.setVolume = function( volume ) {
player.api( 'setVolume', volume );
}
player.setMuted = function( muted ) {
if( muted ) {
player.lastVolume = player.api( 'getVolume' );
player.api( 'setVolume', 0 );
} else {
player.api( 'setVolume', player.lastVolume );
delete player.lastVolume;
}
}
function createEvent(player, pluginMediaElement, eventName, e) {
var obj = {
type: eventName,
target: pluginMediaElement
};
if (eventName == 'timeupdate') {
pluginMediaElement.currentTime = obj.currentTime = e.seconds;
pluginMediaElement.duration = obj.duration = e.duration;
}
pluginMediaElement.dispatchEvent(obj.type, obj);
}
player.addEvent('play', function() {
createEvent(player, pluginMediaElement, 'play');
createEvent(player, pluginMediaElement, 'playing');
});
player.addEvent('pause', function() {
createEvent(player, pluginMediaElement, 'pause');
});
player.addEvent('finish', function() {
createEvent(player, pluginMediaElement, 'ended');
});
player.addEvent('playProgress', function(e) {
createEvent(player, pluginMediaElement, 'timeupdate', e);
});
pluginMediaElement.pluginElement = container;
pluginMediaElement.pluginApi = player;
// init mejs
mejs.MediaPluginBridge.initPlugin(pluginid);
});
}
else {
console.warn("You need to include froogaloop for vimeo to work");
}
break;
}
// hide original element
htmlMediaElement.style.display = 'none';
// prevent browser from autoplaying when using a plugin
htmlMediaElement.removeAttribute('autoplay');
// FYI: options.success will be fired by the MediaPluginBridge
return pluginMediaElement;
},
updateNative: function(playback, options, autoplay, preload) {
var htmlMediaElement = playback.htmlMediaElement,
m;
// add methods to video object to bring it into parity with Flash Object
for (m in mejs.HtmlMediaElement) {
htmlMediaElement[m] = mejs.HtmlMediaElement[m];
}
/*
Chrome now supports preload="none"
if (mejs.MediaFeatures.isChrome) {
// special case to enforce preload attribute (Chrome doesn't respect this)
if (preload === 'none' && !autoplay) {
// forces the browser to stop loading (note: fails in IE9)
htmlMediaElement.src = '';
htmlMediaElement.load();
htmlMediaElement.canceledPreload = true;
htmlMediaElement.addEventListener('play',function() {
if (htmlMediaElement.canceledPreload) {
htmlMediaElement.src = playback.url;
htmlMediaElement.load();
htmlMediaElement.play();
htmlMediaElement.canceledPreload = false;
}
}, false);
// for some reason Chrome forgets how to autoplay sometimes.
} else if (autoplay) {
htmlMediaElement.load();
htmlMediaElement.play();
}
}
*/
// fire success code
options.success(htmlMediaElement, htmlMediaElement);
return htmlMediaElement;
}
};
/*
- test on IE (object vs. embed)
- determine when to use iframe (Firefox, Safari, Mobile) vs. Flash (Chrome, IE)
- fullscreen?
*/
// YouTube Flash and Iframe API
mejs.YouTubeApi = {
isIframeStarted: false,
isIframeLoaded: false,
loadIframeApi: function() {
if (!this.isIframeStarted) {
var tag = document.createElement('script');
tag.src = "//www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
this.isIframeStarted = true;
}
},
iframeQueue: [],
enqueueIframe: function(yt) {
if (this.isLoaded) {
this.createIframe(yt);
} else {
this.loadIframeApi();
this.iframeQueue.push(yt);
}
},
createIframe: function(settings) {
var
pluginMediaElement = settings.pluginMediaElement,
player = new YT.Player(settings.containerId, {
height: settings.height,
width: settings.width,
videoId: settings.videoId,
playerVars: {controls:0},
events: {
'onReady': function() {
// hook up iframe object to MEjs
settings.pluginMediaElement.pluginApi = player;
// init mejs
mejs.MediaPluginBridge.initPlugin(settings.pluginId);
// create timer
setInterval(function() {
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'timeupdate');
}, 250);
},
'onStateChange': function(e) {
mejs.YouTubeApi.handleStateChange(e.data, player, pluginMediaElement);
}
}
});
},
createEvent: function (player, pluginMediaElement, eventName) {
var obj = {
type: eventName,
target: pluginMediaElement
};
if (player && player.getDuration) {
// time
pluginMediaElement.currentTime = obj.currentTime = player.getCurrentTime();
pluginMediaElement.duration = obj.duration = player.getDuration();
// state
obj.paused = pluginMediaElement.paused;
obj.ended = pluginMediaElement.ended;
// sound
obj.muted = player.isMuted();
obj.volume = player.getVolume() / 100;
// progress
obj.bytesTotal = player.getVideoBytesTotal();
obj.bufferedBytes = player.getVideoBytesLoaded();
// fake the W3C buffered TimeRange
var bufferedTime = obj.bufferedBytes / obj.bytesTotal * obj.duration;
obj.target.buffered = obj.buffered = {
start: function(index) {
return 0;
},
end: function (index) {
return bufferedTime;
},
length: 1
};
}
// send event up the chain
pluginMediaElement.dispatchEvent(obj.type, obj);
},
iFrameReady: function() {
this.isLoaded = true;
this.isIframeLoaded = true;
while (this.iframeQueue.length > 0) {
var settings = this.iframeQueue.pop();
this.createIframe(settings);
}
},
// FLASH!
flashPlayers: {},
createFlash: function(settings) {
this.flashPlayers[settings.pluginId] = settings;
/*
settings.container.innerHTML =
'<object type="application/x-shockwave-flash" id="' + settings.pluginId + '" data="//www.youtube.com/apiplayer?enablejsapi=1&playerapiid=' + settings.pluginId + '&version=3&autoplay=0&controls=0&modestbranding=1&loop=0" ' +
'width="' + settings.width + '" height="' + settings.height + '" style="visibility: visible; " class="mejs-shim">' +
'<param name="allowScriptAccess" value="always">' +
'<param name="wmode" value="transparent">' +
'</object>';
*/
var specialIEContainer,
youtubeUrl = '//www.youtube.com/apiplayer?enablejsapi=1&playerapiid=' + settings.pluginId + '&version=3&autoplay=0&controls=0&modestbranding=1&loop=0';
if (mejs.MediaFeatures.isIE) {
specialIEContainer = document.createElement('div');
settings.container.appendChild(specialIEContainer);
specialIEContainer.outerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="//download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" ' +
'id="' + settings.pluginId + '" width="' + settings.width + '" height="' + settings.height + '" class="mejs-shim">' +
'<param name="movie" value="' + youtubeUrl + '" />' +
'<param name="wmode" value="transparent" />' +
'<param name="allowScriptAccess" value="always" />' +
'<param name="allowFullScreen" value="true" />' +
'</object>';
} else {
settings.container.innerHTML =
'<object type="application/x-shockwave-flash" id="' + settings.pluginId + '" data="' + youtubeUrl + '" ' +
'width="' + settings.width + '" height="' + settings.height + '" style="visibility: visible; " class="mejs-shim">' +
'<param name="allowScriptAccess" value="always">' +
'<param name="wmode" value="transparent">' +
'</object>';
}
},
flashReady: function(id) {
var
settings = this.flashPlayers[id],
player = document.getElementById(id),
pluginMediaElement = settings.pluginMediaElement;
// hook up and return to MediaELementPlayer.success
pluginMediaElement.pluginApi =
pluginMediaElement.pluginElement = player;
mejs.MediaPluginBridge.initPlugin(id);
// load the youtube video
player.cueVideoById(settings.videoId);
var callbackName = settings.containerId + '_callback';
window[callbackName] = function(e) {
mejs.YouTubeApi.handleStateChange(e, player, pluginMediaElement);
}
player.addEventListener('onStateChange', callbackName);
setInterval(function() {
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'timeupdate');
}, 250);
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'canplay');
},
handleStateChange: function(youTubeState, player, pluginMediaElement) {
switch (youTubeState) {
case -1: // not started
pluginMediaElement.paused = true;
pluginMediaElement.ended = true;
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'loadedmetadata');
//createYouTubeEvent(player, pluginMediaElement, 'loadeddata');
break;
case 0:
pluginMediaElement.paused = false;
pluginMediaElement.ended = true;
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'ended');
break;
case 1:
pluginMediaElement.paused = false;
pluginMediaElement.ended = false;
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'play');
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'playing');
break;
case 2:
pluginMediaElement.paused = true;
pluginMediaElement.ended = false;
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'pause');
break;
case 3: // buffering
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'progress');
break;
case 5:
// cued?
break;
}
}
}
// IFRAME
function onYouTubePlayerAPIReady() {
mejs.YouTubeApi.iFrameReady();
}
// FLASH
function onYouTubePlayerReady(id) {
mejs.YouTubeApi.flashReady(id);
}
window.mejs = mejs;
window.MediaElement = mejs.MediaElement;
/*
* Adds Internationalization and localization to mediaelement.
*
* This file does not contain translations, you have to add them manually.
* The schema is always the same: me-i18n-locale-[IETF-language-tag].js
*
* Examples are provided both for german and chinese translation.
*
*
* What is the concept beyond i18n?
* http://en.wikipedia.org/wiki/Internationalization_and_localization
*
* What langcode should i use?
* http://en.wikipedia.org/wiki/IETF_language_tag
* https://tools.ietf.org/html/rfc5646
*
*
* License?
*
* The i18n file uses methods from the Drupal project (drupal.js):
* - i18n.methods.t() (modified)
* - i18n.methods.checkPlain() (full copy)
*
* The Drupal project is (like mediaelementjs) licensed under GPLv2.
* - http://drupal.org/licensing/faq/#q1
* - https://github.com/johndyer/mediaelement
* - http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
*
* @author
* Tim Latz ([email protected])
*
*
* @params
* - context - document, iframe ..
* - exports - CommonJS, window ..
*
*/
;(function(context, exports, undefined) {
"use strict";
var i18n = {
"locale": {
// Ensure previous values aren't overwritten.
"language" : (exports.i18n && exports.i18n.locale.language) || '',
"strings" : (exports.i18n && exports.i18n.locale.strings) || {}
},
"ietf_lang_regex" : /^(x\-)?[a-z]{2,}(\-\w{2,})?(\-\w{2,})?$/,
"methods" : {}
};
// start i18n
/**
* Get language, fallback to browser's language if empty
*
* IETF: RFC 5646, https://tools.ietf.org/html/rfc5646
* Examples: en, zh-CN, cmn-Hans-CN, sr-Latn-RS, es-419, x-private
*/
i18n.getLanguage = function () {
var language = i18n.locale.language || window.navigator.userLanguage || window.navigator.language;
return i18n.ietf_lang_regex.exec(language) ? language : null;
//(WAS: convert to iso 639-1 (2-letters, lower case))
//return language.substr(0, 2).toLowerCase();
};
// i18n fixes for compatibility with WordPress
if ( typeof mejsL10n != 'undefined' ) {
i18n.locale.language = mejsL10n.language;
}
/**
* Encode special characters in a plain-text string for display as HTML.
*/
i18n.methods.checkPlain = function (str) {
var character, regex,
replace = {
'&': '&',
'"': '"',
'<': '<',
'>': '>'
};
str = String(str);
for (character in replace) {
if (replace.hasOwnProperty(character)) {
regex = new RegExp(character, 'g');
str = str.replace(regex, replace[character]);
}
}
return str;
};
/**
* Translate strings to the page language or a given language.
*
*
* @param str
* A string containing the English string to translate.
*
* @param options
* - 'context' (defaults to the default context): The context the source string
* belongs to.
*
* @return
* The translated string, escaped via i18n.methods.checkPlain()
*/
i18n.methods.t = function (str, options) {
// Fetch the localized version of the string.
if (i18n.locale.strings && i18n.locale.strings[options.context] && i18n.locale.strings[options.context][str]) {
str = i18n.locale.strings[options.context][str];
}
return i18n.methods.checkPlain(str);
};
/**
* Wrapper for i18n.methods.t()
*
* @see i18n.methods.t()
* @throws InvalidArgumentException
*/
i18n.t = function(str, options) {
if (typeof str === 'string' && str.length > 0) {
// check every time due language can change for
// different reasons (translation, lang switcher ..)
var language = i18n.getLanguage();
options = options || {
"context" : language
};
return i18n.methods.t(str, options);
}
else {
throw {
"name" : 'InvalidArgumentException',
"message" : 'First argument is either not a string or empty.'
};
}
};
// end i18n
exports.i18n = i18n;
}(document, mejs));
// i18n fixes for compatibility with WordPress
;(function(exports, undefined) {
"use strict";
if ( typeof mejsL10n != 'undefined' ) {
exports[mejsL10n.language] = mejsL10n.strings;
}
}(mejs.i18n.locale.strings));
/*!
*
* MediaElementPlayer
* http://mediaelementjs.com/
*
* Creates a controller bar for HTML5 <video> add <audio> tags
* using jQuery and MediaElement.js (HTML5 Flash/Silverlight wrapper)
*
* Copyright 2010-2013, John Dyer (http://j.hn/)
* License: MIT
*
*/
if (typeof jQuery != 'undefined') {
mejs.$ = jQuery;
} else if (typeof ender != 'undefined') {
mejs.$ = ender;
}
(function ($) {
// default player values
mejs.MepDefaults = {
// url to poster (to fix iOS 3.x)
poster: '',
// When the video is ended, we can show the poster.
showPosterWhenEnded: false,
// default if the <video width> is not specified
defaultVideoWidth: 480,
// default if the <video height> is not specified
defaultVideoHeight: 270,
// if set, overrides <video width>
videoWidth: -1,
// if set, overrides <video height>
videoHeight: -1,
// default if the user doesn't specify
defaultAudioWidth: 400,
// default if the user doesn't specify
defaultAudioHeight: 30,
// default amount to move back when back key is pressed
defaultSeekBackwardInterval: function(media) {
return (media.duration * 0.05);
},
// default amount to move forward when forward key is pressed
defaultSeekForwardInterval: function(media) {
return (media.duration * 0.05);
},
// set dimensions via JS instead of CSS
setDimensions: true,
// width of audio player
audioWidth: -1,
// height of audio player
audioHeight: -1,
// initial volume when the player starts (overrided by user cookie)
startVolume: 0.8,
// useful for <audio> player loops
loop: false,
// rewind to beginning when media ends
autoRewind: true,
// resize to media dimensions
enableAutosize: true,
// forces the hour marker (##:00:00)
alwaysShowHours: false,
// show framecount in timecode (##:00:00:00)
showTimecodeFrameCount: false,
// used when showTimecodeFrameCount is set to true
framesPerSecond: 25,
// automatically calculate the width of the progress bar based on the sizes of other elements
autosizeProgress : true,
// Hide controls when playing and mouse is not over the video
alwaysShowControls: false,
// Display the video control
hideVideoControlsOnLoad: false,
// Enable click video element to toggle play/pause
clickToPlayPause: true,
// force iPad's native controls
iPadUseNativeControls: false,
// force iPhone's native controls
iPhoneUseNativeControls: false,
// force Android's native controls
AndroidUseNativeControls: false,
// features to show
features: ['playpause','current','progress','duration','tracks','volume','fullscreen'],
// only for dynamic
isVideo: true,
// turns keyboard support on and off for this instance
enableKeyboard: true,
// whenthis player starts, it will pause other players
pauseOtherPlayers: true,
// array of keyboard actions such as play pause
keyActions: [
{
keys: [
32, // SPACE
179 // GOOGLE play/pause button
],
action: function(player, media) {
if (media.paused || media.ended) {
player.play();
} else {
player.pause();
}
}
},
{
keys: [38], // UP
action: function(player, media) {
player.container.find('.mejs-volume-slider').css('display','block');
if (player.isVideo) {
player.showControls();
player.startControlsTimer();
}
var newVolume = Math.min(media.volume + 0.1, 1);
media.setVolume(newVolume);
}
},
{
keys: [40], // DOWN
action: function(player, media) {
player.container.find('.mejs-volume-slider').css('display','block');
if (player.isVideo) {
player.showControls();
player.startControlsTimer();
}
var newVolume = Math.max(media.volume - 0.1, 0);
media.setVolume(newVolume);
}
},
{
keys: [
37, // LEFT
227 // Google TV rewind
],
action: function(player, media) {
if (!isNaN(media.duration) && media.duration > 0) {
if (player.isVideo) {
player.showControls();
player.startControlsTimer();
}
// 5%
var newTime = Math.max(media.currentTime - player.options.defaultSeekBackwardInterval(media), 0);
media.setCurrentTime(newTime);
}
}
},
{
keys: [
39, // RIGHT
228 // Google TV forward
],
action: function(player, media) {
if (!isNaN(media.duration) && media.duration > 0) {
if (player.isVideo) {
player.showControls();
player.startControlsTimer();
}
// 5%
var newTime = Math.min(media.currentTime + player.options.defaultSeekForwardInterval(media), media.duration);
media.setCurrentTime(newTime);
}
}
},
{
keys: [70], // F
action: function(player, media) {
if (typeof player.enterFullScreen != 'undefined') {
if (player.isFullScreen) {
player.exitFullScreen();
} else {
player.enterFullScreen();
}
}
}
},
{
keys: [77], // M
action: function(player, media) {
player.container.find('.mejs-volume-slider').css('display','block');
if (player.isVideo) {
player.showControls();
player.startControlsTimer();
}
if (player.media.muted) {
player.setMuted(false);
} else {
player.setMuted(true);
}
}
}
]
};
mejs.mepIndex = 0;
mejs.players = {};
// wraps a MediaElement object in player controls
mejs.MediaElementPlayer = function(node, o) {
// enforce object, even without "new" (via John Resig)
if ( !(this instanceof mejs.MediaElementPlayer) ) {
return new mejs.MediaElementPlayer(node, o);
}
var t = this;
// these will be reset after the MediaElement.success fires
t.$media = t.$node = $(node);
t.node = t.media = t.$media[0];
// check for existing player
if (typeof t.node.player != 'undefined') {
return t.node.player;
} else {
// attach player to DOM node for reference
t.node.player = t;
}
// try to get options from data-mejsoptions
if (typeof o == 'undefined') {
o = t.$node.data('mejsoptions');
}
// extend default options
t.options = $.extend({},mejs.MepDefaults,o);
// unique ID
t.id = 'mep_' + mejs.mepIndex++;
// add to player array (for focus events)
mejs.players[t.id] = t;
// start up
t.init();
return t;
};
// actual player
mejs.MediaElementPlayer.prototype = {
hasFocus: false,
controlsAreVisible: true,
init: function() {
var
t = this,
mf = mejs.MediaFeatures,
// options for MediaElement (shim)
meOptions = $.extend(true, {}, t.options, {
success: function(media, domNode) { t.meReady(media, domNode); },
error: function(e) { t.handleError(e);}
}),
tagName = t.media.tagName.toLowerCase();
t.isDynamic = (tagName !== 'audio' && tagName !== 'video');
if (t.isDynamic) {
// get video from src or href?
t.isVideo = t.options.isVideo;
} else {
t.isVideo = (tagName !== 'audio' && t.options.isVideo);
}
// use native controls in iPad, iPhone, and Android
if ((mf.isiPad && t.options.iPadUseNativeControls) || (mf.isiPhone && t.options.iPhoneUseNativeControls)) {
// add controls and stop
t.$media.attr('controls', 'controls');
// attempt to fix iOS 3 bug
//t.$media.removeAttr('poster');
// no Issue found on iOS3 -ttroxell
// override Apple's autoplay override for iPads
if (mf.isiPad && t.media.getAttribute('autoplay') !== null) {
t.play();
}
} else if (mf.isAndroid && t.options.AndroidUseNativeControls) {
// leave default player
} else {
// DESKTOP: use MediaElementPlayer controls
// remove native controls
t.$media.removeAttr('controls');
var videoPlayerTitle = t.isVideo ?
mejs.i18n.t('Video Player') : mejs.i18n.t('Audio Player');
// insert description for screen readers
$('<span class="mejs-offscreen">' + videoPlayerTitle + '</span>').insertBefore(t.$media);
// build container
t.container =
$('<div id="' + t.id + '" class="mejs-container ' + (mejs.MediaFeatures.svg ? 'svg' : 'no-svg') +
'" tabindex="0" role="application" aria-label="' + videoPlayerTitle + '">'+
'<div class="mejs-inner">'+
'<div class="mejs-mediaelement"></div>'+
'<div class="mejs-layers"></div>'+
'<div class="mejs-controls"></div>'+
'<div class="mejs-clear"></div>'+
'</div>' +
'</div>')
.addClass(t.$media[0].className)
.insertBefore(t.$media)
.focus(function ( e ) {
if( !t.controlsAreVisible ) {
t.showControls(true);
var playButton = t.container.find('.mejs-playpause-button > button');
playButton.focus();
}
});
// add classes for user and content
t.container.addClass(
(mf.isAndroid ? 'mejs-android ' : '') +
(mf.isiOS ? 'mejs-ios ' : '') +
(mf.isiPad ? 'mejs-ipad ' : '') +
(mf.isiPhone ? 'mejs-iphone ' : '') +
(t.isVideo ? 'mejs-video ' : 'mejs-audio ')
);
// move the <video/video> tag into the right spot
if (mf.isiOS) {
// sadly, you can't move nodes in iOS, so we have to destroy and recreate it!
var $newMedia = t.$media.clone();
t.container.find('.mejs-mediaelement').append($newMedia);
t.$media.remove();
t.$node = t.$media = $newMedia;
t.node = t.media = $newMedia[0];
} else {
// normal way of moving it into place (doesn't work on iOS)
t.container.find('.mejs-mediaelement').append(t.$media);
}
// find parts
t.controls = t.container.find('.mejs-controls');
t.layers = t.container.find('.mejs-layers');
// determine the size
/* size priority:
(1) videoWidth (forced),
(2) style="width;height;"
(3) width attribute,
(4) defaultVideoWidth (for unspecified cases)
*/
var tagType = (t.isVideo ? 'video' : 'audio'),
capsTagName = tagType.substring(0,1).toUpperCase() + tagType.substring(1);
if (t.options[tagType + 'Width'] > 0 || t.options[tagType + 'Width'].toString().indexOf('%') > -1) {
t.width = t.options[tagType + 'Width'];
} else if (t.media.style.width !== '' && t.media.style.width !== null) {
t.width = t.media.style.width;
} else if (t.media.getAttribute('width') !== null) {
t.width = t.$media.attr('width');
} else {
t.width = t.options['default' + capsTagName + 'Width'];
}
if (t.options[tagType + 'Height'] > 0 || t.options[tagType + 'Height'].toString().indexOf('%') > -1) {
t.height = t.options[tagType + 'Height'];
} else if (t.media.style.height !== '' && t.media.style.height !== null) {
t.height = t.media.style.height;
} else if (t.$media[0].getAttribute('height') !== null) {
t.height = t.$media.attr('height');
} else {
t.height = t.options['default' + capsTagName + 'Height'];
}
// set the size, while we wait for the plugins to load below
t.setPlayerSize(t.width, t.height);
// create MediaElementShim
meOptions.pluginWidth = t.width;
meOptions.pluginHeight = t.height;
}
// create MediaElement shim
mejs.MediaElement(t.$media[0], meOptions);
if (typeof(t.container) != 'undefined' && t.controlsAreVisible){
// controls are shown when loaded
t.container.trigger('controlsshown');
}
},
showControls: function(doAnimation) {
var t = this;
doAnimation = typeof doAnimation == 'undefined' || doAnimation;
if (t.controlsAreVisible)
return;
if (doAnimation) {
t.controls
.css('visibility','visible')
.stop(true, true).fadeIn(200, function() {
t.controlsAreVisible = true;
t.container.trigger('controlsshown');
});
// any additional controls people might add and want to hide
t.container.find('.mejs-control')
.css('visibility','visible')
.stop(true, true).fadeIn(200, function() {t.controlsAreVisible = true;});
} else {
t.controls
.css('visibility','visible')
.css('display','block');
// any additional controls people might add and want to hide
t.container.find('.mejs-control')
.css('visibility','visible')
.css('display','block');
t.controlsAreVisible = true;
t.container.trigger('controlsshown');
}
t.setControlsSize();
},
hideControls: function(doAnimation) {
var t = this;
doAnimation = typeof doAnimation == 'undefined' || doAnimation;
if (!t.controlsAreVisible || t.options.alwaysShowControls || t.keyboardAction)
return;
if (doAnimation) {
// fade out main controls
t.controls.stop(true, true).fadeOut(200, function() {
$(this)
.css('visibility','hidden')
.css('display','block');
t.controlsAreVisible = false;
t.container.trigger('controlshidden');
});
// any additional controls people might add and want to hide
t.container.find('.mejs-control').stop(true, true).fadeOut(200, function() {
$(this)
.css('visibility','hidden')
.css('display','block');
});
} else {
// hide main controls
t.controls
.css('visibility','hidden')
.css('display','block');
// hide others
t.container.find('.mejs-control')
.css('visibility','hidden')
.css('display','block');
t.controlsAreVisible = false;
t.container.trigger('controlshidden');
}
},
controlsTimer: null,
startControlsTimer: function(timeout) {
var t = this;
timeout = typeof timeout != 'undefined' ? timeout : 1500;
t.killControlsTimer('start');
t.controlsTimer = setTimeout(function() {
//
t.hideControls();
t.killControlsTimer('hide');
}, timeout);
},
killControlsTimer: function(src) {
var t = this;
if (t.controlsTimer !== null) {
clearTimeout(t.controlsTimer);
delete t.controlsTimer;
t.controlsTimer = null;
}
},
controlsEnabled: true,
disableControls: function() {
var t= this;
t.killControlsTimer();
t.hideControls(false);
this.controlsEnabled = false;
},
enableControls: function() {
var t= this;
t.showControls(false);
t.controlsEnabled = true;
},
// Sets up all controls and events
meReady: function(media, domNode) {
var t = this,
mf = mejs.MediaFeatures,
autoplayAttr = domNode.getAttribute('autoplay'),
autoplay = !(typeof autoplayAttr == 'undefined' || autoplayAttr === null || autoplayAttr === 'false'),
featureIndex,
feature;
// make sure it can't create itself again if a plugin reloads
if (t.created) {
return;
} else {
t.created = true;
}
t.media = media;
t.domNode = domNode;
if (!(mf.isAndroid && t.options.AndroidUseNativeControls) && !(mf.isiPad && t.options.iPadUseNativeControls) && !(mf.isiPhone && t.options.iPhoneUseNativeControls)) {
// two built in features
t.buildposter(t, t.controls, t.layers, t.media);
t.buildkeyboard(t, t.controls, t.layers, t.media);
t.buildoverlays(t, t.controls, t.layers, t.media);
// grab for use by features
t.findTracks();
// add user-defined features/controls
for (featureIndex in t.options.features) {
feature = t.options.features[featureIndex];
if (t['build' + feature]) {
try {
t['build' + feature](t, t.controls, t.layers, t.media);
} catch (e) {
// TODO: report control error
//throw e;
}
}
}
t.container.trigger('controlsready');
// reset all layers and controls
t.setPlayerSize(t.width, t.height);
t.setControlsSize();
// controls fade
if (t.isVideo) {
if (mejs.MediaFeatures.hasTouch) {
// for touch devices (iOS, Android)
// show/hide without animation on touch
t.$media.bind('touchstart', function() {
// toggle controls
if (t.controlsAreVisible) {
t.hideControls(false);
} else {
if (t.controlsEnabled) {
t.showControls(false);
}
}
});
} else {
// create callback here since it needs access to current
// MediaElement object
t.clickToPlayPauseCallback = function() {
//
if (t.options.clickToPlayPause) {
if (t.media.paused) {
t.play();
} else {
t.pause();
}
}
};
// click to play/pause
t.media.addEventListener('click', t.clickToPlayPauseCallback, false);
// show/hide controls
t.container
.bind('mouseenter mouseover', function () {
if (t.controlsEnabled) {
if (!t.options.alwaysShowControls ) {
t.killControlsTimer('enter');
t.showControls();
t.startControlsTimer(2500);
}
}
})
.bind('mousemove', function() {
if (t.controlsEnabled) {
if (!t.controlsAreVisible) {
t.showControls();
}
if (!t.options.alwaysShowControls) {
t.startControlsTimer(2500);
}
}
})
.bind('mouseleave', function () {
if (t.controlsEnabled) {
if (!t.media.paused && !t.options.alwaysShowControls) {
t.startControlsTimer(1000);
}
}
});
}
if(t.options.hideVideoControlsOnLoad) {
t.hideControls(false);
}
// check for autoplay
if (autoplay && !t.options.alwaysShowControls) {
t.hideControls();
}
// resizer
if (t.options.enableAutosize) {
t.media.addEventListener('loadedmetadata', function(e) {
// if the <video height> was not set and the options.videoHeight was not set
// then resize to the real dimensions
if (t.options.videoHeight <= 0 && t.domNode.getAttribute('height') === null && !isNaN(e.target.videoHeight)) {
t.setPlayerSize(e.target.videoWidth, e.target.videoHeight);
t.setControlsSize();
t.media.setVideoSize(e.target.videoWidth, e.target.videoHeight);
}
}, false);
}
}
// EVENTS
// FOCUS: when a video starts playing, it takes focus from other players (possibily pausing them)
media.addEventListener('play', function() {
var playerIndex;
// go through all other players
for (playerIndex in mejs.players) {
var p = mejs.players[playerIndex];
if (p.id != t.id && t.options.pauseOtherPlayers && !p.paused && !p.ended) {
p.pause();
}
p.hasFocus = false;
}
t.hasFocus = true;
},false);
// ended for all
t.media.addEventListener('ended', function (e) {
if(t.options.autoRewind) {
try{
t.media.setCurrentTime(0);
// Fixing an Android stock browser bug, where "seeked" isn't fired correctly after ending the video and jumping to the beginning
window.setTimeout(function(){
$(t.container).find('.mejs-overlay-loading').parent().hide();
}, 20);
} catch (exp) {
}
}
t.media.pause();
if (t.setProgressRail) {
t.setProgressRail();
}
if (t.setCurrentRail) {
t.setCurrentRail();
}
if (t.options.loop) {
t.play();
} else if (!t.options.alwaysShowControls && t.controlsEnabled) {
t.showControls();
}
}, false);
// resize on the first play
t.media.addEventListener('loadedmetadata', function(e) {
if (t.updateDuration) {
t.updateDuration();
}
if (t.updateCurrent) {
t.updateCurrent();
}
if (!t.isFullScreen) {
t.setPlayerSize(t.width, t.height);
t.setControlsSize();
}
}, false);
t.container.focusout(function (e) {
if( e.relatedTarget ) { //FF is working on supporting focusout https://bugzilla.mozilla.org/show_bug.cgi?id=687787
var $target = $(e.relatedTarget);
if (t.keyboardAction && $target.parents('.mejs-container').length === 0) {
t.keyboardAction = false;
t.hideControls(true);
}
}
});
// webkit has trouble doing this without a delay
setTimeout(function () {
t.setPlayerSize(t.width, t.height);
t.setControlsSize();
}, 50);
// adjust controls whenever window sizes (used to be in fullscreen only)
t.globalBind('resize', function() {
// don't resize for fullscreen mode
if ( !(t.isFullScreen || (mejs.MediaFeatures.hasTrueNativeFullScreen && document.webkitIsFullScreen)) ) {
t.setPlayerSize(t.width, t.height);
}
// always adjust controls
t.setControlsSize();
});
// This is a work-around for a bug in the YouTube iFrame player, which means
// we can't use the play() API for the initial playback on iOS or Android;
// user has to start playback directly by tapping on the iFrame.
if (t.media.pluginType == 'youtube' && ( mf.isiOS || mf.isAndroid ) ) {
t.container.find('.mejs-overlay-play').hide();
}
}
// force autoplay for HTML5
if (autoplay && media.pluginType == 'native') {
t.play();
}
if (t.options.success) {
if (typeof t.options.success == 'string') {
window[t.options.success](t.media, t.domNode, t);
} else {
t.options.success(t.media, t.domNode, t);
}
}
},
handleError: function(e) {
var t = this;
t.controls.hide();
// Tell user that the file cannot be played
if (t.options.error) {
t.options.error(e);
}
},
setPlayerSize: function(width,height) {
var t = this;
if( !t.options.setDimensions ) {
return false;
}
if (typeof width != 'undefined') {
t.width = width;
}
if (typeof height != 'undefined') {
t.height = height;
}
// detect 100% mode - use currentStyle for IE since css() doesn't return percentages
if (t.height.toString().indexOf('%') > 0 || t.$node.css('max-width') === '100%' || (t.$node[0].currentStyle && t.$node[0].currentStyle.maxWidth === '100%')) {
// do we have the native dimensions yet?
var nativeWidth = (function() {
if (t.isVideo) {
if (t.media.videoWidth && t.media.videoWidth > 0) {
return t.media.videoWidth;
} else if (t.media.getAttribute('width') !== null) {
return t.media.getAttribute('width');
} else {
return t.options.defaultVideoWidth;
}
} else {
return t.options.defaultAudioWidth;
}
})();
var nativeHeight = (function() {
if (t.isVideo) {
if (t.media.videoHeight && t.media.videoHeight > 0) {
return t.media.videoHeight;
} else if (t.media.getAttribute('height') !== null) {
return t.media.getAttribute('height');
} else {
return t.options.defaultVideoHeight;
}
} else {
return t.options.defaultAudioHeight;
}
})();
var
parentWidth = t.container.parent().closest(':visible').width(),
parentHeight = t.container.parent().closest(':visible').height(),
newHeight = t.isVideo || !t.options.autosizeProgress ? parseInt(parentWidth * nativeHeight/nativeWidth, 10) : nativeHeight;
// When we use percent, the newHeight can't be calculated so we get the container height
if (isNaN(newHeight)) {
newHeight = parentHeight;
}
if (t.container.parent()[0].tagName.toLowerCase() === 'body') { // && t.container.siblings().count == 0) {
parentWidth = $(window).width();
newHeight = $(window).height();
}
if ( newHeight && parentWidth ) {
// set outer container size
t.container
.width(parentWidth)
.height(newHeight);
// set native <video> or <audio> and shims
t.$media.add(t.container.find('.mejs-shim'))
.width('100%')
.height('100%');
// if shim is ready, send the size to the embeded plugin
if (t.isVideo) {
if (t.media.setVideoSize) {
t.media.setVideoSize(parentWidth, newHeight);
}
}
// set the layers
t.layers.children('.mejs-layer')
.width('100%')
.height('100%');
}
} else {
t.container
.width(t.width)
.height(t.height);
t.layers.children('.mejs-layer')
.width(t.width)
.height(t.height);
}
// special case for big play button so it doesn't go over the controls area
var playLayer = t.layers.find('.mejs-overlay-play'),
playButton = playLayer.find('.mejs-overlay-button');
playLayer.height(t.container.height() - t.controls.height());
playButton.css('margin-top', '-' + (playButton.height()/2 - t.controls.height()/2).toString() + 'px' );
},
setControlsSize: function() {
var t = this,
usedWidth = 0,
railWidth = 0,
rail = t.controls.find('.mejs-time-rail'),
total = t.controls.find('.mejs-time-total'),
current = t.controls.find('.mejs-time-current'),
loaded = t.controls.find('.mejs-time-loaded'),
others = rail.siblings(),
lastControl = others.last(),
lastControlPosition = null;
// skip calculation if hidden
if (!t.container.is(':visible') || !rail.length || !rail.is(':visible')) {
return;
}
// allow the size to come from custom CSS
if (t.options && !t.options.autosizeProgress) {
// Also, frontends devs can be more flexible
// due the opportunity of absolute positioning.
railWidth = parseInt(rail.css('width'), 10);
}
// attempt to autosize
if (railWidth === 0 || !railWidth) {
// find the size of all the other controls besides the rail
others.each(function() {
var $this = $(this);
if ($this.css('position') != 'absolute' && $this.is(':visible')) {
usedWidth += $(this).outerWidth(true);
}
});
// fit the rail into the remaining space
railWidth = t.controls.width() - usedWidth - (rail.outerWidth(true) - rail.width());
}
// resize the rail,
// but then check if the last control (say, the fullscreen button) got pushed down
// this often happens when zoomed
do {
// outer area
rail.width(railWidth);
// dark space
total.width(railWidth - (total.outerWidth(true) - total.width()));
if (lastControl.css('position') != 'absolute') {
lastControlPosition = lastControl.position();
railWidth--;
}
} while (lastControlPosition !== null && lastControlPosition.top > 0 && railWidth > 0);
if (t.setProgressRail)
t.setProgressRail();
if (t.setCurrentRail)
t.setCurrentRail();
},
buildposter: function(player, controls, layers, media) {
var t = this,
poster =
$('<div class="mejs-poster mejs-layer">' +
'</div>')
.appendTo(layers),
posterUrl = player.$media.attr('poster');
// prioriy goes to option (this is useful if you need to support iOS 3.x (iOS completely fails with poster)
if (player.options.poster !== '') {
posterUrl = player.options.poster;
}
// second, try the real poster
if ( posterUrl ) {
t.setPoster(posterUrl);
} else {
poster.hide();
}
media.addEventListener('play',function() {
poster.hide();
}, false);
if(player.options.showPosterWhenEnded && player.options.autoRewind){
media.addEventListener('ended',function() {
poster.show();
}, false);
}
},
setPoster: function(url) {
var t = this,
posterDiv = t.container.find('.mejs-poster'),
posterImg = posterDiv.find('img');
if (posterImg.length === 0) {
posterImg = $('<img width="100%" height="100%" />').appendTo(posterDiv);
}
posterImg.attr('src', url);
posterDiv.css({'background-image' : 'url(' + url + ')'});
},
buildoverlays: function(player, controls, layers, media) {
var t = this;
if (!player.isVideo)
return;
var
loading =
$('<div class="mejs-overlay mejs-layer">'+
'<div class="mejs-overlay-loading"><span></span></div>'+
'</div>')
.hide() // start out hidden
.appendTo(layers),
error =
$('<div class="mejs-overlay mejs-layer">'+
'<div class="mejs-overlay-error"></div>'+
'</div>')
.hide() // start out hidden
.appendTo(layers),
// this needs to come last so it's on top
bigPlay =
$('<div class="mejs-overlay mejs-layer mejs-overlay-play">'+
'<div class="mejs-overlay-button"></div>'+
'</div>')
.appendTo(layers)
.bind('click', function() { // Removed 'touchstart' due issues on Samsung Android devices where a tap on bigPlay started and immediately stopped the video
if (t.options.clickToPlayPause) {
if (media.paused) {
media.play();
}
}
});
/*
if (mejs.MediaFeatures.isiOS || mejs.MediaFeatures.isAndroid) {
bigPlay.remove();
loading.remove();
}
*/
// show/hide big play button
media.addEventListener('play',function() {
bigPlay.hide();
loading.hide();
controls.find('.mejs-time-buffering').hide();
error.hide();
}, false);
media.addEventListener('playing', function() {
bigPlay.hide();
loading.hide();
controls.find('.mejs-time-buffering').hide();
error.hide();
}, false);
media.addEventListener('seeking', function() {
loading.show();
controls.find('.mejs-time-buffering').show();
}, false);
media.addEventListener('seeked', function() {
loading.hide();
controls.find('.mejs-time-buffering').hide();
}, false);
media.addEventListener('pause',function() {
if (!mejs.MediaFeatures.isiPhone) {
bigPlay.show();
}
}, false);
media.addEventListener('waiting', function() {
loading.show();
controls.find('.mejs-time-buffering').show();
}, false);
// show/hide loading
media.addEventListener('loadeddata',function() {
// for some reason Chrome is firing this event
//if (mejs.MediaFeatures.isChrome && media.getAttribute && media.getAttribute('preload') === 'none')
// return;
loading.show();
controls.find('.mejs-time-buffering').show();
// Firing the 'canplay' event after a timeout which isn't getting fired on some Android 4.1 devices (https://github.com/johndyer/mediaelement/issues/1305)
if (mejs.MediaFeatures.isAndroid) {
media.canplayTimeout = window.setTimeout(
function() {
if (document.createEvent) {
var evt = document.createEvent('HTMLEvents');
evt.initEvent('canplay', true, true);
return media.dispatchEvent(evt);
}
}, 300
);
}
}, false);
media.addEventListener('canplay',function() {
loading.hide();
controls.find('.mejs-time-buffering').hide();
clearTimeout(media.canplayTimeout); // Clear timeout inside 'loadeddata' to prevent 'canplay' to fire twice
}, false);
// error handling
media.addEventListener('error',function() {
loading.hide();
controls.find('.mejs-time-buffering').hide();
error.show();
error.find('mejs-overlay-error').html("Error loading this resource");
}, false);
media.addEventListener('keydown', function(e) {
t.onkeydown(player, media, e);
}, false);
},
buildkeyboard: function(player, controls, layers, media) {
var t = this;
t.container.keydown(function () {
t.keyboardAction = true;
});
// listen for key presses
t.globalBind('keydown', function(e) {
return t.onkeydown(player, media, e);
});
// check if someone clicked outside a player region, then kill its focus
t.globalBind('click', function(event) {
player.hasFocus = $(event.target).closest('.mejs-container').length !== 0;
});
},
onkeydown: function(player, media, e) {
if (player.hasFocus && player.options.enableKeyboard) {
// find a matching key
for (var i = 0, il = player.options.keyActions.length; i < il; i++) {
var keyAction = player.options.keyActions[i];
for (var j = 0, jl = keyAction.keys.length; j < jl; j++) {
if (e.keyCode == keyAction.keys[j]) {
if (typeof(e.preventDefault) == "function") e.preventDefault();
keyAction.action(player, media, e.keyCode);
return false;
}
}
}
}
return true;
},
findTracks: function() {
var t = this,
tracktags = t.$media.find('track');
// store for use by plugins
t.tracks = [];
tracktags.each(function(index, track) {
track = $(track);
t.tracks.push({
srclang: (track.attr('srclang')) ? track.attr('srclang').toLowerCase() : '',
src: track.attr('src'),
kind: track.attr('kind'),
label: track.attr('label') || '',
entries: [],
isLoaded: false
});
});
},
changeSkin: function(className) {
this.container[0].className = 'mejs-container ' + className;
this.setPlayerSize(this.width, this.height);
this.setControlsSize();
},
play: function() {
this.load();
this.media.play();
},
pause: function() {
try {
this.media.pause();
} catch (e) {}
},
load: function() {
if (!this.isLoaded) {
this.media.load();
}
this.isLoaded = true;
},
setMuted: function(muted) {
this.media.setMuted(muted);
},
setCurrentTime: function(time) {
this.media.setCurrentTime(time);
},
getCurrentTime: function() {
return this.media.currentTime;
},
setVolume: function(volume) {
this.media.setVolume(volume);
},
getVolume: function() {
return this.media.volume;
},
setSrc: function(src) {
this.media.setSrc(src);
},
remove: function() {
var t = this, featureIndex, feature;
// invoke features cleanup
for (featureIndex in t.options.features) {
feature = t.options.features[featureIndex];
if (t['clean' + feature]) {
try {
t['clean' + feature](t);
} catch (e) {
// TODO: report control error
//throw e;
//
//
}
}
}
// grab video and put it back in place
if (!t.isDynamic) {
t.$media.prop('controls', true);
// detach events from the video
// TODO: detach event listeners better than this;
// also detach ONLY the events attached by this plugin!
t.$node.clone().insertBefore(t.container).show();
t.$node.remove();
} else {
t.$node.insertBefore(t.container);
}
if (t.media.pluginType !== 'native') {
t.media.remove();
}
// Remove the player from the mejs.players object so that pauseOtherPlayers doesn't blow up when trying to pause a non existance flash api.
delete mejs.players[t.id];
if (typeof t.container == 'object') {
t.container.remove();
}
t.globalUnbind();
delete t.node.player;
},
rebuildtracks: function(){
var t = this;
t.findTracks();
t.buildtracks(t, t.controls, t.layers, t.media);
}
};
(function(){
var rwindow = /^((after|before)print|(before)?unload|hashchange|message|o(ff|n)line|page(hide|show)|popstate|resize|storage)\b/;
function splitEvents(events, id) {
// add player ID as an event namespace so it's easier to unbind them all later
var ret = {d: [], w: []};
$.each((events || '').split(' '), function(k, v){
var eventname = v + '.' + id;
if (eventname.indexOf('.') === 0) {
ret.d.push(eventname);
ret.w.push(eventname);
}
else {
ret[rwindow.test(v) ? 'w' : 'd'].push(eventname);
}
});
ret.d = ret.d.join(' ');
ret.w = ret.w.join(' ');
return ret;
}
mejs.MediaElementPlayer.prototype.globalBind = function(events, data, callback) {
var t = this;
events = splitEvents(events, t.id);
if (events.d) $(document).bind(events.d, data, callback);
if (events.w) $(window).bind(events.w, data, callback);
};
mejs.MediaElementPlayer.prototype.globalUnbind = function(events, callback) {
var t = this;
events = splitEvents(events, t.id);
if (events.d) $(document).unbind(events.d, callback);
if (events.w) $(window).unbind(events.w, callback);
};
})();
// turn into jQuery plugin
if (typeof $ != 'undefined') {
$.fn.mediaelementplayer = function (options) {
if (options === false) {
this.each(function () {
var player = $(this).data('mediaelementplayer');
if (player) {
player.remove();
}
$(this).removeData('mediaelementplayer');
});
}
else {
this.each(function () {
$(this).data('mediaelementplayer', new mejs.MediaElementPlayer(this, options));
});
}
return this;
};
$(document).ready(function() {
// auto enable using JSON attribute
$('.mejs-player').mediaelementplayer();
});
}
// push out to window
window.MediaElementPlayer = mejs.MediaElementPlayer;
})(mejs.$);
(function($) {
$.extend(mejs.MepDefaults, {
playText: mejs.i18n.t('Play'),
pauseText: mejs.i18n.t('Pause')
});
// PLAY/pause BUTTON
$.extend(MediaElementPlayer.prototype, {
buildplaypause: function(player, controls, layers, media) {
var
t = this,
op = t.options,
play =
$('<div class="mejs-button mejs-playpause-button mejs-play" >' +
'<button type="button" aria-controls="' + t.id + '" title="' + op.playText + '" aria-label="' + op.playText + '"></button>' +
'</div>')
.appendTo(controls)
.click(function(e) {
e.preventDefault();
if (media.paused) {
media.play();
} else {
media.pause();
}
return false;
}),
play_btn = play.find('button');
function togglePlayPause(which) {
if ('play' === which) {
play.removeClass('mejs-play').addClass('mejs-pause');
play_btn.attr({
'title': op.pauseText,
'aria-label': op.pauseText
});
} else {
play.removeClass('mejs-pause').addClass('mejs-play');
play_btn.attr({
'title': op.playText,
'aria-label': op.playText
});
}
};
togglePlayPause('pse');
media.addEventListener('play',function() {
togglePlayPause('play');
}, false);
media.addEventListener('playing',function() {
togglePlayPause('play');
}, false);
media.addEventListener('pause',function() {
togglePlayPause('pse');
}, false);
media.addEventListener('paused',function() {
togglePlayPause('pse');
}, false);
}
});
})(mejs.$);
(function($) {
$.extend(mejs.MepDefaults, {
stopText: 'Stop'
});
// STOP BUTTON
$.extend(MediaElementPlayer.prototype, {
buildstop: function(player, controls, layers, media) {
var t = this,
stop =
$('<div class="mejs-button mejs-stop-button mejs-stop">' +
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.stopText + '" aria-label="' + t.options.stopText + '"></button>' +
'</div>')
.appendTo(controls)
.click(function() {
if (!media.paused) {
media.pause();
}
if (media.currentTime > 0) {
media.setCurrentTime(0);
media.pause();
controls.find('.mejs-time-current').width('0px');
controls.find('.mejs-time-handle').css('left', '0px');
controls.find('.mejs-time-float-current').html( mejs.Utility.secondsToTimeCode(0) );
controls.find('.mejs-currenttime').html( mejs.Utility.secondsToTimeCode(0) );
layers.find('.mejs-poster').show();
}
});
}
});
})(mejs.$);
(function($) {
$.extend(mejs.MepDefaults, {
progessHelpText: mejs.i18n.t(
'Use Left/Right Arrow keys to advance one second, Up/Down arrows to advance ten seconds.')
});
// progress/loaded bar
$.extend(MediaElementPlayer.prototype, {
buildprogress: function(player, controls, layers, media) {
$('<div class="mejs-time-rail">' +
'<span class="mejs-time-total mejs-time-slider">' +
//'<span class="mejs-offscreen">' + this.options.progessHelpText + '</span>' +
'<span class="mejs-time-buffering"></span>' +
'<span class="mejs-time-loaded"></span>' +
'<span class="mejs-time-current"></span>' +
'<span class="mejs-time-handle"></span>' +
'<span class="mejs-time-float">' +
'<span class="mejs-time-float-current">00:00</span>' +
'<span class="mejs-time-float-corner"></span>' +
'</span>' +
'</div>')
.appendTo(controls);
controls.find('.mejs-time-buffering').hide();
var
t = this,
total = controls.find('.mejs-time-total'),
loaded = controls.find('.mejs-time-loaded'),
current = controls.find('.mejs-time-current'),
handle = controls.find('.mejs-time-handle'),
timefloat = controls.find('.mejs-time-float'),
timefloatcurrent = controls.find('.mejs-time-float-current'),
slider = controls.find('.mejs-time-slider'),
handleMouseMove = function (e) {
var offset = total.offset(),
width = total.outerWidth(true),
percentage = 0,
newTime = 0,
pos = 0,
x;
// mouse or touch position relative to the object
if (e.originalEvent.changedTouches) {
x = e.originalEvent.changedTouches[0].pageX;
}else{
x = e.pageX;
}
if (media.duration) {
if (x < offset.left) {
x = offset.left;
} else if (x > width + offset.left) {
x = width + offset.left;
}
pos = x - offset.left;
percentage = (pos / width);
newTime = (percentage <= 0.02) ? 0 : percentage * media.duration;
// seek to where the mouse is
if (mouseIsDown && newTime !== media.currentTime) {
media.setCurrentTime(newTime);
}
// position floating time box
if (!mejs.MediaFeatures.hasTouch) {
timefloat.css('left', pos);
timefloatcurrent.html( mejs.Utility.secondsToTimeCode(newTime) );
timefloat.show();
}
}
},
mouseIsDown = false,
mouseIsOver = false,
lastKeyPressTime = 0,
startedPaused = false,
autoRewindInitial = player.options.autoRewind;
// Accessibility for slider
var updateSlider = function (e) {
var seconds = media.currentTime,
timeSliderText = mejs.i18n.t('Time Slider'),
time = mejs.Utility.secondsToTimeCode(seconds),
duration = media.duration;
slider.attr({
'aria-label': timeSliderText,
'aria-valuemin': 0,
'aria-valuemax': duration,
'aria-valuenow': seconds,
'aria-valuetext': time,
'role': 'slider',
'tabindex': 0
});
};
var restartPlayer = function () {
var now = new Date();
if (now - lastKeyPressTime >= 1000) {
media.play();
}
};
slider.bind('focus', function (e) {
player.options.autoRewind = false;
});
slider.bind('blur', function (e) {
player.options.autoRewind = autoRewindInitial;
});
slider.bind('keydown', function (e) {
if ((new Date() - lastKeyPressTime) >= 1000) {
startedPaused = media.paused;
}
var keyCode = e.keyCode,
duration = media.duration,
seekTime = media.currentTime;
switch (keyCode) {
case 37: // left
seekTime -= 1;
break;
case 39: // Right
seekTime += 1;
break;
case 38: // Up
seekTime += Math.floor(duration * 0.1);
break;
case 40: // Down
seekTime -= Math.floor(duration * 0.1);
break;
case 36: // Home
seekTime = 0;
break;
case 35: // end
seekTime = duration;
break;
case 10: // enter
media.paused ? media.play() : media.pause();
return;
case 13: // space
media.paused ? media.play() : media.pause();
return;
default:
return;
}
seekTime = seekTime < 0 ? 0 : (seekTime >= duration ? duration : Math.floor(seekTime));
lastKeyPressTime = new Date();
if (!startedPaused) {
media.pause();
}
if (seekTime < media.duration && !startedPaused) {
setTimeout(restartPlayer, 1100);
}
media.setCurrentTime(seekTime);
e.preventDefault();
e.stopPropagation();
return false;
});
// handle clicks
//controls.find('.mejs-time-rail').delegate('span', 'click', handleMouseMove);
total
.bind('mousedown touchstart', function (e) {
// only handle left clicks or touch
if (e.which === 1 || e.which === 0) {
mouseIsDown = true;
handleMouseMove(e);
t.globalBind('mousemove.dur touchmove.dur', function(e) {
handleMouseMove(e);
});
t.globalBind('mouseup.dur touchend.dur', function (e) {
mouseIsDown = false;
timefloat.hide();
t.globalUnbind('.dur');
});
}
})
.bind('mouseenter', function(e) {
mouseIsOver = true;
t.globalBind('mousemove.dur', function(e) {
handleMouseMove(e);
});
if (!mejs.MediaFeatures.hasTouch) {
timefloat.show();
}
})
.bind('mouseleave',function(e) {
mouseIsOver = false;
if (!mouseIsDown) {
t.globalUnbind('.dur');
timefloat.hide();
}
});
// loading
media.addEventListener('progress', function (e) {
player.setProgressRail(e);
player.setCurrentRail(e);
}, false);
// current time
media.addEventListener('timeupdate', function(e) {
player.setProgressRail(e);
player.setCurrentRail(e);
updateSlider(e);
}, false);
// store for later use
t.loaded = loaded;
t.total = total;
t.current = current;
t.handle = handle;
},
setProgressRail: function(e) {
var
t = this,
target = (e !== undefined) ? e.target : t.media,
percent = null;
// newest HTML5 spec has buffered array (FF4, Webkit)
if (target && target.buffered && target.buffered.length > 0 && target.buffered.end && target.duration) {
// TODO: account for a real array with multiple values (only Firefox 4 has this so far)
percent = target.buffered.end(0) / target.duration;
}
// Some browsers (e.g., FF3.6 and Safari 5) cannot calculate target.bufferered.end()
// to be anything other than 0. If the byte count is available we use this instead.
// Browsers that support the else if do not seem to have the bufferedBytes value and
// should skip to there. Tested in Safari 5, Webkit head, FF3.6, Chrome 6, IE 7/8.
else if (target && target.bytesTotal !== undefined && target.bytesTotal > 0 && target.bufferedBytes !== undefined) {
percent = target.bufferedBytes / target.bytesTotal;
}
// Firefox 3 with an Ogg file seems to go this way
else if (e && e.lengthComputable && e.total !== 0) {
percent = e.loaded / e.total;
}
// finally update the progress bar
if (percent !== null) {
percent = Math.min(1, Math.max(0, percent));
// update loaded bar
if (t.loaded && t.total) {
t.loaded.width(t.total.width() * percent);
}
}
},
setCurrentRail: function() {
var t = this;
if (t.media.currentTime !== undefined && t.media.duration) {
// update bar and handle
if (t.total && t.handle) {
var
newWidth = Math.round(t.total.width() * t.media.currentTime / t.media.duration),
handlePos = newWidth - Math.round(t.handle.outerWidth(true) / 2);
t.current.width(newWidth);
t.handle.css('left', handlePos);
}
}
}
});
})(mejs.$);
(function($) {
// options
$.extend(mejs.MepDefaults, {
duration: -1,
timeAndDurationSeparator: '<span> | </span>'
});
// current and duration 00:00 / 00:00
$.extend(MediaElementPlayer.prototype, {
buildcurrent: function(player, controls, layers, media) {
var t = this;
$('<div class="mejs-time" role="timer" aria-live="off">' +
'<span class="mejs-currenttime">' +
(player.options.alwaysShowHours ? '00:' : '') +
(player.options.showTimecodeFrameCount? '00:00:00':'00:00') +
'</span>'+
'</div>')
.appendTo(controls);
t.currenttime = t.controls.find('.mejs-currenttime');
media.addEventListener('timeupdate',function() {
player.updateCurrent();
}, false);
},
buildduration: function(player, controls, layers, media) {
var t = this;
if (controls.children().last().find('.mejs-currenttime').length > 0) {
$(t.options.timeAndDurationSeparator +
'<span class="mejs-duration">' +
(t.options.duration > 0 ?
mejs.Utility.secondsToTimeCode(t.options.duration, t.options.alwaysShowHours || t.media.duration > 3600, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25) :
((player.options.alwaysShowHours ? '00:' : '') + (player.options.showTimecodeFrameCount? '00:00:00':'00:00'))
) +
'</span>')
.appendTo(controls.find('.mejs-time'));
} else {
// add class to current time
controls.find('.mejs-currenttime').parent().addClass('mejs-currenttime-container');
$('<div class="mejs-time mejs-duration-container">'+
'<span class="mejs-duration">' +
(t.options.duration > 0 ?
mejs.Utility.secondsToTimeCode(t.options.duration, t.options.alwaysShowHours || t.media.duration > 3600, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25) :
((player.options.alwaysShowHours ? '00:' : '') + (player.options.showTimecodeFrameCount? '00:00:00':'00:00'))
) +
'</span>' +
'</div>')
.appendTo(controls);
}
t.durationD = t.controls.find('.mejs-duration');
media.addEventListener('timeupdate',function() {
player.updateDuration();
}, false);
},
updateCurrent: function() {
var t = this;
if (t.currenttime) {
t.currenttime.html(mejs.Utility.secondsToTimeCode(t.media.currentTime, t.options.alwaysShowHours || t.media.duration > 3600, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25));
}
},
updateDuration: function() {
var t = this;
//Toggle the long video class if the video is longer than an hour.
t.container.toggleClass("mejs-long-video", t.media.duration > 3600);
if (t.durationD && (t.options.duration > 0 || t.media.duration)) {
t.durationD.html(mejs.Utility.secondsToTimeCode(t.options.duration > 0 ? t.options.duration : t.media.duration, t.options.alwaysShowHours, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25));
}
}
});
})(mejs.$);
(function($) {
$.extend(mejs.MepDefaults, {
muteText: mejs.i18n.t('Mute Toggle'),
allyVolumeControlText: mejs.i18n.t('Use Up/Down Arrow keys to increase or decrease volume.'),
hideVolumeOnTouchDevices: true,
audioVolume: 'horizontal',
videoVolume: 'vertical'
});
$.extend(MediaElementPlayer.prototype, {
buildvolume: function(player, controls, layers, media) {
// Android and iOS don't support volume controls
if ((mejs.MediaFeatures.isAndroid || mejs.MediaFeatures.isiOS) && this.options.hideVolumeOnTouchDevices)
return;
var t = this,
mode = (t.isVideo) ? t.options.videoVolume : t.options.audioVolume,
mute = (mode == 'horizontal') ?
// horizontal version
$('<div class="mejs-button mejs-volume-button mejs-mute">' +
'<button type="button" aria-controls="' + t.id +
'" title="' + t.options.muteText +
'" aria-label="' + t.options.muteText +
'"></button>'+
'</div>' +
'<a href="javascript:void(0);" class="mejs-horizontal-volume-slider">' + // outer background
'<span class="mejs-offscreen">' + t.options.allyVolumeControlText + '</span>' +
'<div class="mejs-horizontal-volume-total"></div>'+ // line background
'<div class="mejs-horizontal-volume-current"></div>'+ // current volume
'<div class="mejs-horizontal-volume-handle"></div>'+ // handle
'</a>'
)
.appendTo(controls) :
// vertical version
$('<div class="mejs-button mejs-volume-button mejs-mute">'+
'<button type="button" aria-controls="' + t.id +
'" title="' + t.options.muteText +
'" aria-label="' + t.options.muteText +
'"></button>'+
'<a href="javascript:void(0);" class="mejs-volume-slider">'+ // outer background
'<span class="mejs-offscreen">' + t.options.allyVolumeControlText + '</span>' +
'<div class="mejs-volume-total"></div>'+ // line background
'<div class="mejs-volume-current"></div>'+ // current volume
'<div class="mejs-volume-handle"></div>'+ // handle
'</a>'+
'</div>')
.appendTo(controls),
volumeSlider = t.container.find('.mejs-volume-slider, .mejs-horizontal-volume-slider'),
volumeTotal = t.container.find('.mejs-volume-total, .mejs-horizontal-volume-total'),
volumeCurrent = t.container.find('.mejs-volume-current, .mejs-horizontal-volume-current'),
volumeHandle = t.container.find('.mejs-volume-handle, .mejs-horizontal-volume-handle'),
positionVolumeHandle = function(volume, secondTry) {
if (!volumeSlider.is(':visible') && typeof secondTry == 'undefined') {
volumeSlider.show();
positionVolumeHandle(volume, true);
volumeSlider.hide();
return;
}
// correct to 0-1
volume = Math.max(0,volume);
volume = Math.min(volume,1);
// ajust mute button style
if (volume === 0) {
mute.removeClass('mejs-mute').addClass('mejs-unmute');
} else {
mute.removeClass('mejs-unmute').addClass('mejs-mute');
}
// top/left of full size volume slider background
var totalPosition = volumeTotal.position();
// position slider
if (mode == 'vertical') {
var
// height of the full size volume slider background
totalHeight = volumeTotal.height(),
// the new top position based on the current volume
// 70% volume on 100px height == top:30px
newTop = totalHeight - (totalHeight * volume);
// handle
volumeHandle.css('top', Math.round(totalPosition.top + newTop - (volumeHandle.height() / 2)));
// show the current visibility
volumeCurrent.height(totalHeight - newTop );
volumeCurrent.css('top', totalPosition.top + newTop);
} else {
var
// height of the full size volume slider background
totalWidth = volumeTotal.width(),
// the new left position based on the current volume
newLeft = totalWidth * volume;
// handle
volumeHandle.css('left', Math.round(totalPosition.left + newLeft - (volumeHandle.width() / 2)));
// rezize the current part of the volume bar
volumeCurrent.width( Math.round(newLeft) );
}
},
handleVolumeMove = function(e) {
var volume = null,
totalOffset = volumeTotal.offset();
// calculate the new volume based on the moust position
if (mode === 'vertical') {
var
railHeight = volumeTotal.height(),
totalTop = parseInt(volumeTotal.css('top').replace(/px/,''),10),
newY = e.pageY - totalOffset.top;
volume = (railHeight - newY) / railHeight;
// the controls just hide themselves (usually when mouse moves too far up)
if (totalOffset.top === 0 || totalOffset.left === 0) {
return;
}
} else {
var
railWidth = volumeTotal.width(),
newX = e.pageX - totalOffset.left;
volume = newX / railWidth;
}
// ensure the volume isn't outside 0-1
volume = Math.max(0,volume);
volume = Math.min(volume,1);
// position the slider and handle
positionVolumeHandle(volume);
// set the media object (this will trigger the volumechanged event)
if (volume === 0) {
media.setMuted(true);
} else {
media.setMuted(false);
}
media.setVolume(volume);
},
mouseIsDown = false,
mouseIsOver = false;
// SLIDER
mute
.hover(function() {
volumeSlider.show();
mouseIsOver = true;
}, function() {
mouseIsOver = false;
if (!mouseIsDown && mode == 'vertical') {
volumeSlider.hide();
}
});
var updateVolumeSlider = function (e) {
var volume = Math.floor(media.volume*100);
volumeSlider.attr({
'aria-label': mejs.i18n.t('volumeSlider'),
'aria-valuemin': 0,
'aria-valuemax': 100,
'aria-valuenow': volume,
'aria-valuetext': volume+'%',
'role': 'slider',
'tabindex': 0
});
};
volumeSlider
.bind('mouseover', function() {
mouseIsOver = true;
})
.bind('mousedown', function (e) {
handleVolumeMove(e);
t.globalBind('mousemove.vol', function(e) {
handleVolumeMove(e);
});
t.globalBind('mouseup.vol', function () {
mouseIsDown = false;
t.globalUnbind('.vol');
if (!mouseIsOver && mode == 'vertical') {
volumeSlider.hide();
}
});
mouseIsDown = true;
return false;
})
.bind('keydown', function (e) {
var keyCode = e.keyCode;
var volume = media.volume;
switch (keyCode) {
case 38: // Up
volume += 0.1;
break;
case 40: // Down
volume = volume - 0.1;
break;
default:
return true;
}
mouseIsDown = false;
positionVolumeHandle(volume);
media.setVolume(volume);
return false;
})
.bind('blur', function () {
volumeSlider.hide();
});
// MUTE button
mute.find('button').click(function() {
media.setMuted( !media.muted );
});
//Keyboard input
mute.find('button').bind('focus', function () {
volumeSlider.show();
});
// listen for volume change events from other sources
media.addEventListener('volumechange', function(e) {
if (!mouseIsDown) {
if (media.muted) {
positionVolumeHandle(0);
mute.removeClass('mejs-mute').addClass('mejs-unmute');
} else {
positionVolumeHandle(media.volume);
mute.removeClass('mejs-unmute').addClass('mejs-mute');
}
}
updateVolumeSlider(e);
}, false);
if (t.container.is(':visible')) {
// set initial volume
positionVolumeHandle(player.options.startVolume);
// mutes the media and sets the volume icon muted if the initial volume is set to 0
if (player.options.startVolume === 0) {
media.setMuted(true);
}
// shim gets the startvolume as a parameter, but we have to set it on the native <video> and <audio> elements
if (media.pluginType === 'native') {
media.setVolume(player.options.startVolume);
}
}
}
});
})(mejs.$);
(function($) {
$.extend(mejs.MepDefaults, {
usePluginFullScreen: true,
newWindowCallback: function() { return '';},
fullscreenText: mejs.i18n.t('Fullscreen')
});
$.extend(MediaElementPlayer.prototype, {
isFullScreen: false,
isNativeFullScreen: false,
isInIframe: false,
buildfullscreen: function(player, controls, layers, media) {
if (!player.isVideo)
return;
player.isInIframe = (window.location != window.parent.location);
// native events
if (mejs.MediaFeatures.hasTrueNativeFullScreen) {
// chrome doesn't alays fire this in an iframe
var func = function(e) {
if (player.isFullScreen) {
if (mejs.MediaFeatures.isFullScreen()) {
player.isNativeFullScreen = true;
// reset the controls once we are fully in full screen
player.setControlsSize();
} else {
player.isNativeFullScreen = false;
// when a user presses ESC
// make sure to put the player back into place
player.exitFullScreen();
}
}
};
player.globalBind(mejs.MediaFeatures.fullScreenEventName, func);
}
var t = this,
normalHeight = 0,
normalWidth = 0,
container = player.container,
fullscreenBtn =
$('<div class="mejs-button mejs-fullscreen-button">' +
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.fullscreenText + '" aria-label="' + t.options.fullscreenText + '"></button>' +
'</div>')
.appendTo(controls);
if (t.media.pluginType === 'native' || (!t.options.usePluginFullScreen && !mejs.MediaFeatures.isFirefox)) {
fullscreenBtn.click(function() {
var isFullScreen = (mejs.MediaFeatures.hasTrueNativeFullScreen && mejs.MediaFeatures.isFullScreen()) || player.isFullScreen;
if (isFullScreen) {
player.exitFullScreen();
} else {
player.enterFullScreen();
}
});
} else {
var hideTimeout = null,
supportsPointerEvents = (function() {
// TAKEN FROM MODERNIZR
var element = document.createElement('x'),
documentElement = document.documentElement,
getComputedStyle = window.getComputedStyle,
supports;
if(!('pointerEvents' in element.style)){
return false;
}
element.style.pointerEvents = 'auto';
element.style.pointerEvents = 'x';
documentElement.appendChild(element);
supports = getComputedStyle &&
getComputedStyle(element, '').pointerEvents === 'auto';
documentElement.removeChild(element);
return !!supports;
})();
//
if (supportsPointerEvents && !mejs.MediaFeatures.isOpera) { // opera doesn't allow this :(
// allows clicking through the fullscreen button and controls down directly to Flash
/*
When a user puts his mouse over the fullscreen button, the controls are disabled
So we put a div over the video and another one on iether side of the fullscreen button
that caputre mouse movement
and restore the controls once the mouse moves outside of the fullscreen button
*/
var fullscreenIsDisabled = false,
restoreControls = function() {
if (fullscreenIsDisabled) {
// hide the hovers
for (var i in hoverDivs) {
hoverDivs[i].hide();
}
// restore the control bar
fullscreenBtn.css('pointer-events', '');
t.controls.css('pointer-events', '');
// prevent clicks from pausing video
t.media.removeEventListener('click', t.clickToPlayPauseCallback);
// store for later
fullscreenIsDisabled = false;
}
},
hoverDivs = {},
hoverDivNames = ['top', 'left', 'right', 'bottom'],
i, len,
positionHoverDivs = function() {
var fullScreenBtnOffsetLeft = fullscreenBtn.offset().left - t.container.offset().left,
fullScreenBtnOffsetTop = fullscreenBtn.offset().top - t.container.offset().top,
fullScreenBtnWidth = fullscreenBtn.outerWidth(true),
fullScreenBtnHeight = fullscreenBtn.outerHeight(true),
containerWidth = t.container.width(),
containerHeight = t.container.height();
for (i in hoverDivs) {
hoverDivs[i].css({position: 'absolute', top: 0, left: 0}); //, backgroundColor: '#f00'});
}
// over video, but not controls
hoverDivs['top']
.width( containerWidth )
.height( fullScreenBtnOffsetTop );
// over controls, but not the fullscreen button
hoverDivs['left']
.width( fullScreenBtnOffsetLeft )
.height( fullScreenBtnHeight )
.css({top: fullScreenBtnOffsetTop});
// after the fullscreen button
hoverDivs['right']
.width( containerWidth - fullScreenBtnOffsetLeft - fullScreenBtnWidth )
.height( fullScreenBtnHeight )
.css({top: fullScreenBtnOffsetTop,
left: fullScreenBtnOffsetLeft + fullScreenBtnWidth});
// under the fullscreen button
hoverDivs['bottom']
.width( containerWidth )
.height( containerHeight - fullScreenBtnHeight - fullScreenBtnOffsetTop )
.css({top: fullScreenBtnOffsetTop + fullScreenBtnHeight});
};
t.globalBind('resize', function() {
positionHoverDivs();
});
for (i = 0, len = hoverDivNames.length; i < len; i++) {
hoverDivs[hoverDivNames[i]] = $('<div class="mejs-fullscreen-hover" />').appendTo(t.container).mouseover(restoreControls).hide();
}
// on hover, kill the fullscreen button's HTML handling, allowing clicks down to Flash
fullscreenBtn.on('mouseover',function() {
if (!t.isFullScreen) {
var buttonPos = fullscreenBtn.offset(),
containerPos = player.container.offset();
// move the button in Flash into place
media.positionFullscreenButton(buttonPos.left - containerPos.left, buttonPos.top - containerPos.top, false);
// allows click through
fullscreenBtn.css('pointer-events', 'none');
t.controls.css('pointer-events', 'none');
// restore click-to-play
t.media.addEventListener('click', t.clickToPlayPauseCallback);
// show the divs that will restore things
for (i in hoverDivs) {
hoverDivs[i].show();
}
positionHoverDivs();
fullscreenIsDisabled = true;
}
});
// restore controls anytime the user enters or leaves fullscreen
media.addEventListener('fullscreenchange', function(e) {
t.isFullScreen = !t.isFullScreen;
// don't allow plugin click to pause video - messes with
// plugin's controls
if (t.isFullScreen) {
t.media.removeEventListener('click', t.clickToPlayPauseCallback);
} else {
t.media.addEventListener('click', t.clickToPlayPauseCallback);
}
restoreControls();
});
// the mouseout event doesn't work on the fullscren button, because we already killed the pointer-events
// so we use the document.mousemove event to restore controls when the mouse moves outside the fullscreen button
t.globalBind('mousemove', function(e) {
// if the mouse is anywhere but the fullsceen button, then restore it all
if (fullscreenIsDisabled) {
var fullscreenBtnPos = fullscreenBtn.offset();
if (e.pageY < fullscreenBtnPos.top || e.pageY > fullscreenBtnPos.top + fullscreenBtn.outerHeight(true) ||
e.pageX < fullscreenBtnPos.left || e.pageX > fullscreenBtnPos.left + fullscreenBtn.outerWidth(true)
) {
fullscreenBtn.css('pointer-events', '');
t.controls.css('pointer-events', '');
fullscreenIsDisabled = false;
}
}
});
} else {
// the hover state will show the fullscreen button in Flash to hover up and click
fullscreenBtn
.on('mouseover', function() {
if (hideTimeout !== null) {
clearTimeout(hideTimeout);
delete hideTimeout;
}
var buttonPos = fullscreenBtn.offset(),
containerPos = player.container.offset();
media.positionFullscreenButton(buttonPos.left - containerPos.left, buttonPos.top - containerPos.top, true);
})
.on('mouseout', function() {
if (hideTimeout !== null) {
clearTimeout(hideTimeout);
delete hideTimeout;
}
hideTimeout = setTimeout(function() {
media.hideFullscreenButton();
}, 1500);
});
}
}
player.fullscreenBtn = fullscreenBtn;
t.globalBind('keydown',function (e) {
if (((mejs.MediaFeatures.hasTrueNativeFullScreen && mejs.MediaFeatures.isFullScreen()) || t.isFullScreen) && e.keyCode == 27) {
player.exitFullScreen();
}
});
},
cleanfullscreen: function(player) {
player.exitFullScreen();
},
containerSizeTimeout: null,
enterFullScreen: function() {
var t = this;
// firefox+flash can't adjust plugin sizes without resetting :(
if (t.media.pluginType !== 'native' && (mejs.MediaFeatures.isFirefox || t.options.usePluginFullScreen)) {
//t.media.setFullscreen(true);
//player.isFullScreen = true;
return;
}
// set it to not show scroll bars so 100% will work
$(document.documentElement).addClass('mejs-fullscreen');
// store sizing
normalHeight = t.container.height();
normalWidth = t.container.width();
// attempt to do true fullscreen (Safari 5.1 and Firefox Nightly only for now)
if (t.media.pluginType === 'native') {
if (mejs.MediaFeatures.hasTrueNativeFullScreen) {
mejs.MediaFeatures.requestFullScreen(t.container[0]);
//return;
if (t.isInIframe) {
// sometimes exiting from fullscreen doesn't work
// notably in Chrome <iframe>. Fixed in version 17
setTimeout(function checkFullscreen() {
if (t.isNativeFullScreen) {
var zoomMultiplier = window["devicePixelRatio"] || 1;
// Use a percent error margin since devicePixelRatio is a float and not exact.
var percentErrorMargin = 0.002; // 0.2%
var windowWidth = zoomMultiplier * $(window).width();
var screenWidth = screen.width;
var absDiff = Math.abs(screenWidth - windowWidth);
var marginError = screenWidth * percentErrorMargin;
// check if the video is suddenly not really fullscreen
if (absDiff > marginError) {
// manually exit
t.exitFullScreen();
} else {
// test again
setTimeout(checkFullscreen, 500);
}
}
}, 500);
}
} else if (mejs.MediaFeatures.hasSemiNativeFullScreen) {
t.media.webkitEnterFullscreen();
return;
}
}
// check for iframe launch
if (t.isInIframe) {
var url = t.options.newWindowCallback(this);
if (url !== '') {
// launch immediately
if (!mejs.MediaFeatures.hasTrueNativeFullScreen) {
t.pause();
window.open(url, t.id, 'top=0,left=0,width=' + screen.availWidth + ',height=' + screen.availHeight + ',resizable=yes,scrollbars=no,status=no,toolbar=no');
return;
} else {
setTimeout(function() {
if (!t.isNativeFullScreen) {
t.pause();
window.open(url, t.id, 'top=0,left=0,width=' + screen.availWidth + ',height=' + screen.availHeight + ',resizable=yes,scrollbars=no,status=no,toolbar=no');
}
}, 250);
}
}
}
// full window code
// make full size
t.container
.addClass('mejs-container-fullscreen')
.width('100%')
.height('100%');
//.css({position: 'fixed', left: 0, top: 0, right: 0, bottom: 0, overflow: 'hidden', width: '100%', height: '100%', 'z-index': 1000});
// Only needed for safari 5.1 native full screen, can cause display issues elsewhere
// Actually, it seems to be needed for IE8, too
//if (mejs.MediaFeatures.hasTrueNativeFullScreen) {
t.containerSizeTimeout = setTimeout(function() {
t.container.css({width: '100%', height: '100%'});
t.setControlsSize();
}, 500);
//}
if (t.media.pluginType === 'native') {
t.$media
.width('100%')
.height('100%');
} else {
t.container.find('.mejs-shim')
.width('100%')
.height('100%');
//if (!mejs.MediaFeatures.hasTrueNativeFullScreen) {
t.media.setVideoSize($(window).width(),$(window).height());
//}
}
t.layers.children('div')
.width('100%')
.height('100%');
if (t.fullscreenBtn) {
t.fullscreenBtn
.removeClass('mejs-fullscreen')
.addClass('mejs-unfullscreen');
}
t.setControlsSize();
t.isFullScreen = true;
t.container.find('.mejs-captions-text').css('font-size', screen.width / t.width * 1.00 * 100 + '%');
t.container.find('.mejs-captions-position').css('bottom', '45px');
},
exitFullScreen: function() {
var t = this;
// Prevent container from attempting to stretch a second time
clearTimeout(t.containerSizeTimeout);
// firefox can't adjust plugins
if (t.media.pluginType !== 'native' && mejs.MediaFeatures.isFirefox) {
t.media.setFullscreen(false);
//player.isFullScreen = false;
return;
}
// come outo of native fullscreen
if (mejs.MediaFeatures.hasTrueNativeFullScreen && (mejs.MediaFeatures.isFullScreen() || t.isFullScreen)) {
mejs.MediaFeatures.cancelFullScreen();
}
// restore scroll bars to document
$(document.documentElement).removeClass('mejs-fullscreen');
t.container
.removeClass('mejs-container-fullscreen')
.width(normalWidth)
.height(normalHeight);
//.css({position: '', left: '', top: '', right: '', bottom: '', overflow: 'inherit', width: normalWidth + 'px', height: normalHeight + 'px', 'z-index': 1});
if (t.media.pluginType === 'native') {
t.$media
.width(normalWidth)
.height(normalHeight);
} else {
t.container.find('.mejs-shim')
.width(normalWidth)
.height(normalHeight);
t.media.setVideoSize(normalWidth, normalHeight);
}
t.layers.children('div')
.width(normalWidth)
.height(normalHeight);
t.fullscreenBtn
.removeClass('mejs-unfullscreen')
.addClass('mejs-fullscreen');
t.setControlsSize();
t.isFullScreen = false;
t.container.find('.mejs-captions-text').css('font-size','');
t.container.find('.mejs-captions-position').css('bottom', '');
}
});
})(mejs.$);
//
// mep-feature-tracks.js with instructure customizations
//
// to see the diff, run:
//
// upstream_url='https://raw.githubusercontent.com/johndyer/mediaelement/743f4465231dc20e6f9e96a5cb8b9d5299ceddd3/src/js/mep-feature-tracks.js'
// diff -bu \
// <(curl -s "${upstream_url}") \
// public/javascripts/mediaelement/mep-feature-tracks-instructure.js
//
(function($) {
// add extra default options
$.extend(mejs.MepDefaults, {
// this will automatically turn on a <track>
startLanguage: '',
tracksText: mejs.i18n.t('Captions/Subtitles'),
// option to remove the [cc] button when no <track kind="subtitles"> are present
hideCaptionsButtonWhenEmpty: true,
// If true and we only have one track, change captions to popup
toggleCaptionsButtonWhenOnlyOne: false,
// #id or .class
slidesSelector: ''
});
$.extend(MediaElementPlayer.prototype, {
hasChapters: false,
buildtracks: function(player, controls, layers, media) {
// INSTRUCTURE added code (the '&& !player.options.can_add_captions' part)
if (player.tracks.length == 0 && !player.options.can_add_captions)
return;
var t = this,
i,
options = '';
if (t.domNode.textTracks) { // if browser will do native captions, prefer mejs captions, loop through tracks and hide
for (var i = t.domNode.textTracks.length - 1; i >= 0; i--) {
t.domNode.textTracks[i].mode = "hidden";
}
}
player.chapters =
$('<div class="mejs-chapters mejs-layer"></div>')
.prependTo(layers).hide();
player.captions =
$('<div class="mejs-captions-layer mejs-layer"><div class="mejs-captions-position mejs-captions-position-hover"><span class="mejs-captions-text"></span></div></div>')
.prependTo(layers).hide();
player.captionsText = player.captions.find('.mejs-captions-text');
player.captionsButton =
$('<div class="mejs-button mejs-captions-button">'+
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.tracksText + '" aria-label="' + t.options.tracksText + '"></button>'+
'<div class="mejs-captions-selector">'+
'<ul>'+
'<li>'+
'<input type="radio" name="' + player.id + '_captions" id="' + player.id + '_captions_none" value="none" checked="checked" />' +
'<label for="' + player.id + '_captions_none">' + mejs.i18n.t('None') +'</label>'+
'</li>' +
'</ul>'+
'</div>'+
'</div>')
.appendTo(controls);
var subtitleCount = 0;
for (i=0; i<player.tracks.length; i++) {
if (player.tracks[i].kind == 'subtitles') {
subtitleCount++;
}
}
// if only one language then just make the button a toggle
if (t.options.toggleCaptionsButtonWhenOnlyOne && subtitleCount == 1){
// click
player.captionsButton.on('click',function() {
if (player.selectedTrack == null) {
var lang = player.tracks[0].srclang;
} else {
var lang = 'none';
}
player.setTrack(lang);
});
} else {
// hover
player.captionsButton.hover(function() {
$(this).find('.mejs-captions-selector').css('visibility','visible');
}, function() {
$(this).find('.mejs-captions-selector').css('visibility','hidden');
})
// handle clicks to the language radio buttons
.on('click','input[type=radio]',function() {
lang = this.value;
player.setTrack(lang);
});
}
if (!player.options.alwaysShowControls) {
// move with controls
player.container
.bind('controlsshown', function () {
// push captions above controls
player.container.find('.mejs-captions-position').addClass('mejs-captions-position-hover');
})
.bind('controlshidden', function () {
if (!media.paused) {
// move back to normal place
player.container.find('.mejs-captions-position').removeClass('mejs-captions-position-hover');
}
});
} else {
player.container.find('.mejs-captions-position').addClass('mejs-captions-position-hover');
}
player.trackToLoad = -1;
player.selectedTrack = null;
player.isLoadingTrack = false;
// add to list
for (i=0; i<player.tracks.length; i++) {
if (player.tracks[i].kind == 'subtitles') {
// INSTRUCTURE added third src argument
player.addTrackButton(player.tracks[i].srclang, player.tracks[i].label, player.tracks[i].src);
}
}
// INSTRUCTURE added code
if (player.options.can_add_captions) player.addUploadTrackButton();
// start loading tracks
player.loadNextTrack();
media.addEventListener('timeupdate',function(e) {
player.displayCaptions();
}, false);
if (player.options.slidesSelector != '') {
player.slidesContainer = $(player.options.slidesSelector);
media.addEventListener('timeupdate',function(e) {
player.displaySlides();
}, false);
}
media.addEventListener('loadedmetadata', function(e) {
player.displayChapters();
}, false);
player.container.hover(
function () {
// chapters
if (player.hasChapters) {
player.chapters.css('visibility','visible');
player.chapters.fadeIn(200).height(player.chapters.find('.mejs-chapter').outerHeight());
}
},
function () {
if (player.hasChapters && !media.paused) {
player.chapters.fadeOut(200, function() {
$(this).css('visibility','hidden');
$(this).css('display','block');
});
}
});
// check for autoplay
if (player.node.getAttribute('autoplay') !== null) {
player.chapters.css('visibility','hidden');
}
},
setTrack: function(lang){
var t = this,
i;
if (lang == 'none') {
t.selectedTrack = null;
t.captionsButton.removeClass('mejs-captions-enabled');
} else {
for (i=0; i<t.tracks.length; i++) {
if (t.tracks[i].srclang == lang) {
if (t.selectedTrack == null)
t.captionsButton.addClass('mejs-captions-enabled');
t.selectedTrack = t.tracks[i];
t.captions.attr('lang', t.selectedTrack.srclang);
t.displayCaptions();
break;
}
}
}
},
loadNextTrack: function() {
var t = this;
t.trackToLoad++;
if (t.trackToLoad < t.tracks.length) {
t.isLoadingTrack = true;
t.loadTrack(t.trackToLoad);
} else {
// add done?
t.isLoadingTrack = false;
t.checkForTracks();
}
},
loadTrack: function(index){
var
t = this,
track = t.tracks[index],
after = function() {
track.isLoaded = true;
// create button
//t.addTrackButton(track.srclang);
t.enableTrackButton(track.srclang, track.label);
t.loadNextTrack();
};
$.ajax({
url: track.src,
dataType: "text",
success: function(d) {
// parse the loaded file
if (typeof d == "string" && (/<tt\s+xml/ig).exec(d)) {
track.entries = mejs.TrackFormatParser.dfxp.parse(d);
} else {
track.entries = mejs.TrackFormatParser.webvvt.parse(d);
}
after();
if (track.kind == 'chapters') {
t.media.addEventListener('play', function(e) {
if (t.media.duration > 0) {
t.displayChapters(track);
}
}, false);
}
if (track.kind == 'slides') {
t.setupSlides(track);
}
},
error: function() {
t.loadNextTrack();
}
});
},
enableTrackButton: function(lang, label) {
var t = this;
if (label === '') {
label = mejs.language.codes[lang] || lang;
}
t.captionsButton
.find('input[value=' + lang + ']')
.prop('disabled',false)
.siblings('label')
.html( label );
// auto select
if (t.options.startLanguage == lang) {
$('#' + t.id + '_captions_' + lang).click();
}
t.adjustLanguageBox();
},
// INSTRUCTURE added code
addUploadTrackButton: function() {
var t = this;
$('<a href="#" style="color:white">Upload subtitles</a>')
.appendTo(t.captionsButton.find('ul'))
.wrap('<li>')
.click(function(e){
e.preventDefault();
require(['compiled/widget/UploadMediaTrackForm'], function(UploadMediaTrackForm){
new UploadMediaTrackForm(t.options.mediaCommentId, t.media.src);
});
});
t.adjustLanguageBox();
},
// INSTRUCTURE added src argument
addTrackButton: function(lang, label, src) {
var t = this;
if (label === '') {
label = mejs.language.codes[lang] || lang;
}
// INSTRUCTURE added code
var deleteButtonHtml = '';
if (t.options.can_add_captions) {
deleteButtonHtml = '<a href="#" data-remove="li" data-confirm="Are you sure you want to delete this track?" data-url="' + src + '">×</a>';
}
t.captionsButton.find('ul').append(
$('<li>'+
'<input type="radio" name="' + t.id + '_captions" id="' + t.id + '_captions_' + lang + '" value="' + lang + '" disabled="disabled" />' +
'<label for="' + t.id + '_captions_' + lang + '">' + label + ' (loading)' + '</label>'+
// INSTRUCTURE added code
deleteButtonHtml +
'</li>')
);
t.adjustLanguageBox();
// remove this from the dropdownlist (if it exists)
t.container.find('.mejs-captions-translations option[value=' + lang + ']').remove();
},
adjustLanguageBox:function() {
var t = this;
// adjust the size of the outer box
t.captionsButton.find('.mejs-captions-selector').height(
t.captionsButton.find('.mejs-captions-selector ul').outerHeight(true) +
t.captionsButton.find('.mejs-captions-translations').outerHeight(true)
);
},
checkForTracks: function() {
var
t = this,
hasSubtitles = false;
// check if any subtitles
if (t.options.hideCaptionsButtonWhenEmpty) {
for (i=0; i<t.tracks.length; i++) {
if (t.tracks[i].kind == 'subtitles') {
hasSubtitles = true;
break;
}
}
// INSTRUCTURE added code (second half of conditional)
if (!hasSubtitles && !t.options.can_add_captions) {
t.captionsButton.hide();
t.setControlsSize();
}
}
},
displayCaptions: function() {
if (typeof this.tracks == 'undefined')
return;
var
t = this,
i,
track = t.selectedTrack;
if (track != null && track.isLoaded) {
for (i=0; i<track.entries.times.length; i++) {
if (t.media.currentTime >= track.entries.times[i].start && t.media.currentTime <= track.entries.times[i].stop){
t.captionsText.html(track.entries.text[i]);
t.captions.show().height(0);
return; // exit out if one is visible;
}
}
t.captions.hide();
} else {
t.captions.hide();
}
},
setupSlides: function(track) {
var t = this;
t.slides = track;
t.slides.entries.imgs = [t.slides.entries.text.length];
t.showSlide(0);
},
showSlide: function(index) {
if (typeof this.tracks == 'undefined' || typeof this.slidesContainer == 'undefined') {
return;
}
var t = this,
url = t.slides.entries.text[index],
img = t.slides.entries.imgs[index];
if (typeof img == 'undefined' || typeof img.fadeIn == 'undefined') {
t.slides.entries.imgs[index] = img = $('<img src="' + url + '">')
.on('load', function() {
img.appendTo(t.slidesContainer)
.hide()
.fadeIn()
.siblings(':visible')
.fadeOut();
});
} else {
if (!img.is(':visible') && !img.is(':animated')) {
//
img.fadeIn()
.siblings(':visible')
.fadeOut();
}
}
},
displaySlides: function() {
if (typeof this.slides == 'undefined')
return;
var
t = this,
slides = t.slides,
i;
for (i=0; i<slides.entries.times.length; i++) {
if (t.media.currentTime >= slides.entries.times[i].start && t.media.currentTime <= slides.entries.times[i].stop){
t.showSlide(i);
return; // exit out if one is visible;
}
}
},
displayChapters: function() {
var
t = this,
i;
for (i=0; i<t.tracks.length; i++) {
if (t.tracks[i].kind == 'chapters' && t.tracks[i].isLoaded) {
t.drawChapters(t.tracks[i]);
t.hasChapters = true;
break;
}
}
},
drawChapters: function(chapters) {
var
t = this,
i,
dur,
//width,
//left,
percent = 0,
usedPercent = 0;
t.chapters.empty();
for (i=0; i<chapters.entries.times.length; i++) {
dur = chapters.entries.times[i].stop - chapters.entries.times[i].start;
percent = Math.floor(dur / t.media.duration * 100);
if (percent + usedPercent > 100 || // too large
i == chapters.entries.times.length-1 && percent + usedPercent < 100) // not going to fill it in
{
percent = 100 - usedPercent;
}
//width = Math.floor(t.width * dur / t.media.duration);
//left = Math.floor(t.width * chapters.entries.times[i].start / t.media.duration);
//if (left + width > t.width) {
// width = t.width - left;
//}
t.chapters.append( $(
'<div class="mejs-chapter" rel="' + chapters.entries.times[i].start + '" style="left: ' + usedPercent.toString() + '%;width: ' + percent.toString() + '%;">' +
'<div class="mejs-chapter-block' + ((i==chapters.entries.times.length-1) ? ' mejs-chapter-block-last' : '') + '">' +
'<span class="ch-title">' + chapters.entries.text[i] + '</span>' +
'<span class="ch-time">' + mejs.Utility.secondsToTimeCode(chapters.entries.times[i].start) + '–' + mejs.Utility.secondsToTimeCode(chapters.entries.times[i].stop) + '</span>' +
'</div>' +
'</div>'));
usedPercent += percent;
}
t.chapters.find('div.mejs-chapter').click(function() {
t.media.setCurrentTime( parseFloat( $(this).attr('rel') ) );
if (t.media.paused) {
t.media.play();
}
});
t.chapters.show();
}
});
mejs.language = {
codes: {
af:'Afrikaans',
sq:'Albanian',
ar:'Arabic',
be:'Belarusian',
bg:'Bulgarian',
ca:'Catalan',
zh:'Chinese',
'zh-cn':'Chinese Simplified',
'zh-tw':'Chinese Traditional',
hr:'Croatian',
cs:'Czech',
da:'Danish',
nl:'Dutch',
en:'English',
et:'Estonian',
tl:'Filipino',
fi:'Finnish',
fr:'French',
gl:'Galician',
de:'German',
el:'Greek',
ht:'Haitian Creole',
iw:'Hebrew',
hi:'Hindi',
hu:'Hungarian',
is:'Icelandic',
id:'Indonesian',
ga:'Irish',
it:'Italian',
ja:'Japanese',
ko:'Korean',
lv:'Latvian',
lt:'Lithuanian',
mk:'Macedonian',
ms:'Malay',
mt:'Maltese',
no:'Norwegian',
fa:'Persian',
pl:'Polish',
pt:'Portuguese',
//'pt-pt':'Portuguese (Portugal)',
ro:'Romanian',
ru:'Russian',
sr:'Serbian',
sk:'Slovak',
sl:'Slovenian',
es:'Spanish',
sw:'Swahili',
sv:'Swedish',
tl:'Tagalog',
th:'Thai',
tr:'Turkish',
uk:'Ukrainian',
vi:'Vietnamese',
cy:'Welsh',
yi:'Yiddish'
}
};
/*
Parses WebVVT format which should be formatted as
================================
WEBVTT
1
00:00:01,1 --> 00:00:05,000
A line of text
2
00:01:15,1 --> 00:02:05,000
A second line of text
===============================
Adapted from: http://www.delphiki.com/html5/playr
*/
mejs.TrackFormatParser = {
webvvt: {
// match start "chapter-" (or anythingelse)
pattern_identifier: /^([a-zA-z]+-)?[0-9]+$/,
pattern_timecode: /^([0-9]{2}:[0-9]{2}:[0-9]{2}([,.][0-9]{1,3})?) --\> ([0-9]{2}:[0-9]{2}:[0-9]{2}([,.][0-9]{3})?)(.*)$/,
parse: function(trackText) {
var
i = 0,
lines = mejs.TrackFormatParser.split2(trackText, /\r?\n/),
entries = {text:[], times:[]},
timecode,
text;
for(; i<lines.length; i++) {
// check for the line number
if (this.pattern_identifier.exec(lines[i])){
// skip to the next line where the start --> end time code should be
i++;
timecode = this.pattern_timecode.exec(lines[i]);
if (timecode && i<lines.length){
i++;
// grab all the (possibly multi-line) text that follows
text = lines[i];
i++;
while(lines[i] !== '' && i<lines.length){
text = text + '\n' + lines[i];
i++;
}
text = $.trim(text).replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, "<a href='$1' target='_blank'>$1</a>");
// Text is in a different array so I can use .join
entries.text.push(text);
entries.times.push(
{
start: (mejs.Utility.convertSMPTEtoSeconds(timecode[1]) == 0) ? 0.200 : mejs.Utility.convertSMPTEtoSeconds(timecode[1]),
stop: mejs.Utility.convertSMPTEtoSeconds(timecode[3]),
settings: timecode[5]
});
}
}
}
return entries;
}
},
// Thanks to Justin Capella: https://github.com/johndyer/mediaelement/pull/420
dfxp: {
parse: function(trackText) {
trackText = $(trackText).filter("tt");
var
i = 0,
container = trackText.children("div").eq(0),
lines = container.find("p"),
styleNode = trackText.find("#" + container.attr("style")),
styles,
begin,
end,
text,
entries = {text:[], times:[]};
if (styleNode.length) {
var attributes = styleNode.removeAttr("id").get(0).attributes;
if (attributes.length) {
styles = {};
for (i = 0; i < attributes.length; i++) {
styles[attributes[i].name.split(":")[1]] = attributes[i].value;
}
}
}
for(i = 0; i<lines.length; i++) {
var style;
var _temp_times = {
start: null,
stop: null,
style: null
};
if (lines.eq(i).attr("begin")) _temp_times.start = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i).attr("begin"));
if (!_temp_times.start && lines.eq(i-1).attr("end")) _temp_times.start = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i-1).attr("end"));
if (lines.eq(i).attr("end")) _temp_times.stop = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i).attr("end"));
if (!_temp_times.stop && lines.eq(i+1).attr("begin")) _temp_times.stop = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i+1).attr("begin"));
if (styles) {
style = "";
for (var _style in styles) {
style += _style + ":" + styles[_style] + ";";
}
}
if (style) _temp_times.style = style;
if (_temp_times.start == 0) _temp_times.start = 0.200;
entries.times.push(_temp_times);
text = $.trim(lines.eq(i).html()).replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, "<a href='$1' target='_blank'>$1</a>");
entries.text.push(text);
if (entries.times.start == 0) entries.times.start = 2;
}
return entries;
}
},
split2: function (text, regex) {
// normal version for compliant browsers
// see below for IE fix
return text.split(regex);
}
};
// test for browsers with bad String.split method.
if ('x\n\ny'.split(/\n/gi).length != 3) {
// add super slow IE8 and below version
mejs.TrackFormatParser.split2 = function(text, regex) {
var
parts = [],
chunk = '',
i;
for (i=0; i<text.length; i++) {
chunk += text.substring(i,i+1);
if (regex.test(chunk)) {
parts.push(chunk.replace(regex, ''));
chunk = '';
}
}
parts.push(chunk);
return parts;
}
}
})(mejs.$);
//
// Playback speed control is based on code from an as-yet-unmerged pull request to mediaelement.js
// See: https://github.com/matthillman/mediaelement/commit/e9efc9473ca38c240b712a11ba4c035651c204d4
// And: https://github.com/johndyer/mediaelement/pull/1249
//
(function($) {
// Speed
$.extend(mejs.MepDefaults, {
// INSTRUCTURE CUSTOMIZATION: adjust default available speeds
speeds: ['2.00', '1.50', '1.00', '0.75', '0.50'],
defaultSpeed: '1.00'
});
$.extend(MediaElementPlayer.prototype, {
// INSTRUCTURE CUSTOMIZATION - pulling latest definition of isIE from ME.js master with IE11 fixes
isIE: function() {
return (window.navigator.appName.match(/microsoft/gi) !== null) || (window.navigator.userAgent.match(/trident/gi) !== null);
},
buildspeed: function(player, controls, layers, media) {
// INSTRUCTURE CUSTOMIZATION: enable playback speed controls for both audio and video
// if (!player.isVideo)
// return;
var t = this;
if (t.media.pluginType !== 'native') { return; }
var s = '<div class="mejs-button mejs-speed-button"><button type="button">'+t.options.defaultSpeed+'x</button><div class="mejs-speed-selector"><ul>';
var i, ss;
if ($.inArray(t.options.defaultSpeed, t.options.speeds) === -1) {
t.options.speeds.push(t.options.defaultSpeed);
}
t.options.speeds.sort(function(a, b) {
return parseFloat(b) - parseFloat(a);
});
for (i = 0; i < t.options.speeds.length; i++) {
s += '<li>';
if (t.options.speeds[i] === t.options.defaultSpeed) {
s += '<label class="mejs-speed-selected">'+ t.options.speeds[i] + 'x';
s += '<input type="radio" name="speed" value="' + t.options.speeds[i] + '" checked=true />';
} else {
s += '<label>'+ t.options.speeds[i] + 'x';
s += '<input type="radio" name="speed" value="' + t.options.speeds[i] + '" />';
}
s += '</label></li>';
}
s += '</ul></div></div>';
player.speedButton = $(s).appendTo(controls);
player.playbackspeed = t.options.defaultSpeed;
player.$media.on('loadedmetadata', function() {
media.playbackRate = parseFloat(player.playbackspeed);
});
player.speedButton.on('click', 'input[type=radio]', function() {
player.playbackspeed = $(this).attr('value');
media.playbackRate = parseFloat(player.playbackspeed);
player.speedButton.find('button').text(player.playbackspeed + 'x');
player.speedButton.find('.mejs-speed-selected').removeClass('mejs-speed-selected');
player.speedButton.find('input[type=radio]:checked').parent().addClass('mejs-speed-selected');
//
// INSTRUCTURE CUSTOMIZATION - IE fixes
//
if (t.isIE()) {
// After playback completes, IE will reset the rate to the
// defaultPlaybackRate of 1.00 (with the UI still reflecting the
// selected value) unless we set defaultPlaybackRate as well.
media.defaultPlaybackRate = media.playbackRate;
// Internet Explorer fires a 'waiting' event in addition to the
// 'ratechange' event when the playback speed is changed, even though
// the HTML5 standard says not to. >_<
//
// Even worse, the 'waiting' state does not resolve with any other
// event that would indicate that we are done waiting, like 'playing'
// or 'seeked', so we are left with nothing to hook on but ye olde
// arbitrary point in the future.
$(media).one('waiting', function() {
setTimeout(function() {
layers.find('.mejs-overlay-loading').parent().hide();
controls.find('.mejs-time-buffering').hide();
}, 500);
});
}
});
ss = player.speedButton.find('.mejs-speed-selector');
ss.height(this.speedButton.find('.mejs-speed-selector ul').outerHeight(true) + player.speedButton.find('.mejs-speed-translations').outerHeight(true));
ss.css('top', (-1 * ss.height()) + 'px');
}
});
})(mejs.$);
// Source Chooser Plugin
(function($) {
$.extend(mejs.MepDefaults, {
sourcechooserText: 'Source Chooser'
});
$.extend(MediaElementPlayer.prototype, {
buildsourcechooser: function(player, controls, layers, media) {
if (!player.isVideo) { return; }
var t = this;
player.sourcechooserButton =
$('<div class="mejs-button mejs-sourcechooser-button">'+
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.sourcechooserText + '" aria-label="' + t.options.sourcechooserText + '"></button>'+
'<div class="mejs-sourcechooser-selector">'+
'<ul>'+
'</ul>'+
'</div>'+
'</div>')
.appendTo(controls)
// hover
.hover(function() {
$(this).find('.mejs-sourcechooser-selector').css('visibility','visible');
}, function() {
$(this).find('.mejs-sourcechooser-selector').css('visibility','hidden');
})
// handle clicks to the language radio buttons
.on('click', 'input[type=radio]', function() {
if (media.currentSrc === this.value) { return; }
var src = this.value;
var currentTime = media.currentTime;
var wasPlaying = !media.paused;
$(media).one('loadedmetadata', function() {
media.setCurrentTime(currentTime);
});
$(media).one('canplay', function() {
if (wasPlaying) {
media.play();
}
});
media.setSrc(src);
media.load();
});
// add to list
for (var i in this.node.children) {
var src = this.node.children[i];
if (src.nodeName === 'SOURCE' && (media.canPlayType(src.type) === 'probably' || media.canPlayType(src.type) === 'maybe')) {
player.addSourceButton(src.src, src.title, src.type, media.src === src.src);
}
}
},
addSourceButton: function(src, label, type, isCurrent) {
var t = this;
if (label === '' || label === undefined) {
label = src;
}
type = type.split('/')[1];
t.sourcechooserButton.find('ul').append(
$('<li>'+
'<label>' +
'<input type="radio" name="' + t.id + '_sourcechooser" value="' + src + '" ' + (isCurrent ? 'checked="checked"' : '') + ' />' +
label + ' (' + type + ')</label>' +
'</li>')
);
t.adjustSourcechooserBox();
},
adjustSourcechooserBox: function() {
var t = this;
// adjust the size of the outer box
t.sourcechooserButton.find('.mejs-sourcechooser-selector').height(
t.sourcechooserButton.find('.mejs-sourcechooser-selector ul').outerHeight(true)
);
}
});
})(mejs.$);
/*
* Google Analytics Plugin
* Requires
*
*/
(function($) {
$.extend(mejs.MepDefaults, {
googleAnalyticsTitle: '',
googleAnalyticsCategory: 'Videos',
googleAnalyticsEventPlay: 'Play',
googleAnalyticsEventPause: 'Pause',
googleAnalyticsEventEnded: 'Ended',
googleAnalyticsEventTime: 'Time'
});
$.extend(MediaElementPlayer.prototype, {
buildgoogleanalytics: function(player, controls, layers, media) {
media.addEventListener('play', function() {
if (typeof _gaq != 'undefined') {
_gaq.push(['_trackEvent',
player.options.googleAnalyticsCategory,
player.options.googleAnalyticsEventPlay,
(player.options.googleAnalyticsTitle === '') ? player.currentSrc : player.options.googleAnalyticsTitle
]);
}
}, false);
media.addEventListener('pause', function() {
if (typeof _gaq != 'undefined') {
_gaq.push(['_trackEvent',
player.options.googleAnalyticsCategory,
player.options.googleAnalyticsEventPause,
(player.options.googleAnalyticsTitle === '') ? player.currentSrc : player.options.googleAnalyticsTitle
]);
}
}, false);
media.addEventListener('ended', function() {
if (typeof _gaq != 'undefined') {
_gaq.push(['_trackEvent',
player.options.googleAnalyticsCategory,
player.options.googleAnalyticsEventEnded,
(player.options.googleAnalyticsTitle === '') ? player.currentSrc : player.options.googleAnalyticsTitle
]);
}
}, false);
/*
media.addEventListener('timeupdate', function() {
if (typeof _gaq != 'undefined') {
_gaq.push(['_trackEvent',
player.options.googleAnalyticsCategory,
player.options.googleAnalyticsEventEnded,
player.options.googleAnalyticsTime,
(player.options.googleAnalyticsTitle === '') ? player.currentSrc : player.options.googleAnalyticsTitle,
player.currentTime
]);
}
}, true);
*/
}
});
})(mejs.$);
return mejs;
});
| shidao-fm/canvas-lms | public/javascripts/vendor/mediaelement-and-player.js | JavaScript | agpl-3.0 | 158,652 |
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
/**
* @fileoverview Browser atom for injecting JavaScript into the page under
* test. There is no point in using this atom directly from JavaScript.
* Instead, it is intended to be used in its compiled form when injecting
* script from another language (e.g. C++).
*
* TODO: Add an example
*/
goog.provide('bot.inject');
goog.provide('bot.inject.cache');
goog.require('bot');
goog.require('bot.Error');
goog.require('bot.ErrorCode');
goog.require('bot.json');
/**
* @suppress {extraRequire} Used as a forward declaration which causes
* compilation errors if missing.
*/
goog.require('bot.response.ResponseObject');
goog.require('goog.array');
goog.require('goog.dom.NodeType');
goog.require('goog.object');
goog.require('goog.userAgent');
/**
* Type definition for the WebDriver's JSON wire protocol representation
* of a DOM element.
* @typedef {{ELEMENT: string}}
* @see bot.inject.ELEMENT_KEY
* @see https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol
*/
bot.inject.JsonElement;
/**
* Type definition for a cached Window object that can be referenced in
* WebDriver's JSON wire protocol. Note, this is a non-standard
* representation.
* @typedef {{WINDOW: string}}
* @see bot.inject.WINDOW_KEY
*/
bot.inject.JsonWindow;
/**
* Key used to identify DOM elements in the WebDriver wire protocol.
* @type {string}
* @const
* @see https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol
*/
bot.inject.ELEMENT_KEY = 'ELEMENT';
/**
* Key used to identify Window objects in the WebDriver wire protocol.
* @type {string}
* @const
*/
bot.inject.WINDOW_KEY = 'WINDOW';
/**
* Converts an element to a JSON friendly value so that it can be
* stringified for transmission to the injector. Values are modified as
* follows:
* <ul>
* <li>booleans, numbers, strings, and null are returned as is</li>
* <li>undefined values are returned as null</li>
* <li>functions are returned as a string</li>
* <li>each element in an array is recursively processed</li>
* <li>DOM Elements are wrapped in object-literals as dictated by the
* WebDriver wire protocol</li>
* <li>all other objects will be treated as hash-maps, and will be
* recursively processed for any string and number key types (all
* other key types are discarded as they cannot be converted to JSON).
* </ul>
*
* @param {*} value The value to make JSON friendly.
* @return {*} The JSON friendly value.
* @see https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol
*/
bot.inject.wrapValue = function(value) {
switch (goog.typeOf(value)) {
case 'string':
case 'number':
case 'boolean':
return value;
case 'function':
return value.toString();
case 'array':
return goog.array.map(/**@type {IArrayLike}*/ (value),
bot.inject.wrapValue);
case 'object':
// Since {*} expands to {Object|boolean|number|string|undefined}, the
// JSCompiler complains that it is too broad a type for the remainder of
// this block where {!Object} is expected. Downcast to prevent generating
// a ton of compiler warnings.
value = /**@type {!Object}*/ (value);
// Sniff out DOM elements. We're using duck-typing instead of an
// instanceof check since the instanceof might not always work
// (e.g. if the value originated from another Firefox component)
if (goog.object.containsKey(value, 'nodeType') &&
(value['nodeType'] == goog.dom.NodeType.ELEMENT ||
value['nodeType'] == goog.dom.NodeType.DOCUMENT)) {
var ret = {};
ret[bot.inject.ELEMENT_KEY] =
bot.inject.cache.addElement(/**@type {!Element}*/ (value));
return ret;
}
// Check if this is a Window
if (goog.object.containsKey(value, 'document')) {
var ret = {};
ret[bot.inject.WINDOW_KEY] =
bot.inject.cache.addElement(/**@type{!Window}*/ (value));
return ret;
}
if (goog.isArrayLike(value)) {
return goog.array.map(/**@type {IArrayLike}*/ (value),
bot.inject.wrapValue);
}
var filtered = goog.object.filter(value, function(val, key) {
return goog.isNumber(key) || goog.isString(key);
});
return goog.object.map(filtered, bot.inject.wrapValue);
default: // goog.typeOf(value) == 'undefined' || 'null'
return null;
}
};
/**
* Unwraps any DOM element's encoded in the given {@code value}.
* @param {*} value The value to unwrap.
* @param {Document=} opt_doc The document whose cache to retrieve wrapped
* elements from. Defaults to the current document.
* @return {*} The unwrapped value.
*/
bot.inject.unwrapValue = function(value, opt_doc) {
if (goog.isArray(value)) {
return goog.array.map(/**@type {IArrayLike}*/ (value),
function(v) { return bot.inject.unwrapValue(v, opt_doc); });
} else if (goog.isObject(value)) {
if (typeof value == 'function') {
return value;
}
if (goog.object.containsKey(value, bot.inject.ELEMENT_KEY)) {
return bot.inject.cache.getElement(value[bot.inject.ELEMENT_KEY],
opt_doc);
}
if (goog.object.containsKey(value, bot.inject.WINDOW_KEY)) {
return bot.inject.cache.getElement(value[bot.inject.WINDOW_KEY],
opt_doc);
}
return goog.object.map(value, function(val) {
return bot.inject.unwrapValue(val, opt_doc);
});
}
return value;
};
/**
* Recompiles {@code fn} in the context of another window so that the
* correct symbol table is used when the function is executed. This
* function assumes the {@code fn} can be decompiled to its source using
* {@code Function.prototype.toString} and that it only refers to symbols
* defined in the target window's context.
*
* @param {!(Function|string)} fn Either the function that shold be
* recompiled, or a string defining the body of an anonymous function
* that should be compiled in the target window's context.
* @param {!Window} theWindow The window to recompile the function in.
* @return {!Function} The recompiled function.
* @private
*/
bot.inject.recompileFunction_ = function(fn, theWindow) {
if (goog.isString(fn)) {
try {
return new theWindow['Function'](fn);
} catch (ex) {
// Try to recover if in IE5-quirks mode
// Need to initialize the script engine on the passed-in window
if (goog.userAgent.IE && theWindow.execScript) {
theWindow.execScript(';');
return new theWindow['Function'](fn);
}
throw ex;
}
}
return theWindow == window ? fn : new theWindow['Function'](
'return (' + fn + ').apply(null,arguments);');
};
/**
* Executes an injected script. This function should never be called from
* within JavaScript itself. Instead, it is used from an external source that
* is injecting a script for execution.
*
* <p/>For example, in a WebDriver Java test, one might have:
* <pre><code>
* Object result = ((JavascriptExecutor) driver).executeScript(
* "return arguments[0] + arguments[1];", 1, 2);
* </code></pre>
*
* <p/>Once transmitted to the driver, this command would be injected into the
* page for evaluation as:
* <pre><code>
* bot.inject.executeScript(
* function() {return arguments[0] + arguments[1];},
* [1, 2]);
* </code></pre>
*
* <p/>The details of how this actually gets injected for evaluation is left
* as an implementation detail for clients of this library.
*
* @param {!(Function|string)} fn Either the function to execute, or a string
* defining the body of an anonymous function that should be executed. This
* function should only contain references to symbols defined in the context
* of the target window ({@code opt_window}). Any references to symbols
* defined in this context will likely generate a ReferenceError.
* @param {Array.<*>} args An array of wrapped script arguments, as defined by
* the WebDriver wire protocol.
* @param {boolean=} opt_stringify Whether the result should be returned as a
* serialized JSON string.
* @param {!Window=} opt_window The window in whose context the function should
* be invoked; defaults to the current window.
* @return {!(string|bot.response.ResponseObject)} The response object. If
* opt_stringify is true, the result will be serialized and returned in
* string format.
*/
bot.inject.executeScript = function(fn, args, opt_stringify, opt_window) {
var win = opt_window || bot.getWindow();
var ret;
try {
fn = bot.inject.recompileFunction_(fn, win);
var unwrappedArgs = /**@type {Object}*/ (bot.inject.unwrapValue(args,
win.document));
ret = bot.inject.wrapResponse(fn.apply(null, unwrappedArgs));
} catch (ex) {
ret = bot.inject.wrapError(ex);
}
return opt_stringify ? bot.json.stringify(ret) : ret;
};
/**
* Executes an injected script, which is expected to finish asynchronously
* before the given {@code timeout}. When the script finishes or an error
* occurs, the given {@code onDone} callback will be invoked. This callback
* will have a single argument, a {@link bot.response.ResponseObject} object.
*
* The script signals its completion by invoking a supplied callback given
* as its last argument. The callback may be invoked with a single value.
*
* The script timeout event will be scheduled with the provided window,
* ensuring the timeout is synchronized with that window's event queue.
* Furthermore, asynchronous scripts do not work across new page loads; if an
* "unload" event is fired on the window while an asynchronous script is
* pending, the script will be aborted and an error will be returned.
*
* Like {@code bot.inject.executeScript}, this function should only be called
* from an external source. It handles wrapping and unwrapping of input/output
* values.
*
* @param {(!Function|string)} fn Either the function to execute, or a string
* defining the body of an anonymous function that should be executed. This
* function should only contain references to symbols defined in the context
* of the target window ({@code opt_window}). Any references to symbols
* defined in this context will likely generate a ReferenceError.
* @param {Array.<*>} args An array of wrapped script arguments, as defined by
* the WebDriver wire protocol.
* @param {number} timeout The amount of time, in milliseconds, the script
* should be permitted to run; must be non-negative.
* @param {function(string)|function(!bot.response.ResponseObject)} onDone
* The function to call when the given {@code fn} invokes its callback,
* or when an exception or timeout occurs. This will always be called.
* @param {boolean=} opt_stringify Whether the result should be returned as a
* serialized JSON string.
* @param {!Window=} opt_window The window to synchronize the script with;
* defaults to the current window.
*/
bot.inject.executeAsyncScript = function(fn, args, timeout, onDone,
opt_stringify, opt_window) {
var win = opt_window || window;
var timeoutId;
var responseSent = false;
function sendResponse(status, value) {
if (!responseSent) {
if (win.removeEventListener) {
win.removeEventListener('unload', onunload, true);
} else {
win.detachEvent('onunload', onunload);
}
win.clearTimeout(timeoutId);
if (status != bot.ErrorCode.SUCCESS) {
var err = new bot.Error(status, value.message || value + '');
err.stack = value.stack;
value = bot.inject.wrapError(err);
} else {
value = bot.inject.wrapResponse(value);
}
onDone(opt_stringify ? bot.json.stringify(value) : value);
responseSent = true;
}
}
var sendError = goog.partial(sendResponse, bot.ErrorCode.UNKNOWN_ERROR);
if (win.closed) {
sendError('Unable to execute script; the target window is closed.');
return;
}
fn = bot.inject.recompileFunction_(fn, win);
args = /** @type {Array.<*>} */ (bot.inject.unwrapValue(args, win.document));
args.push(goog.partial(sendResponse, bot.ErrorCode.SUCCESS));
if (win.addEventListener) {
win.addEventListener('unload', onunload, true);
} else {
win.attachEvent('onunload', onunload);
}
var startTime = goog.now();
try {
fn.apply(win, args);
// Register our timeout *after* the function has been invoked. This will
// ensure we don't timeout on a function that invokes its callback after
// a 0-based timeout.
timeoutId = win.setTimeout(function() {
sendResponse(bot.ErrorCode.SCRIPT_TIMEOUT,
Error('Timed out waiting for asyncrhonous script result ' +
'after ' + (goog.now() - startTime) + ' ms'));
}, Math.max(0, timeout));
} catch (ex) {
sendResponse(ex.code || bot.ErrorCode.UNKNOWN_ERROR, ex);
}
function onunload() {
sendResponse(bot.ErrorCode.UNKNOWN_ERROR,
Error('Detected a page unload event; asynchronous script ' +
'execution does not work across page loads.'));
}
};
/**
* Wraps the response to an injected script that executed successfully so it
* can be JSON-ified for transmission to the process that injected this
* script.
* @param {*} value The script result.
* @return {{status:bot.ErrorCode,value:*}} The wrapped value.
* @see https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol#responses
*/
bot.inject.wrapResponse = function(value) {
return {
'status': bot.ErrorCode.SUCCESS,
'value': bot.inject.wrapValue(value)
};
};
/**
* Wraps a JavaScript error in an object-literal so that it can be JSON-ified
* for transmission to the process that injected this script.
* @param {Error} err The error to wrap.
* @return {{status:bot.ErrorCode,value:*}} The wrapped error object.
* @see https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol#failed-commands
*/
bot.inject.wrapError = function(err) {
// TODO: Parse stackTrace
return {
'status': goog.object.containsKey(err, 'code') ?
err['code'] : bot.ErrorCode.UNKNOWN_ERROR,
// TODO: Parse stackTrace
'value': {
'message': err.message
}
};
};
/**
* The property key used to store the element cache on the DOCUMENT node
* when it is injected into the page. Since compiling each browser atom results
* in a different symbol table, we must use this known key to access the cache.
* This ensures the same object is used between injections of different atoms.
* @private {string}
* @const
*/
bot.inject.cache.CACHE_KEY_ = '$wdc_';
/**
* The prefix for each key stored in an cache.
* @type {string}
* @const
*/
bot.inject.cache.ELEMENT_KEY_PREFIX = ':wdc:';
/**
* Retrieves the cache object for the given window. Will initialize the cache
* if it does not yet exist.
* @param {Document=} opt_doc The document whose cache to retrieve. Defaults to
* the current document.
* @return {Object.<string, (Element|Window)>} The cache object.
* @private
*/
bot.inject.cache.getCache_ = function(opt_doc) {
var doc = opt_doc || document;
var cache = doc[bot.inject.cache.CACHE_KEY_];
if (!cache) {
cache = doc[bot.inject.cache.CACHE_KEY_] = {};
// Store the counter used for generated IDs in the cache so that it gets
// reset whenever the cache does.
cache.nextId = goog.now();
}
// Sometimes the nextId does not get initialized and returns NaN
// TODO: Generate UID on the fly instead.
if (!cache.nextId) {
cache.nextId = goog.now();
}
return cache;
};
/**
* Adds an element to its ownerDocument's cache.
* @param {(Element|Window)} el The element or Window object to add.
* @return {string} The key generated for the cached element.
*/
bot.inject.cache.addElement = function(el) {
// Check if the element already exists in the cache.
var cache = bot.inject.cache.getCache_(el.ownerDocument);
var id = goog.object.findKey(cache, function(value) {
return value == el;
});
if (!id) {
id = bot.inject.cache.ELEMENT_KEY_PREFIX + cache.nextId++;
cache[id] = el;
}
return id;
};
/**
* Retrieves an element from the cache. Will verify that the element is
* still attached to the DOM before returning.
* @param {string} key The element's key in the cache.
* @param {Document=} opt_doc The document whose cache to retrieve the element
* from. Defaults to the current document.
* @return {Element|Window} The cached element.
*/
bot.inject.cache.getElement = function(key, opt_doc) {
key = decodeURIComponent(key);
var doc = opt_doc || document;
var cache = bot.inject.cache.getCache_(doc);
if (!goog.object.containsKey(cache, key)) {
// Throw STALE_ELEMENT_REFERENCE instead of NO_SUCH_ELEMENT since the
// key may have been defined by a prior document's cache.
throw new bot.Error(bot.ErrorCode.STALE_ELEMENT_REFERENCE,
'Element does not exist in cache');
}
var el = cache[key];
// If this is a Window check if it's closed
if (goog.object.containsKey(el, 'setInterval')) {
if (el.closed) {
delete cache[key];
throw new bot.Error(bot.ErrorCode.NO_SUCH_WINDOW,
'Window has been closed.');
}
return el;
}
// Make sure the element is still attached to the DOM before returning.
var node = el;
while (node) {
if (node == doc.documentElement) {
return el;
}
node = node.parentNode;
}
delete cache[key];
throw new bot.Error(bot.ErrorCode.STALE_ELEMENT_REFERENCE,
'Element is no longer attached to the DOM');
};
| alb-i986/selenium | javascript/atoms/inject.js | JavaScript | apache-2.0 | 18,402 |
/*
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 Q = require('q');
var path = require('path');
var shell = require('shelljs');
var Version = require('./Version');
var events = require('cordova-common').events;
var spawn = require('cordova-common').superspawn.spawn;
function MSBuildTools (version, path) {
this.version = version;
this.path = path;
}
MSBuildTools.prototype.buildProject = function(projFile, buildType, buildarch, otherConfigProperties) {
events.emit('log', 'Building project: ' + projFile);
events.emit('log', '\tConfiguration : ' + buildType);
events.emit('log', '\tPlatform : ' + buildarch);
var args = ['/clp:NoSummary;NoItemAndPropertyList;Verbosity=minimal', '/nologo',
'/p:Configuration=' + buildType,
'/p:Platform=' + buildarch];
if (otherConfigProperties) {
var keys = Object.keys(otherConfigProperties);
keys.forEach(function(key) {
args.push('/p:' + key + '=' + otherConfigProperties[key]);
});
}
return spawn(path.join(this.path, 'msbuild'), [projFile].concat(args), { stdio: 'inherit' });
};
// returns full path to msbuild tools required to build the project and tools version
module.exports.findAvailableVersion = function () {
var versions = ['15.0', '14.0', '12.0', '4.0'];
return Q.all(versions.map(checkMSBuildVersion)).then(function (versions) {
// select first msbuild version available, and resolve promise with it
var msbuildTools = versions[0] || versions[1] || versions[2] || versions[3];
return msbuildTools ? Q.resolve(msbuildTools) : Q.reject('MSBuild tools not found');
});
};
module.exports.findAllAvailableVersions = function () {
var versions = ['15.0', '14.0', '12.0', '4.0'];
events.emit('verbose', 'Searching for available MSBuild versions...');
return Q.all(versions.map(checkMSBuildVersion)).then(function(unprocessedResults) {
return unprocessedResults.filter(function(item) {
return !!item;
});
});
};
function checkMSBuildVersion(version) {
return spawn('reg', ['query', 'HKLM\\SOFTWARE\\Microsoft\\MSBuild\\ToolsVersions\\' + version, '/v', 'MSBuildToolsPath'])
.then(function(output) {
// fetch msbuild path from 'reg' output
var toolsPath = /MSBuildToolsPath\s+REG_SZ\s+(.*)/i.exec(output);
if (toolsPath) {
toolsPath = toolsPath[1];
// CB-9565: Windows 10 invokes .NET Native compiler, which only runs on x86 arch,
// so if we're running an x64 Node, make sure to use x86 tools.
if ((version === '15.0' || version === '14.0') && toolsPath.indexOf('amd64') > -1) {
toolsPath = path.resolve(toolsPath, '..');
}
events.emit('verbose', 'Found MSBuild v' + version + ' at ' + toolsPath);
return new MSBuildTools(version, toolsPath);
}
})
.catch(function (err) {
// if 'reg' exits with error, assume that registry key not found
return;
});
}
/// returns an array of available UAP Versions
function getAvailableUAPVersions() {
/*jshint -W069 */
var programFilesFolder = process.env['ProgramFiles(x86)'] || process.env['ProgramFiles'];
// No Program Files folder found, so we won't be able to find UAP SDK
if (!programFilesFolder) return [];
var uapFolderPath = path.join(programFilesFolder, 'Windows Kits', '10', 'Platforms', 'UAP');
if (!shell.test('-e', uapFolderPath)) {
return []; // No UAP SDK exists on this machine
}
var result = [];
shell.ls(uapFolderPath).filter(function(uapDir) {
return shell.test('-d', path.join(uapFolderPath, uapDir));
}).map(function(folder) {
return Version.tryParse(folder);
}).forEach(function(version, index) {
if (version) {
result.push(version);
}
});
return result;
}
module.exports.getAvailableUAPVersions = getAvailableUAPVersions;
| sgrebnov/cordova-windows | template/cordova/lib/MSBuildTools.js | JavaScript | apache-2.0 | 4,798 |
//>>built
define("dojox/grid/enhanced/plugins/Printer","dojo/_base/declare dojo/_base/html dojo/_base/Deferred dojo/_base/lang dojo/_base/sniff dojo/_base/xhr dojo/_base/array dojo/query dojo/DeferredList ../_Plugin ../../EnhancedGrid ./exporter/TableWriter".split(" "),function(k,g,p,e,l,q,m,n,r,s,t,u){k=k("dojox.grid.enhanced.plugins.Printer",s,{name:"printer",constructor:function(a){this.grid=a;this._mixinGrid(a);a.setExportFormatter(function(a,d,h,c){return d.format(h,c)})},_mixinGrid:function(){var a=this.grid;
a.printGrid=e.hitch(this,this.printGrid);a.printSelected=e.hitch(this,this.printSelected);a.exportToHTML=e.hitch(this,this.exportToHTML);a.exportSelectedToHTML=e.hitch(this,this.exportSelectedToHTML);a.normalizePrintedGrid=e.hitch(this,this.normalizeRowHeight)},printGrid:function(a){this.exportToHTML(a,e.hitch(this,this._print))},printSelected:function(a){this.exportSelectedToHTML(a,e.hitch(this,this._print))},exportToHTML:function(a,b){a=this._formalizeArgs(a);var d=this;this.grid.exportGrid("table",
a,function(h){d._wrapHTML(a.title,a.cssFiles,a.titleInBody+h).then(b)})},exportSelectedToHTML:function(a,b){a=this._formalizeArgs(a);var d=this;this.grid.exportSelected("table",a.writerArgs,function(h){d._wrapHTML(a.title,a.cssFiles,a.titleInBody+h).then(b)})},_loadCSSFiles:function(a){a=m.map(a,function(a){a=e.trim(a);if(".css"===a.substring(a.length-4).toLowerCase())return q.get({url:a});var d=new p;d.callback(a);return d});return r.prototype.gatherResults(a)},_print:function(a){var b,d=this,h=
function(b){b=b.document;b.open();b.write(a);b.close();d.normalizeRowHeight(b)};if(window.print)if(l("chrome")||l("opera"))b=window.open("javascript: ''","","status\x3d0,menubar\x3d0,location\x3d0,toolbar\x3d0,width\x3d1,height\x3d1,resizable\x3d0,scrollbars\x3d0"),h(b),b.print(),b.close();else{b=this._printFrame;var c=this.grid.domNode;if(!b){var f=c.id+"_print_frame";if(!(b=g.byId(f)))b=g.create("iframe"),b.id=f,b.frameBorder=0,g.style(b,{width:"1px",height:"1px",position:"absolute",right:0,bottom:0,
border:"none",overflow:"hidden"}),l("ie")||g.style(b,"visibility","hidden"),c.appendChild(b);this._printFrame=b}b=b.contentWindow;h(b);b.focus();b.print()}},_wrapHTML:function(a,b,d){return this._loadCSSFiles(b).then(function(b){var c,f=['\x3c!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"\x3e',"\x3chtml ",g._isBodyLtr()?"":'dir\x3d"rtl"',"\x3e\x3chead\x3e\x3ctitle\x3e",a,'\x3c/title\x3e\x3cmeta http-equiv\x3d"Content-Type" content\x3d"text/html; charset\x3dutf-8"\x3e\x3c/meta\x3e'];
for(c=0;c<b.length;++c)f.push('\x3cstyle type\x3d"text/css"\x3e',b[c],"\x3c/style\x3e");f.push("\x3c/head\x3e");0>d.search(/^\s*<body/i)&&(d="\x3cbody\x3e"+d+"\x3c/body\x3e");f.push(d,"\x3c/html\x3e");return f.join("")})},normalizeRowHeight:function(a){a=n(".grid_view",a.body);var b=m.map(a,function(a){return n(".grid_header",a)[0]}),d=m.map(a,function(a){return n(".grid_row",a)}),h=d[0].length,c,f,e=0;for(c=a.length-1;0<=c;--c)f=g.contentBox(b[c]).h,f>e&&(e=f);for(c=a.length-1;0<=c;--c)g.style(b[c],
"height",e+"px");for(b=0;b<h;++b){e=0;for(c=a.length-1;0<=c;--c)f=g.contentBox(d[c][b]).h,f>e&&(e=f);for(c=a.length-1;0<=c;--c)g.style(d[c][b],"height",e+"px")}d=0;h=g._isBodyLtr();for(c=0;c<a.length;++c)g.style(a[c],h?"left":"right",d+"px"),d+=g.marginBox(a[c]).w},_formalizeArgs:function(a){a=a&&e.isObject(a)?a:{};a.title=String(a.title)||"";e.isArray(a.cssFiles)||(a.cssFiles=[a.cssFiles]);a.titleInBody=a.title?["\x3ch1\x3e",a.title,"\x3c/h1\x3e"].join(""):"";return a}});t.registerPlugin(k,{dependency:["exporter"]});
return k}); | aconyteds/Esri-Ozone-Map-Widget | vendor/js/esri/arcgis_js_api/library/3.12/3.12compact/dojox/grid/enhanced/plugins/Printer.js | JavaScript | apache-2.0 | 3,621 |
/*
* jQuery Plugin: Tokenizing Autocomplete Text Entry
* Version 1.6.2
*
* Copyright (c) 2009 James Smith (http://loopj.com)
* Licensed jointly under the GPL and MIT licenses,
* choose which one suits your project best!
*
*/
;(function ($) {
var DEFAULT_SETTINGS = {
// Search settings
method: "GET",
queryParam: "q",
searchDelay: 300,
minChars: 1,
propertyToSearch: "name",
jsonContainer: null,
contentType: "json",
excludeCurrent: false,
excludeCurrentParameter: "x",
// Prepopulation settings
prePopulate: null,
processPrePopulate: false,
// Display settings
hintText: "Type in a search term",
noResultsText: "No results",
searchingText: "Searching...",
deleteText: "×",
animateDropdown: true,
placeholder: null,
theme: null,
overwriteClasses: null,
zindex: 999,
resultsLimit: null,
enableHTML: false,
resultsFormatter: function(item) {
var string = item[this.propertyToSearch];
return "<li>" + (this.enableHTML ? string : _escapeHTML(string)) + "</li>";
},
tokenFormatter: function(item) {
var string = item[this.propertyToSearch];
return "<li><p>" + (this.enableHTML ? string : _escapeHTML(string)) + "</p></li>";
},
// Tokenization settings
tokenLimit: null,
tokenDelimiter: ",",
preventDuplicates: false,
tokenValue: "id",
// Behavioral settings
allowFreeTagging: false,
allowTabOut: false,
autoSelectFirstResult: false,
// Callbacks
onResult: null,
onCachedResult: null,
onAdd: null,
onFreeTaggingAdd: null,
onDelete: null,
onReady: null,
// Other settings
idPrefix: "token-input-",
// Keep track if the input is currently in disabled mode
disabled: false
};
// Default classes to use when theming
var DEFAULT_CLASSES = {
tokenList : "token-input-list",
token : "token-input-token",
tokenReadOnly : "token-input-token-readonly",
tokenDelete : "token-input-delete-token",
selectedToken : "token-input-selected-token",
highlightedToken : "token-input-highlighted-token",
dropdown : "token-input-dropdown",
dropdownItem : "token-input-dropdown-item",
dropdownItem2 : "token-input-dropdown-item2",
selectedDropdownItem : "token-input-selected-dropdown-item",
inputToken : "token-input-input-token",
focused : "token-input-focused",
disabled : "token-input-disabled"
};
// Input box position "enum"
var POSITION = {
BEFORE : 0,
AFTER : 1,
END : 2
};
// Keys "enum"
var KEY = {
BACKSPACE : 8,
TAB : 9,
ENTER : 13,
ESCAPE : 27,
SPACE : 32,
PAGE_UP : 33,
PAGE_DOWN : 34,
END : 35,
HOME : 36,
LEFT : 37,
UP : 38,
RIGHT : 39,
DOWN : 40,
NUMPAD_ENTER : 108,
COMMA : 188
};
var HTML_ESCAPES = {
'&' : '&',
'<' : '<',
'>' : '>',
'"' : '"',
"'" : ''',
'/' : '/'
};
var HTML_ESCAPE_CHARS = /[&<>"'\/]/g;
function coerceToString(val) {
return String((val === null || val === undefined) ? '' : val);
}
function _escapeHTML(text) {
return coerceToString(text).replace(HTML_ESCAPE_CHARS, function(match) {
return HTML_ESCAPES[match];
});
}
// Additional public (exposed) methods
var methods = {
init: function(url_or_data_or_function, options) {
var settings = $.extend({}, DEFAULT_SETTINGS, options || {});
return this.each(function () {
$(this).data("settings", settings);
$(this).data("tokenInputObject", new $.TokenList(this, url_or_data_or_function, settings));
});
},
clear: function() {
this.data("tokenInputObject").clear();
return this;
},
add: function(item) {
this.data("tokenInputObject").add(item);
return this;
},
remove: function(item) {
this.data("tokenInputObject").remove(item);
return this;
},
get: function() {
return this.data("tokenInputObject").getTokens();
},
toggleDisabled: function(disable) {
this.data("tokenInputObject").toggleDisabled(disable);
return this;
},
setOptions: function(options){
$(this).data("settings", $.extend({}, $(this).data("settings"), options || {}));
return this;
},
destroy: function () {
if (this.data("tokenInputObject")) {
this.data("tokenInputObject").clear();
var tmpInput = this;
var closest = this.parent();
closest.empty();
tmpInput.show();
closest.append(tmpInput);
return tmpInput;
}
}
};
// Expose the .tokenInput function to jQuery as a plugin
$.fn.tokenInput = function (method) {
// Method calling and initialization logic
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else {
return methods.init.apply(this, arguments);
}
};
// TokenList class for each input
$.TokenList = function (input, url_or_data, settings) {
//
// Initialization
//
// Configure the data source
if (typeof(url_or_data) === "string" || typeof(url_or_data) === "function") {
// Set the url to query against
$(input).data("settings").url = url_or_data;
// If the URL is a function, evaluate it here to do our initalization work
var url = computeURL();
// Make a smart guess about cross-domain if it wasn't explicitly specified
if ($(input).data("settings").crossDomain === undefined && typeof url === "string") {
if(url.indexOf("://") === -1) {
$(input).data("settings").crossDomain = false;
} else {
$(input).data("settings").crossDomain = (location.href.split(/\/+/g)[1] !== url.split(/\/+/g)[1]);
}
}
} else if (typeof(url_or_data) === "object") {
// Set the local data to search through
$(input).data("settings").local_data = url_or_data;
}
// Build class names
if($(input).data("settings").classes) {
// Use custom class names
$(input).data("settings").classes = $.extend({}, DEFAULT_CLASSES, $(input).data("settings").classes);
} else if($(input).data("settings").overwriteClasses) {
$(input).data("settings").classes = $.extend({}, DEFAULT_CLASSES, $(input).data("settings").overwriteClasses);
} else if($(input).data("settings").theme) {
// Use theme-suffixed default class names
$(input).data("settings").classes = {};
$.each(DEFAULT_CLASSES, function(key, value) {
$(input).data("settings").classes[key] = value + "-" + $(input).data("settings").theme;
});
} else {
$(input).data("settings").classes = DEFAULT_CLASSES;
}
// Save the tokens
var saved_tokens = [];
// Keep track of the number of tokens in the list
var token_count = 0;
// Basic cache to save on db hits
var cache = new $.TokenList.Cache();
// Keep track of the timeout, old vals
var timeout;
var input_val;
// Create a new text input an attach keyup events
var input_box = $("<input type=\"text\" autocomplete=\"off\" autocapitalize=\"off\"/>")
.css({
outline: "none"
})
.attr("id", $(input).data("settings").idPrefix + input.id)
.focus(function () {
if ($(input).data("settings").disabled) {
return false;
} else
if ($(input).data("settings").tokenLimit === null || $(input).data("settings").tokenLimit !== token_count) {
show_dropdown_hint();
}
token_list.addClass($(input).data("settings").classes.focused);
})
.blur(function () {
hide_dropdown();
if ($(input).data("settings").allowFreeTagging) {
add_freetagging_tokens();
}
$(this).val("");
token_list.removeClass($(input).data("settings").classes.focused);
})
.bind("keyup keydown blur update", resize_input)
.keydown(function (event) {
var previous_token;
var next_token;
switch(event.keyCode) {
case KEY.LEFT:
case KEY.RIGHT:
case KEY.UP:
case KEY.DOWN:
if(this.value.length === 0) {
previous_token = input_token.prev();
next_token = input_token.next();
if((previous_token.length && previous_token.get(0) === selected_token) ||
(next_token.length && next_token.get(0) === selected_token)) {
// Check if there is a previous/next token and it is selected
if(event.keyCode === KEY.LEFT || event.keyCode === KEY.UP) {
deselect_token($(selected_token), POSITION.BEFORE);
} else {
deselect_token($(selected_token), POSITION.AFTER);
}
} else if((event.keyCode === KEY.LEFT || event.keyCode === KEY.UP) && previous_token.length) {
// We are moving left, select the previous token if it exists
select_token($(previous_token.get(0)));
} else if((event.keyCode === KEY.RIGHT || event.keyCode === KEY.DOWN) && next_token.length) {
// We are moving right, select the next token if it exists
select_token($(next_token.get(0)));
}
} else {
var dropdown_item = null;
if (event.keyCode === KEY.DOWN || event.keyCode === KEY.RIGHT) {
dropdown_item = $(dropdown).find('li').first();
if (selected_dropdown_item) {
dropdown_item = $(selected_dropdown_item).next();
}
} else {
dropdown_item = $(dropdown).find('li').last();
if (selected_dropdown_item) {
dropdown_item = $(selected_dropdown_item).prev();
}
}
select_dropdown_item(dropdown_item);
}
break;
case KEY.BACKSPACE:
previous_token = input_token.prev();
if (this.value.length === 0) {
if (selected_token) {
delete_token($(selected_token));
hiddenInput.change();
} else if(previous_token.length) {
select_token($(previous_token.get(0)));
}
return false;
} else if($(this).val().length === 1) {
hide_dropdown();
} else {
// set a timeout just long enough to let this function finish.
setTimeout(function(){ do_search(); }, 5);
}
break;
case KEY.TAB:
case KEY.ENTER:
case KEY.NUMPAD_ENTER:
case KEY.COMMA:
if(selected_dropdown_item) {
add_token($(selected_dropdown_item).data("tokeninput"));
hiddenInput.change();
} else {
if ($(input).data("settings").allowFreeTagging) {
if($(input).data("settings").allowTabOut && $(this).val() === "") {
return true;
} else {
add_freetagging_tokens();
}
} else {
$(this).val("");
if($(input).data("settings").allowTabOut) {
return true;
}
}
event.stopPropagation();
event.preventDefault();
}
return false;
case KEY.ESCAPE:
hide_dropdown();
return true;
default:
if (String.fromCharCode(event.which)) {
// set a timeout just long enough to let this function finish.
setTimeout(function(){ do_search(); }, 5);
}
break;
}
});
// Keep reference for placeholder
if (settings.placeholder) {
input_box.attr("placeholder", settings.placeholder);
}
// Keep a reference to the original input box
var hiddenInput = $(input)
.hide()
.val("")
.focus(function () {
focusWithTimeout(input_box);
})
.blur(function () {
input_box.blur();
//return the object to this can be referenced in the callback functions.
return hiddenInput;
})
;
// Keep a reference to the selected token and dropdown item
var selected_token = null;
var selected_token_index = 0;
var selected_dropdown_item = null;
// The list to store the token items in
var token_list = $("<ul />")
.addClass($(input).data("settings").classes.tokenList)
.click(function (event) {
var li = $(event.target).closest("li");
if(li && li.get(0) && $.data(li.get(0), "tokeninput")) {
toggle_select_token(li);
} else {
// Deselect selected token
if(selected_token) {
deselect_token($(selected_token), POSITION.END);
}
// Focus input box
focusWithTimeout(input_box);
}
})
.mouseover(function (event) {
var li = $(event.target).closest("li");
if(li && selected_token !== this) {
li.addClass($(input).data("settings").classes.highlightedToken);
}
})
.mouseout(function (event) {
var li = $(event.target).closest("li");
if(li && selected_token !== this) {
li.removeClass($(input).data("settings").classes.highlightedToken);
}
})
.insertBefore(hiddenInput);
// The token holding the input box
var input_token = $("<li />")
.addClass($(input).data("settings").classes.inputToken)
.appendTo(token_list)
.append(input_box);
// The list to store the dropdown items in
var dropdown = $("<div/>")
.addClass($(input).data("settings").classes.dropdown)
.appendTo("body")
.hide();
// Magic element to help us resize the text input
var input_resizer = $("<tester/>")
.insertAfter(input_box)
.css({
position: "absolute",
top: -9999,
left: -9999,
width: "auto",
fontSize: input_box.css("fontSize"),
fontFamily: input_box.css("fontFamily"),
fontWeight: input_box.css("fontWeight"),
letterSpacing: input_box.css("letterSpacing"),
whiteSpace: "nowrap"
});
// Pre-populate list if items exist
hiddenInput.val("");
var li_data = $(input).data("settings").prePopulate || hiddenInput.data("pre");
if ($(input).data("settings").processPrePopulate && $.isFunction($(input).data("settings").onResult)) {
li_data = $(input).data("settings").onResult.call(hiddenInput, li_data);
}
if (li_data && li_data.length) {
$.each(li_data, function (index, value) {
insert_token(value);
checkTokenLimit();
input_box.attr("placeholder", null)
});
}
// Check if widget should initialize as disabled
if ($(input).data("settings").disabled) {
toggleDisabled(true);
}
// Initialization is done
if (typeof($(input).data("settings").onReady) === "function") {
$(input).data("settings").onReady.call();
}
//
// Public functions
//
this.clear = function() {
token_list.children("li").each(function() {
if ($(this).children("input").length === 0) {
delete_token($(this));
}
});
};
this.add = function(item) {
add_token(item);
};
this.remove = function(item) {
token_list.children("li").each(function() {
if ($(this).children("input").length === 0) {
var currToken = $(this).data("tokeninput");
var match = true;
for (var prop in item) {
if (item[prop] !== currToken[prop]) {
match = false;
break;
}
}
if (match) {
delete_token($(this));
}
}
});
};
this.getTokens = function() {
return saved_tokens;
};
this.toggleDisabled = function(disable) {
toggleDisabled(disable);
};
// Resize input to maximum width so the placeholder can be seen
resize_input();
//
// Private functions
//
function escapeHTML(text) {
return $(input).data("settings").enableHTML ? text : _escapeHTML(text);
}
// Toggles the widget between enabled and disabled state, or according
// to the [disable] parameter.
function toggleDisabled(disable) {
if (typeof disable === 'boolean') {
$(input).data("settings").disabled = disable
} else {
$(input).data("settings").disabled = !$(input).data("settings").disabled;
}
input_box.attr('disabled', $(input).data("settings").disabled);
token_list.toggleClass($(input).data("settings").classes.disabled, $(input).data("settings").disabled);
// if there is any token selected we deselect it
if(selected_token) {
deselect_token($(selected_token), POSITION.END);
}
hiddenInput.attr('disabled', $(input).data("settings").disabled);
}
function checkTokenLimit() {
if($(input).data("settings").tokenLimit !== null && token_count >= $(input).data("settings").tokenLimit) {
input_box.hide();
hide_dropdown();
return;
}
}
function resize_input() {
if(input_val === (input_val = input_box.val())) {return;}
// Get width left on the current line
var width_left = token_list.width() - input_box.offset().left - token_list.offset().left;
// Enter new content into resizer and resize input accordingly
input_resizer.html(_escapeHTML(input_val) || _escapeHTML(settings.placeholder));
// Get maximum width, minimum the size of input and maximum the widget's width
input_box.width(Math.min(token_list.width(),
Math.max(width_left, input_resizer.width() + 30)));
}
function add_freetagging_tokens() {
var value = $.trim(input_box.val());
var tokens = value.split($(input).data("settings").tokenDelimiter);
$.each(tokens, function(i, token) {
if (!token) {
return;
}
if ($.isFunction($(input).data("settings").onFreeTaggingAdd)) {
token = $(input).data("settings").onFreeTaggingAdd.call(hiddenInput, token);
}
var object = {};
object[$(input).data("settings").tokenValue] = object[$(input).data("settings").propertyToSearch] = token;
add_token(object);
});
}
// Inner function to a token to the list
function insert_token(item) {
var $this_token = $($(input).data("settings").tokenFormatter(item));
var readonly = item.readonly === true;
if(readonly) $this_token.addClass($(input).data("settings").classes.tokenReadOnly);
$this_token.addClass($(input).data("settings").classes.token).insertBefore(input_token);
// The 'delete token' button
if(!readonly) {
$("<span>" + $(input).data("settings").deleteText + "</span>")
.addClass($(input).data("settings").classes.tokenDelete)
.appendTo($this_token)
.click(function () {
if (!$(input).data("settings").disabled) {
delete_token($(this).parent());
hiddenInput.change();
return false;
}
});
}
// Store data on the token
var token_data = item;
$.data($this_token.get(0), "tokeninput", item);
// Save this token for duplicate checking
saved_tokens = saved_tokens.slice(0,selected_token_index).concat([token_data]).concat(saved_tokens.slice(selected_token_index));
selected_token_index++;
// Update the hidden input
update_hiddenInput(saved_tokens, hiddenInput);
token_count += 1;
// Check the token limit
if($(input).data("settings").tokenLimit !== null && token_count >= $(input).data("settings").tokenLimit) {
input_box.hide();
hide_dropdown();
}
return $this_token;
}
// Add a token to the token list based on user input
function add_token (item) {
var callback = $(input).data("settings").onAdd;
// See if the token already exists and select it if we don't want duplicates
if(token_count > 0 && $(input).data("settings").preventDuplicates) {
var found_existing_token = null;
token_list.children().each(function () {
var existing_token = $(this);
var existing_data = $.data(existing_token.get(0), "tokeninput");
if(existing_data && existing_data[settings.tokenValue] === item[settings.tokenValue]) {
found_existing_token = existing_token;
return false;
}
});
if(found_existing_token) {
select_token(found_existing_token);
input_token.insertAfter(found_existing_token);
focusWithTimeout(input_box);
return;
}
}
// Squeeze input_box so we force no unnecessary line break
input_box.width(1);
// Insert the new tokens
if($(input).data("settings").tokenLimit == null || token_count < $(input).data("settings").tokenLimit) {
insert_token(item);
// Remove the placeholder so it's not seen after you've added a token
input_box.attr("placeholder", null);
checkTokenLimit();
}
// Clear input box
input_box.val("");
// Don't show the help dropdown, they've got the idea
hide_dropdown();
// Execute the onAdd callback if defined
if($.isFunction(callback)) {
callback.call(hiddenInput,item);
}
}
// Select a token in the token list
function select_token (token) {
if (!$(input).data("settings").disabled) {
token.addClass($(input).data("settings").classes.selectedToken);
selected_token = token.get(0);
// Hide input box
input_box.val("");
// Hide dropdown if it is visible (eg if we clicked to select token)
hide_dropdown();
}
}
// Deselect a token in the token list
function deselect_token (token, position) {
token.removeClass($(input).data("settings").classes.selectedToken);
selected_token = null;
if(position === POSITION.BEFORE) {
input_token.insertBefore(token);
selected_token_index--;
} else if(position === POSITION.AFTER) {
input_token.insertAfter(token);
selected_token_index++;
} else {
input_token.appendTo(token_list);
selected_token_index = token_count;
}
// Show the input box and give it focus again
focusWithTimeout(input_box);
}
// Toggle selection of a token in the token list
function toggle_select_token(token) {
var previous_selected_token = selected_token;
if(selected_token) {
deselect_token($(selected_token), POSITION.END);
}
if(previous_selected_token === token.get(0)) {
deselect_token(token, POSITION.END);
} else {
select_token(token);
}
}
// Delete a token from the token list
function delete_token (token) {
// Remove the id from the saved list
var token_data = $.data(token.get(0), "tokeninput");
var callback = $(input).data("settings").onDelete;
var index = token.prevAll().length;
if(index > selected_token_index) index--;
// Delete the token
token.remove();
selected_token = null;
// Show the input box and give it focus again
focusWithTimeout(input_box);
// Remove this token from the saved list
saved_tokens = saved_tokens.slice(0,index).concat(saved_tokens.slice(index+1));
if (saved_tokens.length == 0) {
input_box.attr("placeholder", settings.placeholder)
}
if(index < selected_token_index) selected_token_index--;
// Update the hidden input
update_hiddenInput(saved_tokens, hiddenInput);
token_count -= 1;
if($(input).data("settings").tokenLimit !== null) {
input_box
.show()
.val("");
focusWithTimeout(input_box);
}
// Execute the onDelete callback if defined
if($.isFunction(callback)) {
callback.call(hiddenInput,token_data);
}
}
// Update the hidden input box value
function update_hiddenInput(saved_tokens, hiddenInput) {
var token_values = $.map(saved_tokens, function (el) {
if(typeof $(input).data("settings").tokenValue == 'function')
return $(input).data("settings").tokenValue.call(this, el);
return el[$(input).data("settings").tokenValue];
});
hiddenInput.val(token_values.join($(input).data("settings").tokenDelimiter));
}
// Hide and clear the results dropdown
function hide_dropdown () {
dropdown.hide().empty();
selected_dropdown_item = null;
}
function show_dropdown() {
dropdown
.css({
position: "absolute",
top: token_list.offset().top + token_list.outerHeight(true),
left: token_list.offset().left,
width: token_list.width(),
'z-index': $(input).data("settings").zindex
})
.show();
}
function show_dropdown_searching () {
if($(input).data("settings").searchingText) {
dropdown.html("<p>" + escapeHTML($(input).data("settings").searchingText) + "</p>");
show_dropdown();
}
}
function show_dropdown_hint () {
if($(input).data("settings").hintText) {
dropdown.html("<p>" + escapeHTML($(input).data("settings").hintText) + "</p>");
show_dropdown();
}
}
var regexp_special_chars = new RegExp('[.\\\\+*?\\[\\^\\]$(){}=!<>|:\\-]', 'g');
function regexp_escape(term) {
return term.replace(regexp_special_chars, '\\$&');
}
// Highlight the query part of the search term
function highlight_term(value, term) {
return value.replace(
new RegExp(
"(?![^&;]+;)(?!<[^<>]*)(" + regexp_escape(term) + ")(?![^<>]*>)(?![^&;]+;)",
"gi"
), function(match, p1) {
return "<b>" + escapeHTML(p1) + "</b>";
}
);
}
function find_value_and_highlight_term(template, value, term) {
return template.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + regexp_escape(value) + ")(?![^<>]*>)(?![^&;]+;)", "g"), highlight_term(value, term));
}
// exclude existing tokens from dropdown, so the list is clearer
function excludeCurrent(results) {
if ($(input).data("settings").excludeCurrent) {
var currentTokens = $(input).data("tokenInputObject").getTokens(),
trimmedList = [];
if (currentTokens.length) {
$.each(results, function(index, value) {
var notFound = true;
$.each(currentTokens, function(cIndex, cValue) {
if (value[$(input).data("settings").propertyToSearch] == cValue[$(input).data("settings").propertyToSearch]) {
notFound = false;
return false;
}
});
if (notFound) {
trimmedList.push(value);
}
});
results = trimmedList;
}
}
return results;
}
// Populate the results dropdown with some results
function populateDropdown (query, results) {
// exclude current tokens if configured
results = excludeCurrent(results);
if(results && results.length) {
dropdown.empty();
var dropdown_ul = $("<ul/>")
.appendTo(dropdown)
.mouseover(function (event) {
select_dropdown_item($(event.target).closest("li"));
})
.mousedown(function (event) {
add_token($(event.target).closest("li").data("tokeninput"));
hiddenInput.change();
return false;
})
.hide();
if ($(input).data("settings").resultsLimit && results.length > $(input).data("settings").resultsLimit) {
results = results.slice(0, $(input).data("settings").resultsLimit);
}
$.each(results, function(index, value) {
var this_li = $(input).data("settings").resultsFormatter(value);
this_li = find_value_and_highlight_term(this_li ,value[$(input).data("settings").propertyToSearch], query);
this_li = $(this_li).appendTo(dropdown_ul);
if(index % 2) {
this_li.addClass($(input).data("settings").classes.dropdownItem);
} else {
this_li.addClass($(input).data("settings").classes.dropdownItem2);
}
if(index === 0 && $(input).data("settings").autoSelectFirstResult) {
select_dropdown_item(this_li);
}
$.data(this_li.get(0), "tokeninput", value);
});
show_dropdown();
if($(input).data("settings").animateDropdown) {
dropdown_ul.slideDown("fast");
} else {
dropdown_ul.show();
}
} else {
if($(input).data("settings").noResultsText) {
dropdown.html("<p>" + escapeHTML($(input).data("settings").noResultsText) + "</p>");
show_dropdown();
}
}
}
// Highlight an item in the results dropdown
function select_dropdown_item (item) {
if(item) {
if(selected_dropdown_item) {
deselect_dropdown_item($(selected_dropdown_item));
}
item.addClass($(input).data("settings").classes.selectedDropdownItem);
selected_dropdown_item = item.get(0);
}
}
// Remove highlighting from an item in the results dropdown
function deselect_dropdown_item (item) {
item.removeClass($(input).data("settings").classes.selectedDropdownItem);
selected_dropdown_item = null;
}
// Do a search and show the "searching" dropdown if the input is longer
// than $(input).data("settings").minChars
function do_search() {
var query = input_box.val();
if(query && query.length) {
if(selected_token) {
deselect_token($(selected_token), POSITION.AFTER);
}
if(query.length >= $(input).data("settings").minChars) {
show_dropdown_searching();
clearTimeout(timeout);
timeout = setTimeout(function(){
run_search(query);
}, $(input).data("settings").searchDelay);
} else {
hide_dropdown();
}
}
}
// Do the actual search
function run_search(query) {
var cache_key = query + computeURL();
var cached_results = cache.get(cache_key);
if (cached_results) {
if ($.isFunction($(input).data("settings").onCachedResult)) {
cached_results = $(input).data("settings").onCachedResult.call(hiddenInput, cached_results);
}
populateDropdown(query, cached_results);
} else {
// Are we doing an ajax search or local data search?
if($(input).data("settings").url) {
var url = computeURL();
// Extract existing get params
var ajax_params = {};
ajax_params.data = {};
if(url.indexOf("?") > -1) {
var parts = url.split("?");
ajax_params.url = parts[0];
var param_array = parts[1].split("&");
$.each(param_array, function (index, value) {
var kv = value.split("=");
ajax_params.data[kv[0]] = kv[1];
});
} else {
ajax_params.url = url;
}
// Prepare the request
ajax_params.data[$(input).data("settings").queryParam] = query;
ajax_params.type = $(input).data("settings").method;
ajax_params.dataType = $(input).data("settings").contentType;
if ($(input).data("settings").crossDomain) {
ajax_params.dataType = "jsonp";
}
// exclude current tokens?
// send exclude list to the server, so it can also exclude existing tokens
if ($(input).data("settings").excludeCurrent) {
var currentTokens = $(input).data("tokenInputObject").getTokens();
var tokenList = $.map(currentTokens, function (el) {
if(typeof $(input).data("settings").tokenValue == 'function')
return $(input).data("settings").tokenValue.call(this, el);
return el[$(input).data("settings").tokenValue];
});
ajax_params.data[$(input).data("settings").excludeCurrentParameter] = tokenList.join($(input).data("settings").tokenDelimiter);
}
// Attach the success callback
ajax_params.success = function(results) {
cache.add(cache_key, $(input).data("settings").jsonContainer ? results[$(input).data("settings").jsonContainer] : results);
if($.isFunction($(input).data("settings").onResult)) {
results = $(input).data("settings").onResult.call(hiddenInput, results);
}
// only populate the dropdown if the results are associated with the active search query
if(input_box.val() === query) {
populateDropdown(query, $(input).data("settings").jsonContainer ? results[$(input).data("settings").jsonContainer] : results);
}
};
// Provide a beforeSend callback
if (settings.onSend) {
settings.onSend(ajax_params);
}
// Make the request
$.ajax(ajax_params);
} else if($(input).data("settings").local_data) {
// Do the search through local data
var results = $.grep($(input).data("settings").local_data, function (row) {
return row[$(input).data("settings").propertyToSearch].toLowerCase().indexOf(query.toLowerCase()) > -1;
});
cache.add(cache_key, results);
if($.isFunction($(input).data("settings").onResult)) {
results = $(input).data("settings").onResult.call(hiddenInput, results);
}
populateDropdown(query, results);
}
}
}
// compute the dynamic URL
function computeURL() {
var settings = $(input).data("settings");
return typeof settings.url == 'function' ? settings.url.call(settings) : settings.url;
}
// Bring browser focus to the specified object.
// Use of setTimeout is to get around an IE bug.
// (See, e.g., http://stackoverflow.com/questions/2600186/focus-doesnt-work-in-ie)
//
// obj: a jQuery object to focus()
function focusWithTimeout(object) {
setTimeout(
function() {
object.focus();
},
50
);
}
};
// Really basic cache for the results
$.TokenList.Cache = function (options) {
var settings, data = {}, size = 0, flush;
settings = $.extend({ max_size: 500 }, options);
flush = function () {
data = {};
size = 0;
};
this.add = function (query, results) {
if (size > settings.max_size) {
flush();
}
if (!data[query]) {
size += 1;
}
data[query] = results;
};
this.get = function (query) {
return data[query];
};
};
}(jQuery));
| younisd/domjudge | www/js/jquery.tokeninput.js | JavaScript | gpl-2.0 | 39,820 |
/**
* @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'button', 'sq', {
selectedLabel: '%1 (Përzgjedhur)'
} );
| SeeyaSia/www | web/libraries/ckeditor/plugins/button/lang/sq.js | JavaScript | gpl-2.0 | 246 |
L.Polyline.Measure = L.Draw.Polyline.extend({
addHooks: function() {
L.Draw.Polyline.prototype.addHooks.call(this);
if (this._map) {
this._markerGroup = new L.LayerGroup();
this._map.addLayer(this._markerGroup);
this._markers = [];
this._map.on('click', this._onClick, this);
this._startShape();
}
},
removeHooks: function () {
L.Draw.Polyline.prototype.removeHooks.call(this);
this._clearHideErrorTimeout();
//!\ Still useful when control is disabled before any drawing (refactor needed?)
this._map.off('mousemove', this._onMouseMove);
this._clearGuides();
this._container.style.cursor = '';
this._removeShape();
this._map.off('click', this._onClick, this);
},
_startShape: function() {
this._drawing = true;
this._poly = new L.Polyline([], this.options.shapeOptions);
this._container.style.cursor = 'crosshair';
this._updateTooltip();
this._map.on('mousemove', this._onMouseMove, this);
},
_finishShape: function () {
this._drawing = false;
this._cleanUpShape();
this._clearGuides();
this._updateTooltip();
this._map.off('mousemove', this._onMouseMove, this);
this._container.style.cursor = '';
},
_removeShape: function() {
if (!this._poly)
return;
this._map.removeLayer(this._poly);
delete this._poly;
this._markers.splice(0);
this._markerGroup.clearLayers();
},
_onClick: function(e) {
if (!this._drawing && e.originalEvent.target.id !== 'btn-elevation-profile') {
this._removeShape();
this._startShape();
return;
}
else if (!this._drawing && e.originalEvent.target.id === 'btn-elevation-profile') {
this._elevationProfile();
}
},
_getTooltipText: function() {
var labelText = L.Draw.Polyline.prototype._getTooltipText.call(this),
elevLabel,
elevButton;
if (!this._drawing) {
elevLabel = gettext('elevation profile');
labelText.text = '<button class="btn btn-default" id="btn-elevation-profile">' + elevLabel + '</button>';
}
return labelText;
},
_elevationProfile: function () {
Ns.body.currentView.panels.currentView.drawElevation(this._poly.toGeoJSON());
this.disable();
}
});
L.Polyline.Elevation = L.Polyline.Measure.extend({
_getTooltipText: function() {
var labelText = L.Draw.Polyline.prototype._getTooltipText.call(this);
if (!this._drawing) {
labelText.text = '';
}
return labelText;
},
_finishShape: function () {
L.Polyline.Measure.prototype._finishShape.call(this);
this._elevationProfile();
},
});
L.Polygon.Measure = L.Draw.Polygon.extend({
options: { showArea: true },
addHooks: function() {
L.Draw.Polygon.prototype.addHooks.call(this);
if (this._map) {
this._markerGroup = new L.LayerGroup();
this._map.addLayer(this._markerGroup);
this._markers = [];
this._map.on('click', this._onClick, this);
this._startShape();
}
},
removeHooks: function () {
L.Draw.Polygon.prototype.removeHooks.call(this);
this._clearHideErrorTimeout();
//!\ Still useful when control is disabled before any drawing (refactor needed?)
this._map.off('mousemove', this._onMouseMove);
this._clearGuides();
this._container.style.cursor = '';
this._removeShape();
this._map.off('click', this._onClick, this);
},
_startShape: function() {
this._drawing = true;
this._poly = new L.Polygon([], this.options.shapeOptions);
this._container.style.cursor = 'crosshair';
this._updateTooltip();
this._map.on('mousemove', this._onMouseMove, this);
},
_finishShape: function () {
this._drawing = false;
this._cleanUpShape();
this._clearGuides();
this._updateTooltip();
this._map.off('mousemove', this._onMouseMove, this);
this._container.style.cursor = '';
},
_removeShape: function() {
if (!this._poly)
return;
this._map.removeLayer(this._poly);
delete this._poly;
this._markers.splice(0);
this._markerGroup.clearLayers();
},
_onClick: function(e) {
if (!this._drawing) {
this._removeShape();
this._startShape();
return;
}
},
_getTooltipText: function() {
var labelText = L.Draw.Polygon.prototype._getTooltipText.call(this);
if (!this._drawing) {
labelText.text = '';
labelText.subtext = this._getArea();
}
return labelText;
},
_getArea: function() {
var latLng = [],
geodisc;
for(var i=0, len=this._markers.length; i < len; i++) {
latLng.push(this._markers[i]._latlng);
}
geodisc = L.GeometryUtil.geodesicArea(latLng);
return L.GeometryUtil.readableArea(geodisc, true);
}
});
| sephiroth6/nodeshot | nodeshot/ui/default/static/ui/lib/js/leaflet.measurecontrol-customized.js | JavaScript | gpl-3.0 | 5,309 |
/*
* re-quote.js
*
* Copyright (C) 2009-13 by RStudio, Inc.
*
* This program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
module.exports = function(str){
// List derived from http://stackoverflow.com/questions/399078/what-special-characters-must-be-escaped-in-regular-expressions
return str.replace(/[.\^$*+?()[{\\|\-\]]/g, '\\$&');
} | rstudio/shiny-server | lib/core/re-quote.js | JavaScript | agpl-3.0 | 656 |
define(
//begin v1.x content
{
"months-format-narrow": [
"E",
"F",
"M",
"A",
"M",
"J",
"J",
"A",
"S",
"O",
"N",
"D"
],
"field-weekday": "día de la semana",
"dateFormatItem-yyQQQQ": "QQQQ 'de' yy",
"dateFormatItem-yQQQ": "QQQ y",
"dateFormatItem-yMEd": "EEE d/M/y",
"dateFormatItem-MMMEd": "E d MMM",
"eraNarrow": [
"a.C.",
"d.C."
],
"dateFormatItem-MMMdd": "dd-MMM",
"dateFormat-long": "d 'de' MMMM 'de' y",
"months-format-wide": [
"enero",
"febrero",
"marzo",
"abril",
"mayo",
"junio",
"julio",
"agosto",
"septiembre",
"octubre",
"noviembre",
"diciembre"
],
"dateFormatItem-EEEd": "EEE d",
"dayPeriods-format-wide-pm": "p.m.",
"dateFormat-full": "EEEE d 'de' MMMM 'de' y",
"dateFormatItem-Md": "d/M",
"field-era": "era",
"dateFormatItem-yM": "M/y",
"months-standAlone-wide": [
"enero",
"febrero",
"marzo",
"abril",
"mayo",
"junio",
"julio",
"agosto",
"septiembre",
"octubre",
"noviembre",
"diciembre"
],
"timeFormat-short": "HH:mm",
"quarters-format-wide": [
"1er trimestre",
"2º trimestre",
"3er trimestre",
"4º trimestre"
],
"timeFormat-long": "HH:mm:ss z",
"field-year": "año",
"dateFormatItem-yMMM": "MMM y",
"dateFormatItem-yQ": "Q y",
"field-hour": "hora",
"months-format-abbr": [
"ene",
"feb",
"mar",
"abr",
"may",
"jun",
"jul",
"ago",
"sep",
"oct",
"nov",
"dic"
],
"dateFormatItem-yyQ": "Q yy",
"timeFormat-full": "HH:mm:ss zzzz",
"field-day-relative+0": "hoy",
"field-day-relative+1": "mañana",
"field-day-relative+2": "pasado mañana",
"field-day-relative+3": "Dentro de tres días",
"months-standAlone-abbr": [
"ene",
"feb",
"mar",
"abr",
"may",
"jun",
"jul",
"ago",
"sep",
"oct",
"nov",
"dic"
],
"quarters-format-abbr": [
"T1",
"T2",
"T3",
"T4"
],
"quarters-standAlone-wide": [
"1er trimestre",
"2º trimestre",
"3er trimestre",
"4º trimestre"
],
"dateFormatItem-M": "L",
"days-standAlone-wide": [
"domingo",
"lunes",
"martes",
"miércoles",
"jueves",
"viernes",
"sábado"
],
"dateFormatItem-MMMMd": "d 'de' MMMM",
"dateFormatItem-yyMMM": "MMM-yy",
"timeFormat-medium": "HH:mm:ss",
"dateFormatItem-Hm": "HH:mm",
"quarters-standAlone-abbr": [
"T1",
"T2",
"T3",
"T4"
],
"eraAbbr": [
"a.C.",
"d.C."
],
"field-minute": "minuto",
"field-dayperiod": "periodo del día",
"days-standAlone-abbr": [
"dom",
"lun",
"mar",
"mié",
"jue",
"vie",
"sáb"
],
"dateFormatItem-d": "d",
"dateFormatItem-ms": "mm:ss",
"field-day-relative+-1": "ayer",
"dateFormatItem-h": "hh a",
"field-day-relative+-2": "antes de ayer",
"field-day-relative+-3": "Hace tres días",
"dateFormatItem-MMMd": "d MMM",
"dateFormatItem-MEd": "E, d/M",
"dateFormatItem-yMMMM": "MMMM 'de' y",
"field-day": "día",
"days-format-wide": [
"domingo",
"lunes",
"martes",
"miércoles",
"jueves",
"viernes",
"sábado"
],
"field-zone": "zona",
"dateFormatItem-yyyyMM": "MM/yyyy",
"dateFormatItem-y": "y",
"months-standAlone-narrow": [
"E",
"F",
"M",
"A",
"M",
"J",
"J",
"A",
"S",
"O",
"N",
"D"
],
"dateFormatItem-yyMM": "MM/yy",
"dateFormatItem-hm": "hh:mm a",
"days-format-abbr": [
"dom",
"lun",
"mar",
"mié",
"jue",
"vie",
"sáb"
],
"eraNames": [
"antes de Cristo",
"anno Dómini"
],
"days-format-narrow": [
"D",
"L",
"M",
"M",
"J",
"V",
"S"
],
"field-month": "mes",
"days-standAlone-narrow": [
"D",
"L",
"M",
"M",
"J",
"V",
"S"
],
"dateFormatItem-MMM": "LLL",
"dayPeriods-format-wide-am": "a.m.",
"dateFormat-short": "dd/MM/yy",
"dateFormatItem-MMd": "d/MM",
"field-second": "segundo",
"dateFormatItem-yMMMEd": "EEE, d MMM y",
"field-week": "semana",
"dateFormat-medium": "dd/MM/yyyy",
"dateFormatItem-Hms": "HH:mm:ss",
"dateFormatItem-hms": "hh:mm:ss a"
}
//end v1.x content
); | sulistionoadi/belajar-springmvc-dojo | training-web/src/main/webapp/js/dojotoolkit/dojo/cldr/nls/es/gregorian.js | JavaScript | apache-2.0 | 3,916 |
steal("jquerypp/event/hover", 'funcunit/syn', 'funcunit/qunit', function ($, Syn) {
module("jquerypp/dom/hover")
test("hovering", function () {
$("#qunit-test-area").append("<div id='hover'>Content<div>")
var hoverenters = 0,
hoverinits = 0,
hoverleaves = 0,
delay = 15;
$("#hover").bind("hoverinit", function (ev, hover) {
hover.delay(delay);
hoverinits++;
})
.bind('hoverenter', function () {
hoverenters++;
})
.bind('hoverleave', function () {
hoverleaves++;
})
var hover = $("#hover")
var off = hover.offset();
//add a mouseenter, and 2 mouse moves
Syn("mouseover", {pageX : off.top, pageY : off.left}, hover[0])
ok(hoverinits, 'hoverinit');
ok(hoverenters === 0, "hoverinit hasn't been called");
stop();
setTimeout(function () {
ok(hoverenters === 1, "hoverenter has been called");
ok(hoverleaves === 0, "hoverleave hasn't been called");
Syn("mouseout", {pageX : off.top, pageY : off.left}, hover[0]);
ok(hoverleaves === 1, "hoverleave has been called");
delay = 30;
Syn("mouseover", {pageX : off.top, pageY : off.left}, hover[0]);
ok(hoverinits === 2, 'hoverinit');
setTimeout(function () {
Syn("mouseout", {pageX : off.top, pageY : off.left}, hover[0]);
setTimeout(function () {
ok(hoverenters === 1, "hoverenter was not called");
ok(hoverleaves === 1, "hoverleave was not called");
start();
}, 30)
}, 10)
}, 30)
});
test("hoverInit delay 0 triggers hoverenter (issue #57)", function () {
$("#qunit-test-area").append("<div id='hoverzero'>Content<div>");
var hoverenters = 0,
hoverinits = 0,
hoverleaves = 0,
delay = 0;
$("#hoverzero").on({
hoverinit : function (ev, hover) {
hover.delay(delay);
hoverinits++;
},
hoverenter : function () {
hoverenters++;
},
'hoverleave' : function () {
hoverleaves++;
}
});
var hover = $("#hoverzero")
var off = hover.offset();
//add a mouseenter, and 2 mouse moves
Syn("mouseover", { pageX : off.top, pageY : off.left }, hover[0])
ok(hoverinits, 'hoverinit');
ok(hoverenters === 1, "hoverenter has been called");
});
});
| willametteuniversity/webcirc2 | static/jquerypp/event/hover/hover_test.js | JavaScript | apache-2.0 | 2,166 |
"use strict";
function $__interopRequire(id) {
id = require(id);
return id && id.__esModule && id || {default: id};
}
Object.defineProperties(module.exports, {
__esModule: {value: true},
entries: {
enumerable: true,
get: function() {
return entries;
}
},
keys: {
enumerable: true,
get: function() {
return keys;
}
},
values: {
enumerable: true,
get: function() {
return values;
}
}
});
var $__createClass = $__interopRequire("traceur/dist/commonjs/runtime/modules/createClass.js").default;
var $__3 = require("./utils.js"),
toObject = $__3.toObject,
toUint32 = $__3.toUint32,
createIteratorResultObject = $__3.createIteratorResultObject;
var ARRAY_ITERATOR_KIND_KEYS = 1;
var ARRAY_ITERATOR_KIND_VALUES = 2;
var ARRAY_ITERATOR_KIND_ENTRIES = 3;
var ArrayIterator = function() {
var $__1;
function ArrayIterator() {}
return ($__createClass)(ArrayIterator, ($__1 = {}, Object.defineProperty($__1, "next", {
value: function() {
var iterator = toObject(this);
var array = iterator.iteratorObject_;
if (!array) {
throw new TypeError('Object is not an ArrayIterator');
}
var index = iterator.arrayIteratorNextIndex_;
var itemKind = iterator.arrayIterationKind_;
var length = toUint32(array.length);
if (index >= length) {
iterator.arrayIteratorNextIndex_ = Infinity;
return createIteratorResultObject(undefined, true);
}
iterator.arrayIteratorNextIndex_ = index + 1;
if (itemKind == ARRAY_ITERATOR_KIND_VALUES)
return createIteratorResultObject(array[index], false);
if (itemKind == ARRAY_ITERATOR_KIND_ENTRIES)
return createIteratorResultObject([index, array[index]], false);
return createIteratorResultObject(index, false);
},
configurable: true,
enumerable: true,
writable: true
}), Object.defineProperty($__1, Symbol.iterator, {
value: function() {
return this;
},
configurable: true,
enumerable: true,
writable: true
}), $__1), {});
}();
function createArrayIterator(array, kind) {
var object = toObject(array);
var iterator = new ArrayIterator;
iterator.iteratorObject_ = object;
iterator.arrayIteratorNextIndex_ = 0;
iterator.arrayIterationKind_ = kind;
return iterator;
}
function entries() {
return createArrayIterator(this, ARRAY_ITERATOR_KIND_ENTRIES);
}
function keys() {
return createArrayIterator(this, ARRAY_ITERATOR_KIND_KEYS);
}
function values() {
return createArrayIterator(this, ARRAY_ITERATOR_KIND_VALUES);
}
| Haeresis/TestCaseAtlas | webapp/src/assets/traceur/dist/commonjs/runtime/polyfills/ArrayIterator.js | JavaScript | gpl-2.0 | 2,600 |
// This file is part of Moodle - http://moodle.org/
//
// Moodle 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.
//
// Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>.
/* jshint node: true, browser: false */
/* eslint-env node */
/**
* @copyright 2014 Andrew Nicols
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
/**
* Grunt configuration
*/
module.exports = function(grunt) {
var path = require('path'),
tasks = {},
cwd = process.env.PWD || process.cwd(),
async = require('async'),
DOMParser = require('xmldom').DOMParser,
xpath = require('xpath'),
semver = require('semver');
// Verify the node version is new enough.
var expected = semver.validRange(grunt.file.readJSON('package.json').engines.node);
var actual = semver.valid(process.version);
if (!semver.satisfies(actual, expected)) {
grunt.fail.fatal('Node version too old. Require ' + expected + ', version installed: ' + actual);
}
// Windows users can't run grunt in a subdirectory, so allow them to set
// the root by passing --root=path/to/dir.
if (grunt.option('root')) {
var root = grunt.option('root');
if (grunt.file.exists(__dirname, root)) {
cwd = path.join(__dirname, root);
grunt.log.ok('Setting root to ' + cwd);
} else {
grunt.fail.fatal('Setting root to ' + root + ' failed - path does not exist');
}
}
var inAMD = path.basename(cwd) == 'amd';
// Globbing pattern for matching all AMD JS source files.
var amdSrc = [inAMD ? cwd + '/src/*.js' : '**/amd/src/*.js'];
/**
* Function to generate the destination for the uglify task
* (e.g. build/file.min.js). This function will be passed to
* the rename property of files array when building dynamically:
* http://gruntjs.com/configuring-tasks#building-the-files-object-dynamically
*
* @param {String} destPath the current destination
* @param {String} srcPath the matched src path
* @return {String} The rewritten destination path.
*/
var uglifyRename = function(destPath, srcPath) {
destPath = srcPath.replace('src', 'build');
destPath = destPath.replace('.js', '.min.js');
destPath = path.resolve(cwd, destPath);
return destPath;
};
/**
* Find thirdpartylibs.xml and generate an array of paths contained within
* them (used to generate ignore files and so on).
*
* @return {array} The list of thirdparty paths.
*/
var getThirdPartyPathsFromXML = function() {
var thirdpartyfiles = grunt.file.expand('*/**/thirdpartylibs.xml');
var libs = ['node_modules/', 'vendor/'];
thirdpartyfiles.forEach(function(file) {
var dirname = path.dirname(file);
var doc = new DOMParser().parseFromString(grunt.file.read(file));
var nodes = xpath.select("/libraries/library/location/text()", doc);
nodes.forEach(function(node) {
var lib = path.join(dirname, node.toString());
if (grunt.file.isDir(lib)) {
// Ensure trailing slash on dirs.
lib = lib.replace(/\/?$/, '/');
}
// Look for duplicate paths before adding to array.
if (libs.indexOf(lib) === -1) {
libs.push(lib);
}
});
});
return libs;
};
// Project configuration.
grunt.initConfig({
eslint: {
// Even though warnings dont stop the build we don't display warnings by default because
// at this moment we've got too many core warnings.
options: {quiet: !grunt.option('show-lint-warnings')},
amd: {
src: amdSrc,
// Check AMD with some slightly stricter rules.
rules: {
'no-unused-vars': 'error',
'no-implicit-globals': 'error'
}
},
// Check YUI module source files.
yui: {
src: ['**/yui/src/**/*.js', '!*/**/yui/src/*/meta/*.js'],
options: {
// Disable some rules which we can't safely define for YUI rollups.
rules: {
'no-undef': 'off',
'no-unused-vars': 'off',
'no-unused-expressions': 'off'
}
}
}
},
uglify: {
amd: {
files: [{
expand: true,
src: amdSrc,
rename: uglifyRename
}],
options: {report: 'none'}
}
},
less: {
bootstrapbase: {
files: {
"theme/bootstrapbase/style/moodle.css": "theme/bootstrapbase/less/moodle.less",
"theme/bootstrapbase/style/editor.css": "theme/bootstrapbase/less/editor.less",
},
options: {
compress: false // We must not compress to keep the comments.
}
}
},
watch: {
options: {
nospawn: true // We need not to spawn so config can be changed dynamically.
},
amd: {
files: ['**/amd/src/**/*.js'],
tasks: ['amd']
},
bootstrapbase: {
files: ["theme/bootstrapbase/less/**/*.less"],
tasks: ["css"]
},
yui: {
files: ['**/yui/src/**/*.js'],
tasks: ['yui']
},
gherkinlint: {
files: ['**/tests/behat/*.feature'],
tasks: ['gherkinlint']
}
},
shifter: {
options: {
recursive: true,
paths: [cwd]
}
},
gherkinlint: {
options: {
files: ['**/tests/behat/*.feature'],
}
},
stylelint: {
less: {
options: {
syntax: 'less',
configOverrides: {
rules: {
// These rules have to be disabled in .stylelintrc for scss compat.
"at-rule-no-unknown": true,
"no-browser-hacks": [true, {"severity": "warning"}]
}
}
},
src: ['theme/**/*.less']
},
scss: {
options: {syntax: 'scss'},
src: ['*/**/*.scss']
},
css: {
src: ['*/**/*.css'],
options: {
configOverrides: {
rules: {
// These rules have to be disabled in .stylelintrc for scss compat.
"at-rule-no-unknown": true,
"no-browser-hacks": [true, {"severity": "warning"}]
}
}
}
}
}
});
/**
* Generate ignore files (utilising thirdpartylibs.xml data)
*/
tasks.ignorefiles = function() {
// An array of paths to third party directories.
var thirdPartyPaths = getThirdPartyPathsFromXML();
// Generate .eslintignore.
var eslintIgnores = ['# Generated by "grunt ignorefiles"', '*/**/yui/src/*/meta/', '*/**/build/'].concat(thirdPartyPaths);
grunt.file.write('.eslintignore', eslintIgnores.join('\n'));
// Generate .stylelintignore.
var stylelintIgnores = [
'# Generated by "grunt ignorefiles"',
'theme/bootstrapbase/style/',
'theme/clean/style/custom.css',
'theme/more/style/custom.css'
].concat(thirdPartyPaths);
grunt.file.write('.stylelintignore', stylelintIgnores.join('\n'));
};
/**
* Shifter task. Is configured with a path to a specific file or a directory,
* in the case of a specific file it will work out the right module to be built.
*
* Note that this task runs the invidiaul shifter jobs async (becase it spawns
* so be careful to to call done().
*/
tasks.shifter = function() {
var done = this.async(),
options = grunt.config('shifter.options');
// Run the shifter processes one at a time to avoid confusing output.
async.eachSeries(options.paths, function(src, filedone) {
var args = [];
args.push(path.normalize(__dirname + '/node_modules/shifter/bin/shifter'));
// Always ignore the node_modules directory.
args.push('--excludes', 'node_modules');
// Determine the most appropriate options to run with based upon the current location.
if (grunt.file.isMatch('**/yui/**/*.js', src)) {
// When passed a JS file, build our containing module (this happen with
// watch).
grunt.log.debug('Shifter passed a specific JS file');
src = path.dirname(path.dirname(src));
options.recursive = false;
} else if (grunt.file.isMatch('**/yui/src', src)) {
// When in a src directory --walk all modules.
grunt.log.debug('In a src directory');
args.push('--walk');
options.recursive = false;
} else if (grunt.file.isMatch('**/yui/src/*', src)) {
// When in module, only build our module.
grunt.log.debug('In a module directory');
options.recursive = false;
} else if (grunt.file.isMatch('**/yui/src/*/js', src)) {
// When in module src, only build our module.
grunt.log.debug('In a source directory');
src = path.dirname(src);
options.recursive = false;
}
if (grunt.option('watch')) {
grunt.fail.fatal('The --watch option has been removed, please use `grunt watch` instead');
}
// Add the stderr option if appropriate
if (grunt.option('verbose')) {
args.push('--lint-stderr');
}
if (grunt.option('no-color')) {
args.push('--color=false');
}
var execShifter = function() {
grunt.log.ok("Running shifter on " + src);
grunt.util.spawn({
cmd: "node",
args: args,
opts: {cwd: src, stdio: 'inherit', env: process.env}
}, function(error, result, code) {
if (code) {
grunt.fail.fatal('Shifter failed with code: ' + code);
} else {
grunt.log.ok('Shifter build complete.');
filedone();
}
});
};
// Actually run shifter.
if (!options.recursive) {
execShifter();
} else {
// Check that there are yui modules otherwise shifter ends with exit code 1.
if (grunt.file.expand({cwd: src}, '**/yui/src/**/*.js').length > 0) {
args.push('--recursive');
execShifter();
} else {
grunt.log.ok('No YUI modules to build.');
filedone();
}
}
}, done);
};
tasks.gherkinlint = function() {
var done = this.async(),
options = grunt.config('gherkinlint.options');
var args = grunt.file.expand(options.files);
args.unshift(path.normalize(__dirname + '/node_modules/.bin/gherkin-lint'));
grunt.util.spawn({
cmd: 'node',
args: args,
opts: {stdio: 'inherit', env: process.env}
}, function(error, result, code) {
// Propagate the exit code.
done(code === 0);
});
};
tasks.startup = function() {
// Are we in a YUI directory?
if (path.basename(path.resolve(cwd, '../../')) == 'yui') {
grunt.task.run('yui');
// Are we in an AMD directory?
} else if (inAMD) {
grunt.task.run('amd');
} else {
// Run them all!.
grunt.task.run('css');
grunt.task.run('js');
grunt.task.run('gherkinlint');
}
};
// On watch, we dynamically modify config to build only affected files. This
// method is slightly complicated to deal with multiple changed files at once (copied
// from the grunt-contrib-watch readme).
var changedFiles = Object.create(null);
var onChange = grunt.util._.debounce(function() {
var files = Object.keys(changedFiles);
grunt.config('eslint.amd.src', files);
grunt.config('eslint.yui.src', files);
grunt.config('uglify.amd.files', [{expand: true, src: files, rename: uglifyRename}]);
grunt.config('shifter.options.paths', files);
grunt.config('stylelint.less.src', files);
grunt.config('gherkinlint.options.files', files);
changedFiles = Object.create(null);
}, 200);
grunt.event.on('watch', function(action, filepath) {
changedFiles[filepath] = action;
onChange();
});
// Register NPM tasks.
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-less');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-eslint');
grunt.loadNpmTasks('grunt-stylelint');
// Register JS tasks.
grunt.registerTask('shifter', 'Run Shifter against the current directory', tasks.shifter);
grunt.registerTask('gherkinlint', 'Run gherkinlint against the current directory', tasks.gherkinlint);
grunt.registerTask('ignorefiles', 'Generate ignore files for linters', tasks.ignorefiles);
grunt.registerTask('yui', ['eslint:yui', 'shifter']);
grunt.registerTask('amd', ['eslint:amd', 'uglify']);
grunt.registerTask('js', ['amd', 'yui']);
// Register CSS taks.
grunt.registerTask('css', ['stylelint:scss', 'stylelint:less', 'less:bootstrapbase', 'stylelint:css']);
// Register the startup task.
grunt.registerTask('startup', 'Run the correct tasks for the current directory', tasks.startup);
// Register the default task.
grunt.registerTask('default', ['startup']);
};
| macuco/moodlemacuco | Gruntfile.js | JavaScript | gpl-3.0 | 15,185 |
/**
* @license
* Copyright The Closure Library Authors.
* SPDX-License-Identifier: Apache-2.0
*/
/**
* @fileoverview Contains utility methods to extract text content from HTML.
* @supported IE 10+, Chrome 26+, Firefox 22+, Safari 7.1+, Opera 15+
*/
goog.provide('goog.html.textExtractor');
goog.require('goog.dom.TagName');
goog.require('goog.html.sanitizer.HtmlSanitizer');
goog.require('goog.object');
goog.require('goog.userAgent');
/**
* Safely extracts text from an untrusted HTML string using the HtmlSanitizer.
* Compared to goog.html.utils.stripHtmlTags, it tries to be smarter about
* printing newlines between blocks and leave out textual content that would not
* be displayed to the user (such as SCRIPT and STYLE tags).
* @param {string} html The untrusted HTML string.
* @return {string}
*/
// TODO(pelizzi): consider an optional bool parameter to also extract the text
// content of alt attributes and such.
goog.html.textExtractor.extractTextContent = function(html) {
'use strict';
if (!goog.html.textExtractor.isSupported()) {
return '';
}
// Disable all attributes except style to protect against DOM clobbering.
var sanitizer = new goog.html.sanitizer.HtmlSanitizer.Builder()
.onlyAllowAttributes(['style'])
.allowCssStyles()
.build();
// The default policy of the sanitizer strips the content of tags such as
// SCRIPT and STYLE, whose non-textual content would otherwise end up in the
// extracted text.
var sanitizedNodes = sanitizer.sanitizeToDomNode(html);
// textContent and innerText do not handle spacing between block elements
// properly. We need to reimplement a similar algorithm ourselves and account
// for spacing between block elements.
return goog.html.textExtractor.extractTextContentFromNode_(sanitizedNodes)
.trim();
};
/**
* Recursively extract text from the supplied DOM node and its descendants.
* @param {!Node} node
* @return {string}
* @private
*/
goog.html.textExtractor.extractTextContentFromNode_ = function(node) {
'use strict';
switch (node.nodeType) {
case Node.ELEMENT_NODE:
var element = /** @type {!Element} */ (node);
if (element.tagName == goog.dom.TagName.BR) {
return '\n';
}
var result = Array.prototype.map
.call(
node.childNodes,
goog.html.textExtractor.extractTextContentFromNode_)
.join('');
if (goog.html.textExtractor.isBlockElement_(element)) {
result = '\n' + result + '\n';
}
return result;
case Node.TEXT_NODE:
return node.nodeValue.replace(/\s+/g, ' ').trim();
default:
return '';
}
};
/**
* A set of block elements.
* @private @const {!Object<!goog.dom.TagName, boolean>}
*/
goog.html.textExtractor.BLOCK_ELEMENTS_ = goog.object.createSet(
goog.dom.TagName.ADDRESS, goog.dom.TagName.BLOCKQUOTE,
goog.dom.TagName.CENTER, goog.dom.TagName.DIV, goog.dom.TagName.DL,
goog.dom.TagName.FIELDSET, goog.dom.TagName.FORM, goog.dom.TagName.H1,
goog.dom.TagName.H2, goog.dom.TagName.H3, goog.dom.TagName.H4,
goog.dom.TagName.H5, goog.dom.TagName.H6, goog.dom.TagName.HR,
goog.dom.TagName.OL, goog.dom.TagName.P, goog.dom.TagName.PRE,
goog.dom.TagName.TABLE, goog.dom.TagName.UL);
/**
* Returns true whether this is a block element, i.e. the browser would visually
* separate the text content from the text content of the previous node.
* @param {!Element} element
* @return {boolean}
* @private
*/
goog.html.textExtractor.isBlockElement_ = function(element) {
'use strict';
return element.style.display == 'block' ||
goog.html.textExtractor.BLOCK_ELEMENTS_.hasOwnProperty(element.tagName);
};
/**
* Whether the browser supports the text extractor. The extractor depends on the
* HTML Sanitizer, which only supports IE starting from version 10.
* Visible for testing.
* @return {boolean}
* @package
*/
goog.html.textExtractor.isSupported = function() {
'use strict';
return !goog.userAgent.IE || goog.userAgent.isVersionOrHigher(10);
};
| scheib/chromium | third_party/google-closure-library/closure/goog/html/textextractor.js | JavaScript | bsd-3-clause | 4,176 |
define({
root: ({
_widgetLabel: "Demo",
label1: "Ich bin ein Demo-Widget.",
label2: "Dies ist konfigurierbar."
}),
"ar": 0,
"cs": 0,
"da": 0,
"de": 0,
"el": 0,
"es": 0,
"et": 0,
"fi": 0,
"fr": 0,
"he": 0,
"it": 0,
"ja": 0,
"ko": 0,
"lt": 0,
"lv": 0,
"nb": 0,
"nl": 0,
"pl": 0,
"pt-br": 0,
"pt-pt": 0,
"ro": 0,
"ru": 0,
"sv": 0,
"th": 0,
"tr": 0,
"vi": 0,
"zh-cn": 1
});
| cmccullough2/cmv-wab-widgets | wab/2.3/widgets/samplewidgets/Demo/nls/de/strings.js | JavaScript | mit | 443 |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/*
* Date: 26 November 2000
*
*
*SUMMARY: Passing a RegExp object to a RegExp() constructor.
*This test arose from Bugzilla bug 61266. The ECMA3 section is:
*
* 15.10.4.1 new RegExp(pattern, flags)
*
* If pattern is an object R whose [[Class]] property is "RegExp" and
* flags is undefined, then let P be the pattern used to construct R
* and let F be the flags used to construct R. If pattern is an object R
* whose [[Class]] property is "RegExp" and flags is not undefined,
* then throw a TypeError exception. Otherwise, let P be the empty string
* if pattern is undefined and ToString(pattern) otherwise, and let F be
* the empty string if flags is undefined and ToString(flags) otherwise.
*
*
*The current test will check the first scenario outlined above:
*
* "pattern" is itself a RegExp object R
* "flags" is undefined
*
* We check that a new RegExp object obj2 defined from these parameters
* is morally the same as the original RegExp object obj1. Of course, they
* can't be equal as objects - so we check their enumerable properties...
*
* In this test, the initial RegExp object obj1 will not include a
* flag. This test is identical to test 15.10.4.1-1.js, except that
* here we use this syntax:
*
* obj2 = new RegExp(obj1, undefined);
*
* instead of:
*
* obj2 = new RegExp(obj1);
*/
//-----------------------------------------------------------------------------
var gTestfile = '15.10.4.1-2.js';
var BUGNUMBER = '61266';
var summary = 'Passing a RegExp object to a RegExp() constructor';
var statprefix = 'Applying RegExp() twice to pattern ';
var statsuffix = '; testing property ';
var singlequote = "'";
var i = -1; var s = '';
var obj1 = {}; var obj2 = {};
var status = ''; var actual = ''; var expect = ''; var msg = '';
var patterns = new Array();
// various regular expressions to try -
patterns[0] = '';
patterns[1] = 'abc';
patterns[2] = '(.*)(3-1)\s\w';
patterns[3] = '(.*)(...)\\s\\w';
patterns[4] = '[^A-Za-z0-9_]';
patterns[5] = '[^\f\n\r\t\v](123.5)([4 - 8]$)';
//-------------------------------------------------------------------------------------------------
test();
//-------------------------------------------------------------------------------------------------
function test()
{
enterFunc ('test');
printBugNumber(BUGNUMBER);
printStatus (summary);
for (i in patterns)
{
s = patterns[i];
status =getStatus(s);
obj1 = new RegExp(s);
obj2 = new RegExp(obj1, undefined); // see introduction to bug
reportCompare (obj1 + '', obj2 + '', status);
}
exitFunc ('test');
}
function getStatus(regexp)
{
return (statprefix + quote(regexp) + statsuffix);
}
function quote(text)
{
return (singlequote + text + singlequote);
}
| sam/htmlunit-rhino-fork | testsrc/tests/ecma_3/RegExp/15.10.4.1-2.js | JavaScript | mpl-2.0 | 3,091 |
/*!
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
(function () {
angular.module('piwikApp.filter').filter('htmldecode', htmldecode);
htmldecode.$inject = ['piwik'];
/**
* Be aware that this filter can cause XSS so only use it when you're sure it is safe.
* Eg it should be safe when it is afterwards escaped by angular sanitize again.
*/
function htmldecode(piwik) {
return function(text) {
if (text && text.length) {
return piwik.helper.htmlDecode(text);
}
return text;
};
}
})();
| befair/soulShape | wp/soulshape.earth/piwik/plugins/CoreHome/angularjs/common/filters/htmldecode.js | JavaScript | agpl-3.0 | 686 |
/*
* Copyright (C) 2007, 2008 Apple Inc. All rights reserved.
* Copyright (C) 2008 Matt Lilek <[email protected]>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
WebInspector.ElementsPanel = function()
{
WebInspector.Panel.call(this);
this.element.addStyleClass("elements");
this.contentElement = document.createElement("div");
this.contentElement.id = "elements-content";
this.contentElement.className = "outline-disclosure";
this.treeOutline = new WebInspector.ElementsTreeOutline();
this.treeOutline.panel = this;
this.treeOutline.includeRootDOMNode = false;
this.treeOutline.selectEnabled = true;
this.treeOutline.focusedNodeChanged = function(forceUpdate)
{
if (this.panel.visible && WebInspector.currentFocusElement !== document.getElementById("search"))
WebInspector.currentFocusElement = document.getElementById("main-panels");
this.panel.updateBreadcrumb(forceUpdate);
for (var pane in this.panel.sidebarPanes)
this.panel.sidebarPanes[pane].needsUpdate = true;
this.panel.updateStyles(true);
this.panel.updateMetrics();
this.panel.updateProperties();
if (InspectorController.searchingForNode()) {
InspectorController.toggleNodeSearch();
this.panel.nodeSearchButton.removeStyleClass("toggled-on");
}
};
this.contentElement.appendChild(this.treeOutline.element);
this.crumbsElement = document.createElement("div");
this.crumbsElement.className = "crumbs";
this.crumbsElement.addEventListener("mousemove", this._mouseMovedInCrumbs.bind(this), false);
this.crumbsElement.addEventListener("mouseout", this._mouseMovedOutOfCrumbs.bind(this), false);
this.sidebarPanes = {};
this.sidebarPanes.styles = new WebInspector.StylesSidebarPane();
this.sidebarPanes.metrics = new WebInspector.MetricsSidebarPane();
this.sidebarPanes.properties = new WebInspector.PropertiesSidebarPane();
this.sidebarPanes.styles.onexpand = this.updateStyles.bind(this);
this.sidebarPanes.metrics.onexpand = this.updateMetrics.bind(this);
this.sidebarPanes.properties.onexpand = this.updateProperties.bind(this);
this.sidebarPanes.styles.expanded = true;
this.sidebarPanes.styles.addEventListener("style edited", this._stylesPaneEdited, this);
this.sidebarPanes.styles.addEventListener("style property toggled", this._stylesPaneEdited, this);
this.sidebarPanes.metrics.addEventListener("metrics edited", this._metricsPaneEdited, this);
this.sidebarElement = document.createElement("div");
this.sidebarElement.id = "elements-sidebar";
this.sidebarElement.appendChild(this.sidebarPanes.styles.element);
this.sidebarElement.appendChild(this.sidebarPanes.metrics.element);
this.sidebarElement.appendChild(this.sidebarPanes.properties.element);
this.sidebarResizeElement = document.createElement("div");
this.sidebarResizeElement.className = "sidebar-resizer-vertical";
this.sidebarResizeElement.addEventListener("mousedown", this.rightSidebarResizerDragStart.bind(this), false);
this.nodeSearchButton = document.createElement("button");
this.nodeSearchButton.title = WebInspector.UIString("Select an element in the page to inspect it.");
this.nodeSearchButton.id = "node-search-status-bar-item";
this.nodeSearchButton.className = "status-bar-item";
this.nodeSearchButton.addEventListener("click", this._nodeSearchButtonClicked.bind(this), false);
this.searchingForNode = false;
this.element.appendChild(this.contentElement);
this.element.appendChild(this.sidebarElement);
this.element.appendChild(this.sidebarResizeElement);
this._mutationMonitoredWindows = [];
this._nodeInsertedEventListener = InspectorController.wrapCallback(this._nodeInserted.bind(this));
this._nodeRemovedEventListener = InspectorController.wrapCallback(this._nodeRemoved.bind(this));
this._contentLoadedEventListener = InspectorController.wrapCallback(this._contentLoaded.bind(this));
this.reset();
}
WebInspector.ElementsPanel.prototype = {
toolbarItemClass: "elements",
get toolbarItemLabel()
{
return WebInspector.UIString("Elements");
},
get statusBarItems()
{
return [this.nodeSearchButton, this.crumbsElement];
},
updateStatusBarItems: function()
{
this.updateBreadcrumbSizes();
},
show: function()
{
WebInspector.Panel.prototype.show.call(this);
this.sidebarResizeElement.style.right = (this.sidebarElement.offsetWidth - 3) + "px";
this.updateBreadcrumb();
this.treeOutline.updateSelection();
if (this.recentlyModifiedNodes.length)
this._updateModifiedNodes();
},
hide: function()
{
WebInspector.Panel.prototype.hide.call(this);
WebInspector.hoveredDOMNode = null;
if (InspectorController.searchingForNode()) {
InspectorController.toggleNodeSearch();
this.nodeSearchButton.removeStyleClass("toggled-on");
}
},
resize: function()
{
this.treeOutline.updateSelection();
this.updateBreadcrumbSizes();
},
reset: function()
{
this.rootDOMNode = null;
this.focusedDOMNode = null;
WebInspector.hoveredDOMNode = null;
if (InspectorController.searchingForNode()) {
InspectorController.toggleNodeSearch();
this.nodeSearchButton.removeStyleClass("toggled-on");
}
this.recentlyModifiedNodes = [];
this.unregisterAllMutationEventListeners();
delete this.currentQuery;
this.searchCanceled();
var inspectedWindow = InspectorController.inspectedWindow();
if (!inspectedWindow || !inspectedWindow.document)
return;
if (!inspectedWindow.document.firstChild) {
function contentLoaded()
{
inspectedWindow.document.removeEventListener("DOMContentLoaded", contentLoadedCallback, false);
this.reset();
}
var contentLoadedCallback = InspectorController.wrapCallback(contentLoaded.bind(this));
inspectedWindow.document.addEventListener("DOMContentLoaded", contentLoadedCallback, false);
return;
}
// If the window isn't visible, return early so the DOM tree isn't built
// and mutation event listeners are not added.
if (!InspectorController.isWindowVisible())
return;
this.registerMutationEventListeners(inspectedWindow);
var inspectedRootDocument = inspectedWindow.document;
this.rootDOMNode = inspectedRootDocument;
var canidateFocusNode = inspectedRootDocument.body || inspectedRootDocument.documentElement;
if (canidateFocusNode) {
this.treeOutline.suppressSelectHighlight = true;
this.focusedDOMNode = canidateFocusNode;
this.treeOutline.suppressSelectHighlight = false;
if (this.treeOutline.selectedTreeElement)
this.treeOutline.selectedTreeElement.expand();
}
},
includedInSearchResultsPropertyName: "__includedInInspectorSearchResults",
searchCanceled: function()
{
if (this._searchResults) {
const searchResultsProperty = this.includedInSearchResultsPropertyName;
for (var i = 0; i < this._searchResults.length; ++i) {
var node = this._searchResults[i];
// Remove the searchResultsProperty since there might be an unfinished search.
delete node[searchResultsProperty];
var treeElement = this.treeOutline.findTreeElement(node);
if (treeElement)
treeElement.highlighted = false;
}
}
WebInspector.updateSearchMatchesCount(0, this);
if (this._currentSearchChunkIntervalIdentifier) {
clearInterval(this._currentSearchChunkIntervalIdentifier);
delete this._currentSearchChunkIntervalIdentifier;
}
this._currentSearchResultIndex = 0;
this._searchResults = [];
},
performSearch: function(query)
{
// Call searchCanceled since it will reset everything we need before doing a new search.
this.searchCanceled();
const whitespaceTrimmedQuery = query.trimWhitespace();
if (!whitespaceTrimmedQuery.length)
return;
var tagNameQuery = whitespaceTrimmedQuery;
var attributeNameQuery = whitespaceTrimmedQuery;
var startTagFound = (tagNameQuery.indexOf("<") === 0);
var endTagFound = (tagNameQuery.lastIndexOf(">") === (tagNameQuery.length - 1));
if (startTagFound || endTagFound) {
var tagNameQueryLength = tagNameQuery.length;
tagNameQuery = tagNameQuery.substring((startTagFound ? 1 : 0), (endTagFound ? (tagNameQueryLength - 1) : tagNameQueryLength));
}
// Check the tagNameQuery is it is a possibly valid tag name.
if (!/^[a-zA-Z0-9\-_:]+$/.test(tagNameQuery))
tagNameQuery = null;
// Check the attributeNameQuery is it is a possibly valid tag name.
if (!/^[a-zA-Z0-9\-_:]+$/.test(attributeNameQuery))
attributeNameQuery = null;
const escapedQuery = query.escapeCharacters("'");
const escapedTagNameQuery = (tagNameQuery ? tagNameQuery.escapeCharacters("'") : null);
const escapedWhitespaceTrimmedQuery = whitespaceTrimmedQuery.escapeCharacters("'");
const searchResultsProperty = this.includedInSearchResultsPropertyName;
var updatedMatchCountOnce = false;
var matchesCountUpdateTimeout = null;
function updateMatchesCount()
{
WebInspector.updateSearchMatchesCount(this._searchResults.length, this);
matchesCountUpdateTimeout = null;
updatedMatchCountOnce = true;
}
function updateMatchesCountSoon()
{
if (!updatedMatchCountOnce)
return updateMatchesCount.call(this);
if (matchesCountUpdateTimeout)
return;
// Update the matches count every half-second so it doesn't feel twitchy.
matchesCountUpdateTimeout = setTimeout(updateMatchesCount.bind(this), 500);
}
function addNodesToResults(nodes, length, getItem)
{
if (!length)
return;
for (var i = 0; i < length; ++i) {
var node = getItem.call(nodes, i);
// Skip this node if it already has the property.
if (searchResultsProperty in node)
continue;
if (!this._searchResults.length) {
this._currentSearchResultIndex = 0;
this.focusedDOMNode = node;
}
node[searchResultsProperty] = true;
this._searchResults.push(node);
// Highlight the tree element to show it matched the search.
// FIXME: highlight the substrings in text nodes and attributes.
var treeElement = this.treeOutline.findTreeElement(node);
if (treeElement)
treeElement.highlighted = true;
}
updateMatchesCountSoon.call(this);
}
function matchExactItems(doc)
{
matchExactId.call(this, doc);
matchExactClassNames.call(this, doc);
matchExactTagNames.call(this, doc);
matchExactAttributeNames.call(this, doc);
}
function matchExactId(doc)
{
const result = doc.__proto__.getElementById.call(doc, whitespaceTrimmedQuery);
addNodesToResults.call(this, result, (result ? 1 : 0), function() { return this });
}
function matchExactClassNames(doc)
{
const result = doc.__proto__.getElementsByClassName.call(doc, whitespaceTrimmedQuery);
addNodesToResults.call(this, result, result.length, result.item);
}
function matchExactTagNames(doc)
{
if (!tagNameQuery)
return;
const result = doc.__proto__.getElementsByTagName.call(doc, tagNameQuery);
addNodesToResults.call(this, result, result.length, result.item);
}
function matchExactAttributeNames(doc)
{
if (!attributeNameQuery)
return;
const result = doc.__proto__.querySelectorAll.call(doc, "[" + attributeNameQuery + "]");
addNodesToResults.call(this, result, result.length, result.item);
}
function matchPartialTagNames(doc)
{
if (!tagNameQuery)
return;
const result = doc.__proto__.evaluate.call(doc, "//*[contains(name(), '" + escapedTagNameQuery + "')]", doc, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE);
addNodesToResults.call(this, result, result.snapshotLength, result.snapshotItem);
}
function matchStartOfTagNames(doc)
{
if (!tagNameQuery)
return;
const result = doc.__proto__.evaluate.call(doc, "//*[starts-with(name(), '" + escapedTagNameQuery + "')]", doc, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE);
addNodesToResults.call(this, result, result.snapshotLength, result.snapshotItem);
}
function matchPartialTagNamesAndAttributeValues(doc)
{
if (!tagNameQuery) {
matchPartialAttributeValues.call(this, doc);
return;
}
const result = doc.__proto__.evaluate.call(doc, "//*[contains(name(), '" + escapedTagNameQuery + "') or contains(@*, '" + escapedQuery + "')]", doc, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE);
addNodesToResults.call(this, result, result.snapshotLength, result.snapshotItem);
}
function matchPartialAttributeValues(doc)
{
const result = doc.__proto__.evaluate.call(doc, "//*[contains(@*, '" + escapedQuery + "')]", doc, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE);
addNodesToResults.call(this, result, result.snapshotLength, result.snapshotItem);
}
function matchStyleSelector(doc)
{
const result = doc.__proto__.querySelectorAll.call(doc, whitespaceTrimmedQuery);
addNodesToResults.call(this, result, result.length, result.item);
}
function matchPlainText(doc)
{
const result = doc.__proto__.evaluate.call(doc, "//text()[contains(., '" + escapedQuery + "')] | //comment()[contains(., '" + escapedQuery + "')]", doc, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE);
addNodesToResults.call(this, result, result.snapshotLength, result.snapshotItem);
}
function matchXPathQuery(doc)
{
const result = doc.__proto__.evaluate.call(doc, whitespaceTrimmedQuery, doc, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE);
addNodesToResults.call(this, result, result.snapshotLength, result.snapshotItem);
}
function finishedSearching()
{
// Remove the searchResultsProperty now that the search is finished.
for (var i = 0; i < this._searchResults.length; ++i)
delete this._searchResults[i][searchResultsProperty];
}
const mainFrameDocument = InspectorController.inspectedWindow().document;
const searchDocuments = [mainFrameDocument];
if (tagNameQuery && startTagFound && endTagFound)
const searchFunctions = [matchExactTagNames, matchPlainText];
else if (tagNameQuery && startTagFound)
const searchFunctions = [matchStartOfTagNames, matchPlainText];
else if (tagNameQuery && endTagFound) {
// FIXME: we should have a matchEndOfTagNames search function if endTagFound is true but not startTagFound.
// This requires ends-with() support in XPath, WebKit only supports starts-with() and contains().
const searchFunctions = [matchPartialTagNames, matchPlainText];
} else if (whitespaceTrimmedQuery === "//*" || whitespaceTrimmedQuery === "*") {
// These queries will match every node. Matching everything isn't useful and can be slow for large pages,
// so limit the search functions list to plain text and attribute matching.
const searchFunctions = [matchPartialAttributeValues, matchPlainText];
} else
const searchFunctions = [matchExactItems, matchStyleSelector, matchPartialTagNamesAndAttributeValues, matchPlainText, matchXPathQuery];
// Find all frames, iframes and object elements to search their documents.
const querySelectorAllFunction = InspectorController.inspectedWindow().Document.prototype.querySelectorAll;
const subdocumentResult = querySelectorAllFunction.call(mainFrameDocument, "iframe, frame, object");
for (var i = 0; i < subdocumentResult.length; ++i) {
var element = subdocumentResult.item(i);
if (element.contentDocument)
searchDocuments.push(element.contentDocument);
}
const panel = this;
var documentIndex = 0;
var searchFunctionIndex = 0;
var chunkIntervalIdentifier = null;
// Split up the work into chunks so we don't block the UI thread while processing.
function processChunk()
{
var searchDocument = searchDocuments[documentIndex];
var searchFunction = searchFunctions[searchFunctionIndex];
if (++searchFunctionIndex > searchFunctions.length) {
searchFunction = searchFunctions[0];
searchFunctionIndex = 0;
if (++documentIndex > searchDocuments.length) {
if (panel._currentSearchChunkIntervalIdentifier === chunkIntervalIdentifier)
delete panel._currentSearchChunkIntervalIdentifier;
clearInterval(chunkIntervalIdentifier);
finishedSearching.call(panel);
return;
}
searchDocument = searchDocuments[documentIndex];
}
if (!searchDocument || !searchFunction)
return;
try {
searchFunction.call(panel, searchDocument);
} catch(err) {
// ignore any exceptions. the query might be malformed, but we allow that.
}
}
processChunk();
chunkIntervalIdentifier = setInterval(processChunk, 25);
this._currentSearchChunkIntervalIdentifier = chunkIntervalIdentifier;
},
jumpToNextSearchResult: function()
{
if (!this._searchResults || !this._searchResults.length)
return;
if (++this._currentSearchResultIndex >= this._searchResults.length)
this._currentSearchResultIndex = 0;
this.focusedDOMNode = this._searchResults[this._currentSearchResultIndex];
},
jumpToPreviousSearchResult: function()
{
if (!this._searchResults || !this._searchResults.length)
return;
if (--this._currentSearchResultIndex < 0)
this._currentSearchResultIndex = (this._searchResults.length - 1);
this.focusedDOMNode = this._searchResults[this._currentSearchResultIndex];
},
inspectedWindowCleared: function(window)
{
if (InspectorController.isWindowVisible())
this.updateMutationEventListeners(window);
},
_addMutationEventListeners: function(monitoredWindow)
{
monitoredWindow.document.addEventListener("DOMNodeInserted", this._nodeInsertedEventListener, true);
monitoredWindow.document.addEventListener("DOMNodeRemoved", this._nodeRemovedEventListener, true);
if (monitoredWindow.frameElement)
monitoredWindow.addEventListener("DOMContentLoaded", this._contentLoadedEventListener, true);
},
_removeMutationEventListeners: function(monitoredWindow)
{
if (monitoredWindow.frameElement)
monitoredWindow.removeEventListener("DOMContentLoaded", this._contentLoadedEventListener, true);
if (!monitoredWindow.document)
return;
monitoredWindow.document.removeEventListener("DOMNodeInserted", this._nodeInsertedEventListener, true);
monitoredWindow.document.removeEventListener("DOMNodeRemoved", this._nodeRemovedEventListener, true);
},
updateMutationEventListeners: function(monitoredWindow)
{
this._addMutationEventListeners(monitoredWindow);
},
registerMutationEventListeners: function(monitoredWindow)
{
if (!monitoredWindow || this._mutationMonitoredWindows.indexOf(monitoredWindow) !== -1)
return;
this._mutationMonitoredWindows.push(monitoredWindow);
if (InspectorController.isWindowVisible())
this._addMutationEventListeners(monitoredWindow);
},
unregisterMutationEventListeners: function(monitoredWindow)
{
if (!monitoredWindow || this._mutationMonitoredWindows.indexOf(monitoredWindow) === -1)
return;
this._mutationMonitoredWindows.remove(monitoredWindow);
this._removeMutationEventListeners(monitoredWindow);
},
unregisterAllMutationEventListeners: function()
{
for (var i = 0; i < this._mutationMonitoredWindows.length; ++i)
this._removeMutationEventListeners(this._mutationMonitoredWindows[i]);
this._mutationMonitoredWindows = [];
},
get rootDOMNode()
{
return this.treeOutline.rootDOMNode;
},
set rootDOMNode(x)
{
this.treeOutline.rootDOMNode = x;
},
get focusedDOMNode()
{
return this.treeOutline.focusedDOMNode;
},
set focusedDOMNode(x)
{
this.treeOutline.focusedDOMNode = x;
},
_contentLoaded: function(event)
{
this.recentlyModifiedNodes.push({node: event.target, parent: event.target.defaultView.frameElement, replaced: true});
if (this.visible)
this._updateModifiedNodesSoon();
},
_nodeInserted: function(event)
{
this.recentlyModifiedNodes.push({node: event.target, parent: event.relatedNode, inserted: true});
if (this.visible)
this._updateModifiedNodesSoon();
},
_nodeRemoved: function(event)
{
this.recentlyModifiedNodes.push({node: event.target, parent: event.relatedNode, removed: true});
if (this.visible)
this._updateModifiedNodesSoon();
},
_updateModifiedNodesSoon: function()
{
if ("_updateModifiedNodesTimeout" in this)
return;
this._updateModifiedNodesTimeout = setTimeout(this._updateModifiedNodes.bind(this), 0);
},
_updateModifiedNodes: function()
{
if ("_updateModifiedNodesTimeout" in this) {
clearTimeout(this._updateModifiedNodesTimeout);
delete this._updateModifiedNodesTimeout;
}
var updatedParentTreeElements = [];
var updateBreadcrumbs = false;
for (var i = 0; i < this.recentlyModifiedNodes.length; ++i) {
var replaced = this.recentlyModifiedNodes[i].replaced;
var parent = this.recentlyModifiedNodes[i].parent;
if (!parent)
continue;
var parentNodeItem = this.treeOutline.findTreeElement(parent, null, null, objectsAreSame);
if (parentNodeItem && !parentNodeItem.alreadyUpdatedChildren) {
parentNodeItem.updateChildren(replaced);
parentNodeItem.alreadyUpdatedChildren = true;
updatedParentTreeElements.push(parentNodeItem);
}
if (!updateBreadcrumbs && (objectsAreSame(this.focusedDOMNode, parent) || isAncestorIncludingParentFrames(this.focusedDOMNode, parent)))
updateBreadcrumbs = true;
}
for (var i = 0; i < updatedParentTreeElements.length; ++i)
delete updatedParentTreeElements[i].alreadyUpdatedChildren;
this.recentlyModifiedNodes = [];
if (updateBreadcrumbs)
this.updateBreadcrumb(true);
},
_stylesPaneEdited: function()
{
this.sidebarPanes.metrics.needsUpdate = true;
this.updateMetrics();
},
_metricsPaneEdited: function()
{
this.sidebarPanes.styles.needsUpdate = true;
this.updateStyles(true);
},
_mouseMovedInCrumbs: function(event)
{
var nodeUnderMouse = document.elementFromPoint(event.pageX, event.pageY);
var crumbElement = nodeUnderMouse.enclosingNodeOrSelfWithClass("crumb");
WebInspector.hoveredDOMNode = (crumbElement ? crumbElement.representedObject : null);
if ("_mouseOutOfCrumbsTimeout" in this) {
clearTimeout(this._mouseOutOfCrumbsTimeout);
delete this._mouseOutOfCrumbsTimeout;
}
},
_mouseMovedOutOfCrumbs: function(event)
{
var nodeUnderMouse = document.elementFromPoint(event.pageX, event.pageY);
if (nodeUnderMouse.isDescendant(this.crumbsElement))
return;
WebInspector.hoveredDOMNode = null;
this._mouseOutOfCrumbsTimeout = setTimeout(this.updateBreadcrumbSizes.bind(this), 1000);
},
updateBreadcrumb: function(forceUpdate)
{
if (!this.visible)
return;
var crumbs = this.crumbsElement;
var handled = false;
var foundRoot = false;
var crumb = crumbs.firstChild;
while (crumb) {
if (objectsAreSame(crumb.representedObject, this.rootDOMNode))
foundRoot = true;
if (foundRoot)
crumb.addStyleClass("dimmed");
else
crumb.removeStyleClass("dimmed");
if (objectsAreSame(crumb.representedObject, this.focusedDOMNode)) {
crumb.addStyleClass("selected");
handled = true;
} else {
crumb.removeStyleClass("selected");
}
crumb = crumb.nextSibling;
}
if (handled && !forceUpdate) {
// We don't need to rebuild the crumbs, but we need to adjust sizes
// to reflect the new focused or root node.
this.updateBreadcrumbSizes();
return;
}
crumbs.removeChildren();
var panel = this;
function selectCrumbFunction(event)
{
var crumb = event.currentTarget;
if (crumb.hasStyleClass("collapsed")) {
// Clicking a collapsed crumb will expose the hidden crumbs.
if (crumb === panel.crumbsElement.firstChild) {
// If the focused crumb is the first child, pick the farthest crumb
// that is still hidden. This allows the user to expose every crumb.
var currentCrumb = crumb;
while (currentCrumb) {
var hidden = currentCrumb.hasStyleClass("hidden");
var collapsed = currentCrumb.hasStyleClass("collapsed");
if (!hidden && !collapsed)
break;
crumb = currentCrumb;
currentCrumb = currentCrumb.nextSibling;
}
}
panel.updateBreadcrumbSizes(crumb);
} else {
// Clicking a dimmed crumb or double clicking (event.detail >= 2)
// will change the root node in addition to the focused node.
if (event.detail >= 2 || crumb.hasStyleClass("dimmed"))
panel.rootDOMNode = crumb.representedObject.parentNode;
panel.focusedDOMNode = crumb.representedObject;
}
event.preventDefault();
}
foundRoot = false;
for (var current = this.focusedDOMNode; current; current = parentNodeOrFrameElement(current)) {
if (current.nodeType === Node.DOCUMENT_NODE)
continue;
if (objectsAreSame(current, this.rootDOMNode))
foundRoot = true;
var crumb = document.createElement("span");
crumb.className = "crumb";
crumb.representedObject = current;
crumb.addEventListener("mousedown", selectCrumbFunction, false);
var crumbTitle;
switch (current.nodeType) {
case Node.ELEMENT_NODE:
crumbTitle = current.nodeName.toLowerCase();
var nameElement = document.createElement("span");
nameElement.textContent = crumbTitle;
crumb.appendChild(nameElement);
var idAttribute = current.getAttribute("id");
if (idAttribute) {
var idElement = document.createElement("span");
crumb.appendChild(idElement);
var part = "#" + idAttribute;
crumbTitle += part;
idElement.appendChild(document.createTextNode(part));
// Mark the name as extra, since the ID is more important.
nameElement.className = "extra";
}
var classAttribute = current.getAttribute("class");
if (classAttribute) {
var classes = classAttribute.split(/\s+/);
var foundClasses = {};
if (classes.length) {
var classesElement = document.createElement("span");
classesElement.className = "extra";
crumb.appendChild(classesElement);
for (var i = 0; i < classes.length; ++i) {
var className = classes[i];
if (className && !(className in foundClasses)) {
var part = "." + className;
crumbTitle += part;
classesElement.appendChild(document.createTextNode(part));
foundClasses[className] = true;
}
}
}
}
break;
case Node.TEXT_NODE:
if (isNodeWhitespace.call(current))
crumbTitle = WebInspector.UIString("(whitespace)");
else
crumbTitle = WebInspector.UIString("(text)");
break
case Node.COMMENT_NODE:
crumbTitle = "<!-->";
break;
case Node.DOCUMENT_TYPE_NODE:
crumbTitle = "<!DOCTYPE>";
break;
default:
crumbTitle = current.nodeName.toLowerCase();
}
if (!crumb.childNodes.length) {
var nameElement = document.createElement("span");
nameElement.textContent = crumbTitle;
crumb.appendChild(nameElement);
}
crumb.title = crumbTitle;
if (foundRoot)
crumb.addStyleClass("dimmed");
if (objectsAreSame(current, this.focusedDOMNode))
crumb.addStyleClass("selected");
if (!crumbs.childNodes.length)
crumb.addStyleClass("end");
crumbs.appendChild(crumb);
}
if (crumbs.hasChildNodes())
crumbs.lastChild.addStyleClass("start");
this.updateBreadcrumbSizes();
},
updateBreadcrumbSizes: function(focusedCrumb)
{
if (!this.visible)
return;
if (document.body.offsetWidth <= 0) {
// The stylesheet hasn't loaded yet or the window is closed,
// so we can't calculate what is need. Return early.
return;
}
var crumbs = this.crumbsElement;
if (!crumbs.childNodes.length || crumbs.offsetWidth <= 0)
return; // No crumbs, do nothing.
// A Zero index is the right most child crumb in the breadcrumb.
var selectedIndex = 0;
var focusedIndex = 0;
var selectedCrumb;
var i = 0;
var crumb = crumbs.firstChild;
while (crumb) {
// Find the selected crumb and index.
if (!selectedCrumb && crumb.hasStyleClass("selected")) {
selectedCrumb = crumb;
selectedIndex = i;
}
// Find the focused crumb index.
if (crumb === focusedCrumb)
focusedIndex = i;
// Remove any styles that affect size before
// deciding to shorten any crumbs.
if (crumb !== crumbs.lastChild)
crumb.removeStyleClass("start");
if (crumb !== crumbs.firstChild)
crumb.removeStyleClass("end");
crumb.removeStyleClass("compact");
crumb.removeStyleClass("collapsed");
crumb.removeStyleClass("hidden");
crumb = crumb.nextSibling;
++i;
}
// Restore the start and end crumb classes in case they got removed in coalesceCollapsedCrumbs().
// The order of the crumbs in the document is opposite of the visual order.
crumbs.firstChild.addStyleClass("end");
crumbs.lastChild.addStyleClass("start");
function crumbsAreSmallerThanContainer()
{
var rightPadding = 20;
var errorWarningElement = document.getElementById("error-warning-count");
if (!WebInspector.console.visible && errorWarningElement)
rightPadding += errorWarningElement.offsetWidth;
return ((crumbs.totalOffsetLeft + crumbs.offsetWidth + rightPadding) < window.innerWidth);
}
if (crumbsAreSmallerThanContainer())
return; // No need to compact the crumbs, they all fit at full size.
var BothSides = 0;
var AncestorSide = -1;
var ChildSide = 1;
function makeCrumbsSmaller(shrinkingFunction, direction, significantCrumb)
{
if (!significantCrumb)
significantCrumb = (focusedCrumb || selectedCrumb);
if (significantCrumb === selectedCrumb)
var significantIndex = selectedIndex;
else if (significantCrumb === focusedCrumb)
var significantIndex = focusedIndex;
else {
var significantIndex = 0;
for (var i = 0; i < crumbs.childNodes.length; ++i) {
if (crumbs.childNodes[i] === significantCrumb) {
significantIndex = i;
break;
}
}
}
function shrinkCrumbAtIndex(index)
{
var shrinkCrumb = crumbs.childNodes[index];
if (shrinkCrumb && shrinkCrumb !== significantCrumb)
shrinkingFunction(shrinkCrumb);
if (crumbsAreSmallerThanContainer())
return true; // No need to compact the crumbs more.
return false;
}
// Shrink crumbs one at a time by applying the shrinkingFunction until the crumbs
// fit in the container or we run out of crumbs to shrink.
if (direction) {
// Crumbs are shrunk on only one side (based on direction) of the signifcant crumb.
var index = (direction > 0 ? 0 : crumbs.childNodes.length - 1);
while (index !== significantIndex) {
if (shrinkCrumbAtIndex(index))
return true;
index += (direction > 0 ? 1 : -1);
}
} else {
// Crumbs are shrunk in order of descending distance from the signifcant crumb,
// with a tie going to child crumbs.
var startIndex = 0;
var endIndex = crumbs.childNodes.length - 1;
while (startIndex != significantIndex || endIndex != significantIndex) {
var startDistance = significantIndex - startIndex;
var endDistance = endIndex - significantIndex;
if (startDistance >= endDistance)
var index = startIndex++;
else
var index = endIndex--;
if (shrinkCrumbAtIndex(index))
return true;
}
}
// We are not small enough yet, return false so the caller knows.
return false;
}
function coalesceCollapsedCrumbs()
{
var crumb = crumbs.firstChild;
var collapsedRun = false;
var newStartNeeded = false;
var newEndNeeded = false;
while (crumb) {
var hidden = crumb.hasStyleClass("hidden");
if (!hidden) {
var collapsed = crumb.hasStyleClass("collapsed");
if (collapsedRun && collapsed) {
crumb.addStyleClass("hidden");
crumb.removeStyleClass("compact");
crumb.removeStyleClass("collapsed");
if (crumb.hasStyleClass("start")) {
crumb.removeStyleClass("start");
newStartNeeded = true;
}
if (crumb.hasStyleClass("end")) {
crumb.removeStyleClass("end");
newEndNeeded = true;
}
continue;
}
collapsedRun = collapsed;
if (newEndNeeded) {
newEndNeeded = false;
crumb.addStyleClass("end");
}
} else
collapsedRun = true;
crumb = crumb.nextSibling;
}
if (newStartNeeded) {
crumb = crumbs.lastChild;
while (crumb) {
if (!crumb.hasStyleClass("hidden")) {
crumb.addStyleClass("start");
break;
}
crumb = crumb.previousSibling;
}
}
}
function compact(crumb)
{
if (crumb.hasStyleClass("hidden"))
return;
crumb.addStyleClass("compact");
}
function collapse(crumb, dontCoalesce)
{
if (crumb.hasStyleClass("hidden"))
return;
crumb.addStyleClass("collapsed");
crumb.removeStyleClass("compact");
if (!dontCoalesce)
coalesceCollapsedCrumbs();
}
function compactDimmed(crumb)
{
if (crumb.hasStyleClass("dimmed"))
compact(crumb);
}
function collapseDimmed(crumb)
{
if (crumb.hasStyleClass("dimmed"))
collapse(crumb);
}
if (!focusedCrumb) {
// When not focused on a crumb we can be biased and collapse less important
// crumbs that the user might not care much about.
// Compact child crumbs.
if (makeCrumbsSmaller(compact, ChildSide))
return;
// Collapse child crumbs.
if (makeCrumbsSmaller(collapse, ChildSide))
return;
// Compact dimmed ancestor crumbs.
if (makeCrumbsSmaller(compactDimmed, AncestorSide))
return;
// Collapse dimmed ancestor crumbs.
if (makeCrumbsSmaller(collapseDimmed, AncestorSide))
return;
}
// Compact ancestor crumbs, or from both sides if focused.
if (makeCrumbsSmaller(compact, (focusedCrumb ? BothSides : AncestorSide)))
return;
// Collapse ancestor crumbs, or from both sides if focused.
if (makeCrumbsSmaller(collapse, (focusedCrumb ? BothSides : AncestorSide)))
return;
if (!selectedCrumb)
return;
// Compact the selected crumb.
compact(selectedCrumb);
if (crumbsAreSmallerThanContainer())
return;
// Collapse the selected crumb as a last resort. Pass true to prevent coalescing.
collapse(selectedCrumb, true);
},
updateStyles: function(forceUpdate)
{
var stylesSidebarPane = this.sidebarPanes.styles;
if (!stylesSidebarPane.expanded || !stylesSidebarPane.needsUpdate)
return;
stylesSidebarPane.update(this.focusedDOMNode, null, forceUpdate);
stylesSidebarPane.needsUpdate = false;
},
updateMetrics: function()
{
var metricsSidebarPane = this.sidebarPanes.metrics;
if (!metricsSidebarPane.expanded || !metricsSidebarPane.needsUpdate)
return;
metricsSidebarPane.update(this.focusedDOMNode);
metricsSidebarPane.needsUpdate = false;
},
updateProperties: function()
{
var propertiesSidebarPane = this.sidebarPanes.properties;
if (!propertiesSidebarPane.expanded || !propertiesSidebarPane.needsUpdate)
return;
propertiesSidebarPane.update(this.focusedDOMNode);
propertiesSidebarPane.needsUpdate = false;
},
handleKeyEvent: function(event)
{
this.treeOutline.handleKeyEvent(event);
},
handleCopyEvent: function(event)
{
// Don't prevent the normal copy if the user has a selection.
if (!window.getSelection().isCollapsed)
return;
switch (this.focusedDOMNode.nodeType) {
case Node.ELEMENT_NODE:
var data = this.focusedDOMNode.outerHTML;
break;
case Node.COMMENT_NODE:
var data = "<!--" + this.focusedDOMNode.nodeValue + "-->";
break;
default:
case Node.TEXT_NODE:
var data = this.focusedDOMNode.nodeValue;
}
event.clipboardData.clearData();
event.preventDefault();
if (data)
event.clipboardData.setData("text/plain", data);
},
rightSidebarResizerDragStart: function(event)
{
WebInspector.elementDragStart(this.sidebarElement, this.rightSidebarResizerDrag.bind(this), this.rightSidebarResizerDragEnd.bind(this), event, "col-resize");
},
rightSidebarResizerDragEnd: function(event)
{
WebInspector.elementDragEnd(event);
},
rightSidebarResizerDrag: function(event)
{
var x = event.pageX;
var newWidth = Number.constrain(window.innerWidth - x, Preferences.minElementsSidebarWidth, window.innerWidth * 0.66);
this.sidebarElement.style.width = newWidth + "px";
this.contentElement.style.right = newWidth + "px";
this.sidebarResizeElement.style.right = (newWidth - 3) + "px";
this.treeOutline.updateSelection();
event.preventDefault();
},
_nodeSearchButtonClicked: function(event)
{
InspectorController.toggleNodeSearch();
if (InspectorController.searchingForNode())
this.nodeSearchButton.addStyleClass("toggled-on");
else
this.nodeSearchButton.removeStyleClass("toggled-on");
}
}
WebInspector.ElementsPanel.prototype.__proto__ = WebInspector.Panel.prototype;
| RLovelett/qt | src/3rdparty/webkit/WebCore/inspector/front-end/ElementsPanel.js | JavaScript | lgpl-2.1 | 45,561 |
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2016 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
sap.ui.define(function(){"use strict";var T={};T.render=function(r,c){var s=c.isInline()||this.hasControlData;if(!s){r.write("<div");r.writeControlData(c);r.writeStyles();r.writeClasses();r.write(">");}var R=this.renderTemplate||c.getTemplateRenderer();if(R){R.apply(this,arguments);}if(!s){r.write("</div>");}};return T;},true);
| and1985129/digitalofficemobile | www/lib/ui5/sap/ui/core/tmpl/TemplateControlRenderer.js | JavaScript | apache-2.0 | 516 |
// Copyright 2018 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Flags: --allow-natives-syntax
(function() {
function foo(p) { return p.catch(); }
%PrepareFunctionForOptimization(foo);
foo(Promise.resolve(1));
foo(Promise.resolve(1));
%OptimizeFunctionOnNextCall(foo);
foo(Promise.resolve(1));
})();
(function() {
function foo(p) { return p.catch(foo); }
%PrepareFunctionForOptimization(foo);
foo(Promise.resolve(1));
foo(Promise.resolve(1));
%OptimizeFunctionOnNextCall(foo);
foo(Promise.resolve(1));
})();
(function() {
function foo(p) { return p.catch(foo, undefined); }
%PrepareFunctionForOptimization(foo);
foo(Promise.resolve(1));
foo(Promise.resolve(1));
%OptimizeFunctionOnNextCall(foo);
foo(Promise.resolve(1));
})();
| zero-rp/miniblink49 | v8_7_5/test/mjsunit/compiler/promise-prototype-catch.js | JavaScript | apache-2.0 | 872 |
/*
* 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 LoginController = function($scope, $log, $uibModal, authService, userService) {
$scope.credentials = {
username: '',
password: ''
};
$scope.login = function($event, credentials) {
var $btn = $($event.target);
$btn.prop('disabled', true); // disable the login button to prevent multiple clicks
authService.login(credentials.username, credentials.password)
.then(
function() {
$btn.prop('disabled', false); // re-enable it
}
);
};
$scope.resetPassword = function() {
var modalInstance = $uibModal.open({
templateUrl: 'common/modules/dialog/reset/dialog.reset.tpl.html',
controller: 'DialogResetController'
});
modalInstance.result.then(function(email) {
userService.resetPassword(email);
}, function () {
});
};
var init = function() {};
init();
};
LoginController.$inject = ['$scope', '$log', '$uibModal', 'authService', 'userService'];
module.exports = LoginController;
| jeffmart/incubator-trafficcontrol | traffic_portal/app/src/modules/public/login/LoginController.js | JavaScript | apache-2.0 | 1,916 |
import { j as _inherits, k as _createSuper, c as _classCallCheck, T as Type, b as _createClass, R as Range, N as Node, g as YAMLSemanticError, l as _get, m as _getPrototypeOf, Y as YAMLSyntaxError, C as Char, e as _defineProperty, P as PlainValue } from './PlainValue-b8036b75.js';
var BlankLine = /*#__PURE__*/function (_Node) {
_inherits(BlankLine, _Node);
var _super = _createSuper(BlankLine);
function BlankLine() {
_classCallCheck(this, BlankLine);
return _super.call(this, Type.BLANK_LINE);
}
/* istanbul ignore next */
_createClass(BlankLine, [{
key: "includesTrailingLines",
get: function get() {
// This is never called from anywhere, but if it were,
// this is the value it should return.
return true;
}
/**
* Parses a blank line from the source
*
* @param {ParseContext} context
* @param {number} start - Index of first \n character
* @returns {number} - Index of the character after this
*/
}, {
key: "parse",
value: function parse(context, start) {
this.context = context;
this.range = new Range(start, start + 1);
return start + 1;
}
}]);
return BlankLine;
}(Node);
var CollectionItem = /*#__PURE__*/function (_Node) {
_inherits(CollectionItem, _Node);
var _super = _createSuper(CollectionItem);
function CollectionItem(type, props) {
var _this;
_classCallCheck(this, CollectionItem);
_this = _super.call(this, type, props);
_this.node = null;
return _this;
}
_createClass(CollectionItem, [{
key: "includesTrailingLines",
get: function get() {
return !!this.node && this.node.includesTrailingLines;
}
/**
* @param {ParseContext} context
* @param {number} start - Index of first character
* @returns {number} - Index of the character after this
*/
}, {
key: "parse",
value: function parse(context, start) {
this.context = context;
var parseNode = context.parseNode,
src = context.src;
var atLineStart = context.atLineStart,
lineStart = context.lineStart;
if (!atLineStart && this.type === Type.SEQ_ITEM) this.error = new YAMLSemanticError(this, 'Sequence items must not have preceding content on the same line');
var indent = atLineStart ? start - lineStart : context.indent;
var offset = Node.endOfWhiteSpace(src, start + 1);
var ch = src[offset];
var inlineComment = ch === '#';
var comments = [];
var blankLine = null;
while (ch === '\n' || ch === '#') {
if (ch === '#') {
var _end = Node.endOfLine(src, offset + 1);
comments.push(new Range(offset, _end));
offset = _end;
} else {
atLineStart = true;
lineStart = offset + 1;
var wsEnd = Node.endOfWhiteSpace(src, lineStart);
if (src[wsEnd] === '\n' && comments.length === 0) {
blankLine = new BlankLine();
lineStart = blankLine.parse({
src: src
}, lineStart);
}
offset = Node.endOfIndent(src, lineStart);
}
ch = src[offset];
}
if (Node.nextNodeIsIndented(ch, offset - (lineStart + indent), this.type !== Type.SEQ_ITEM)) {
this.node = parseNode({
atLineStart: atLineStart,
inCollection: false,
indent: indent,
lineStart: lineStart,
parent: this
}, offset);
} else if (ch && lineStart > start + 1) {
offset = lineStart - 1;
}
if (this.node) {
if (blankLine) {
// Only blank lines preceding non-empty nodes are captured. Note that
// this means that collection item range start indices do not always
// increase monotonically. -- eemeli/yaml#126
var items = context.parent.items || context.parent.contents;
if (items) items.push(blankLine);
}
if (comments.length) Array.prototype.push.apply(this.props, comments);
offset = this.node.range.end;
} else {
if (inlineComment) {
var c = comments[0];
this.props.push(c);
offset = c.end;
} else {
offset = Node.endOfLine(src, start + 1);
}
}
var end = this.node ? this.node.valueRange.end : offset;
this.valueRange = new Range(start, end);
return offset;
}
}, {
key: "setOrigRanges",
value: function setOrigRanges(cr, offset) {
offset = _get(_getPrototypeOf(CollectionItem.prototype), "setOrigRanges", this).call(this, cr, offset);
return this.node ? this.node.setOrigRanges(cr, offset) : offset;
}
}, {
key: "toString",
value: function toString() {
var src = this.context.src,
node = this.node,
range = this.range,
value = this.value;
if (value != null) return value;
var str = node ? src.slice(range.start, node.range.start) + String(node) : src.slice(range.start, range.end);
return Node.addStringTerminator(src, range.end, str);
}
}]);
return CollectionItem;
}(Node);
var Comment = /*#__PURE__*/function (_Node) {
_inherits(Comment, _Node);
var _super = _createSuper(Comment);
function Comment() {
_classCallCheck(this, Comment);
return _super.call(this, Type.COMMENT);
}
/**
* Parses a comment line from the source
*
* @param {ParseContext} context
* @param {number} start - Index of first character
* @returns {number} - Index of the character after this scalar
*/
_createClass(Comment, [{
key: "parse",
value: function parse(context, start) {
this.context = context;
var offset = this.parseComment(start);
this.range = new Range(start, offset);
return offset;
}
}]);
return Comment;
}(Node);
function grabCollectionEndComments(node) {
var cnode = node;
while (cnode instanceof CollectionItem) {
cnode = cnode.node;
}
if (!(cnode instanceof Collection)) return null;
var len = cnode.items.length;
var ci = -1;
for (var i = len - 1; i >= 0; --i) {
var n = cnode.items[i];
if (n.type === Type.COMMENT) {
// Keep sufficiently indented comments with preceding node
var _n$context = n.context,
indent = _n$context.indent,
lineStart = _n$context.lineStart;
if (indent > 0 && n.range.start >= lineStart + indent) break;
ci = i;
} else if (n.type === Type.BLANK_LINE) ci = i;else break;
}
if (ci === -1) return null;
var ca = cnode.items.splice(ci, len - ci);
var prevEnd = ca[0].range.start;
while (true) {
cnode.range.end = prevEnd;
if (cnode.valueRange && cnode.valueRange.end > prevEnd) cnode.valueRange.end = prevEnd;
if (cnode === node) break;
cnode = cnode.context.parent;
}
return ca;
}
var Collection = /*#__PURE__*/function (_Node) {
_inherits(Collection, _Node);
var _super = _createSuper(Collection);
function Collection(firstItem) {
var _this;
_classCallCheck(this, Collection);
_this = _super.call(this, firstItem.type === Type.SEQ_ITEM ? Type.SEQ : Type.MAP);
for (var i = firstItem.props.length - 1; i >= 0; --i) {
if (firstItem.props[i].start < firstItem.context.lineStart) {
// props on previous line are assumed by the collection
_this.props = firstItem.props.slice(0, i + 1);
firstItem.props = firstItem.props.slice(i + 1);
var itemRange = firstItem.props[0] || firstItem.valueRange;
firstItem.range.start = itemRange.start;
break;
}
}
_this.items = [firstItem];
var ec = grabCollectionEndComments(firstItem);
if (ec) Array.prototype.push.apply(_this.items, ec);
return _this;
}
_createClass(Collection, [{
key: "includesTrailingLines",
get: function get() {
return this.items.length > 0;
}
/**
* @param {ParseContext} context
* @param {number} start - Index of first character
* @returns {number} - Index of the character after this
*/
}, {
key: "parse",
value: function parse(context, start) {
this.context = context;
var parseNode = context.parseNode,
src = context.src; // It's easier to recalculate lineStart here rather than tracking down the
// last context from which to read it -- eemeli/yaml#2
var lineStart = Node.startOfLine(src, start);
var firstItem = this.items[0]; // First-item context needs to be correct for later comment handling
// -- eemeli/yaml#17
firstItem.context.parent = this;
this.valueRange = Range.copy(firstItem.valueRange);
var indent = firstItem.range.start - firstItem.context.lineStart;
var offset = start;
offset = Node.normalizeOffset(src, offset);
var ch = src[offset];
var atLineStart = Node.endOfWhiteSpace(src, lineStart) === offset;
var prevIncludesTrailingLines = false;
while (ch) {
while (ch === '\n' || ch === '#') {
if (atLineStart && ch === '\n' && !prevIncludesTrailingLines) {
var blankLine = new BlankLine();
offset = blankLine.parse({
src: src
}, offset);
this.valueRange.end = offset;
if (offset >= src.length) {
ch = null;
break;
}
this.items.push(blankLine);
offset -= 1; // blankLine.parse() consumes terminal newline
} else if (ch === '#') {
if (offset < lineStart + indent && !Collection.nextContentHasIndent(src, offset, indent)) {
return offset;
}
var comment = new Comment();
offset = comment.parse({
indent: indent,
lineStart: lineStart,
src: src
}, offset);
this.items.push(comment);
this.valueRange.end = offset;
if (offset >= src.length) {
ch = null;
break;
}
}
lineStart = offset + 1;
offset = Node.endOfIndent(src, lineStart);
if (Node.atBlank(src, offset)) {
var wsEnd = Node.endOfWhiteSpace(src, offset);
var next = src[wsEnd];
if (!next || next === '\n' || next === '#') {
offset = wsEnd;
}
}
ch = src[offset];
atLineStart = true;
}
if (!ch) {
break;
}
if (offset !== lineStart + indent && (atLineStart || ch !== ':')) {
if (offset < lineStart + indent) {
if (lineStart > start) offset = lineStart;
break;
} else if (!this.error) {
var msg = 'All collection items must start at the same column';
this.error = new YAMLSyntaxError(this, msg);
}
}
if (firstItem.type === Type.SEQ_ITEM) {
if (ch !== '-') {
if (lineStart > start) offset = lineStart;
break;
}
} else if (ch === '-' && !this.error) {
// map key may start with -, as long as it's followed by a non-whitespace char
var _next = src[offset + 1];
if (!_next || _next === '\n' || _next === '\t' || _next === ' ') {
var _msg = 'A collection cannot be both a mapping and a sequence';
this.error = new YAMLSyntaxError(this, _msg);
}
}
var node = parseNode({
atLineStart: atLineStart,
inCollection: true,
indent: indent,
lineStart: lineStart,
parent: this
}, offset);
if (!node) return offset; // at next document start
this.items.push(node);
this.valueRange.end = node.valueRange.end;
offset = Node.normalizeOffset(src, node.range.end);
ch = src[offset];
atLineStart = false;
prevIncludesTrailingLines = node.includesTrailingLines; // Need to reset lineStart and atLineStart here if preceding node's range
// has advanced to check the current line's indentation level
// -- eemeli/yaml#10 & eemeli/yaml#38
if (ch) {
var ls = offset - 1;
var prev = src[ls];
while (prev === ' ' || prev === '\t') {
prev = src[--ls];
}
if (prev === '\n') {
lineStart = ls + 1;
atLineStart = true;
}
}
var ec = grabCollectionEndComments(node);
if (ec) Array.prototype.push.apply(this.items, ec);
}
return offset;
}
}, {
key: "setOrigRanges",
value: function setOrigRanges(cr, offset) {
offset = _get(_getPrototypeOf(Collection.prototype), "setOrigRanges", this).call(this, cr, offset);
this.items.forEach(function (node) {
offset = node.setOrigRanges(cr, offset);
});
return offset;
}
}, {
key: "toString",
value: function toString() {
var src = this.context.src,
items = this.items,
range = this.range,
value = this.value;
if (value != null) return value;
var str = src.slice(range.start, items[0].range.start) + String(items[0]);
for (var i = 1; i < items.length; ++i) {
var item = items[i];
var _item$context = item.context,
atLineStart = _item$context.atLineStart,
indent = _item$context.indent;
if (atLineStart) for (var _i = 0; _i < indent; ++_i) {
str += ' ';
}
str += String(item);
}
return Node.addStringTerminator(src, range.end, str);
}
}], [{
key: "nextContentHasIndent",
value: function nextContentHasIndent(src, offset, indent) {
var lineStart = Node.endOfLine(src, offset) + 1;
offset = Node.endOfWhiteSpace(src, lineStart);
var ch = src[offset];
if (!ch) return false;
if (offset >= lineStart + indent) return true;
if (ch !== '#' && ch !== '\n') return false;
return Collection.nextContentHasIndent(src, offset, indent);
}
}]);
return Collection;
}(Node);
var Directive = /*#__PURE__*/function (_Node) {
_inherits(Directive, _Node);
var _super = _createSuper(Directive);
function Directive() {
var _this;
_classCallCheck(this, Directive);
_this = _super.call(this, Type.DIRECTIVE);
_this.name = null;
return _this;
}
_createClass(Directive, [{
key: "parameters",
get: function get() {
var raw = this.rawValue;
return raw ? raw.trim().split(/[ \t]+/) : [];
}
}, {
key: "parseName",
value: function parseName(start) {
var src = this.context.src;
var offset = start;
var ch = src[offset];
while (ch && ch !== '\n' && ch !== '\t' && ch !== ' ') {
ch = src[offset += 1];
}
this.name = src.slice(start, offset);
return offset;
}
}, {
key: "parseParameters",
value: function parseParameters(start) {
var src = this.context.src;
var offset = start;
var ch = src[offset];
while (ch && ch !== '\n' && ch !== '#') {
ch = src[offset += 1];
}
this.valueRange = new Range(start, offset);
return offset;
}
}, {
key: "parse",
value: function parse(context, start) {
this.context = context;
var offset = this.parseName(start + 1);
offset = this.parseParameters(offset);
offset = this.parseComment(offset);
this.range = new Range(start, offset);
return offset;
}
}]);
return Directive;
}(Node);
var Document = /*#__PURE__*/function (_Node) {
_inherits(Document, _Node);
var _super = _createSuper(Document);
function Document() {
var _this;
_classCallCheck(this, Document);
_this = _super.call(this, Type.DOCUMENT);
_this.directives = null;
_this.contents = null;
_this.directivesEndMarker = null;
_this.documentEndMarker = null;
return _this;
}
_createClass(Document, [{
key: "parseDirectives",
value: function parseDirectives(start) {
var src = this.context.src;
this.directives = [];
var atLineStart = true;
var hasDirectives = false;
var offset = start;
while (!Node.atDocumentBoundary(src, offset, Char.DIRECTIVES_END)) {
offset = Document.startCommentOrEndBlankLine(src, offset);
switch (src[offset]) {
case '\n':
if (atLineStart) {
var blankLine = new BlankLine();
offset = blankLine.parse({
src: src
}, offset);
if (offset < src.length) {
this.directives.push(blankLine);
}
} else {
offset += 1;
atLineStart = true;
}
break;
case '#':
{
var comment = new Comment();
offset = comment.parse({
src: src
}, offset);
this.directives.push(comment);
atLineStart = false;
}
break;
case '%':
{
var directive = new Directive();
offset = directive.parse({
parent: this,
src: src
}, offset);
this.directives.push(directive);
hasDirectives = true;
atLineStart = false;
}
break;
default:
if (hasDirectives) {
this.error = new YAMLSemanticError(this, 'Missing directives-end indicator line');
} else if (this.directives.length > 0) {
this.contents = this.directives;
this.directives = [];
}
return offset;
}
}
if (src[offset]) {
this.directivesEndMarker = new Range(offset, offset + 3);
return offset + 3;
}
if (hasDirectives) {
this.error = new YAMLSemanticError(this, 'Missing directives-end indicator line');
} else if (this.directives.length > 0) {
this.contents = this.directives;
this.directives = [];
}
return offset;
}
}, {
key: "parseContents",
value: function parseContents(start) {
var _this$context = this.context,
parseNode = _this$context.parseNode,
src = _this$context.src;
if (!this.contents) this.contents = [];
var lineStart = start;
while (src[lineStart - 1] === '-') {
lineStart -= 1;
}
var offset = Node.endOfWhiteSpace(src, start);
var atLineStart = lineStart === start;
this.valueRange = new Range(offset);
while (!Node.atDocumentBoundary(src, offset, Char.DOCUMENT_END)) {
switch (src[offset]) {
case '\n':
if (atLineStart) {
var blankLine = new BlankLine();
offset = blankLine.parse({
src: src
}, offset);
if (offset < src.length) {
this.contents.push(blankLine);
}
} else {
offset += 1;
atLineStart = true;
}
lineStart = offset;
break;
case '#':
{
var comment = new Comment();
offset = comment.parse({
src: src
}, offset);
this.contents.push(comment);
atLineStart = false;
}
break;
default:
{
var iEnd = Node.endOfIndent(src, offset);
var context = {
atLineStart: atLineStart,
indent: -1,
inFlow: false,
inCollection: false,
lineStart: lineStart,
parent: this
};
var node = parseNode(context, iEnd);
if (!node) return this.valueRange.end = iEnd; // at next document start
this.contents.push(node);
offset = node.range.end;
atLineStart = false;
var ec = grabCollectionEndComments(node);
if (ec) Array.prototype.push.apply(this.contents, ec);
}
}
offset = Document.startCommentOrEndBlankLine(src, offset);
}
this.valueRange.end = offset;
if (src[offset]) {
this.documentEndMarker = new Range(offset, offset + 3);
offset += 3;
if (src[offset]) {
offset = Node.endOfWhiteSpace(src, offset);
if (src[offset] === '#') {
var _comment = new Comment();
offset = _comment.parse({
src: src
}, offset);
this.contents.push(_comment);
}
switch (src[offset]) {
case '\n':
offset += 1;
break;
case undefined:
break;
default:
this.error = new YAMLSyntaxError(this, 'Document end marker line cannot have a non-comment suffix');
}
}
}
return offset;
}
/**
* @param {ParseContext} context
* @param {number} start - Index of first character
* @returns {number} - Index of the character after this
*/
}, {
key: "parse",
value: function parse(context, start) {
context.root = this;
this.context = context;
var src = context.src;
var offset = src.charCodeAt(start) === 0xfeff ? start + 1 : start; // skip BOM
offset = this.parseDirectives(offset);
offset = this.parseContents(offset);
return offset;
}
}, {
key: "setOrigRanges",
value: function setOrigRanges(cr, offset) {
offset = _get(_getPrototypeOf(Document.prototype), "setOrigRanges", this).call(this, cr, offset);
this.directives.forEach(function (node) {
offset = node.setOrigRanges(cr, offset);
});
if (this.directivesEndMarker) offset = this.directivesEndMarker.setOrigRange(cr, offset);
this.contents.forEach(function (node) {
offset = node.setOrigRanges(cr, offset);
});
if (this.documentEndMarker) offset = this.documentEndMarker.setOrigRange(cr, offset);
return offset;
}
}, {
key: "toString",
value: function toString() {
var contents = this.contents,
directives = this.directives,
value = this.value;
if (value != null) return value;
var str = directives.join('');
if (contents.length > 0) {
if (directives.length > 0 || contents[0].type === Type.COMMENT) str += '---\n';
str += contents.join('');
}
if (str[str.length - 1] !== '\n') str += '\n';
return str;
}
}], [{
key: "startCommentOrEndBlankLine",
value: function startCommentOrEndBlankLine(src, start) {
var offset = Node.endOfWhiteSpace(src, start);
var ch = src[offset];
return ch === '#' || ch === '\n' ? offset : start;
}
}]);
return Document;
}(Node);
var Alias = /*#__PURE__*/function (_Node) {
_inherits(Alias, _Node);
var _super = _createSuper(Alias);
function Alias() {
_classCallCheck(this, Alias);
return _super.apply(this, arguments);
}
_createClass(Alias, [{
key: "parse",
value:
/**
* Parses an *alias from the source
*
* @param {ParseContext} context
* @param {number} start - Index of first character
* @returns {number} - Index of the character after this scalar
*/
function parse(context, start) {
this.context = context;
var src = context.src;
var offset = Node.endOfIdentifier(src, start + 1);
this.valueRange = new Range(start + 1, offset);
offset = Node.endOfWhiteSpace(src, offset);
offset = this.parseComment(offset);
return offset;
}
}]);
return Alias;
}(Node);
var Chomp = {
CLIP: 'CLIP',
KEEP: 'KEEP',
STRIP: 'STRIP'
};
var BlockValue = /*#__PURE__*/function (_Node) {
_inherits(BlockValue, _Node);
var _super = _createSuper(BlockValue);
function BlockValue(type, props) {
var _this;
_classCallCheck(this, BlockValue);
_this = _super.call(this, type, props);
_this.blockIndent = null;
_this.chomping = Chomp.CLIP;
_this.header = null;
return _this;
}
_createClass(BlockValue, [{
key: "includesTrailingLines",
get: function get() {
return this.chomping === Chomp.KEEP;
}
}, {
key: "strValue",
get: function get() {
if (!this.valueRange || !this.context) return null;
var _this$valueRange = this.valueRange,
start = _this$valueRange.start,
end = _this$valueRange.end;
var _this$context = this.context,
indent = _this$context.indent,
src = _this$context.src;
if (this.valueRange.isEmpty()) return '';
var lastNewLine = null;
var ch = src[end - 1];
while (ch === '\n' || ch === '\t' || ch === ' ') {
end -= 1;
if (end <= start) {
if (this.chomping === Chomp.KEEP) break;else return ''; // probably never happens
}
if (ch === '\n') lastNewLine = end;
ch = src[end - 1];
}
var keepStart = end + 1;
if (lastNewLine) {
if (this.chomping === Chomp.KEEP) {
keepStart = lastNewLine;
end = this.valueRange.end;
} else {
end = lastNewLine;
}
}
var bi = indent + this.blockIndent;
var folded = this.type === Type.BLOCK_FOLDED;
var atStart = true;
var str = '';
var sep = '';
var prevMoreIndented = false;
for (var i = start; i < end; ++i) {
for (var j = 0; j < bi; ++j) {
if (src[i] !== ' ') break;
i += 1;
}
var _ch = src[i];
if (_ch === '\n') {
if (sep === '\n') str += '\n';else sep = '\n';
} else {
var lineEnd = Node.endOfLine(src, i);
var line = src.slice(i, lineEnd);
i = lineEnd;
if (folded && (_ch === ' ' || _ch === '\t') && i < keepStart) {
if (sep === ' ') sep = '\n';else if (!prevMoreIndented && !atStart && sep === '\n') sep = '\n\n';
str += sep + line; //+ ((lineEnd < end && src[lineEnd]) || '')
sep = lineEnd < end && src[lineEnd] || '';
prevMoreIndented = true;
} else {
str += sep + line;
sep = folded && i < keepStart ? ' ' : '\n';
prevMoreIndented = false;
}
if (atStart && line !== '') atStart = false;
}
}
return this.chomping === Chomp.STRIP ? str : str + '\n';
}
}, {
key: "parseBlockHeader",
value: function parseBlockHeader(start) {
var src = this.context.src;
var offset = start + 1;
var bi = '';
while (true) {
var ch = src[offset];
switch (ch) {
case '-':
this.chomping = Chomp.STRIP;
break;
case '+':
this.chomping = Chomp.KEEP;
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
bi += ch;
break;
default:
this.blockIndent = Number(bi) || null;
this.header = new Range(start, offset);
return offset;
}
offset += 1;
}
}
}, {
key: "parseBlockValue",
value: function parseBlockValue(start) {
var _this$context2 = this.context,
indent = _this$context2.indent,
src = _this$context2.src;
var explicit = !!this.blockIndent;
var offset = start;
var valueEnd = start;
var minBlockIndent = 1;
for (var ch = src[offset]; ch === '\n'; ch = src[offset]) {
offset += 1;
if (Node.atDocumentBoundary(src, offset)) break;
var end = Node.endOfBlockIndent(src, indent, offset); // should not include tab?
if (end === null) break;
var _ch2 = src[end];
var lineIndent = end - (offset + indent);
if (!this.blockIndent) {
// no explicit block indent, none yet detected
if (src[end] !== '\n') {
// first line with non-whitespace content
if (lineIndent < minBlockIndent) {
var msg = 'Block scalars with more-indented leading empty lines must use an explicit indentation indicator';
this.error = new YAMLSemanticError(this, msg);
}
this.blockIndent = lineIndent;
} else if (lineIndent > minBlockIndent) {
// empty line with more whitespace
minBlockIndent = lineIndent;
}
} else if (_ch2 && _ch2 !== '\n' && lineIndent < this.blockIndent) {
if (src[end] === '#') break;
if (!this.error) {
var _src = explicit ? 'explicit indentation indicator' : 'first line';
var _msg = "Block scalars must not be less indented than their ".concat(_src);
this.error = new YAMLSemanticError(this, _msg);
}
}
if (src[end] === '\n') {
offset = end;
} else {
offset = valueEnd = Node.endOfLine(src, end);
}
}
if (this.chomping !== Chomp.KEEP) {
offset = src[valueEnd] ? valueEnd + 1 : valueEnd;
}
this.valueRange = new Range(start + 1, offset);
return offset;
}
/**
* Parses a block value from the source
*
* Accepted forms are:
* ```
* BS
* block
* lines
*
* BS #comment
* block
* lines
* ```
* where the block style BS matches the regexp `[|>][-+1-9]*` and block lines
* are empty or have an indent level greater than `indent`.
*
* @param {ParseContext} context
* @param {number} start - Index of first character
* @returns {number} - Index of the character after this block
*/
}, {
key: "parse",
value: function parse(context, start) {
this.context = context;
var src = context.src;
var offset = this.parseBlockHeader(start);
offset = Node.endOfWhiteSpace(src, offset);
offset = this.parseComment(offset);
offset = this.parseBlockValue(offset);
return offset;
}
}, {
key: "setOrigRanges",
value: function setOrigRanges(cr, offset) {
offset = _get(_getPrototypeOf(BlockValue.prototype), "setOrigRanges", this).call(this, cr, offset);
return this.header ? this.header.setOrigRange(cr, offset) : offset;
}
}]);
return BlockValue;
}(Node);
var FlowCollection = /*#__PURE__*/function (_Node) {
_inherits(FlowCollection, _Node);
var _super = _createSuper(FlowCollection);
function FlowCollection(type, props) {
var _this;
_classCallCheck(this, FlowCollection);
_this = _super.call(this, type, props);
_this.items = null;
return _this;
}
_createClass(FlowCollection, [{
key: "prevNodeIsJsonLike",
value: function prevNodeIsJsonLike() {
var idx = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.items.length;
var node = this.items[idx - 1];
return !!node && (node.jsonLike || node.type === Type.COMMENT && this.prevNodeIsJsonLike(idx - 1));
}
/**
* @param {ParseContext} context
* @param {number} start - Index of first character
* @returns {number} - Index of the character after this
*/
}, {
key: "parse",
value: function parse(context, start) {
this.context = context;
var parseNode = context.parseNode,
src = context.src;
var indent = context.indent,
lineStart = context.lineStart;
var char = src[start]; // { or [
this.items = [{
char: char,
offset: start
}];
var offset = Node.endOfWhiteSpace(src, start + 1);
char = src[offset];
while (char && char !== ']' && char !== '}') {
switch (char) {
case '\n':
{
lineStart = offset + 1;
var wsEnd = Node.endOfWhiteSpace(src, lineStart);
if (src[wsEnd] === '\n') {
var blankLine = new BlankLine();
lineStart = blankLine.parse({
src: src
}, lineStart);
this.items.push(blankLine);
}
offset = Node.endOfIndent(src, lineStart);
if (offset <= lineStart + indent) {
char = src[offset];
if (offset < lineStart + indent || char !== ']' && char !== '}') {
var msg = 'Insufficient indentation in flow collection';
this.error = new YAMLSemanticError(this, msg);
}
}
}
break;
case ',':
{
this.items.push({
char: char,
offset: offset
});
offset += 1;
}
break;
case '#':
{
var comment = new Comment();
offset = comment.parse({
src: src
}, offset);
this.items.push(comment);
}
break;
case '?':
case ':':
{
var next = src[offset + 1];
if (next === '\n' || next === '\t' || next === ' ' || next === ',' || // in-flow : after JSON-like key does not need to be followed by whitespace
char === ':' && this.prevNodeIsJsonLike()) {
this.items.push({
char: char,
offset: offset
});
offset += 1;
break;
}
}
// fallthrough
default:
{
var node = parseNode({
atLineStart: false,
inCollection: false,
inFlow: true,
indent: -1,
lineStart: lineStart,
parent: this
}, offset);
if (!node) {
// at next document start
this.valueRange = new Range(start, offset);
return offset;
}
this.items.push(node);
offset = Node.normalizeOffset(src, node.range.end);
}
}
offset = Node.endOfWhiteSpace(src, offset);
char = src[offset];
}
this.valueRange = new Range(start, offset + 1);
if (char) {
this.items.push({
char: char,
offset: offset
});
offset = Node.endOfWhiteSpace(src, offset + 1);
offset = this.parseComment(offset);
}
return offset;
}
}, {
key: "setOrigRanges",
value: function setOrigRanges(cr, offset) {
offset = _get(_getPrototypeOf(FlowCollection.prototype), "setOrigRanges", this).call(this, cr, offset);
this.items.forEach(function (node) {
if (node instanceof Node) {
offset = node.setOrigRanges(cr, offset);
} else if (cr.length === 0) {
node.origOffset = node.offset;
} else {
var i = offset;
while (i < cr.length) {
if (cr[i] > node.offset) break;else ++i;
}
node.origOffset = node.offset + i;
offset = i;
}
});
return offset;
}
}, {
key: "toString",
value: function toString() {
var src = this.context.src,
items = this.items,
range = this.range,
value = this.value;
if (value != null) return value;
var nodes = items.filter(function (item) {
return item instanceof Node;
});
var str = '';
var prevEnd = range.start;
nodes.forEach(function (node) {
var prefix = src.slice(prevEnd, node.range.start);
prevEnd = node.range.end;
str += prefix + String(node);
if (str[str.length - 1] === '\n' && src[prevEnd - 1] !== '\n' && src[prevEnd] === '\n') {
// Comment range does not include the terminal newline, but its
// stringified value does. Without this fix, newlines at comment ends
// get duplicated.
prevEnd += 1;
}
});
str += src.slice(prevEnd, range.end);
return Node.addStringTerminator(src, range.end, str);
}
}]);
return FlowCollection;
}(Node);
var QuoteDouble = /*#__PURE__*/function (_Node) {
_inherits(QuoteDouble, _Node);
var _super = _createSuper(QuoteDouble);
function QuoteDouble() {
_classCallCheck(this, QuoteDouble);
return _super.apply(this, arguments);
}
_createClass(QuoteDouble, [{
key: "strValue",
get:
/**
* @returns {string | { str: string, errors: YAMLSyntaxError[] }}
*/
function get() {
if (!this.valueRange || !this.context) return null;
var errors = [];
var _this$valueRange = this.valueRange,
start = _this$valueRange.start,
end = _this$valueRange.end;
var _this$context = this.context,
indent = _this$context.indent,
src = _this$context.src;
if (src[end - 1] !== '"') errors.push(new YAMLSyntaxError(this, 'Missing closing "quote')); // Using String#replace is too painful with escaped newlines preceded by
// escaped backslashes; also, this should be faster.
var str = '';
for (var i = start + 1; i < end - 1; ++i) {
var ch = src[i];
if (ch === '\n') {
if (Node.atDocumentBoundary(src, i + 1)) errors.push(new YAMLSemanticError(this, 'Document boundary indicators are not allowed within string values'));
var _Node$foldNewline = Node.foldNewline(src, i, indent),
fold = _Node$foldNewline.fold,
offset = _Node$foldNewline.offset,
error = _Node$foldNewline.error;
str += fold;
i = offset;
if (error) errors.push(new YAMLSemanticError(this, 'Multi-line double-quoted string needs to be sufficiently indented'));
} else if (ch === '\\') {
i += 1;
switch (src[i]) {
case '0':
str += '\0';
break;
// null character
case 'a':
str += '\x07';
break;
// bell character
case 'b':
str += '\b';
break;
// backspace
case 'e':
str += '\x1b';
break;
// escape character
case 'f':
str += '\f';
break;
// form feed
case 'n':
str += '\n';
break;
// line feed
case 'r':
str += '\r';
break;
// carriage return
case 't':
str += '\t';
break;
// horizontal tab
case 'v':
str += '\v';
break;
// vertical tab
case 'N':
str += "\x85";
break;
// Unicode next line
case '_':
str += "\xA0";
break;
// Unicode non-breaking space
case 'L':
str += "\u2028";
break;
// Unicode line separator
case 'P':
str += "\u2029";
break;
// Unicode paragraph separator
case ' ':
str += ' ';
break;
case '"':
str += '"';
break;
case '/':
str += '/';
break;
case '\\':
str += '\\';
break;
case '\t':
str += '\t';
break;
case 'x':
str += this.parseCharCode(i + 1, 2, errors);
i += 2;
break;
case 'u':
str += this.parseCharCode(i + 1, 4, errors);
i += 4;
break;
case 'U':
str += this.parseCharCode(i + 1, 8, errors);
i += 8;
break;
case '\n':
// skip escaped newlines, but still trim the following line
while (src[i + 1] === ' ' || src[i + 1] === '\t') {
i += 1;
}
break;
default:
errors.push(new YAMLSyntaxError(this, "Invalid escape sequence ".concat(src.substr(i - 1, 2))));
str += '\\' + src[i];
}
} else if (ch === ' ' || ch === '\t') {
// trim trailing whitespace
var wsStart = i;
var next = src[i + 1];
while (next === ' ' || next === '\t') {
i += 1;
next = src[i + 1];
}
if (next !== '\n') str += i > wsStart ? src.slice(wsStart, i + 1) : ch;
} else {
str += ch;
}
}
return errors.length > 0 ? {
errors: errors,
str: str
} : str;
}
}, {
key: "parseCharCode",
value: function parseCharCode(offset, length, errors) {
var src = this.context.src;
var cc = src.substr(offset, length);
var ok = cc.length === length && /^[0-9a-fA-F]+$/.test(cc);
var code = ok ? parseInt(cc, 16) : NaN;
if (isNaN(code)) {
errors.push(new YAMLSyntaxError(this, "Invalid escape sequence ".concat(src.substr(offset - 2, length + 2))));
return src.substr(offset - 2, length + 2);
}
return String.fromCodePoint(code);
}
/**
* Parses a "double quoted" value from the source
*
* @param {ParseContext} context
* @param {number} start - Index of first character
* @returns {number} - Index of the character after this scalar
*/
}, {
key: "parse",
value: function parse(context, start) {
this.context = context;
var src = context.src;
var offset = QuoteDouble.endOfQuote(src, start + 1);
this.valueRange = new Range(start, offset);
offset = Node.endOfWhiteSpace(src, offset);
offset = this.parseComment(offset);
return offset;
}
}], [{
key: "endOfQuote",
value: function endOfQuote(src, offset) {
var ch = src[offset];
while (ch && ch !== '"') {
offset += ch === '\\' ? 2 : 1;
ch = src[offset];
}
return offset + 1;
}
}]);
return QuoteDouble;
}(Node);
var QuoteSingle = /*#__PURE__*/function (_Node) {
_inherits(QuoteSingle, _Node);
var _super = _createSuper(QuoteSingle);
function QuoteSingle() {
_classCallCheck(this, QuoteSingle);
return _super.apply(this, arguments);
}
_createClass(QuoteSingle, [{
key: "strValue",
get:
/**
* @returns {string | { str: string, errors: YAMLSyntaxError[] }}
*/
function get() {
if (!this.valueRange || !this.context) return null;
var errors = [];
var _this$valueRange = this.valueRange,
start = _this$valueRange.start,
end = _this$valueRange.end;
var _this$context = this.context,
indent = _this$context.indent,
src = _this$context.src;
if (src[end - 1] !== "'") errors.push(new YAMLSyntaxError(this, "Missing closing 'quote"));
var str = '';
for (var i = start + 1; i < end - 1; ++i) {
var ch = src[i];
if (ch === '\n') {
if (Node.atDocumentBoundary(src, i + 1)) errors.push(new YAMLSemanticError(this, 'Document boundary indicators are not allowed within string values'));
var _Node$foldNewline = Node.foldNewline(src, i, indent),
fold = _Node$foldNewline.fold,
offset = _Node$foldNewline.offset,
error = _Node$foldNewline.error;
str += fold;
i = offset;
if (error) errors.push(new YAMLSemanticError(this, 'Multi-line single-quoted string needs to be sufficiently indented'));
} else if (ch === "'") {
str += ch;
i += 1;
if (src[i] !== "'") errors.push(new YAMLSyntaxError(this, 'Unescaped single quote? This should not happen.'));
} else if (ch === ' ' || ch === '\t') {
// trim trailing whitespace
var wsStart = i;
var next = src[i + 1];
while (next === ' ' || next === '\t') {
i += 1;
next = src[i + 1];
}
if (next !== '\n') str += i > wsStart ? src.slice(wsStart, i + 1) : ch;
} else {
str += ch;
}
}
return errors.length > 0 ? {
errors: errors,
str: str
} : str;
}
/**
* Parses a 'single quoted' value from the source
*
* @param {ParseContext} context
* @param {number} start - Index of first character
* @returns {number} - Index of the character after this scalar
*/
}, {
key: "parse",
value: function parse(context, start) {
this.context = context;
var src = context.src;
var offset = QuoteSingle.endOfQuote(src, start + 1);
this.valueRange = new Range(start, offset);
offset = Node.endOfWhiteSpace(src, offset);
offset = this.parseComment(offset);
return offset;
}
}], [{
key: "endOfQuote",
value: function endOfQuote(src, offset) {
var ch = src[offset];
while (ch) {
if (ch === "'") {
if (src[offset + 1] !== "'") break;
ch = src[offset += 2];
} else {
ch = src[offset += 1];
}
}
return offset + 1;
}
}]);
return QuoteSingle;
}(Node);
function createNewNode(type, props) {
switch (type) {
case Type.ALIAS:
return new Alias(type, props);
case Type.BLOCK_FOLDED:
case Type.BLOCK_LITERAL:
return new BlockValue(type, props);
case Type.FLOW_MAP:
case Type.FLOW_SEQ:
return new FlowCollection(type, props);
case Type.MAP_KEY:
case Type.MAP_VALUE:
case Type.SEQ_ITEM:
return new CollectionItem(type, props);
case Type.COMMENT:
case Type.PLAIN:
return new PlainValue(type, props);
case Type.QUOTE_DOUBLE:
return new QuoteDouble(type, props);
case Type.QUOTE_SINGLE:
return new QuoteSingle(type, props);
/* istanbul ignore next */
default:
return null;
// should never happen
}
}
/**
* @param {boolean} atLineStart - Node starts at beginning of line
* @param {boolean} inFlow - true if currently in a flow context
* @param {boolean} inCollection - true if currently in a collection context
* @param {number} indent - Current level of indentation
* @param {number} lineStart - Start of the current line
* @param {Node} parent - The parent of the node
* @param {string} src - Source of the YAML document
*/
var ParseContext = /*#__PURE__*/function () {
function ParseContext() {
var _this = this;
var orig = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
atLineStart = _ref.atLineStart,
inCollection = _ref.inCollection,
inFlow = _ref.inFlow,
indent = _ref.indent,
lineStart = _ref.lineStart,
parent = _ref.parent;
_classCallCheck(this, ParseContext);
_defineProperty(this, "parseNode", function (overlay, start) {
if (Node.atDocumentBoundary(_this.src, start)) return null;
var context = new ParseContext(_this, overlay);
var _context$parseProps = context.parseProps(start),
props = _context$parseProps.props,
type = _context$parseProps.type,
valueStart = _context$parseProps.valueStart;
var node = createNewNode(type, props);
var offset = node.parse(context, valueStart);
node.range = new Range(start, offset);
/* istanbul ignore if */
if (offset <= start) {
// This should never happen, but if it does, let's make sure to at least
// step one character forward to avoid a busy loop.
node.error = new Error("Node#parse consumed no characters");
node.error.parseEnd = offset;
node.error.source = node;
node.range.end = start + 1;
}
if (context.nodeStartsCollection(node)) {
if (!node.error && !context.atLineStart && context.parent.type === Type.DOCUMENT) {
node.error = new YAMLSyntaxError(node, 'Block collection must not have preceding content here (e.g. directives-end indicator)');
}
var collection = new Collection(node);
offset = collection.parse(new ParseContext(context), offset);
collection.range = new Range(start, offset);
return collection;
}
return node;
});
this.atLineStart = atLineStart != null ? atLineStart : orig.atLineStart || false;
this.inCollection = inCollection != null ? inCollection : orig.inCollection || false;
this.inFlow = inFlow != null ? inFlow : orig.inFlow || false;
this.indent = indent != null ? indent : orig.indent;
this.lineStart = lineStart != null ? lineStart : orig.lineStart;
this.parent = parent != null ? parent : orig.parent || {};
this.root = orig.root;
this.src = orig.src;
}
_createClass(ParseContext, [{
key: "nodeStartsCollection",
value: function nodeStartsCollection(node) {
var inCollection = this.inCollection,
inFlow = this.inFlow,
src = this.src;
if (inCollection || inFlow) return false;
if (node instanceof CollectionItem) return true; // check for implicit key
var offset = node.range.end;
if (src[offset] === '\n' || src[offset - 1] === '\n') return false;
offset = Node.endOfWhiteSpace(src, offset);
return src[offset] === ':';
} // Anchor and tag are before type, which determines the node implementation
// class; hence this intermediate step.
}, {
key: "parseProps",
value: function parseProps(offset) {
var inFlow = this.inFlow,
parent = this.parent,
src = this.src;
var props = [];
var lineHasProps = false;
offset = this.atLineStart ? Node.endOfIndent(src, offset) : Node.endOfWhiteSpace(src, offset);
var ch = src[offset];
while (ch === Char.ANCHOR || ch === Char.COMMENT || ch === Char.TAG || ch === '\n') {
if (ch === '\n') {
var inEnd = offset;
var lineStart = void 0;
do {
lineStart = inEnd + 1;
inEnd = Node.endOfIndent(src, lineStart);
} while (src[inEnd] === '\n');
var indentDiff = inEnd - (lineStart + this.indent);
var noIndicatorAsIndent = parent.type === Type.SEQ_ITEM && parent.context.atLineStart;
if (src[inEnd] !== '#' && !Node.nextNodeIsIndented(src[inEnd], indentDiff, !noIndicatorAsIndent)) break;
this.atLineStart = true;
this.lineStart = lineStart;
lineHasProps = false;
offset = inEnd;
} else if (ch === Char.COMMENT) {
var end = Node.endOfLine(src, offset + 1);
props.push(new Range(offset, end));
offset = end;
} else {
var _end = Node.endOfIdentifier(src, offset + 1);
if (ch === Char.TAG && src[_end] === ',' && /^[a-zA-Z0-9-]+\.[a-zA-Z0-9-]+,\d\d\d\d(-\d\d){0,2}\/\S/.test(src.slice(offset + 1, _end + 13))) {
// Let's presume we're dealing with a YAML 1.0 domain tag here, rather
// than an empty but 'foo.bar' private-tagged node in a flow collection
// followed without whitespace by a plain string starting with a year
// or date divided by something.
_end = Node.endOfIdentifier(src, _end + 5);
}
props.push(new Range(offset, _end));
lineHasProps = true;
offset = Node.endOfWhiteSpace(src, _end);
}
ch = src[offset];
} // '- &a : b' has an anchor on an empty node
if (lineHasProps && ch === ':' && Node.atBlank(src, offset + 1, true)) offset -= 1;
var type = ParseContext.parseType(src, offset, inFlow);
return {
props: props,
type: type,
valueStart: offset
};
}
/**
* Parses a node from the source
* @param {ParseContext} overlay
* @param {number} start - Index of first non-whitespace character for the node
* @returns {?Node} - null if at a document boundary
*/
}], [{
key: "parseType",
value: function parseType(src, offset, inFlow) {
switch (src[offset]) {
case '*':
return Type.ALIAS;
case '>':
return Type.BLOCK_FOLDED;
case '|':
return Type.BLOCK_LITERAL;
case '{':
return Type.FLOW_MAP;
case '[':
return Type.FLOW_SEQ;
case '?':
return !inFlow && Node.atBlank(src, offset + 1, true) ? Type.MAP_KEY : Type.PLAIN;
case ':':
return !inFlow && Node.atBlank(src, offset + 1, true) ? Type.MAP_VALUE : Type.PLAIN;
case '-':
return !inFlow && Node.atBlank(src, offset + 1, true) ? Type.SEQ_ITEM : Type.PLAIN;
case '"':
return Type.QUOTE_DOUBLE;
case "'":
return Type.QUOTE_SINGLE;
default:
return Type.PLAIN;
}
}
}]);
return ParseContext;
}();
// Published as 'yaml/parse-cst'
function parse(src) {
var cr = [];
if (src.indexOf('\r') !== -1) {
src = src.replace(/\r\n?/g, function (match, offset) {
if (match.length > 1) cr.push(offset);
return '\n';
});
}
var documents = [];
var offset = 0;
do {
var doc = new Document();
var context = new ParseContext({
src: src
});
offset = doc.parse(context, offset);
documents.push(doc);
} while (offset < src.length);
documents.setOrigRanges = function () {
if (cr.length === 0) return false;
for (var i = 1; i < cr.length; ++i) {
cr[i] -= i;
}
var crOffset = 0;
for (var _i = 0; _i < documents.length; ++_i) {
crOffset = documents[_i].setOrigRanges(cr, crOffset);
}
cr.splice(0, cr.length);
return true;
};
documents.toString = function () {
return documents.join('...\n');
};
return documents;
}
export { parse };
| GoogleCloudPlatform/prometheus-engine | third_party/prometheus_ui/base/web/ui/react-app/node_modules/yaml/browser/dist/parse-cst.js | JavaScript | apache-2.0 | 54,633 |
version https://git-lfs.github.com/spec/v1
oid sha256:d57f539203e9219f4c43532d12ca16d51ce822bf08d658cabd06aa84fc61dda2
size 661
| yogeshsaroya/new-cdnjs | ajax/libs/dojo/1.5.4/cldr/nls/sv/number.js | JavaScript | mit | 128 |
'use strict';
var Promise = require('../../lib/ext/promise');
var conf = require('ember-cli-internal-test-helpers/lib/helpers/conf');
var ember = require('../helpers/ember');
var fs = require('fs-extra');
var outputFile = Promise.denodeify(fs.outputFile);
var path = require('path');
var remove = Promise.denodeify(fs.remove);
var replaceFile = require('ember-cli-internal-test-helpers/lib/helpers/file-utils').replaceFile;
var root = process.cwd();
var tmproot = path.join(root, 'tmp');
var Blueprint = require('../../lib/models/blueprint');
var BlueprintNpmTask = require('ember-cli-internal-test-helpers/lib/helpers/disable-npm-on-blueprint');
var mkTmpDirIn = require('../../lib/utilities/mk-tmp-dir-in');
var chai = require('../chai');
var expect = chai.expect;
var file = chai.file;
describe('Acceptance: ember generate', function() {
this.timeout(20000);
var tmpdir;
before(function() {
BlueprintNpmTask.disableNPM(Blueprint);
conf.setup();
});
after(function() {
BlueprintNpmTask.restoreNPM(Blueprint);
conf.restore();
});
beforeEach(function() {
return mkTmpDirIn(tmproot).then(function(dir) {
tmpdir = dir;
process.chdir(tmpdir);
});
});
afterEach(function() {
process.chdir(root);
return remove(tmproot);
});
function initApp() {
return ember([
'init',
'--name=my-app',
'--skip-npm',
'--skip-bower'
]);
}
function generate(args) {
var generateArgs = ['generate'].concat(args);
return initApp().then(function() {
return ember(generateArgs);
});
}
it('component x-foo', function() {
return generate(['component', 'x-foo']).then(function() {
expect(file('app/components/x-foo.js'))
.to.contain("import Ember from 'ember';")
.to.contain("export default Ember.Component.extend({")
.to.contain("});");
expect(file('app/templates/components/x-foo.hbs'))
.to.contain("{{yield}}");
expect(file('tests/integration/components/x-foo-test.js'))
.to.contain("import { moduleForComponent, test } from 'ember-qunit';")
.to.contain("import hbs from 'htmlbars-inline-precompile';")
.to.contain("moduleForComponent('x-foo'")
.to.contain("integration: true")
.to.contain("{{x-foo}}")
.to.contain("{{#x-foo}}");
});
});
it('component foo/x-foo', function() {
return generate(['component', 'foo/x-foo']).then(function() {
expect(file('app/components/foo/x-foo.js'))
.to.contain("import Ember from 'ember';")
.to.contain("export default Ember.Component.extend({")
.to.contain("});");
expect(file('app/templates/components/foo/x-foo.hbs'))
.to.contain("{{yield}}");
expect(file('tests/integration/components/foo/x-foo-test.js'))
.to.contain("import { moduleForComponent, test } from 'ember-qunit';")
.to.contain("import hbs from 'htmlbars-inline-precompile';")
.to.contain("moduleForComponent('foo/x-foo'")
.to.contain("integration: true")
.to.contain("{{foo/x-foo}}")
.to.contain("{{#foo/x-foo}}");
});
});
it('component x-foo ignores --path option', function() {
return generate(['component', 'x-foo', '--path', 'foo']).then(function() {
expect(file('app/components/x-foo.js'))
.to.contain("import Ember from 'ember';")
.to.contain("export default Ember.Component.extend({")
.to.contain("});");
expect(file('app/templates/components/x-foo.hbs'))
.to.contain("{{yield}}");
expect(file('tests/integration/components/x-foo-test.js'))
.to.contain("import { moduleForComponent, test } from 'ember-qunit';")
.to.contain("import hbs from 'htmlbars-inline-precompile';")
.to.contain("moduleForComponent('x-foo'")
.to.contain("integration: true")
.to.contain("{{x-foo}}")
.to.contain("{{#x-foo}}");
});
});
it('blueprint foo', function() {
return generate(['blueprint', 'foo']).then(function() {
expect(file('blueprints/foo/index.js'))
.to.contain("module.exports = {\n" +
" description: ''\n" +
"\n" +
" // locals: function(options) {\n" +
" // // Return custom template variables here.\n" +
" // return {\n" +
" // foo: options.entity.options.foo\n" +
" // };\n" +
" // }\n" +
"\n" +
" // afterInstall: function(options) {\n" +
" // // Perform extra work here.\n" +
" // }\n" +
"};");
});
});
it('blueprint foo/bar', function() {
return generate(['blueprint', 'foo/bar']).then(function() {
expect(file('blueprints/foo/bar/index.js'))
.to.contain("module.exports = {\n" +
" description: ''\n" +
"\n" +
" // locals: function(options) {\n" +
" // // Return custom template variables here.\n" +
" // return {\n" +
" // foo: options.entity.options.foo\n" +
" // };\n" +
" // }\n" +
"\n" +
" // afterInstall: function(options) {\n" +
" // // Perform extra work here.\n" +
" // }\n" +
"};");
});
});
it('http-mock foo', function() {
return generate(['http-mock', 'foo']).then(function() {
expect(file('server/index.js'))
.to.contain("mocks.forEach(function(route) { route(app); });");
expect(file('server/mocks/foo.js'))
.to.contain("module.exports = function(app) {\n" +
" var express = require('express');\n" +
" var fooRouter = express.Router();\n" +
"\n" +
" fooRouter.get('/', function(req, res) {\n" +
" res.send({\n" +
" 'foo': []\n" +
" });\n" +
" });\n" +
"\n" +
" fooRouter.post('/', function(req, res) {\n" +
" res.status(201).end();\n" +
" });\n" +
"\n" +
" fooRouter.get('/:id', function(req, res) {\n" +
" res.send({\n" +
" 'foo': {\n" +
" id: req.params.id\n" +
" }\n" +
" });\n" +
" });\n" +
"\n" +
" fooRouter.put('/:id', function(req, res) {\n" +
" res.send({\n" +
" 'foo': {\n" +
" id: req.params.id\n" +
" }\n" +
" });\n" +
" });\n" +
"\n" +
" fooRouter.delete('/:id', function(req, res) {\n" +
" res.status(204).end();\n" +
" });\n" +
"\n" +
" // The POST and PUT call will not contain a request body\n" +
" // because the body-parser is not included by default.\n" +
" // To use req.body, run:\n" +
"\n" +
" // npm install --save-dev body-parser\n" +
"\n" +
" // After installing, you need to `use` the body-parser for\n" +
" // this mock uncommenting the following line:\n" +
" //\n" +
" //app.use('/api/foo', require('body-parser').json());\n" +
" app.use('/api/foo', fooRouter);\n" +
"};");
expect(file('server/.jshintrc'))
.to.contain('{\n "node": true\n}');
});
});
it('http-mock foo-bar', function() {
return generate(['http-mock', 'foo-bar']).then(function() {
expect(file('server/index.js'))
.to.contain("mocks.forEach(function(route) { route(app); });");
expect(file('server/mocks/foo-bar.js'))
.to.contain("module.exports = function(app) {\n" +
" var express = require('express');\n" +
" var fooBarRouter = express.Router();\n" +
"\n" +
" fooBarRouter.get('/', function(req, res) {\n" +
" res.send({\n" +
" 'foo-bar': []\n" +
" });\n" +
" });\n" +
"\n" +
" fooBarRouter.post('/', function(req, res) {\n" +
" res.status(201).end();\n" +
" });\n" +
"\n" +
" fooBarRouter.get('/:id', function(req, res) {\n" +
" res.send({\n" +
" 'foo-bar': {\n" +
" id: req.params.id\n" +
" }\n" +
" });\n" +
" });\n" +
"\n" +
" fooBarRouter.put('/:id', function(req, res) {\n" +
" res.send({\n" +
" 'foo-bar': {\n" +
" id: req.params.id\n" +
" }\n" +
" });\n" +
" });\n" +
"\n" +
" fooBarRouter.delete('/:id', function(req, res) {\n" +
" res.status(204).end();\n" +
" });\n" +
"\n" +
" // The POST and PUT call will not contain a request body\n" +
" // because the body-parser is not included by default.\n" +
" // To use req.body, run:\n" +
"\n" +
" // npm install --save-dev body-parser\n" +
"\n" +
" // After installing, you need to `use` the body-parser for\n" +
" // this mock uncommenting the following line:\n" +
" //\n" +
" //app.use('/api/foo-bar', require('body-parser').json());\n" +
" app.use('/api/foo-bar', fooBarRouter);\n" +
"};");
expect(file('server/.jshintrc'))
.to.contain('{\n "node": true\n}');
});
});
it('http-proxy foo', function() {
return generate(['http-proxy', 'foo', 'http://localhost:5000']).then(function() {
expect(file('server/index.js'))
.to.contain("proxies.forEach(function(route) { route(app); });");
expect(file('server/proxies/foo.js'))
.to.contain("var proxyPath = '/foo';\n" +
"\n" +
"module.exports = function(app) {\n" +
" // For options, see:\n" +
" // https://github.com/nodejitsu/node-http-proxy\n" +
" var proxy = require('http-proxy').createProxyServer({});\n" +
"\n" +
" proxy.on('error', function(err, req) {\n" +
" console.error(err, req.url);\n" +
" });\n" +
"\n" +
" app.use(proxyPath, function(req, res, next){\n" +
" // include root path in proxied request\n" +
" req.url = proxyPath + '/' + req.url;\n" +
" proxy.web(req, res, { target: 'http://localhost:5000' });\n" +
" });\n" +
"};");
expect(file('server/.jshintrc'))
.to.contain('{\n "node": true\n}');
});
});
it('uses blueprints from the project directory', function() {
return initApp()
.then(function() {
return outputFile(
'blueprints/foo/files/app/foos/__name__.js',
"import Ember from 'ember';\n" +
'export default Ember.Object.extend({ foo: true });\n'
);
})
.then(function() {
return ember(['generate', 'foo', 'bar']);
})
.then(function() {
expect(file('app/foos/bar.js')).to.contain('foo: true');
});
});
it('allows custom blueprints to override built-ins', function() {
return initApp()
.then(function() {
return outputFile(
'blueprints/controller/files/app/controllers/__name__.js',
"import Ember from 'ember';\n\n" +
"export default Ember.Controller.extend({ custom: true });\n"
);
})
.then(function() {
return ember(['generate', 'controller', 'foo']);
})
.then(function() {
expect(file('app/controllers/foo.js')).to.contain('custom: true');
});
});
it('passes custom cli arguments to blueprint options', function() {
return initApp()
.then(function() {
outputFile(
'blueprints/customblue/files/app/__name__.js',
"Q: Can I has custom command? A: <%= hasCustomCommand %>"
);
return outputFile(
'blueprints/customblue/index.js',
"module.exports = {\n" +
" locals: function(options) {\n" +
" var loc = {};\n" +
" loc.hasCustomCommand = (options.customCommand) ? 'Yes!' : 'No. :C';\n" +
" return loc;\n" +
" },\n" +
"};\n"
);
})
.then(function() {
return ember(['generate', 'customblue', 'foo', '--custom-command']);
})
.then(function() {
expect(file('app/foo.js')).to.contain('A: Yes!');
});
});
it('correctly identifies the root of the project', function() {
return initApp()
.then(function() {
return outputFile(
'blueprints/controller/files/app/controllers/__name__.js',
"import Ember from 'ember';\n\n" +
"export default Ember.Controller.extend({ custom: true });\n"
);
})
.then(function() {
process.chdir(path.join(tmpdir, 'app'));
})
.then(function() {
return ember(['generate', 'controller', 'foo']);
})
.then(function() {
process.chdir(tmpdir);
})
.then(function() {
expect(file('app/controllers/foo.js')).to.contain('custom: true');
});
});
it('route foo --dry-run does not change router.js', function() {
return generate(['route', 'foo', '--dry-run']).then(function() {
expect(file('app/router.js')).to.not.contain("route('foo')");
});
});
it('server', function() {
return generate(['server']).then(function() {
expect(file('server/index.js')).to.exist;
expect(file('server/.jshintrc')).to.exist;
});
});
it('availableOptions work with aliases.', function() {
return generate(['route', 'foo', '-d']).then(function() {
expect(file('app/router.js')).to.not.contain("route('foo')");
});
});
it('lib', function() {
return generate(['lib']).then(function() {
expect(file('lib/.jshintrc')).to.exist;
});
});
it('custom blueprint availableOptions', function() {
return initApp().then(function() {
return ember(['generate', 'blueprint', 'foo']).then(function() {
replaceFile('blueprints/foo/index.js', 'module.exports = {',
'module.exports = {\navailableOptions: [ \n' +
'{ name: \'foo\',\ntype: String, \n' +
'values: [\'one\', \'two\'],\n' +
'default: \'one\',\n' +
'aliases: [ {\'one\': \'one\'}, {\'two\': \'two\'} ] } ],\n' +
'locals: function(options) {\n' +
'return { foo: options.foo };\n' +
'},');
return outputFile(
'blueprints/foo/files/app/foos/__name__.js',
"import Ember from 'ember';\n" +
'export default Ember.Object.extend({ foo: <%= foo %> });\n'
).then(function() {
return ember(['generate','foo','bar','-two']);
});
});
}).then(function() {
expect(file('app/foos/bar.js')).to.contain('export default Ember.Object.extend({ foo: two });');
});
});
});
| lazybensch/ember-cli | tests/acceptance/generate-test.js | JavaScript | mit | 16,507 |
module.exports={A:{A:{"1":"A B","2":"I C G E SB"},B:{"1":"D g q K"},C:{"1":"0 1 2 F H I C G E A B D g q K L M N O P Q R S T U V s X Y Z a b c d e f J h i j k l m n o p u v w t y r W","2":"3 QB OB NB"},D:{"1":"0 1 2 6 9 K L M N O P Q R S T U V s X Y Z a b c d e f J h i j k l m n o p u v w t y r W CB RB AB","16":"F H I C G E A B D g q"},E:{"1":"H I C G E A DB EB FB GB HB IB","2":"7 F BB"},F:{"1":"K L M N O P Q R S T U V s X Y Z a b c d e f J h i j k l m n o p","16":"E JB","132":"4 5 B D KB LB MB PB z"},G:{"1":"G TB UB VB WB XB YB ZB aB","2":"7 8 x"},H:{"132":"bB"},I:{"1":"3 F W eB fB x gB hB","16":"cB dB"},J:{"1":"C A"},K:{"1":"J","132":"4 5 A B D z"},L:{"1":"6"},M:{"1":"r"},N:{"1":"A B"},O:{"1":"iB"},P:{"1":"F H"},Q:{"1":"jB"},R:{"1":"kB"}},B:7,C:":optional CSS pseudo-class"};
| keeyanajones/Samples | streamingProject/twitch/bots/NodeJsChatBot/node_modules/caniuse-lite/data/features/css-optional-pseudo.js | JavaScript | mit | 787 |
import Ember from 'ember';
import { module, test } from 'qunit';
import Confirmation from 'ember-validations/validators/local/confirmation';
import Mixin from 'ember-validations/mixin';
import buildContainer from '../../../helpers/build-container';
var model, Model, options, validator;
var get = Ember.get;
var set = Ember.set;
var run = Ember.run;
module('Confirmation Validator', {
setup: function() {
Model = Ember.Object.extend(Mixin, {
container: buildContainer()
});
run(function() {
model = Model.create();
});
}
});
test('when values match', function(assert) {
options = { message: 'failed validation' };
run(function() {
validator = Confirmation.create({model: model, property: 'attribute', options: options});
set(model, 'attribute', 'test');
set(model, 'attributeConfirmation', 'test');
});
assert.deepEqual(validator.errors, []);
run(function() {
set(model, 'attributeConfirmation', 'newTest');
});
assert.deepEqual(validator.errors, ['failed validation']);
run(function() {
set(model, 'attribute', 'newTest');
});
assert.deepEqual(validator.errors, []);
});
test('when values do not match', function(assert) {
options = { message: 'failed validation' };
run(function() {
validator = Confirmation.create({model: model, property: 'attribute', options: options});
set(model, 'attribute', 'test');
});
assert.deepEqual(validator.errors, ['failed validation']);
});
test('when original is null', function(assert) {
run(function() {
validator = Confirmation.create({model: model, property: 'attribute'});
model.set('attribute', null);
});
assert.ok(Ember.isEmpty(validator.errors));
});
test('when confirmation is null', function(assert) {
run(function() {
validator = Confirmation.create({model: model, property: 'attribute'});
model.set('attributeConfirmation', null);
});
assert.ok(Ember.isEmpty(validator.errors));
});
test('when options is true', function(assert) {
options = true;
run(function() {
validator = Confirmation.create({model: model, property: 'attribute', options: options});
set(model, 'attribute', 'test');
});
assert.deepEqual(validator.errors, ["doesn't match attribute"]);
});
test('message integration on model, prints message on Confirmation property', function(assert) {
var otherModel, OtherModel = Model.extend({
validations: {
attribute: {
confirmation: true
}
}
});
run(function() {
otherModel = OtherModel.create();
set(otherModel, 'attribute', 'test');
});
assert.deepEqual(get(otherModel, 'errors.attributeConfirmation'), ["doesn't match attribute"]);
assert.deepEqual(get(otherModel, 'errors.attribute'), []);
});
| meszike123/ember-validations | tests/unit/validators/local/confirmation-test.js | JavaScript | mit | 2,746 |
'use strict';
const existsSync = require('exists-sync');
const path = require('path');
const LiveReloadServer = require('./server/livereload-server');
const ExpressServer = require('./server/express-server');
const RSVP = require('rsvp');
const Task = require('../models/task');
const Watcher = require('../models/watcher');
const ServerWatcher = require('../models/server-watcher');
const Builder = require('../models/builder');
const Promise = RSVP.Promise;
class ServeTask extends Task {
constructor(options) {
super(options);
this._runDeferred = null;
this._builder = null;
}
run(options) {
let builder = this._builder = options._builder || new Builder({
ui: this.ui,
outputPath: options.outputPath,
project: this.project,
environment: options.environment,
});
let watcher = options._watcher || new Watcher({
ui: this.ui,
builder,
analytics: this.analytics,
options,
serving: true,
});
let serverRoot = './server';
let serverWatcher = null;
if (existsSync(serverRoot)) {
serverWatcher = new ServerWatcher({
ui: this.ui,
analytics: this.analytics,
watchedDir: path.resolve(serverRoot),
options,
});
}
let expressServer = options._expressServer || new ExpressServer({
ui: this.ui,
project: this.project,
watcher,
serverRoot,
serverWatcher,
});
let liveReloadServer = options._liveReloadServer || new LiveReloadServer({
ui: this.ui,
analytics: this.analytics,
project: this.project,
watcher,
expressServer,
});
/* hang until the user exits */
this._runDeferred = RSVP.defer();
return Promise.all([
liveReloadServer.start(options),
expressServer.start(options),
]).then(() => this._runDeferred.promise);
}
/**
* Exit silently
*
* @private
* @method onInterrupt
*/
onInterrupt() {
return this._builder.cleanup().then(() => this._runDeferred.resolve());
}
}
module.exports = ServeTask;
| gabz75/ember-cli-deploy-redis-publish | node_modules/ember-cli/lib/tasks/serve.js | JavaScript | mit | 2,076 |
/*
Copyright (c) 2011 Eli Grey, http://eligrey.com
This file is based on:
https://github.com/eligrey/FileSaver.js/blob/master/FileSaver.js ,
licensed under X11/MIT.
See https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md
This file is part of SwitchySharp.
SwitchySharp 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.
SwitchySharp 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 SwitchySharp. If not, see <http://www.gnu.org/licenses/>.
*/
var saveAs = saveAs || (function (view) {
"use strict";
var
doc = view.document
// only get URL when necessary in case BlobBuilder.js hasn't overridden it yet
, get_URL = function () {
return view.URL || view.webkitURL || view;
}
, URL = view.URL || view.webkitURL || view
, save_link = doc.createElementNS("http://www.w3.org/1999/xhtml", "a")
, can_use_save_link = "download" in save_link
, click = function (node) {
var event = doc.createEvent("MouseEvents");
event.initMouseEvent(
"click", true, false, view, 0, 0, 0, 0, 0
, false, false, false, false, 0, null
);
return node.dispatchEvent(event); // false if event was cancelled
}
, webkit_req_fs = view.webkitRequestFileSystem
, req_fs = view.requestFileSystem || webkit_req_fs || view.mozRequestFileSystem
, throw_outside = function (ex) {
(view.setImmediate || view.setTimeout)(function () {
throw ex;
}, 0);
}
, force_saveable_type = "application/octet-stream"
, fs_min_size = 0
, deletion_queue = []
, process_deletion_queue = function () {
var i = deletion_queue.length;
while (i--) {
var file = deletion_queue[i];
if (typeof file === "string") { // file is an object URL
URL.revokeObjectURL(file);
} else { // file is a File
file.remove();
}
}
deletion_queue.length = 0; // clear queue
}
, dispatch = function (filesaver, event_types, event) {
event_types = [].concat(event_types);
var i = event_types.length;
while (i--) {
var listener = filesaver["on" + event_types[i]];
if (typeof listener === "function") {
try {
listener.call(filesaver, event || filesaver);
} catch (ex) {
throw_outside(ex);
}
}
}
}
, FileSaver = function (blob, name) {
// First try a.download, then web filesystem, then object URLs
var
filesaver = this
, type = blob.type
, blob_changed = false
, object_url
, target_view
, get_object_url = function (blob) {
var object_url = get_URL().createObjectURL(blob);
deletion_queue.push(object_url);
return object_url;
}
, dispatch_all = function () {
dispatch(filesaver, "writestart progress write writeend".split(" "));
}
// on any filesys errors revert to saving with object URLs
, fs_error = function () {
// don't create more object URLs than needed
if (blob_changed || !object_url) {
object_url = get_object_url(blob);
}
target_view.location.href = object_url;
filesaver.readyState = filesaver.DONE;
dispatch_all();
}
, abortable = function (func) {
return function () {
if (filesaver.readyState !== filesaver.DONE) {
return func.apply(this, arguments);
}
};
}
, create_if_not_found = {create:true, exclusive:false}
, slice
;
filesaver.readyState = filesaver.INIT;
if (!name) {
name = "download";
}
if (can_use_save_link) {
object_url = get_object_url(blob);
save_link.href = object_url;
save_link.download = name;
if (click(save_link)) {
filesaver.readyState = filesaver.DONE;
dispatch_all();
return;
}
}
// Object and web filesystem URLs have a problem saving in Google Chrome when
// viewed in a tab, so I force save with application/octet-stream
// http://code.google.com/p/chromium/issues/detail?id=91158
if (view.chrome && type && type !== force_saveable_type) {
slice = blob.slice || blob.webkitSlice;
blob = slice.call(blob, 0, blob.size, force_saveable_type);
blob_changed = true;
}
// Since I can't be sure that the guessed media type will trigger a download
// in WebKit, I append .download to the filename.
// https://bugs.webkit.org/show_bug.cgi?id=65440
//if (webkit_req_fs && name !== "download") {
// name += ".download";
//}
if (type === force_saveable_type || webkit_req_fs) {
target_view = view;
} else {
target_view = view.open();
}
if (!req_fs) {
fs_error();
return;
}
fs_min_size += blob.size;
req_fs(view.TEMPORARY, fs_min_size, abortable(function (fs) {
fs.root.getDirectory("saved", create_if_not_found, abortable(function (dir) {
var save = function () {
dir.getFile(name, create_if_not_found, abortable(function (file) {
file.createWriter(abortable(function (writer) {
writer.onwriteend = function (event) {
target_view.location.href = file.toURL();
deletion_queue.push(file);
filesaver.readyState = filesaver.DONE;
dispatch(filesaver, "writeend", event);
};
writer.onerror = function () {
var error = writer.error;
if (error.code !== error.ABORT_ERR) {
fs_error();
}
};
"writestart progress write abort".split(" ").forEach(function (event) {
writer["on" + event] = filesaver["on" + event];
});
writer.write(blob);
filesaver.abort = function () {
writer.abort();
filesaver.readyState = filesaver.DONE;
};
filesaver.readyState = filesaver.WRITING;
}), fs_error);
}), fs_error);
};
dir.getFile(name, {create:false}, abortable(function (file) {
// delete file if it already exists
file.remove();
save();
}), abortable(function (ex) {
if (ex.code === ex.NOT_FOUND_ERR) {
save();
} else {
fs_error();
}
}));
}), fs_error);
}), fs_error);
}
, FS_proto = FileSaver.prototype
, saveAs = function (blob, name) {
return new FileSaver(blob, name);
}
;
FS_proto.abort = function () {
var filesaver = this;
filesaver.readyState = filesaver.DONE;
dispatch(filesaver, "abort");
};
FS_proto.readyState = FS_proto.INIT = 0;
FS_proto.WRITING = 1;
FS_proto.DONE = 2;
FS_proto.error =
FS_proto.onwritestart =
FS_proto.onprogress =
FS_proto.onwrite =
FS_proto.onabort =
FS_proto.onerror =
FS_proto.onwriteend =
null;
view.addEventListener("unload", process_deletion_queue, false);
return saveAs;
}(self));
| FrankLiu/nscrapy | plugin/SwitchySharp/assets/libs/FileSaver.js | JavaScript | apache-2.0 | 9,450 |
(function(__global) {
var isWorker = typeof window == 'undefined' && typeof self != 'undefined' && typeof importScripts != 'undefined';
var isBrowser = typeof window != 'undefined' && typeof document != 'undefined';
var isWindows = typeof process != 'undefined' && typeof process.platform != 'undefined' && !!process.platform.match(/^win/);
if (!__global.console)
__global.console = { assert: function() {} };
// IE8 support
var indexOf = Array.prototype.indexOf || function(item) {
for (var i = 0, thisLen = this.length; i < thisLen; i++) {
if (this[i] === item) {
return i;
}
}
return -1;
};
var defineProperty;
(function () {
try {
if (!!Object.defineProperty({}, 'a', {}))
defineProperty = Object.defineProperty;
}
catch (e) {
defineProperty = function(obj, prop, opt) {
try {
obj[prop] = opt.value || opt.get.call(obj);
}
catch(e) {}
}
}
})();
function addToError(err, msg) {
var newErr;
if (err instanceof Error) {
newErr = new Error(err.message, err.fileName, err.lineNumber);
if (isBrowser) {
newErr.message = err.message + '\n\t' + msg;
newErr.stack = err.stack;
}
else {
// node errors only look correct with the stack modified
newErr.message = err.message;
newErr.stack = err.stack + '\n\t' + msg;
}
}
else {
newErr = err + '\n\t' + msg;
}
return newErr;
}
function __eval(source, debugName, context) {
try {
new Function(source).call(context);
}
catch(e) {
throw addToError(e, 'Evaluating ' + debugName);
}
}
var baseURI;
// environent baseURI detection
if (typeof document != 'undefined' && document.getElementsByTagName) {
baseURI = document.baseURI;
if (!baseURI) {
var bases = document.getElementsByTagName('base');
baseURI = bases[0] && bases[0].href || window.location.href;
}
// sanitize out the hash and querystring
baseURI = baseURI.split('#')[0].split('?')[0];
baseURI = baseURI.substr(0, baseURI.lastIndexOf('/') + 1);
}
else if (typeof process != 'undefined' && process.cwd) {
baseURI = 'file://' + (isWindows ? '/' : '') + process.cwd() + '/';
if (isWindows)
baseURI = baseURI.replace(/\\/g, '/');
}
else if (typeof location != 'undefined') {
baseURI = __global.location.href;
}
else {
throw new TypeError('No environment baseURI');
}
var URL = __global.URLPolyfill || __global.URL;
| ApprecieOpenSource/Apprecie | public/a/node_modules/es6-module-loader/src/wrapper-start.js | JavaScript | mit | 2,575 |
import { Animation } from '../animations/animation';
import { isPresent } from '../util/util';
import { PageTransition } from './page-transition';
const /** @type {?} */ DURATION = 500;
const /** @type {?} */ EASING = 'cubic-bezier(0.36,0.66,0.04,1)';
const /** @type {?} */ OPACITY = 'opacity';
const /** @type {?} */ TRANSFORM = 'transform';
const /** @type {?} */ TRANSLATEX = 'translateX';
const /** @type {?} */ OFF_RIGHT = '99.5%';
const /** @type {?} */ OFF_LEFT = '-33%';
const /** @type {?} */ CENTER = '0%';
const /** @type {?} */ OFF_OPACITY = 0.8;
const /** @type {?} */ SHOW_BACK_BTN_CSS = 'show-back-button';
export class IOSTransition extends PageTransition {
/**
* @return {?}
*/
init() {
super.init();
const /** @type {?} */ plt = this.plt;
const /** @type {?} */ enteringView = this.enteringView;
const /** @type {?} */ leavingView = this.leavingView;
const /** @type {?} */ opts = this.opts;
this.duration(isPresent(opts.duration) ? opts.duration : DURATION);
this.easing(isPresent(opts.easing) ? opts.easing : EASING);
const /** @type {?} */ backDirection = (opts.direction === 'back');
const /** @type {?} */ enteringHasNavbar = (enteringView && enteringView.hasNavbar());
const /** @type {?} */ leavingHasNavbar = (leavingView && leavingView.hasNavbar());
if (enteringView) {
// get the native element for the entering page
const /** @type {?} */ enteringPageEle = enteringView.pageRef().nativeElement;
// entering content
const /** @type {?} */ enteringContent = new Animation(plt, enteringView.contentRef());
enteringContent.element(enteringPageEle.querySelectorAll('ion-header > *:not(ion-navbar),ion-footer > *'));
this.add(enteringContent);
if (backDirection) {
// entering content, back direction
enteringContent
.fromTo(TRANSLATEX, OFF_LEFT, CENTER, true)
.fromTo(OPACITY, OFF_OPACITY, 1, true);
}
else {
// entering content, forward direction
enteringContent
.beforeClearStyles([OPACITY])
.fromTo(TRANSLATEX, OFF_RIGHT, CENTER, true);
}
if (enteringHasNavbar) {
// entering page has a navbar
const /** @type {?} */ enteringNavbarEle = enteringPageEle.querySelector('ion-navbar');
const /** @type {?} */ enteringNavBar = new Animation(plt, enteringNavbarEle);
this.add(enteringNavBar);
const /** @type {?} */ enteringTitle = new Animation(plt, enteringNavbarEle.querySelector('ion-title'));
const /** @type {?} */ enteringNavbarItems = new Animation(plt, enteringNavbarEle.querySelectorAll('ion-buttons,[menuToggle]'));
const /** @type {?} */ enteringNavbarBg = new Animation(plt, enteringNavbarEle.querySelector('.toolbar-background'));
const /** @type {?} */ enteringBackButton = new Animation(plt, enteringNavbarEle.querySelector('.back-button'));
enteringNavBar
.add(enteringTitle)
.add(enteringNavbarItems)
.add(enteringNavbarBg)
.add(enteringBackButton);
enteringTitle.fromTo(OPACITY, 0.01, 1, true);
enteringNavbarItems.fromTo(OPACITY, 0.01, 1, true);
// set properties depending on direction
if (backDirection) {
// entering navbar, back direction
enteringTitle.fromTo(TRANSLATEX, OFF_LEFT, CENTER, true);
if (enteringView.enableBack()) {
// back direction, entering page has a back button
enteringBackButton
.beforeAddClass(SHOW_BACK_BTN_CSS)
.fromTo(OPACITY, 0.01, 1, true);
}
}
else {
// entering navbar, forward direction
enteringTitle.fromTo(TRANSLATEX, OFF_RIGHT, CENTER, true);
enteringNavbarBg
.beforeClearStyles([OPACITY])
.fromTo(TRANSLATEX, OFF_RIGHT, CENTER, true);
if (enteringView.enableBack()) {
// forward direction, entering page has a back button
enteringBackButton
.beforeAddClass(SHOW_BACK_BTN_CSS)
.fromTo(OPACITY, 0.01, 1, true);
const /** @type {?} */ enteringBackBtnText = new Animation(plt, enteringNavbarEle.querySelector('.back-button-text'));
enteringBackBtnText.fromTo(TRANSLATEX, '100px', '0px');
enteringNavBar.add(enteringBackBtnText);
}
else {
enteringBackButton.beforeRemoveClass(SHOW_BACK_BTN_CSS);
}
}
}
}
// setup leaving view
if (leavingView && leavingView.pageRef()) {
// leaving content
const /** @type {?} */ leavingPageEle = leavingView.pageRef().nativeElement;
const /** @type {?} */ leavingContent = new Animation(plt, leavingView.contentRef());
leavingContent.element(leavingPageEle.querySelectorAll('ion-header > *:not(ion-navbar),ion-footer > *'));
this.add(leavingContent);
if (backDirection) {
// leaving content, back direction
leavingContent
.beforeClearStyles([OPACITY])
.fromTo(TRANSLATEX, CENTER, '100%');
}
else {
// leaving content, forward direction
leavingContent
.fromTo(TRANSLATEX, CENTER, OFF_LEFT)
.fromTo(OPACITY, 1, OFF_OPACITY)
.afterClearStyles([TRANSFORM, OPACITY]);
}
if (leavingHasNavbar) {
// leaving page has a navbar
const /** @type {?} */ leavingNavbarEle = leavingPageEle.querySelector('ion-navbar');
const /** @type {?} */ leavingNavBar = new Animation(plt, leavingNavbarEle);
const /** @type {?} */ leavingTitle = new Animation(plt, leavingNavbarEle.querySelector('ion-title'));
const /** @type {?} */ leavingNavbarItems = new Animation(plt, leavingNavbarEle.querySelectorAll('ion-buttons,[menuToggle]'));
const /** @type {?} */ leavingNavbarBg = new Animation(plt, leavingNavbarEle.querySelector('.toolbar-background'));
const /** @type {?} */ leavingBackButton = new Animation(plt, leavingNavbarEle.querySelector('.back-button'));
leavingNavBar
.add(leavingTitle)
.add(leavingNavbarItems)
.add(leavingBackButton)
.add(leavingNavbarBg);
this.add(leavingNavBar);
// fade out leaving navbar items
leavingBackButton.fromTo(OPACITY, 0.99, 0);
leavingTitle.fromTo(OPACITY, 0.99, 0);
leavingNavbarItems.fromTo(OPACITY, 0.99, 0);
if (backDirection) {
// leaving navbar, back direction
leavingTitle.fromTo(TRANSLATEX, CENTER, '100%');
// leaving navbar, back direction, and there's no entering navbar
// should just slide out, no fading out
leavingNavbarBg
.beforeClearStyles([OPACITY])
.fromTo(TRANSLATEX, CENTER, '100%');
let /** @type {?} */ leavingBackBtnText = new Animation(plt, leavingNavbarEle.querySelector('.back-button-text'));
leavingBackBtnText.fromTo(TRANSLATEX, CENTER, (300) + 'px');
leavingNavBar.add(leavingBackBtnText);
}
else {
// leaving navbar, forward direction
leavingTitle
.fromTo(TRANSLATEX, CENTER, OFF_LEFT)
.afterClearStyles([TRANSFORM]);
leavingBackButton.afterClearStyles([OPACITY]);
leavingTitle.afterClearStyles([OPACITY]);
leavingNavbarItems.afterClearStyles([OPACITY]);
}
}
}
}
}
//# sourceMappingURL=transition-ios.js.map | ortroyaner/GithubFinder | node_modules/ionic-angular/es2015/transitions/transition-ios.js | JavaScript | mit | 8,705 |
'use strict';
var gulp = tars.packages.gulp;
var cache = tars.packages.cache;
var plumber = tars.packages.plumber;
var notifier = tars.helpers.notifier;
var browserSync = tars.packages.browserSync;
var staticFolderName = tars.config.fs.staticFolderName;
/**
* Move fonts-files to dev directory
*/
module.exports = function () {
return gulp.task('other:move-fonts', function () {
return gulp.src('./markup/' + staticFolderName + '/fonts/**/*.*')
.pipe(plumber({
errorHandler: function (error) {
notifier.error('An error occurred while moving fonts.', error);
}
}))
.pipe(cache('move-fonts'))
.pipe(gulp.dest('./dev/' + staticFolderName + '/fonts'))
.pipe(browserSync.reload({ stream: true }))
.pipe(
notifier.success('Fonts\'ve been moved')
);
});
};
| mik639/TZA | tars/tasks/other/move-fonts.js | JavaScript | mit | 923 |
var class_mix_e_r_p_1_1_net_1_1_schemas_1_1_core_1_1_data_1_1_salesperson =
[
[ "Add", "class_mix_e_r_p_1_1_net_1_1_schemas_1_1_core_1_1_data_1_1_salesperson.html#a09c5124ac0346ca253954882b2baf692", null ],
[ "AddOrEdit", "class_mix_e_r_p_1_1_net_1_1_schemas_1_1_core_1_1_data_1_1_salesperson.html#a84c644b0aa4e0436ed6494a6b98b8daf", null ],
[ "BulkImport", "class_mix_e_r_p_1_1_net_1_1_schemas_1_1_core_1_1_data_1_1_salesperson.html#afe6ac4bae7cbc1f24c754c765930c1af", null ],
[ "Count", "class_mix_e_r_p_1_1_net_1_1_schemas_1_1_core_1_1_data_1_1_salesperson.html#a2eae7e989e13feedf0cb4643a7b3a36a", null ],
[ "CountFiltered", "class_mix_e_r_p_1_1_net_1_1_schemas_1_1_core_1_1_data_1_1_salesperson.html#a1e65e12c1dba36f9033c2708c7a84919", null ],
[ "CountWhere", "class_mix_e_r_p_1_1_net_1_1_schemas_1_1_core_1_1_data_1_1_salesperson.html#acd1013cc18d022b9f3033cbaf032efae", null ],
[ "Delete", "class_mix_e_r_p_1_1_net_1_1_schemas_1_1_core_1_1_data_1_1_salesperson.html#aeded2d8819f7f6043d15fe687566ed0d", null ],
[ "Get", "class_mix_e_r_p_1_1_net_1_1_schemas_1_1_core_1_1_data_1_1_salesperson.html#a0992fdeb7754c8e197a72500094c7a8b", null ],
[ "Get", "class_mix_e_r_p_1_1_net_1_1_schemas_1_1_core_1_1_data_1_1_salesperson.html#adb88c943097a1d7ab636531500046df3", null ],
[ "Get", "class_mix_e_r_p_1_1_net_1_1_schemas_1_1_core_1_1_data_1_1_salesperson.html#a18876872d962687244735d92c430bed0", null ],
[ "GetCustomFields", "class_mix_e_r_p_1_1_net_1_1_schemas_1_1_core_1_1_data_1_1_salesperson.html#abe55b0942f682729b34f31f7bed27e45", null ],
[ "GetDisplayFields", "class_mix_e_r_p_1_1_net_1_1_schemas_1_1_core_1_1_data_1_1_salesperson.html#a9dc230551a07158a42d8ce21e2abb798", null ],
[ "GetFiltered", "class_mix_e_r_p_1_1_net_1_1_schemas_1_1_core_1_1_data_1_1_salesperson.html#a900f45806a0cf94a45c6e99f97ae65fd", null ],
[ "GetPagedResult", "class_mix_e_r_p_1_1_net_1_1_schemas_1_1_core_1_1_data_1_1_salesperson.html#aa3d9194e34f9908f9876aec6665422b5", null ],
[ "GetPagedResult", "class_mix_e_r_p_1_1_net_1_1_schemas_1_1_core_1_1_data_1_1_salesperson.html#a6693529ae870edafa6a9ae698c9a2ce4", null ],
[ "GetWhere", "class_mix_e_r_p_1_1_net_1_1_schemas_1_1_core_1_1_data_1_1_salesperson.html#a23e3a32eb78486082c4738c41cf3dd69", null ],
[ "Update", "class_mix_e_r_p_1_1_net_1_1_schemas_1_1_core_1_1_data_1_1_salesperson.html#aa0dc26c6a4c866cddf5dd4d7272627c3", null ],
[ "ObjectName", "class_mix_e_r_p_1_1_net_1_1_schemas_1_1_core_1_1_data_1_1_salesperson.html#a10be6c6b1875bdd156ba1d4c11d8eac9", null ],
[ "ObjectNamespace", "class_mix_e_r_p_1_1_net_1_1_schemas_1_1_core_1_1_data_1_1_salesperson.html#a8960b603ff321c1d4e05c7046fda81cd", null ],
[ "Catalog", "class_mix_e_r_p_1_1_net_1_1_schemas_1_1_core_1_1_data_1_1_salesperson.html#af18cdac10ecaf56d80ca72a63fa03776", null ],
[ "LoginId", "class_mix_e_r_p_1_1_net_1_1_schemas_1_1_core_1_1_data_1_1_salesperson.html#ace99aa8112a764fa4a7bbd564257838e", null ],
[ "UserId", "class_mix_e_r_p_1_1_net_1_1_schemas_1_1_core_1_1_data_1_1_salesperson.html#a1438bbaf3d0555c6102d5606c8bf5dad", null ]
]; | gjms2000/mixerp | docs/api/class_mix_e_r_p_1_1_net_1_1_schemas_1_1_core_1_1_data_1_1_salesperson.js | JavaScript | gpl-2.0 | 3,133 |
t = db.capped1;
t.drop();
db.createCollection("capped1" , {capped:true, size:1024 });
v = t.validate();
assert( v.valid , "A : " + tojson( v ) ); // SERVER-485
t.save( { x : 1 } )
assert( t.validate().valid , "B" )
| barakav/robomongo | src/third-party/mongodb/jstests/capped1.js | JavaScript | gpl-3.0 | 220 |
// Copyright 2015 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Flags: --allow-natives-syntax --harmony-do-expressions
function f(x) {
switch (x) {
case 1: return "one";
case 2: return "two";
case do { for (var i = 0; i < 10; i++) { if (i == 5) %OptimizeOsr(); } }:
case 3: return "WAT";
}
}
assertEquals("one", f(1));
assertEquals("two", f(2));
assertEquals("WAT", f(3));
| macchina-io/macchina.io | platform/JS/V8/v8/test/mjsunit/regress/regress-osr-in-case-label.js | JavaScript | apache-2.0 | 502 |
// Squarified Treemaps by Mark Bruls, Kees Huizing, and Jarke J. van Wijk
// Modified to support a target aspect ratio by Jeff Heer
d3.layout.treemap = function() {
var hierarchy = d3.layout.hierarchy(),
round = Math.round,
size = [1, 1], // width, height
padding = null,
pad = d3_layout_treemapPadNull,
sticky = false,
stickies,
mode = "squarify",
ratio = 0.5 * (1 + Math.sqrt(5)); // golden ratio
// Compute the area for each child based on value & scale.
function scale(children, k) {
var i = -1,
n = children.length,
child,
area;
while (++i < n) {
area = (child = children[i]).value * (k < 0 ? 0 : k);
child.area = isNaN(area) || area <= 0 ? 0 : area;
}
}
// Recursively arranges the specified node's children into squarified rows.
function squarify(node) {
var children = node.children;
if (children && children.length) {
var rect = pad(node),
row = [],
remaining = children.slice(), // copy-on-write
child,
best = Infinity, // the best row score so far
score, // the current row score
u = mode === "slice" ? rect.dx
: mode === "dice" ? rect.dy
: mode === "slice-dice" ? node.depth & 1 ? rect.dy : rect.dx
: Math.min(rect.dx, rect.dy), // initial orientation
n;
scale(remaining, rect.dx * rect.dy / node.value);
row.area = 0;
while ((n = remaining.length) > 0) {
row.push(child = remaining[n - 1]);
row.area += child.area;
if (mode !== "squarify" || (score = worst(row, u)) <= best) { // continue with this orientation
remaining.pop();
best = score;
} else { // abort, and try a different orientation
row.area -= row.pop().area;
position(row, u, rect, false);
u = Math.min(rect.dx, rect.dy);
row.length = row.area = 0;
best = Infinity;
}
}
if (row.length) {
position(row, u, rect, true);
row.length = row.area = 0;
}
children.forEach(squarify);
}
}
// Recursively resizes the specified node's children into existing rows.
// Preserves the existing layout!
function stickify(node) {
var children = node.children;
if (children && children.length) {
var rect = pad(node),
remaining = children.slice(), // copy-on-write
child,
row = [];
scale(remaining, rect.dx * rect.dy / node.value);
row.area = 0;
while (child = remaining.pop()) {
row.push(child);
row.area += child.area;
if (child.z != null) {
position(row, child.z ? rect.dx : rect.dy, rect, !remaining.length);
row.length = row.area = 0;
}
}
children.forEach(stickify);
}
}
// Computes the score for the specified row, as the worst aspect ratio.
function worst(row, u) {
var s = row.area,
r,
rmax = 0,
rmin = Infinity,
i = -1,
n = row.length;
while (++i < n) {
if (!(r = row[i].area)) continue;
if (r < rmin) rmin = r;
if (r > rmax) rmax = r;
}
s *= s;
u *= u;
return s
? Math.max((u * rmax * ratio) / s, s / (u * rmin * ratio))
: Infinity;
}
// Positions the specified row of nodes. Modifies `rect`.
function position(row, u, rect, flush) {
var i = -1,
n = row.length,
x = rect.x,
y = rect.y,
v = u ? round(row.area / u) : 0,
o;
if (u == rect.dx) { // horizontal subdivision
if (flush || v > rect.dy) v = rect.dy; // over+underflow
while (++i < n) {
o = row[i];
o.x = x;
o.y = y;
o.dy = v;
x += o.dx = Math.min(rect.x + rect.dx - x, v ? round(o.area / v) : 0);
}
o.z = true;
o.dx += rect.x + rect.dx - x; // rounding error
rect.y += v;
rect.dy -= v;
} else { // vertical subdivision
if (flush || v > rect.dx) v = rect.dx; // over+underflow
while (++i < n) {
o = row[i];
o.x = x;
o.y = y;
o.dx = v;
y += o.dy = Math.min(rect.y + rect.dy - y, v ? round(o.area / v) : 0);
}
o.z = false;
o.dy += rect.y + rect.dy - y; // rounding error
rect.x += v;
rect.dx -= v;
}
}
function treemap(d) {
var nodes = stickies || hierarchy(d),
root = nodes[0];
root.x = 0;
root.y = 0;
root.dx = size[0];
root.dy = size[1];
if (stickies) hierarchy.revalue(root);
scale([root], root.dx * root.dy / root.value);
(stickies ? stickify : squarify)(root);
if (sticky) stickies = nodes;
return nodes;
}
treemap.size = function(x) {
if (!arguments.length) return size;
size = x;
return treemap;
};
treemap.padding = function(x) {
if (!arguments.length) return padding;
function padFunction(node) {
var p = x.call(treemap, node, node.depth);
return p == null
? d3_layout_treemapPadNull(node)
: d3_layout_treemapPad(node, typeof p === "number" ? [p, p, p, p] : p);
}
function padConstant(node) {
return d3_layout_treemapPad(node, x);
}
var type;
pad = (padding = x) == null ? d3_layout_treemapPadNull
: (type = typeof x) === "function" ? padFunction
: type === "number" ? (x = [x, x, x, x], padConstant)
: padConstant;
return treemap;
};
treemap.round = function(x) {
if (!arguments.length) return round != Number;
round = x ? Math.round : Number;
return treemap;
};
treemap.sticky = function(x) {
if (!arguments.length) return sticky;
sticky = x;
stickies = null;
return treemap;
};
treemap.ratio = function(x) {
if (!arguments.length) return ratio;
ratio = x;
return treemap;
};
treemap.mode = function(x) {
if (!arguments.length) return mode;
mode = x + "";
return treemap;
};
return d3_layout_hierarchyRebind(treemap, hierarchy);
};
function d3_layout_treemapPadNull(node) {
return {x: node.x, y: node.y, dx: node.dx, dy: node.dy};
}
function d3_layout_treemapPad(node, padding) {
var x = node.x + padding[3],
y = node.y + padding[0],
dx = node.dx - padding[1] - padding[3],
dy = node.dy - padding[0] - padding[2];
if (dx < 0) { x += dx / 2; dx = 0; }
if (dy < 0) { y += dy / 2; dy = 0; }
return {x: x, y: y, dx: dx, dy: dy};
}
| zziuni/d3 | src/layout/treemap.js | JavaScript | bsd-3-clause | 6,511 |
version https://git-lfs.github.com/spec/v1
oid sha256:cdaff690080dec73e2f9044eb89e1426fd2645ea6d8b253cd51cd992717b8a06
size 1772
| yogeshsaroya/new-cdnjs | ajax/libs/codemirror/5.1.0/mode/shell/test.js | JavaScript | mit | 129 |
/**
* Authentication controller.
*
* Here we just bind together the Docs.Auth and AuthForm component.
*/
Ext.define('Docs.controller.Auth', {
extend: 'Ext.app.Controller',
requires: [
'Docs.Auth',
'Docs.Comments'
],
refs: [
{
ref: "authHeaderForm",
selector: "authHeaderForm"
}
],
init: function() {
this.control({
'authHeaderForm, authForm': {
login: this.login,
logout: this.logout
}
});
// HACK:
// Because the initialization of comments involves adding an
// additional tab, we need to ensure that we do this addition
// after Tabs controller has been launched.
var tabs = this.getController("Tabs");
tabs.onLaunch = Ext.Function.createSequence(tabs.onLaunch, this.afterTabsLaunch, this);
},
afterTabsLaunch: function() {
if (Docs.Comments.isEnabled()) {
if (Docs.Auth.isLoggedIn()) {
this.setLoggedIn();
}
else {
this.setLoggedOut();
}
}
},
login: function(form, username, password, remember) {
Docs.Auth.login({
username: username,
password: password,
remember: remember,
success: this.setLoggedIn,
failure: function(reason) {
form.showMessage(reason);
},
scope: this
});
},
logout: function(form) {
Docs.Auth.logout(this.setLoggedOut, this);
},
setLoggedIn: function() {
Docs.Comments.loadSubscriptions(function() {
this.getAuthHeaderForm().showLoggedIn(Docs.Auth.getUser());
this.eachCmp("commentsListWithForm", function(list) {
list.showCommentingForm();
});
this.eachCmp("commentsList", function(list) {
list.refresh();
});
this.getController("Tabs").showCommentsTab();
}, this);
},
setLoggedOut: function() {
Docs.Comments.clearSubscriptions();
this.getAuthHeaderForm().showLoggedOut();
this.eachCmp("commentsListWithForm", function(list) {
list.showAuthForm();
});
this.eachCmp("commentsList", function(list) {
list.refresh();
});
this.getController("Tabs").hideCommentsTab();
},
eachCmp: function(selector, callback, scope) {
Ext.Array.forEach(Ext.ComponentQuery.query(selector), callback, scope);
}
});
| ckeditor/jsduck | template/app/controller/Auth.js | JavaScript | gpl-3.0 | 2,613 |
Proj4js.defs["EPSG:4933"] = "+proj=longlat +ellps=GRS80 +towgs84=0.0,0.0,0.0,0.0,0.0,0.0,0.0 +no_defs"; | debard/georchestra-ird | mapfishapp/src/main/webapp/lib/proj4js/lib/defs/EPSG4933.js | JavaScript | gpl-3.0 | 103 |
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('estraverse')) :
typeof define === 'function' && define.amd ? define(['estraverse'], factory) :
(global = global || self, global.esquery = factory(global.estraverse));
}(this, (function (estraverse) { 'use strict';
estraverse = estraverse && Object.prototype.hasOwnProperty.call(estraverse, 'default') ? estraverse['default'] : estraverse;
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function (obj) {
return typeof obj;
};
} else {
_typeof = function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _slicedToArray(arr, i) {
return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
}
function _toConsumableArray(arr) {
return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
}
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) return _arrayLikeToArray(arr);
}
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
function _iterableToArray(iter) {
if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter);
}
function _iterableToArrayLimit(arr, i) {
if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return;
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"] != null) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(o);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
return arr2;
}
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _nonIterableRest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _createForOfIteratorHelper(o, allowArrayLike) {
var it;
if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) {
if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
if (it) o = it;
var i = 0;
var F = function () {};
return {
s: F,
n: function () {
if (i >= o.length) return {
done: true
};
return {
done: false,
value: o[i++]
};
},
e: function (e) {
throw e;
},
f: F
};
}
throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
var normalCompletion = true,
didErr = false,
err;
return {
s: function () {
it = o[Symbol.iterator]();
},
n: function () {
var step = it.next();
normalCompletion = step.done;
return step;
},
e: function (e) {
didErr = true;
err = e;
},
f: function () {
try {
if (!normalCompletion && it.return != null) it.return();
} finally {
if (didErr) throw err;
}
}
};
}
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
var parser = createCommonjsModule(function (module) {
/*
* Generated by PEG.js 0.10.0.
*
* http://pegjs.org/
*/
(function (root, factory) {
if ( module.exports) {
module.exports = factory();
}
})(commonjsGlobal, function () {
function peg$subclass(child, parent) {
function ctor() {
this.constructor = child;
}
ctor.prototype = parent.prototype;
child.prototype = new ctor();
}
function peg$SyntaxError(message, expected, found, location) {
this.message = message;
this.expected = expected;
this.found = found;
this.location = location;
this.name = "SyntaxError";
if (typeof Error.captureStackTrace === "function") {
Error.captureStackTrace(this, peg$SyntaxError);
}
}
peg$subclass(peg$SyntaxError, Error);
peg$SyntaxError.buildMessage = function (expected, found) {
var DESCRIBE_EXPECTATION_FNS = {
literal: function literal(expectation) {
return "\"" + literalEscape(expectation.text) + "\"";
},
"class": function _class(expectation) {
var escapedParts = "",
i;
for (i = 0; i < expectation.parts.length; i++) {
escapedParts += expectation.parts[i] instanceof Array ? classEscape(expectation.parts[i][0]) + "-" + classEscape(expectation.parts[i][1]) : classEscape(expectation.parts[i]);
}
return "[" + (expectation.inverted ? "^" : "") + escapedParts + "]";
},
any: function any(expectation) {
return "any character";
},
end: function end(expectation) {
return "end of input";
},
other: function other(expectation) {
return expectation.description;
}
};
function hex(ch) {
return ch.charCodeAt(0).toString(16).toUpperCase();
}
function literalEscape(s) {
return s.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\0/g, '\\0').replace(/\t/g, '\\t').replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/[\x00-\x0F]/g, function (ch) {
return '\\x0' + hex(ch);
}).replace(/[\x10-\x1F\x7F-\x9F]/g, function (ch) {
return '\\x' + hex(ch);
});
}
function classEscape(s) {
return s.replace(/\\/g, '\\\\').replace(/\]/g, '\\]').replace(/\^/g, '\\^').replace(/-/g, '\\-').replace(/\0/g, '\\0').replace(/\t/g, '\\t').replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/[\x00-\x0F]/g, function (ch) {
return '\\x0' + hex(ch);
}).replace(/[\x10-\x1F\x7F-\x9F]/g, function (ch) {
return '\\x' + hex(ch);
});
}
function describeExpectation(expectation) {
return DESCRIBE_EXPECTATION_FNS[expectation.type](expectation);
}
function describeExpected(expected) {
var descriptions = new Array(expected.length),
i,
j;
for (i = 0; i < expected.length; i++) {
descriptions[i] = describeExpectation(expected[i]);
}
descriptions.sort();
if (descriptions.length > 0) {
for (i = 1, j = 1; i < descriptions.length; i++) {
if (descriptions[i - 1] !== descriptions[i]) {
descriptions[j] = descriptions[i];
j++;
}
}
descriptions.length = j;
}
switch (descriptions.length) {
case 1:
return descriptions[0];
case 2:
return descriptions[0] + " or " + descriptions[1];
default:
return descriptions.slice(0, -1).join(", ") + ", or " + descriptions[descriptions.length - 1];
}
}
function describeFound(found) {
return found ? "\"" + literalEscape(found) + "\"" : "end of input";
}
return "Expected " + describeExpected(expected) + " but " + describeFound(found) + " found.";
};
function peg$parse(input, options) {
options = options !== void 0 ? options : {};
var peg$FAILED = {},
peg$startRuleFunctions = {
start: peg$parsestart
},
peg$startRuleFunction = peg$parsestart,
peg$c0 = function peg$c0(ss) {
return ss.length === 1 ? ss[0] : {
type: 'matches',
selectors: ss
};
},
peg$c1 = function peg$c1() {
return void 0;
},
peg$c2 = " ",
peg$c3 = peg$literalExpectation(" ", false),
peg$c4 = /^[^ [\],():#!=><~+.]/,
peg$c5 = peg$classExpectation([" ", "[", "]", ",", "(", ")", ":", "#", "!", "=", ">", "<", "~", "+", "."], true, false),
peg$c6 = function peg$c6(i) {
return i.join('');
},
peg$c7 = ">",
peg$c8 = peg$literalExpectation(">", false),
peg$c9 = function peg$c9() {
return 'child';
},
peg$c10 = "~",
peg$c11 = peg$literalExpectation("~", false),
peg$c12 = function peg$c12() {
return 'sibling';
},
peg$c13 = "+",
peg$c14 = peg$literalExpectation("+", false),
peg$c15 = function peg$c15() {
return 'adjacent';
},
peg$c16 = function peg$c16() {
return 'descendant';
},
peg$c17 = ",",
peg$c18 = peg$literalExpectation(",", false),
peg$c19 = function peg$c19(s, ss) {
return [s].concat(ss.map(function (s) {
return s[3];
}));
},
peg$c20 = function peg$c20(a, ops) {
return ops.reduce(function (memo, rhs) {
return {
type: rhs[0],
left: memo,
right: rhs[1]
};
}, a);
},
peg$c21 = "!",
peg$c22 = peg$literalExpectation("!", false),
peg$c23 = function peg$c23(subject, as) {
var b = as.length === 1 ? as[0] : {
type: 'compound',
selectors: as
};
if (subject) b.subject = true;
return b;
},
peg$c24 = "*",
peg$c25 = peg$literalExpectation("*", false),
peg$c26 = function peg$c26(a) {
return {
type: 'wildcard',
value: a
};
},
peg$c27 = "#",
peg$c28 = peg$literalExpectation("#", false),
peg$c29 = function peg$c29(i) {
return {
type: 'identifier',
value: i
};
},
peg$c30 = "[",
peg$c31 = peg$literalExpectation("[", false),
peg$c32 = "]",
peg$c33 = peg$literalExpectation("]", false),
peg$c34 = function peg$c34(v) {
return v;
},
peg$c35 = /^[><!]/,
peg$c36 = peg$classExpectation([">", "<", "!"], false, false),
peg$c37 = "=",
peg$c38 = peg$literalExpectation("=", false),
peg$c39 = function peg$c39(a) {
return (a || '') + '=';
},
peg$c40 = /^[><]/,
peg$c41 = peg$classExpectation([">", "<"], false, false),
peg$c42 = ".",
peg$c43 = peg$literalExpectation(".", false),
peg$c44 = function peg$c44(a, as) {
return [].concat.apply([a], as).join('');
},
peg$c45 = function peg$c45(name, op, value) {
return {
type: 'attribute',
name: name,
operator: op,
value: value
};
},
peg$c46 = function peg$c46(name) {
return {
type: 'attribute',
name: name
};
},
peg$c47 = "\"",
peg$c48 = peg$literalExpectation("\"", false),
peg$c49 = /^[^\\"]/,
peg$c50 = peg$classExpectation(["\\", "\""], true, false),
peg$c51 = "\\",
peg$c52 = peg$literalExpectation("\\", false),
peg$c53 = peg$anyExpectation(),
peg$c54 = function peg$c54(a, b) {
return a + b;
},
peg$c55 = function peg$c55(d) {
return {
type: 'literal',
value: strUnescape(d.join(''))
};
},
peg$c56 = "'",
peg$c57 = peg$literalExpectation("'", false),
peg$c58 = /^[^\\']/,
peg$c59 = peg$classExpectation(["\\", "'"], true, false),
peg$c60 = /^[0-9]/,
peg$c61 = peg$classExpectation([["0", "9"]], false, false),
peg$c62 = function peg$c62(a, b) {
// Can use `a.flat().join('')` once supported
var leadingDecimals = a ? [].concat.apply([], a).join('') : '';
return {
type: 'literal',
value: parseFloat(leadingDecimals + b.join(''))
};
},
peg$c63 = function peg$c63(i) {
return {
type: 'literal',
value: i
};
},
peg$c64 = "type(",
peg$c65 = peg$literalExpectation("type(", false),
peg$c66 = /^[^ )]/,
peg$c67 = peg$classExpectation([" ", ")"], true, false),
peg$c68 = ")",
peg$c69 = peg$literalExpectation(")", false),
peg$c70 = function peg$c70(t) {
return {
type: 'type',
value: t.join('')
};
},
peg$c71 = /^[imsu]/,
peg$c72 = peg$classExpectation(["i", "m", "s", "u"], false, false),
peg$c73 = "/",
peg$c74 = peg$literalExpectation("/", false),
peg$c75 = /^[^\/]/,
peg$c76 = peg$classExpectation(["/"], true, false),
peg$c77 = function peg$c77(d, flgs) {
return {
type: 'regexp',
value: new RegExp(d.join(''), flgs ? flgs.join('') : '')
};
},
peg$c78 = function peg$c78(i, is) {
return {
type: 'field',
name: is.reduce(function (memo, p) {
return memo + p[0] + p[1];
}, i)
};
},
peg$c79 = ":not(",
peg$c80 = peg$literalExpectation(":not(", false),
peg$c81 = function peg$c81(ss) {
return {
type: 'not',
selectors: ss
};
},
peg$c82 = ":matches(",
peg$c83 = peg$literalExpectation(":matches(", false),
peg$c84 = function peg$c84(ss) {
return {
type: 'matches',
selectors: ss
};
},
peg$c85 = ":has(",
peg$c86 = peg$literalExpectation(":has(", false),
peg$c87 = function peg$c87(ss) {
return {
type: 'has',
selectors: ss
};
},
peg$c88 = ":first-child",
peg$c89 = peg$literalExpectation(":first-child", false),
peg$c90 = function peg$c90() {
return nth(1);
},
peg$c91 = ":last-child",
peg$c92 = peg$literalExpectation(":last-child", false),
peg$c93 = function peg$c93() {
return nthLast(1);
},
peg$c94 = ":nth-child(",
peg$c95 = peg$literalExpectation(":nth-child(", false),
peg$c96 = function peg$c96(n) {
return nth(parseInt(n.join(''), 10));
},
peg$c97 = ":nth-last-child(",
peg$c98 = peg$literalExpectation(":nth-last-child(", false),
peg$c99 = function peg$c99(n) {
return nthLast(parseInt(n.join(''), 10));
},
peg$c100 = ":",
peg$c101 = peg$literalExpectation(":", false),
peg$c102 = "statement",
peg$c103 = peg$literalExpectation("statement", true),
peg$c104 = "expression",
peg$c105 = peg$literalExpectation("expression", true),
peg$c106 = "declaration",
peg$c107 = peg$literalExpectation("declaration", true),
peg$c108 = "function",
peg$c109 = peg$literalExpectation("function", true),
peg$c110 = "pattern",
peg$c111 = peg$literalExpectation("pattern", true),
peg$c112 = function peg$c112(c) {
return {
type: 'class',
name: c
};
},
peg$currPos = 0,
peg$posDetailsCache = [{
line: 1,
column: 1
}],
peg$maxFailPos = 0,
peg$maxFailExpected = [],
peg$resultsCache = {},
peg$result;
if ("startRule" in options) {
if (!(options.startRule in peg$startRuleFunctions)) {
throw new Error("Can't start parsing from rule \"" + options.startRule + "\".");
}
peg$startRuleFunction = peg$startRuleFunctions[options.startRule];
}
function peg$literalExpectation(text, ignoreCase) {
return {
type: "literal",
text: text,
ignoreCase: ignoreCase
};
}
function peg$classExpectation(parts, inverted, ignoreCase) {
return {
type: "class",
parts: parts,
inverted: inverted,
ignoreCase: ignoreCase
};
}
function peg$anyExpectation() {
return {
type: "any"
};
}
function peg$endExpectation() {
return {
type: "end"
};
}
function peg$computePosDetails(pos) {
var details = peg$posDetailsCache[pos],
p;
if (details) {
return details;
} else {
p = pos - 1;
while (!peg$posDetailsCache[p]) {
p--;
}
details = peg$posDetailsCache[p];
details = {
line: details.line,
column: details.column
};
while (p < pos) {
if (input.charCodeAt(p) === 10) {
details.line++;
details.column = 1;
} else {
details.column++;
}
p++;
}
peg$posDetailsCache[pos] = details;
return details;
}
}
function peg$computeLocation(startPos, endPos) {
var startPosDetails = peg$computePosDetails(startPos),
endPosDetails = peg$computePosDetails(endPos);
return {
start: {
offset: startPos,
line: startPosDetails.line,
column: startPosDetails.column
},
end: {
offset: endPos,
line: endPosDetails.line,
column: endPosDetails.column
}
};
}
function peg$fail(expected) {
if (peg$currPos < peg$maxFailPos) {
return;
}
if (peg$currPos > peg$maxFailPos) {
peg$maxFailPos = peg$currPos;
peg$maxFailExpected = [];
}
peg$maxFailExpected.push(expected);
}
function peg$buildStructuredError(expected, found, location) {
return new peg$SyntaxError(peg$SyntaxError.buildMessage(expected, found), expected, found, location);
}
function peg$parsestart() {
var s0, s1, s2, s3;
var key = peg$currPos * 30 + 0,
cached = peg$resultsCache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
s1 = peg$parse_();
if (s1 !== peg$FAILED) {
s2 = peg$parseselectors();
if (s2 !== peg$FAILED) {
s3 = peg$parse_();
if (s3 !== peg$FAILED) {
s1 = peg$c0(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
s1 = peg$parse_();
if (s1 !== peg$FAILED) {
s1 = peg$c1();
}
s0 = s1;
}
peg$resultsCache[key] = {
nextPos: peg$currPos,
result: s0
};
return s0;
}
function peg$parse_() {
var s0, s1;
var key = peg$currPos * 30 + 1,
cached = peg$resultsCache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = [];
if (input.charCodeAt(peg$currPos) === 32) {
s1 = peg$c2;
peg$currPos++;
} else {
s1 = peg$FAILED;
{
peg$fail(peg$c3);
}
}
while (s1 !== peg$FAILED) {
s0.push(s1);
if (input.charCodeAt(peg$currPos) === 32) {
s1 = peg$c2;
peg$currPos++;
} else {
s1 = peg$FAILED;
{
peg$fail(peg$c3);
}
}
}
peg$resultsCache[key] = {
nextPos: peg$currPos,
result: s0
};
return s0;
}
function peg$parseidentifierName() {
var s0, s1, s2;
var key = peg$currPos * 30 + 2,
cached = peg$resultsCache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
s1 = [];
if (peg$c4.test(input.charAt(peg$currPos))) {
s2 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s2 = peg$FAILED;
{
peg$fail(peg$c5);
}
}
if (s2 !== peg$FAILED) {
while (s2 !== peg$FAILED) {
s1.push(s2);
if (peg$c4.test(input.charAt(peg$currPos))) {
s2 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s2 = peg$FAILED;
{
peg$fail(peg$c5);
}
}
}
} else {
s1 = peg$FAILED;
}
if (s1 !== peg$FAILED) {
s1 = peg$c6(s1);
}
s0 = s1;
peg$resultsCache[key] = {
nextPos: peg$currPos,
result: s0
};
return s0;
}
function peg$parsebinaryOp() {
var s0, s1, s2, s3;
var key = peg$currPos * 30 + 3,
cached = peg$resultsCache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
s1 = peg$parse_();
if (s1 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 62) {
s2 = peg$c7;
peg$currPos++;
} else {
s2 = peg$FAILED;
{
peg$fail(peg$c8);
}
}
if (s2 !== peg$FAILED) {
s3 = peg$parse_();
if (s3 !== peg$FAILED) {
s1 = peg$c9();
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
s1 = peg$parse_();
if (s1 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 126) {
s2 = peg$c10;
peg$currPos++;
} else {
s2 = peg$FAILED;
{
peg$fail(peg$c11);
}
}
if (s2 !== peg$FAILED) {
s3 = peg$parse_();
if (s3 !== peg$FAILED) {
s1 = peg$c12();
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
s1 = peg$parse_();
if (s1 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 43) {
s2 = peg$c13;
peg$currPos++;
} else {
s2 = peg$FAILED;
{
peg$fail(peg$c14);
}
}
if (s2 !== peg$FAILED) {
s3 = peg$parse_();
if (s3 !== peg$FAILED) {
s1 = peg$c15();
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 32) {
s1 = peg$c2;
peg$currPos++;
} else {
s1 = peg$FAILED;
{
peg$fail(peg$c3);
}
}
if (s1 !== peg$FAILED) {
s2 = peg$parse_();
if (s2 !== peg$FAILED) {
s1 = peg$c16();
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
}
}
}
peg$resultsCache[key] = {
nextPos: peg$currPos,
result: s0
};
return s0;
}
function peg$parseselectors() {
var s0, s1, s2, s3, s4, s5, s6, s7;
var key = peg$currPos * 30 + 4,
cached = peg$resultsCache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
s1 = peg$parseselector();
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$currPos;
s4 = peg$parse_();
if (s4 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 44) {
s5 = peg$c17;
peg$currPos++;
} else {
s5 = peg$FAILED;
{
peg$fail(peg$c18);
}
}
if (s5 !== peg$FAILED) {
s6 = peg$parse_();
if (s6 !== peg$FAILED) {
s7 = peg$parseselector();
if (s7 !== peg$FAILED) {
s4 = [s4, s5, s6, s7];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$FAILED;
}
} else {
peg$currPos = s3;
s3 = peg$FAILED;
}
} else {
peg$currPos = s3;
s3 = peg$FAILED;
}
} else {
peg$currPos = s3;
s3 = peg$FAILED;
}
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$currPos;
s4 = peg$parse_();
if (s4 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 44) {
s5 = peg$c17;
peg$currPos++;
} else {
s5 = peg$FAILED;
{
peg$fail(peg$c18);
}
}
if (s5 !== peg$FAILED) {
s6 = peg$parse_();
if (s6 !== peg$FAILED) {
s7 = peg$parseselector();
if (s7 !== peg$FAILED) {
s4 = [s4, s5, s6, s7];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$FAILED;
}
} else {
peg$currPos = s3;
s3 = peg$FAILED;
}
} else {
peg$currPos = s3;
s3 = peg$FAILED;
}
} else {
peg$currPos = s3;
s3 = peg$FAILED;
}
}
if (s2 !== peg$FAILED) {
s1 = peg$c19(s1, s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
peg$resultsCache[key] = {
nextPos: peg$currPos,
result: s0
};
return s0;
}
function peg$parseselector() {
var s0, s1, s2, s3, s4, s5;
var key = peg$currPos * 30 + 5,
cached = peg$resultsCache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
s1 = peg$parsesequence();
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$currPos;
s4 = peg$parsebinaryOp();
if (s4 !== peg$FAILED) {
s5 = peg$parsesequence();
if (s5 !== peg$FAILED) {
s4 = [s4, s5];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$FAILED;
}
} else {
peg$currPos = s3;
s3 = peg$FAILED;
}
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$currPos;
s4 = peg$parsebinaryOp();
if (s4 !== peg$FAILED) {
s5 = peg$parsesequence();
if (s5 !== peg$FAILED) {
s4 = [s4, s5];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$FAILED;
}
} else {
peg$currPos = s3;
s3 = peg$FAILED;
}
}
if (s2 !== peg$FAILED) {
s1 = peg$c20(s1, s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
peg$resultsCache[key] = {
nextPos: peg$currPos,
result: s0
};
return s0;
}
function peg$parsesequence() {
var s0, s1, s2, s3;
var key = peg$currPos * 30 + 6,
cached = peg$resultsCache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 33) {
s1 = peg$c21;
peg$currPos++;
} else {
s1 = peg$FAILED;
{
peg$fail(peg$c22);
}
}
if (s1 === peg$FAILED) {
s1 = null;
}
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$parseatom();
if (s3 !== peg$FAILED) {
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$parseatom();
}
} else {
s2 = peg$FAILED;
}
if (s2 !== peg$FAILED) {
s1 = peg$c23(s1, s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
peg$resultsCache[key] = {
nextPos: peg$currPos,
result: s0
};
return s0;
}
function peg$parseatom() {
var s0;
var key = peg$currPos * 30 + 7,
cached = peg$resultsCache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$parsewildcard();
if (s0 === peg$FAILED) {
s0 = peg$parseidentifier();
if (s0 === peg$FAILED) {
s0 = peg$parseattr();
if (s0 === peg$FAILED) {
s0 = peg$parsefield();
if (s0 === peg$FAILED) {
s0 = peg$parsenegation();
if (s0 === peg$FAILED) {
s0 = peg$parsematches();
if (s0 === peg$FAILED) {
s0 = peg$parsehas();
if (s0 === peg$FAILED) {
s0 = peg$parsefirstChild();
if (s0 === peg$FAILED) {
s0 = peg$parselastChild();
if (s0 === peg$FAILED) {
s0 = peg$parsenthChild();
if (s0 === peg$FAILED) {
s0 = peg$parsenthLastChild();
if (s0 === peg$FAILED) {
s0 = peg$parseclass();
}
}
}
}
}
}
}
}
}
}
}
peg$resultsCache[key] = {
nextPos: peg$currPos,
result: s0
};
return s0;
}
function peg$parsewildcard() {
var s0, s1;
var key = peg$currPos * 30 + 8,
cached = peg$resultsCache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 42) {
s1 = peg$c24;
peg$currPos++;
} else {
s1 = peg$FAILED;
{
peg$fail(peg$c25);
}
}
if (s1 !== peg$FAILED) {
s1 = peg$c26(s1);
}
s0 = s1;
peg$resultsCache[key] = {
nextPos: peg$currPos,
result: s0
};
return s0;
}
function peg$parseidentifier() {
var s0, s1, s2;
var key = peg$currPos * 30 + 9,
cached = peg$resultsCache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 35) {
s1 = peg$c27;
peg$currPos++;
} else {
s1 = peg$FAILED;
{
peg$fail(peg$c28);
}
}
if (s1 === peg$FAILED) {
s1 = null;
}
if (s1 !== peg$FAILED) {
s2 = peg$parseidentifierName();
if (s2 !== peg$FAILED) {
s1 = peg$c29(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
peg$resultsCache[key] = {
nextPos: peg$currPos,
result: s0
};
return s0;
}
function peg$parseattr() {
var s0, s1, s2, s3, s4, s5;
var key = peg$currPos * 30 + 10,
cached = peg$resultsCache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 91) {
s1 = peg$c30;
peg$currPos++;
} else {
s1 = peg$FAILED;
{
peg$fail(peg$c31);
}
}
if (s1 !== peg$FAILED) {
s2 = peg$parse_();
if (s2 !== peg$FAILED) {
s3 = peg$parseattrValue();
if (s3 !== peg$FAILED) {
s4 = peg$parse_();
if (s4 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 93) {
s5 = peg$c32;
peg$currPos++;
} else {
s5 = peg$FAILED;
{
peg$fail(peg$c33);
}
}
if (s5 !== peg$FAILED) {
s1 = peg$c34(s3);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
peg$resultsCache[key] = {
nextPos: peg$currPos,
result: s0
};
return s0;
}
function peg$parseattrOps() {
var s0, s1, s2;
var key = peg$currPos * 30 + 11,
cached = peg$resultsCache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (peg$c35.test(input.charAt(peg$currPos))) {
s1 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s1 = peg$FAILED;
{
peg$fail(peg$c36);
}
}
if (s1 === peg$FAILED) {
s1 = null;
}
if (s1 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 61) {
s2 = peg$c37;
peg$currPos++;
} else {
s2 = peg$FAILED;
{
peg$fail(peg$c38);
}
}
if (s2 !== peg$FAILED) {
s1 = peg$c39(s1);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
if (s0 === peg$FAILED) {
if (peg$c40.test(input.charAt(peg$currPos))) {
s0 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s0 = peg$FAILED;
{
peg$fail(peg$c41);
}
}
}
peg$resultsCache[key] = {
nextPos: peg$currPos,
result: s0
};
return s0;
}
function peg$parseattrEqOps() {
var s0, s1, s2;
var key = peg$currPos * 30 + 12,
cached = peg$resultsCache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 33) {
s1 = peg$c21;
peg$currPos++;
} else {
s1 = peg$FAILED;
{
peg$fail(peg$c22);
}
}
if (s1 === peg$FAILED) {
s1 = null;
}
if (s1 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 61) {
s2 = peg$c37;
peg$currPos++;
} else {
s2 = peg$FAILED;
{
peg$fail(peg$c38);
}
}
if (s2 !== peg$FAILED) {
s1 = peg$c39(s1);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
peg$resultsCache[key] = {
nextPos: peg$currPos,
result: s0
};
return s0;
}
function peg$parseattrName() {
var s0, s1, s2, s3, s4, s5;
var key = peg$currPos * 30 + 13,
cached = peg$resultsCache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
s1 = peg$parseidentifierName();
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 46) {
s4 = peg$c42;
peg$currPos++;
} else {
s4 = peg$FAILED;
{
peg$fail(peg$c43);
}
}
if (s4 !== peg$FAILED) {
s5 = peg$parseidentifierName();
if (s5 !== peg$FAILED) {
s4 = [s4, s5];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$FAILED;
}
} else {
peg$currPos = s3;
s3 = peg$FAILED;
}
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 46) {
s4 = peg$c42;
peg$currPos++;
} else {
s4 = peg$FAILED;
{
peg$fail(peg$c43);
}
}
if (s4 !== peg$FAILED) {
s5 = peg$parseidentifierName();
if (s5 !== peg$FAILED) {
s4 = [s4, s5];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$FAILED;
}
} else {
peg$currPos = s3;
s3 = peg$FAILED;
}
}
if (s2 !== peg$FAILED) {
s1 = peg$c44(s1, s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
peg$resultsCache[key] = {
nextPos: peg$currPos,
result: s0
};
return s0;
}
function peg$parseattrValue() {
var s0, s1, s2, s3, s4, s5;
var key = peg$currPos * 30 + 14,
cached = peg$resultsCache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
s1 = peg$parseattrName();
if (s1 !== peg$FAILED) {
s2 = peg$parse_();
if (s2 !== peg$FAILED) {
s3 = peg$parseattrEqOps();
if (s3 !== peg$FAILED) {
s4 = peg$parse_();
if (s4 !== peg$FAILED) {
s5 = peg$parsetype();
if (s5 === peg$FAILED) {
s5 = peg$parseregex();
}
if (s5 !== peg$FAILED) {
s1 = peg$c45(s1, s3, s5);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
s1 = peg$parseattrName();
if (s1 !== peg$FAILED) {
s2 = peg$parse_();
if (s2 !== peg$FAILED) {
s3 = peg$parseattrOps();
if (s3 !== peg$FAILED) {
s4 = peg$parse_();
if (s4 !== peg$FAILED) {
s5 = peg$parsestring();
if (s5 === peg$FAILED) {
s5 = peg$parsenumber();
if (s5 === peg$FAILED) {
s5 = peg$parsepath();
}
}
if (s5 !== peg$FAILED) {
s1 = peg$c45(s1, s3, s5);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
s1 = peg$parseattrName();
if (s1 !== peg$FAILED) {
s1 = peg$c46(s1);
}
s0 = s1;
}
}
peg$resultsCache[key] = {
nextPos: peg$currPos,
result: s0
};
return s0;
}
function peg$parsestring() {
var s0, s1, s2, s3, s4, s5;
var key = peg$currPos * 30 + 15,
cached = peg$resultsCache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 34) {
s1 = peg$c47;
peg$currPos++;
} else {
s1 = peg$FAILED;
{
peg$fail(peg$c48);
}
}
if (s1 !== peg$FAILED) {
s2 = [];
if (peg$c49.test(input.charAt(peg$currPos))) {
s3 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s3 = peg$FAILED;
{
peg$fail(peg$c50);
}
}
if (s3 === peg$FAILED) {
s3 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 92) {
s4 = peg$c51;
peg$currPos++;
} else {
s4 = peg$FAILED;
{
peg$fail(peg$c52);
}
}
if (s4 !== peg$FAILED) {
if (input.length > peg$currPos) {
s5 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s5 = peg$FAILED;
{
peg$fail(peg$c53);
}
}
if (s5 !== peg$FAILED) {
s4 = peg$c54(s4, s5);
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$FAILED;
}
} else {
peg$currPos = s3;
s3 = peg$FAILED;
}
}
while (s3 !== peg$FAILED) {
s2.push(s3);
if (peg$c49.test(input.charAt(peg$currPos))) {
s3 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s3 = peg$FAILED;
{
peg$fail(peg$c50);
}
}
if (s3 === peg$FAILED) {
s3 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 92) {
s4 = peg$c51;
peg$currPos++;
} else {
s4 = peg$FAILED;
{
peg$fail(peg$c52);
}
}
if (s4 !== peg$FAILED) {
if (input.length > peg$currPos) {
s5 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s5 = peg$FAILED;
{
peg$fail(peg$c53);
}
}
if (s5 !== peg$FAILED) {
s4 = peg$c54(s4, s5);
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$FAILED;
}
} else {
peg$currPos = s3;
s3 = peg$FAILED;
}
}
}
if (s2 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 34) {
s3 = peg$c47;
peg$currPos++;
} else {
s3 = peg$FAILED;
{
peg$fail(peg$c48);
}
}
if (s3 !== peg$FAILED) {
s1 = peg$c55(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 39) {
s1 = peg$c56;
peg$currPos++;
} else {
s1 = peg$FAILED;
{
peg$fail(peg$c57);
}
}
if (s1 !== peg$FAILED) {
s2 = [];
if (peg$c58.test(input.charAt(peg$currPos))) {
s3 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s3 = peg$FAILED;
{
peg$fail(peg$c59);
}
}
if (s3 === peg$FAILED) {
s3 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 92) {
s4 = peg$c51;
peg$currPos++;
} else {
s4 = peg$FAILED;
{
peg$fail(peg$c52);
}
}
if (s4 !== peg$FAILED) {
if (input.length > peg$currPos) {
s5 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s5 = peg$FAILED;
{
peg$fail(peg$c53);
}
}
if (s5 !== peg$FAILED) {
s4 = peg$c54(s4, s5);
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$FAILED;
}
} else {
peg$currPos = s3;
s3 = peg$FAILED;
}
}
while (s3 !== peg$FAILED) {
s2.push(s3);
if (peg$c58.test(input.charAt(peg$currPos))) {
s3 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s3 = peg$FAILED;
{
peg$fail(peg$c59);
}
}
if (s3 === peg$FAILED) {
s3 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 92) {
s4 = peg$c51;
peg$currPos++;
} else {
s4 = peg$FAILED;
{
peg$fail(peg$c52);
}
}
if (s4 !== peg$FAILED) {
if (input.length > peg$currPos) {
s5 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s5 = peg$FAILED;
{
peg$fail(peg$c53);
}
}
if (s5 !== peg$FAILED) {
s4 = peg$c54(s4, s5);
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$FAILED;
}
} else {
peg$currPos = s3;
s3 = peg$FAILED;
}
}
}
if (s2 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 39) {
s3 = peg$c56;
peg$currPos++;
} else {
s3 = peg$FAILED;
{
peg$fail(peg$c57);
}
}
if (s3 !== peg$FAILED) {
s1 = peg$c55(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
}
peg$resultsCache[key] = {
nextPos: peg$currPos,
result: s0
};
return s0;
}
function peg$parsenumber() {
var s0, s1, s2, s3;
var key = peg$currPos * 30 + 16,
cached = peg$resultsCache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
s1 = peg$currPos;
s2 = [];
if (peg$c60.test(input.charAt(peg$currPos))) {
s3 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s3 = peg$FAILED;
{
peg$fail(peg$c61);
}
}
while (s3 !== peg$FAILED) {
s2.push(s3);
if (peg$c60.test(input.charAt(peg$currPos))) {
s3 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s3 = peg$FAILED;
{
peg$fail(peg$c61);
}
}
}
if (s2 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 46) {
s3 = peg$c42;
peg$currPos++;
} else {
s3 = peg$FAILED;
{
peg$fail(peg$c43);
}
}
if (s3 !== peg$FAILED) {
s2 = [s2, s3];
s1 = s2;
} else {
peg$currPos = s1;
s1 = peg$FAILED;
}
} else {
peg$currPos = s1;
s1 = peg$FAILED;
}
if (s1 === peg$FAILED) {
s1 = null;
}
if (s1 !== peg$FAILED) {
s2 = [];
if (peg$c60.test(input.charAt(peg$currPos))) {
s3 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s3 = peg$FAILED;
{
peg$fail(peg$c61);
}
}
if (s3 !== peg$FAILED) {
while (s3 !== peg$FAILED) {
s2.push(s3);
if (peg$c60.test(input.charAt(peg$currPos))) {
s3 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s3 = peg$FAILED;
{
peg$fail(peg$c61);
}
}
}
} else {
s2 = peg$FAILED;
}
if (s2 !== peg$FAILED) {
s1 = peg$c62(s1, s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
peg$resultsCache[key] = {
nextPos: peg$currPos,
result: s0
};
return s0;
}
function peg$parsepath() {
var s0, s1;
var key = peg$currPos * 30 + 17,
cached = peg$resultsCache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
s1 = peg$parseidentifierName();
if (s1 !== peg$FAILED) {
s1 = peg$c63(s1);
}
s0 = s1;
peg$resultsCache[key] = {
nextPos: peg$currPos,
result: s0
};
return s0;
}
function peg$parsetype() {
var s0, s1, s2, s3, s4, s5;
var key = peg$currPos * 30 + 18,
cached = peg$resultsCache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.substr(peg$currPos, 5) === peg$c64) {
s1 = peg$c64;
peg$currPos += 5;
} else {
s1 = peg$FAILED;
{
peg$fail(peg$c65);
}
}
if (s1 !== peg$FAILED) {
s2 = peg$parse_();
if (s2 !== peg$FAILED) {
s3 = [];
if (peg$c66.test(input.charAt(peg$currPos))) {
s4 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s4 = peg$FAILED;
{
peg$fail(peg$c67);
}
}
if (s4 !== peg$FAILED) {
while (s4 !== peg$FAILED) {
s3.push(s4);
if (peg$c66.test(input.charAt(peg$currPos))) {
s4 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s4 = peg$FAILED;
{
peg$fail(peg$c67);
}
}
}
} else {
s3 = peg$FAILED;
}
if (s3 !== peg$FAILED) {
s4 = peg$parse_();
if (s4 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 41) {
s5 = peg$c68;
peg$currPos++;
} else {
s5 = peg$FAILED;
{
peg$fail(peg$c69);
}
}
if (s5 !== peg$FAILED) {
s1 = peg$c70(s3);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
peg$resultsCache[key] = {
nextPos: peg$currPos,
result: s0
};
return s0;
}
function peg$parseflags() {
var s0, s1;
var key = peg$currPos * 30 + 19,
cached = peg$resultsCache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = [];
if (peg$c71.test(input.charAt(peg$currPos))) {
s1 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s1 = peg$FAILED;
{
peg$fail(peg$c72);
}
}
if (s1 !== peg$FAILED) {
while (s1 !== peg$FAILED) {
s0.push(s1);
if (peg$c71.test(input.charAt(peg$currPos))) {
s1 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s1 = peg$FAILED;
{
peg$fail(peg$c72);
}
}
}
} else {
s0 = peg$FAILED;
}
peg$resultsCache[key] = {
nextPos: peg$currPos,
result: s0
};
return s0;
}
function peg$parseregex() {
var s0, s1, s2, s3, s4;
var key = peg$currPos * 30 + 20,
cached = peg$resultsCache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 47) {
s1 = peg$c73;
peg$currPos++;
} else {
s1 = peg$FAILED;
{
peg$fail(peg$c74);
}
}
if (s1 !== peg$FAILED) {
s2 = [];
if (peg$c75.test(input.charAt(peg$currPos))) {
s3 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s3 = peg$FAILED;
{
peg$fail(peg$c76);
}
}
if (s3 !== peg$FAILED) {
while (s3 !== peg$FAILED) {
s2.push(s3);
if (peg$c75.test(input.charAt(peg$currPos))) {
s3 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s3 = peg$FAILED;
{
peg$fail(peg$c76);
}
}
}
} else {
s2 = peg$FAILED;
}
if (s2 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 47) {
s3 = peg$c73;
peg$currPos++;
} else {
s3 = peg$FAILED;
{
peg$fail(peg$c74);
}
}
if (s3 !== peg$FAILED) {
s4 = peg$parseflags();
if (s4 === peg$FAILED) {
s4 = null;
}
if (s4 !== peg$FAILED) {
s1 = peg$c77(s2, s4);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
peg$resultsCache[key] = {
nextPos: peg$currPos,
result: s0
};
return s0;
}
function peg$parsefield() {
var s0, s1, s2, s3, s4, s5, s6;
var key = peg$currPos * 30 + 21,
cached = peg$resultsCache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 46) {
s1 = peg$c42;
peg$currPos++;
} else {
s1 = peg$FAILED;
{
peg$fail(peg$c43);
}
}
if (s1 !== peg$FAILED) {
s2 = peg$parseidentifierName();
if (s2 !== peg$FAILED) {
s3 = [];
s4 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 46) {
s5 = peg$c42;
peg$currPos++;
} else {
s5 = peg$FAILED;
{
peg$fail(peg$c43);
}
}
if (s5 !== peg$FAILED) {
s6 = peg$parseidentifierName();
if (s6 !== peg$FAILED) {
s5 = [s5, s6];
s4 = s5;
} else {
peg$currPos = s4;
s4 = peg$FAILED;
}
} else {
peg$currPos = s4;
s4 = peg$FAILED;
}
while (s4 !== peg$FAILED) {
s3.push(s4);
s4 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 46) {
s5 = peg$c42;
peg$currPos++;
} else {
s5 = peg$FAILED;
{
peg$fail(peg$c43);
}
}
if (s5 !== peg$FAILED) {
s6 = peg$parseidentifierName();
if (s6 !== peg$FAILED) {
s5 = [s5, s6];
s4 = s5;
} else {
peg$currPos = s4;
s4 = peg$FAILED;
}
} else {
peg$currPos = s4;
s4 = peg$FAILED;
}
}
if (s3 !== peg$FAILED) {
s1 = peg$c78(s2, s3);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
peg$resultsCache[key] = {
nextPos: peg$currPos,
result: s0
};
return s0;
}
function peg$parsenegation() {
var s0, s1, s2, s3, s4, s5;
var key = peg$currPos * 30 + 22,
cached = peg$resultsCache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.substr(peg$currPos, 5) === peg$c79) {
s1 = peg$c79;
peg$currPos += 5;
} else {
s1 = peg$FAILED;
{
peg$fail(peg$c80);
}
}
if (s1 !== peg$FAILED) {
s2 = peg$parse_();
if (s2 !== peg$FAILED) {
s3 = peg$parseselectors();
if (s3 !== peg$FAILED) {
s4 = peg$parse_();
if (s4 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 41) {
s5 = peg$c68;
peg$currPos++;
} else {
s5 = peg$FAILED;
{
peg$fail(peg$c69);
}
}
if (s5 !== peg$FAILED) {
s1 = peg$c81(s3);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
peg$resultsCache[key] = {
nextPos: peg$currPos,
result: s0
};
return s0;
}
function peg$parsematches() {
var s0, s1, s2, s3, s4, s5;
var key = peg$currPos * 30 + 23,
cached = peg$resultsCache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.substr(peg$currPos, 9) === peg$c82) {
s1 = peg$c82;
peg$currPos += 9;
} else {
s1 = peg$FAILED;
{
peg$fail(peg$c83);
}
}
if (s1 !== peg$FAILED) {
s2 = peg$parse_();
if (s2 !== peg$FAILED) {
s3 = peg$parseselectors();
if (s3 !== peg$FAILED) {
s4 = peg$parse_();
if (s4 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 41) {
s5 = peg$c68;
peg$currPos++;
} else {
s5 = peg$FAILED;
{
peg$fail(peg$c69);
}
}
if (s5 !== peg$FAILED) {
s1 = peg$c84(s3);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
peg$resultsCache[key] = {
nextPos: peg$currPos,
result: s0
};
return s0;
}
function peg$parsehas() {
var s0, s1, s2, s3, s4, s5;
var key = peg$currPos * 30 + 24,
cached = peg$resultsCache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.substr(peg$currPos, 5) === peg$c85) {
s1 = peg$c85;
peg$currPos += 5;
} else {
s1 = peg$FAILED;
{
peg$fail(peg$c86);
}
}
if (s1 !== peg$FAILED) {
s2 = peg$parse_();
if (s2 !== peg$FAILED) {
s3 = peg$parseselectors();
if (s3 !== peg$FAILED) {
s4 = peg$parse_();
if (s4 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 41) {
s5 = peg$c68;
peg$currPos++;
} else {
s5 = peg$FAILED;
{
peg$fail(peg$c69);
}
}
if (s5 !== peg$FAILED) {
s1 = peg$c87(s3);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
peg$resultsCache[key] = {
nextPos: peg$currPos,
result: s0
};
return s0;
}
function peg$parsefirstChild() {
var s0, s1;
var key = peg$currPos * 30 + 25,
cached = peg$resultsCache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.substr(peg$currPos, 12) === peg$c88) {
s1 = peg$c88;
peg$currPos += 12;
} else {
s1 = peg$FAILED;
{
peg$fail(peg$c89);
}
}
if (s1 !== peg$FAILED) {
s1 = peg$c90();
}
s0 = s1;
peg$resultsCache[key] = {
nextPos: peg$currPos,
result: s0
};
return s0;
}
function peg$parselastChild() {
var s0, s1;
var key = peg$currPos * 30 + 26,
cached = peg$resultsCache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.substr(peg$currPos, 11) === peg$c91) {
s1 = peg$c91;
peg$currPos += 11;
} else {
s1 = peg$FAILED;
{
peg$fail(peg$c92);
}
}
if (s1 !== peg$FAILED) {
s1 = peg$c93();
}
s0 = s1;
peg$resultsCache[key] = {
nextPos: peg$currPos,
result: s0
};
return s0;
}
function peg$parsenthChild() {
var s0, s1, s2, s3, s4, s5;
var key = peg$currPos * 30 + 27,
cached = peg$resultsCache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.substr(peg$currPos, 11) === peg$c94) {
s1 = peg$c94;
peg$currPos += 11;
} else {
s1 = peg$FAILED;
{
peg$fail(peg$c95);
}
}
if (s1 !== peg$FAILED) {
s2 = peg$parse_();
if (s2 !== peg$FAILED) {
s3 = [];
if (peg$c60.test(input.charAt(peg$currPos))) {
s4 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s4 = peg$FAILED;
{
peg$fail(peg$c61);
}
}
if (s4 !== peg$FAILED) {
while (s4 !== peg$FAILED) {
s3.push(s4);
if (peg$c60.test(input.charAt(peg$currPos))) {
s4 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s4 = peg$FAILED;
{
peg$fail(peg$c61);
}
}
}
} else {
s3 = peg$FAILED;
}
if (s3 !== peg$FAILED) {
s4 = peg$parse_();
if (s4 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 41) {
s5 = peg$c68;
peg$currPos++;
} else {
s5 = peg$FAILED;
{
peg$fail(peg$c69);
}
}
if (s5 !== peg$FAILED) {
s1 = peg$c96(s3);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
peg$resultsCache[key] = {
nextPos: peg$currPos,
result: s0
};
return s0;
}
function peg$parsenthLastChild() {
var s0, s1, s2, s3, s4, s5;
var key = peg$currPos * 30 + 28,
cached = peg$resultsCache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.substr(peg$currPos, 16) === peg$c97) {
s1 = peg$c97;
peg$currPos += 16;
} else {
s1 = peg$FAILED;
{
peg$fail(peg$c98);
}
}
if (s1 !== peg$FAILED) {
s2 = peg$parse_();
if (s2 !== peg$FAILED) {
s3 = [];
if (peg$c60.test(input.charAt(peg$currPos))) {
s4 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s4 = peg$FAILED;
{
peg$fail(peg$c61);
}
}
if (s4 !== peg$FAILED) {
while (s4 !== peg$FAILED) {
s3.push(s4);
if (peg$c60.test(input.charAt(peg$currPos))) {
s4 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s4 = peg$FAILED;
{
peg$fail(peg$c61);
}
}
}
} else {
s3 = peg$FAILED;
}
if (s3 !== peg$FAILED) {
s4 = peg$parse_();
if (s4 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 41) {
s5 = peg$c68;
peg$currPos++;
} else {
s5 = peg$FAILED;
{
peg$fail(peg$c69);
}
}
if (s5 !== peg$FAILED) {
s1 = peg$c99(s3);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
peg$resultsCache[key] = {
nextPos: peg$currPos,
result: s0
};
return s0;
}
function peg$parseclass() {
var s0, s1, s2;
var key = peg$currPos * 30 + 29,
cached = peg$resultsCache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 58) {
s1 = peg$c100;
peg$currPos++;
} else {
s1 = peg$FAILED;
{
peg$fail(peg$c101);
}
}
if (s1 !== peg$FAILED) {
if (input.substr(peg$currPos, 9).toLowerCase() === peg$c102) {
s2 = input.substr(peg$currPos, 9);
peg$currPos += 9;
} else {
s2 = peg$FAILED;
{
peg$fail(peg$c103);
}
}
if (s2 === peg$FAILED) {
if (input.substr(peg$currPos, 10).toLowerCase() === peg$c104) {
s2 = input.substr(peg$currPos, 10);
peg$currPos += 10;
} else {
s2 = peg$FAILED;
{
peg$fail(peg$c105);
}
}
if (s2 === peg$FAILED) {
if (input.substr(peg$currPos, 11).toLowerCase() === peg$c106) {
s2 = input.substr(peg$currPos, 11);
peg$currPos += 11;
} else {
s2 = peg$FAILED;
{
peg$fail(peg$c107);
}
}
if (s2 === peg$FAILED) {
if (input.substr(peg$currPos, 8).toLowerCase() === peg$c108) {
s2 = input.substr(peg$currPos, 8);
peg$currPos += 8;
} else {
s2 = peg$FAILED;
{
peg$fail(peg$c109);
}
}
if (s2 === peg$FAILED) {
if (input.substr(peg$currPos, 7).toLowerCase() === peg$c110) {
s2 = input.substr(peg$currPos, 7);
peg$currPos += 7;
} else {
s2 = peg$FAILED;
{
peg$fail(peg$c111);
}
}
}
}
}
}
if (s2 !== peg$FAILED) {
s1 = peg$c112(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
peg$resultsCache[key] = {
nextPos: peg$currPos,
result: s0
};
return s0;
}
function nth(n) {
return {
type: 'nth-child',
index: {
type: 'literal',
value: n
}
};
}
function nthLast(n) {
return {
type: 'nth-last-child',
index: {
type: 'literal',
value: n
}
};
}
function strUnescape(s) {
return s.replace(/\\(.)/g, function (match, ch) {
switch (ch) {
case 'b':
return '\b';
case 'f':
return '\f';
case 'n':
return '\n';
case 'r':
return '\r';
case 't':
return '\t';
case 'v':
return '\v';
default:
return ch;
}
});
}
peg$result = peg$startRuleFunction();
if (peg$result !== peg$FAILED && peg$currPos === input.length) {
return peg$result;
} else {
if (peg$result !== peg$FAILED && peg$currPos < input.length) {
peg$fail(peg$endExpectation());
}
throw peg$buildStructuredError(peg$maxFailExpected, peg$maxFailPos < input.length ? input.charAt(peg$maxFailPos) : null, peg$maxFailPos < input.length ? peg$computeLocation(peg$maxFailPos, peg$maxFailPos + 1) : peg$computeLocation(peg$maxFailPos, peg$maxFailPos));
}
}
return {
SyntaxError: peg$SyntaxError,
parse: peg$parse
};
});
});
function _objectEntries(obj) {
var entries = [];
var keys = Object.keys(obj);
for (var k = 0; k < keys.length; k++) entries.push([keys[k], obj[keys[k]]]);
return entries;
}
/**
* @typedef {"LEFT_SIDE"|"RIGHT_SIDE"} Side
*/
var LEFT_SIDE = 'LEFT_SIDE';
var RIGHT_SIDE = 'RIGHT_SIDE';
/**
* @external AST
* @see https://esprima.readthedocs.io/en/latest/syntax-tree-format.html
*/
/**
* One of the rules of `grammar.pegjs`
* @typedef {PlainObject} SelectorAST
* @see grammar.pegjs
*/
/**
* The `sequence` production of `grammar.pegjs`
* @typedef {PlainObject} SelectorSequenceAST
*/
/**
* Get the value of a property which may be multiple levels down
* in the object.
* @param {?PlainObject} obj
* @param {string} key
* @returns {undefined|boolean|string|number|external:AST}
*/
function getPath(obj, key) {
var keys = key.split('.');
var _iterator = _createForOfIteratorHelper(keys),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var _key = _step.value;
if (obj == null) {
return obj;
}
obj = obj[_key];
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
return obj;
}
/**
* Determine whether `node` can be reached by following `path`,
* starting at `ancestor`.
* @param {?external:AST} node
* @param {?external:AST} ancestor
* @param {string[]} path
* @returns {boolean}
*/
function inPath(node, ancestor, path) {
if (path.length === 0) {
return node === ancestor;
}
if (ancestor == null) {
return false;
}
var field = ancestor[path[0]];
var remainingPath = path.slice(1);
if (Array.isArray(field)) {
var _iterator2 = _createForOfIteratorHelper(field),
_step2;
try {
for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
var component = _step2.value;
if (inPath(node, component, remainingPath)) {
return true;
}
}
} catch (err) {
_iterator2.e(err);
} finally {
_iterator2.f();
}
return false;
} else {
return inPath(node, field, remainingPath);
}
}
/**
* @callback TraverseOptionFallback
* @param {external:AST} node The given node.
* @returns {string[]} An array of visitor keys for the given node.
*/
/**
* @typedef {object} ESQueryOptions
* @property { { [nodeType: string]: string[] } } [visitorKeys] By passing `visitorKeys` mapping, we can extend the properties of the nodes that traverse the node.
* @property {TraverseOptionFallback} [fallback] By passing `fallback` option, we can control the properties of traversing nodes when encountering unknown nodes.
*/
/**
* Given a `node` and its ancestors, determine if `node` is matched
* by `selector`.
* @param {?external:AST} node
* @param {?SelectorAST} selector
* @param {external:AST[]} [ancestry=[]]
* @param {ESQueryOptions} [options]
* @throws {Error} Unknowns (operator, class name, selector type, or
* selector value type)
* @returns {boolean}
*/
function matches(node, selector, ancestry, options) {
if (!selector) {
return true;
}
if (!node) {
return false;
}
if (!ancestry) {
ancestry = [];
}
switch (selector.type) {
case 'wildcard':
return true;
case 'identifier':
return selector.value.toLowerCase() === node.type.toLowerCase();
case 'field':
{
var path = selector.name.split('.');
var ancestor = ancestry[path.length - 1];
return inPath(node, ancestor, path);
}
case 'matches':
var _iterator3 = _createForOfIteratorHelper(selector.selectors),
_step3;
try {
for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
var sel = _step3.value;
if (matches(node, sel, ancestry, options)) {
return true;
}
}
} catch (err) {
_iterator3.e(err);
} finally {
_iterator3.f();
}
return false;
case 'compound':
var _iterator4 = _createForOfIteratorHelper(selector.selectors),
_step4;
try {
for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
var _sel = _step4.value;
if (!matches(node, _sel, ancestry, options)) {
return false;
}
}
} catch (err) {
_iterator4.e(err);
} finally {
_iterator4.f();
}
return true;
case 'not':
var _iterator5 = _createForOfIteratorHelper(selector.selectors),
_step5;
try {
for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
var _sel2 = _step5.value;
if (matches(node, _sel2, ancestry, options)) {
return false;
}
}
} catch (err) {
_iterator5.e(err);
} finally {
_iterator5.f();
}
return true;
case 'has':
{
var _ret = function () {
var collector = [];
var _iterator6 = _createForOfIteratorHelper(selector.selectors),
_step6;
try {
var _loop = function _loop() {
var sel = _step6.value;
var a = [];
estraverse.traverse(node, {
enter: function enter(node, parent) {
if (parent != null) {
a.unshift(parent);
}
if (matches(node, sel, a, options)) {
collector.push(node);
}
},
leave: function leave() {
a.shift();
},
keys: options && options.visitorKeys,
fallback: options && options.fallback || 'iteration'
});
};
for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {
_loop();
}
} catch (err) {
_iterator6.e(err);
} finally {
_iterator6.f();
}
return {
v: collector.length !== 0
};
}();
if (_typeof(_ret) === "object") return _ret.v;
}
case 'child':
if (matches(node, selector.right, ancestry, options)) {
return matches(ancestry[0], selector.left, ancestry.slice(1), options);
}
return false;
case 'descendant':
if (matches(node, selector.right, ancestry, options)) {
for (var i = 0, l = ancestry.length; i < l; ++i) {
if (matches(ancestry[i], selector.left, ancestry.slice(i + 1), options)) {
return true;
}
}
}
return false;
case 'attribute':
{
var p = getPath(node, selector.name);
switch (selector.operator) {
case void 0:
return p != null;
case '=':
switch (selector.value.type) {
case 'regexp':
return typeof p === 'string' && selector.value.value.test(p);
case 'literal':
return "".concat(selector.value.value) === "".concat(p);
case 'type':
return selector.value.value === _typeof(p);
}
throw new Error("Unknown selector value type: ".concat(selector.value.type));
case '!=':
switch (selector.value.type) {
case 'regexp':
return !selector.value.value.test(p);
case 'literal':
return "".concat(selector.value.value) !== "".concat(p);
case 'type':
return selector.value.value !== _typeof(p);
}
throw new Error("Unknown selector value type: ".concat(selector.value.type));
case '<=':
return p <= selector.value.value;
case '<':
return p < selector.value.value;
case '>':
return p > selector.value.value;
case '>=':
return p >= selector.value.value;
}
throw new Error("Unknown operator: ".concat(selector.operator));
}
case 'sibling':
return matches(node, selector.right, ancestry, options) && sibling(node, selector.left, ancestry, LEFT_SIDE, options) || selector.left.subject && matches(node, selector.left, ancestry, options) && sibling(node, selector.right, ancestry, RIGHT_SIDE, options);
case 'adjacent':
return matches(node, selector.right, ancestry, options) && adjacent(node, selector.left, ancestry, LEFT_SIDE, options) || selector.right.subject && matches(node, selector.left, ancestry, options) && adjacent(node, selector.right, ancestry, RIGHT_SIDE, options);
case 'nth-child':
return matches(node, selector.right, ancestry, options) && nthChild(node, ancestry, function () {
return selector.index.value - 1;
}, options);
case 'nth-last-child':
return matches(node, selector.right, ancestry, options) && nthChild(node, ancestry, function (length) {
return length - selector.index.value;
}, options);
case 'class':
switch (selector.name.toLowerCase()) {
case 'statement':
if (node.type.slice(-9) === 'Statement') return true;
// fallthrough: interface Declaration <: Statement { }
case 'declaration':
return node.type.slice(-11) === 'Declaration';
case 'pattern':
if (node.type.slice(-7) === 'Pattern') return true;
// fallthrough: interface Expression <: Node, Pattern { }
case 'expression':
return node.type.slice(-10) === 'Expression' || node.type.slice(-7) === 'Literal' || node.type === 'Identifier' && (ancestry.length === 0 || ancestry[0].type !== 'MetaProperty') || node.type === 'MetaProperty';
case 'function':
return node.type === 'FunctionDeclaration' || node.type === 'FunctionExpression' || node.type === 'ArrowFunctionExpression';
}
throw new Error("Unknown class name: ".concat(selector.name));
}
throw new Error("Unknown selector type: ".concat(selector.type));
}
/**
* Get visitor keys of a given node.
* @param {external:AST} node The AST node to get keys.
* @param {ESQueryOptions|undefined} options
* @returns {string[]} Visitor keys of the node.
*/
function getVisitorKeys(node, options) {
var nodeType = node.type;
if (options && options.visitorKeys && options.visitorKeys[nodeType]) {
return options.visitorKeys[nodeType];
}
if (estraverse.VisitorKeys[nodeType]) {
return estraverse.VisitorKeys[nodeType];
}
if (options && typeof options.fallback === 'function') {
return options.fallback(node);
} // 'iteration' fallback
return Object.keys(node).filter(function (key) {
return key !== 'type';
});
}
/**
* Check whether the given value is an ASTNode or not.
* @param {any} node The value to check.
* @returns {boolean} `true` if the value is an ASTNode.
*/
function isNode(node) {
return node !== null && _typeof(node) === 'object' && typeof node.type === 'string';
}
/**
* Determines if the given node has a sibling that matches the
* given selector.
* @param {external:AST} node
* @param {SelectorSequenceAST} selector
* @param {external:AST[]} ancestry
* @param {Side} side
* @param {ESQueryOptions|undefined} options
* @returns {boolean}
*/
function sibling(node, selector, ancestry, side, options) {
var _ancestry = _slicedToArray(ancestry, 1),
parent = _ancestry[0];
if (!parent) {
return false;
}
var keys = getVisitorKeys(parent, options);
var _iterator7 = _createForOfIteratorHelper(keys),
_step7;
try {
for (_iterator7.s(); !(_step7 = _iterator7.n()).done;) {
var key = _step7.value;
var listProp = parent[key];
if (Array.isArray(listProp)) {
var startIndex = listProp.indexOf(node);
if (startIndex < 0) {
continue;
}
var lowerBound = void 0,
upperBound = void 0;
if (side === LEFT_SIDE) {
lowerBound = 0;
upperBound = startIndex;
} else {
lowerBound = startIndex + 1;
upperBound = listProp.length;
}
for (var k = lowerBound; k < upperBound; ++k) {
if (isNode(listProp[k]) && matches(listProp[k], selector, ancestry, options)) {
return true;
}
}
}
}
} catch (err) {
_iterator7.e(err);
} finally {
_iterator7.f();
}
return false;
}
/**
* Determines if the given node has an adjacent sibling that matches
* the given selector.
* @param {external:AST} node
* @param {SelectorSequenceAST} selector
* @param {external:AST[]} ancestry
* @param {Side} side
* @param {ESQueryOptions|undefined} options
* @returns {boolean}
*/
function adjacent(node, selector, ancestry, side, options) {
var _ancestry2 = _slicedToArray(ancestry, 1),
parent = _ancestry2[0];
if (!parent) {
return false;
}
var keys = getVisitorKeys(parent, options);
var _iterator8 = _createForOfIteratorHelper(keys),
_step8;
try {
for (_iterator8.s(); !(_step8 = _iterator8.n()).done;) {
var key = _step8.value;
var listProp = parent[key];
if (Array.isArray(listProp)) {
var idx = listProp.indexOf(node);
if (idx < 0) {
continue;
}
if (side === LEFT_SIDE && idx > 0 && isNode(listProp[idx - 1]) && matches(listProp[idx - 1], selector, ancestry, options)) {
return true;
}
if (side === RIGHT_SIDE && idx < listProp.length - 1 && isNode(listProp[idx + 1]) && matches(listProp[idx + 1], selector, ancestry, options)) {
return true;
}
}
}
} catch (err) {
_iterator8.e(err);
} finally {
_iterator8.f();
}
return false;
}
/**
* @callback IndexFunction
* @param {Integer} len Containing list's length
* @returns {Integer}
*/
/**
* Determines if the given node is the nth child, determined by
* `idxFn`, which is given the containing list's length.
* @param {external:AST} node
* @param {external:AST[]} ancestry
* @param {IndexFunction} idxFn
* @param {ESQueryOptions|undefined} options
* @returns {boolean}
*/
function nthChild(node, ancestry, idxFn, options) {
var _ancestry3 = _slicedToArray(ancestry, 1),
parent = _ancestry3[0];
if (!parent) {
return false;
}
var keys = getVisitorKeys(parent, options);
var _iterator9 = _createForOfIteratorHelper(keys),
_step9;
try {
for (_iterator9.s(); !(_step9 = _iterator9.n()).done;) {
var key = _step9.value;
var listProp = parent[key];
if (Array.isArray(listProp)) {
var idx = listProp.indexOf(node);
if (idx >= 0 && idx === idxFn(listProp.length)) {
return true;
}
}
}
} catch (err) {
_iterator9.e(err);
} finally {
_iterator9.f();
}
return false;
}
/**
* For each selector node marked as a subject, find the portion of the
* selector that the subject must match.
* @param {SelectorAST} selector
* @param {SelectorAST} [ancestor] Defaults to `selector`
* @returns {SelectorAST[]}
*/
function subjects(selector, ancestor) {
if (selector == null || _typeof(selector) != 'object') {
return [];
}
if (ancestor == null) {
ancestor = selector;
}
var results = selector.subject ? [ancestor] : [];
for (var _i = 0, _Object$entries = _objectEntries(selector); _i < _Object$entries.length; _i++) {
var _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2),
p = _Object$entries$_i[0],
sel = _Object$entries$_i[1];
results.push.apply(results, _toConsumableArray(subjects(sel, p === 'left' ? sel : ancestor)));
}
return results;
}
/**
* @callback TraverseVisitor
* @param {?external:AST} node
* @param {?external:AST} parent
* @param {external:AST[]} ancestry
*/
/**
* From a JS AST and a selector AST, collect all JS AST nodes that
* match the selector.
* @param {external:AST} ast
* @param {?SelectorAST} selector
* @param {TraverseVisitor} visitor
* @param {ESQueryOptions} [options]
* @returns {external:AST[]}
*/
function traverse(ast, selector, visitor, options) {
if (!selector) {
return;
}
var ancestry = [];
var altSubjects = subjects(selector);
estraverse.traverse(ast, {
enter: function enter(node, parent) {
if (parent != null) {
ancestry.unshift(parent);
}
if (matches(node, selector, ancestry, options)) {
if (altSubjects.length) {
for (var i = 0, l = altSubjects.length; i < l; ++i) {
if (matches(node, altSubjects[i], ancestry, options)) {
visitor(node, parent, ancestry);
}
for (var k = 0, m = ancestry.length; k < m; ++k) {
var succeedingAncestry = ancestry.slice(k + 1);
if (matches(ancestry[k], altSubjects[i], succeedingAncestry, options)) {
visitor(ancestry[k], parent, succeedingAncestry);
}
}
}
} else {
visitor(node, parent, ancestry);
}
}
},
leave: function leave() {
ancestry.shift();
},
keys: options && options.visitorKeys,
fallback: options && options.fallback || 'iteration'
});
}
/**
* From a JS AST and a selector AST, collect all JS AST nodes that
* match the selector.
* @param {external:AST} ast
* @param {?SelectorAST} selector
* @param {ESQueryOptions} [options]
* @returns {external:AST[]}
*/
function match(ast, selector, options) {
var results = [];
traverse(ast, selector, function (node) {
results.push(node);
}, options);
return results;
}
/**
* Parse a selector string and return its AST.
* @param {string} selector
* @returns {SelectorAST}
*/
function parse(selector) {
return parser.parse(selector);
}
/**
* Query the code AST using the selector string.
* @param {external:AST} ast
* @param {string} selector
* @param {ESQueryOptions} [options]
* @returns {external:AST[]}
*/
function query(ast, selector, options) {
return match(ast, parse(selector), options);
}
query.parse = parse;
query.match = match;
query.traverse = traverse;
query.matches = matches;
query.query = query;
return query;
})));
| GoogleCloudPlatform/prometheus-engine | third_party/prometheus_ui/base/web/ui/react-app/node_modules/esquery/dist/esquery.lite.js | JavaScript | apache-2.0 | 105,133 |
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* The production x ^= y is the same as x = x ^ y
*
* @path ch11/11.13/11.13.2/S11.13.2_A4.10_T2.2.js
* @description Type(x) is different from Type(y) and both types vary between Number (primitive or object) and String (primitive and object)
*/
//CHECK#1
x = "1";
x ^= 1;
if (x !== 0) {
$ERROR('#1: x = "1"; x ^= 1; x === 0. Actual: ' + (x));
}
//CHECK#2
x = 1;
x ^= "1";
if (x !== 0) {
$ERROR('#2: x = 1; x ^= "1"; x === 0. Actual: ' + (x));
}
//CHECK#3
x = new String("1");
x ^= 1;
if (x !== 0) {
$ERROR('#3: x = new String("1"); x ^= 1; x === 0. Actual: ' + (x));
}
//CHECK#4
x = 1;
x ^= new String("1");
if (x !== 0) {
$ERROR('#4: x = 1; x ^= new String("1"); x === 0. Actual: ' + (x));
}
//CHECK#5
x = "1";
x ^= new Number(1);
if (x !== 0) {
$ERROR('#5: x = "1"; x ^= new Number(1); x === 0. Actual: ' + (x));
}
//CHECK#6
x = new Number(1);
x ^= "1";
if (x !== 0) {
$ERROR('#6: x = new Number(1); x ^= "1"; x === 0. Actual: ' + (x));
}
//CHECK#7
x = new String("1");
x ^= new Number(1);
if (x !== 0) {
$ERROR('#7: x = new String("1"); x ^= new Number(1); x === 0. Actual: ' + (x));
}
//CHECK#8
x = new Number(1);
x ^= new String("1");
if (x !== 0) {
$ERROR('#8: x = new Number(1); x ^= new String("1"); x === 0. Actual: ' + (x));
}
//CHECK#9
x = "x";
x ^= 1;
if (x !== 1) {
$ERROR('#9: x = "x"; x ^= 1; x === 1. Actual: ' + (x));
}
//CHECK#10
x = 1;
x ^= "x";
if (x !== 1) {
$ERROR('#10: x = 1; x ^= "x"; x === 1. Actual: ' + (x));
}
| hippich/typescript | tests/Fidelity/test262/suite/ch11/11.13/11.13.2/S11.13.2_A4.10_T2.2.js | JavaScript | apache-2.0 | 1,611 |
cdb.admin.overlays.LayerSelector = cdb.core.View.extend({
tagName: 'div',
className: 'cartodb-layer-selector-box',
events: {
"click": '_openDropdown',
"dblclick": 'killEvent',
"mousedown": 'killEvent'
},
default_options: {
timeout: 0,
msg: ''
},
initialize: function() {
_.bindAll(this, "_close");
this.map = this.options.mapView.map;
this.mapView = this.options.mapView;
this.mapView.bind('click zoomstart drag', function() {
this.dropdown && this.dropdown.hide()
}, this);
this.add_related_model(this.mapView);
this.layers = [];
this.map = this.options.map;
_.defaults(this.options, this.default_options);
this._setupModels();
},
_killEvent: function(e) {
e && e.preventDefault();
e && e.stopPropagation();
},
// Setup the internal and custom model
_setupModels: function() {
this.model = this.options.model;
this.model.on("change:display", this._onChangeDisplay, this);
this.model.on("change:y", this._onChangeY, this);
this.model.on("change:x", this._onChangeX, this);
this.model.on("destroy", function() {
this.$el.remove();
}, this);
},
_onChangeX: function() {
var x = this.model.get("x");
this.$el.animate({ right: x }, 150);
this.trigger("change_x", this);
//this.model.save();
},
_onChangeY: function() {
var y = this.model.get("y");
this.$el.animate({ top: y }, 150);
this.trigger("change_y", this);
//this.model.save();
},
_onChangeDisplay: function() {
var display = this.model.get("display");
if (display) {
this.show();
} else {
this.hide();
}
},
_checkZoom: function() {
var zoom = this.map.get('zoom');
this.$('.zoom_in')[ zoom < this.map.get('maxZoom') ? 'removeClass' : 'addClass' ]('disabled')
this.$('.zoom_out')[ zoom > this.map.get('minZoom') ? 'removeClass' : 'addClass' ]('disabled')
},
zoom_in: function(ev) {
if (this.map.get("maxZoom") > this.map.getZoom()) {
this.map.setZoom(this.map.getZoom() + 1);
}
ev.preventDefault();
ev.stopPropagation();
},
zoom_out: function(ev) {
if (this.map.get("minZoom") < this.map.getZoom()) {
this.map.setZoom(this.map.getZoom() - 1);
}
ev.preventDefault();
ev.stopPropagation();
},
_onMouseDown: function() { },
_onMouseEnterText: function() { },
_onMouseLeaveText: function() { },
_onMouseEnter: function() { },
_onMouseLeave: function() { },
show: function() {
this.$el.fadeIn(250);
},
hide: function(callback) {
var self = this;
callback && callback();
this.$el.fadeOut(250);
},
_close: function(e) {
this._killEvent(e);
var self = this;
this.hide(function() {
self.trigger("remove", self);
});
},
_toggleFullScreen: function(ev) {
ev.stopPropagation();
ev.preventDefault();
var doc = window.document;
var docEl = doc.documentElement;
if (this.options.doc) { // we use a custom element
docEl = $(this.options.doc)[0];
}
var requestFullScreen = docEl.requestFullscreen || docEl.mozRequestFullScreen || docEl.webkitRequestFullScreen;
var cancelFullScreen = doc.exitFullscreen || doc.mozCancelFullScreen || doc.webkitExitFullscreen;
var mapView = this.options.mapView;
if (!doc.fullscreenElement && !doc.mozFullScreenElement && !doc.webkitFullscreenElement) {
requestFullScreen.call(docEl);
if (mapView) {
if (this.model.get("allowWheelOnFullscreen")) {
mapView.options.map.set("scrollwheel", true);
}
}
} else {
cancelFullScreen.call(doc);
}
},
_getLayers: function() {
var self = this;
this.layers = [];
_.each(this.mapView.map.layers.models, function(layer) {
if (layer.get("type") == 'layergroup' || layer.get('type') === 'namedmap') {
var layerGroupView = self.mapView.getLayerByCid(layer.cid);
for (var i = 0 ; i < layerGroupView.getLayerCount(); ++i) {
var l = layerGroupView.getLayer(i);
var m = new cdb.core.Model(l);
m.set('order', i);
m.set('type', 'layergroup');
m.set('visible', !layerGroupView.getSubLayer(i).get('hidden'));
m.bind('change:visible', function(model) {
this.trigger("change:visible", model.get('visible'), model.get('order'), model);
model.save();
}, self);
if(self.options.layer_names) {
m.set('layer_name', self.options.layer_names[i]);
} else {
m.set('layer_name', l.options.layer_name);
}
var layerView = self._createLayer('LayerViewFromLayerGroup', {
model: m,
layerView: layerGroupView,
layerIndex: i
});
layerView.bind('switchChanged', self._setCount, self);
self.layers.push(layerView);
}
} else if (layer.get("type") === "CartoDB" || layer.get('type') === 'torque') {
var layerView = self._createLayer('LayerView', { model: layer });
layerView.bind('switchChanged', self._setCount, self);
self.layers.push(layerView);
layerView.model.bind('change:visible', function(model) {
this.trigger("change:visible", model.get('visible'), model.get('order'), model);
model.save();
}, self);
}
});
},
_createLayer: function(_class, opts) {
var layerView = new cdb.geo.ui[_class](opts);
this.$("ul").append(layerView.render().el);
this.addView(layerView);
return layerView;
},
_setCount: function() {
var count = 0;
for (var i = 0, l = this.layers.length; i < l; ++i) {
var lyr = this.layers[i];
if (lyr.model.get('visible')) {
count++;
}
}
this.$('.count').text(count);
this.trigger("switchChanged", this);
},
_openDropdown: function() {
this.dropdown.open();
},
render: function() {
var self = this;
this.$el.html(this.options.template(this.options));
this.$el.css({ right: this.model.get("x"), top: this.model.get("y") });
this.dropdown = new cdb.ui.common.Dropdown({
className:"cartodb-dropdown border",
template: this.options.dropdown_template,
target: this.$el.find("a"),
speedIn: 300,
speedOut: 200,
position: "position",
tick: "right",
vertical_position: "down",
horizontal_position: "right",
vertical_offset: 7,
horizontal_offset: 13
});
if (cdb.god) cdb.god.bind("closeDialogs", this.dropdown.hide, this.dropdown);
this.$el.append(this.dropdown.render().el);
this._getLayers();
this._setCount();
return this;
}
});
| nyimbi/cartodb | lib/assets/javascripts/cartodb/table/overlays/layer_selector.js | JavaScript | bsd-3-clause | 6,825 |
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails react-core
*/
'use strict';
const React = require('react');
const ReactDOM = require('react-dom');
describe('ReactMount', () => {
it('should destroy a react root upon request', () => {
const mainContainerDiv = document.createElement('div');
document.body.appendChild(mainContainerDiv);
const instanceOne = <div className="firstReactDiv" />;
const firstRootDiv = document.createElement('div');
mainContainerDiv.appendChild(firstRootDiv);
ReactDOM.render(instanceOne, firstRootDiv);
const instanceTwo = <div className="secondReactDiv" />;
const secondRootDiv = document.createElement('div');
mainContainerDiv.appendChild(secondRootDiv);
ReactDOM.render(instanceTwo, secondRootDiv);
// Test that two react roots are rendered in isolation
expect(firstRootDiv.firstChild.className).toBe('firstReactDiv');
expect(secondRootDiv.firstChild.className).toBe('secondReactDiv');
// Test that after unmounting each, they are no longer in the document.
ReactDOM.unmountComponentAtNode(firstRootDiv);
expect(firstRootDiv.firstChild).toBeNull();
ReactDOM.unmountComponentAtNode(secondRootDiv);
expect(secondRootDiv.firstChild).toBeNull();
});
it('should warn when unmounting a non-container root node', () => {
const mainContainerDiv = document.createElement('div');
const component = (
<div>
<div />
</div>
);
ReactDOM.render(component, mainContainerDiv);
// Test that unmounting at a root node gives a helpful warning
const rootDiv = mainContainerDiv.firstChild;
expect(() => ReactDOM.unmountComponentAtNode(rootDiv)).toWarnDev(
"Warning: unmountComponentAtNode(): The node you're attempting to " +
'unmount was rendered by React and is not a top-level container. You ' +
'may have accidentally passed in a React root node instead of its ' +
'container.',
{withoutStack: true},
);
});
it('should warn when unmounting a non-container, non-root node', () => {
const mainContainerDiv = document.createElement('div');
const component = (
<div>
<div>
<div />
</div>
</div>
);
ReactDOM.render(component, mainContainerDiv);
// Test that unmounting at a non-root node gives a different warning
const nonRootDiv = mainContainerDiv.firstChild.firstChild;
expect(() => ReactDOM.unmountComponentAtNode(nonRootDiv)).toWarnDev(
"Warning: unmountComponentAtNode(): The node you're attempting to " +
'unmount was rendered by React and is not a top-level container. ' +
'Instead, have the parent component update its state and rerender in ' +
'order to remove this component.',
{withoutStack: true},
);
});
});
| jdlehman/react | packages/react-dom/src/__tests__/ReactMountDestruction-test.js | JavaScript | mit | 2,971 |
/**
@module ember-data
*/
import Ember from 'ember';
import Model from "ember-data/model";
var get = Ember.get;
var capitalize = Ember.String.capitalize;
var underscore = Ember.String.underscore;
const { assert } = Ember;
/*
Extend `Ember.DataAdapter` with ED specific code.
@class DebugAdapter
@namespace DS
@extends Ember.DataAdapter
@private
*/
export default Ember.DataAdapter.extend({
getFilters() {
return [
{ name: 'isNew', desc: 'New' },
{ name: 'isModified', desc: 'Modified' },
{ name: 'isClean', desc: 'Clean' }
];
},
detect(typeClass) {
return typeClass !== Model && Model.detect(typeClass);
},
columnsForType(typeClass) {
var columns = [{
name: 'id',
desc: 'Id'
}];
var count = 0;
var self = this;
get(typeClass, 'attributes').forEach((meta, name) => {
if (count++ > self.attributeLimit) { return false; }
var desc = capitalize(underscore(name).replace('_', ' '));
columns.push({ name: name, desc: desc });
});
return columns;
},
getRecords(modelClass, modelName) {
if (arguments.length < 2) {
// Legacy Ember.js < 1.13 support
let containerKey = modelClass._debugContainerKey;
if (containerKey) {
let match = containerKey.match(/model:(.*)/);
if (match) {
modelName = match[1];
}
}
}
assert("Cannot find model name. Please upgrade to Ember.js >= 1.13 for Ember Inspector support", !!modelName);
return this.get('store').peekAll(modelName);
},
getRecordColumnValues(record) {
var count = 0;
var columnValues = { id: get(record, 'id') };
record.eachAttribute((key) => {
if (count++ > this.attributeLimit) {
return false;
}
var value = get(record, key);
columnValues[key] = value;
});
return columnValues;
},
getRecordKeywords(record) {
var keywords = [];
var keys = Ember.A(['id']);
record.eachAttribute((key) => keys.push(key));
keys.forEach((key) => keywords.push(get(record, key)));
return keywords;
},
getRecordFilterValues(record) {
return {
isNew: record.get('isNew'),
isModified: record.get('hasDirtyAttributes') && !record.get('isNew'),
isClean: !record.get('hasDirtyAttributes')
};
},
getRecordColor(record) {
var color = 'black';
if (record.get('isNew')) {
color = 'green';
} else if (record.get('hasDirtyAttributes')) {
color = 'blue';
}
return color;
},
observeRecord(record, recordUpdated) {
var releaseMethods = Ember.A();
var keysToObserve = Ember.A(['id', 'isNew', 'hasDirtyAttributes']);
record.eachAttribute((key) => keysToObserve.push(key));
var adapter = this;
keysToObserve.forEach(function(key) {
var handler = function() {
recordUpdated(adapter.wrapRecord(record));
};
Ember.addObserver(record, key, handler);
releaseMethods.push(function() {
Ember.removeObserver(record, key, handler);
});
});
var release = function() {
releaseMethods.forEach((fn) => fn());
};
return release;
}
});
| r0zar/ember-rails-stocks | stocks/node_modules/ember-data/addon/-private/system/debug/debug-adapter.js | JavaScript | mit | 3,163 |
define("core_editor/events",["exports","core/event_dispatcher","jquery","core/yui"],(function(_exports,_event_dispatcher,_jquery,_yui){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}
/**
* Javascript events for the `core_editor` subsystem.
*
* @module core_editor/events
* @copyright 2021 Andrew Nicols <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @since 4.0
*/Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.notifyEditorContentRestored=_exports.eventTypes=void 0,_jquery=_interopRequireDefault(_jquery),_yui=_interopRequireDefault(_yui);const eventTypes={editorContentRestored:"core_editor/contentRestored"};_exports.eventTypes=eventTypes;_exports.notifyEditorContentRestored=editor=>(editor||window.console.warn("The HTMLElement representing the editor that was modified should be provided to notifyEditorContentRestored."),(0,_event_dispatcher.dispatchEvent)(eventTypes.editorContentRestored,{},editor||document));let legacyEventsRegistered=!1;legacyEventsRegistered||(_yui.default.use("event","moodle-core-event",(()=>{document.addEventListener(eventTypes.editorContentRestored,(()=>{(0,_jquery.default)(document).trigger(M.core.event.EDITOR_CONTENT_RESTORED),_yui.default.fire(M.core.event.EDITOR_CONTENT_RESTORED)}))})),legacyEventsRegistered=!0)}));
//# sourceMappingURL=events.min.js.map | timhunt/moodle | lib/editor/amd/build/events.min.js | JavaScript | gpl-3.0 | 1,429 |
/*!
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
(function () {
describe('startFromFilter', function() {
var startFrom;
beforeEach(module('piwikApp.filter'));
beforeEach(inject(function($injector) {
var $filter = $injector.get('$filter');
startFrom = $filter('startFrom');
}));
describe('#startFrom()', function() {
it('should return all entries if index is zero', function() {
var result = startFrom([1,2,3], 0);
expect(result).to.eql([1,2,3]);
});
it('should return only partial entries if filter is higher than zero', function() {
var result = startFrom([1,2,3], 2);
expect(result).to.eql([3]);
});
it('should return no entries if start is higher than input length', function() {
var result = startFrom([1,2,3], 11);
expect(result).to.eql([]);
});
});
});
})(); | befair/soulShape | wp/soulshape.earth/piwik/plugins/CoreHome/angularjs/common/filters/startfrom.spec.js | JavaScript | agpl-3.0 | 1,121 |
({"replaceDialogText":"Foram substituídas ${0} ocorrências.","eofDialogTextFind":"localizado","eofDialogText":"Última ocorrência ${0}","backwards":"Para trás","replaceButton":"Substituir","replaceLabel":"Substituir por:","matchCase":"Correspondência de maiúsculas/minúsculas","findTooltip":"Introduzir texto a localizar","replaceTooltip":"Introduzir texto de substituição","replaceAllButton":"Substituir tudo","eofDialogTextReplace":"substituído","findReplace":"Localizar e substituir","backwardsTooltip":"Procura de texto para trás","replaceAllButtonTooltip":"Substituir todo o texto","replaceButtonTooltip":"Substituir o texto","findLabel":"Localizar:","findButton":"Localizar","matchCaseTooltip":"Correspondência de maiúsculas/minúsculas","findButtonTooltip":"Localizar o texto","replaceAll":"Todas as ocorrências"}) | skobbler/AddressHunter | web-app/public/js/dojox/editor/plugins/nls/pt-pt/FindReplace.js | JavaScript | bsd-3-clause | 835 |
/**
* Module dependencies
*/
var fs = require('fs-extra')
, _ = require('lodash')
, path = require('path')
, reportback = require('reportback')();
/**
* Generate a JSON file
*
* @option {String} rootPath
* @option {Object} data
* [@option {Boolean} force=false]
*
* @handlers success
* @handlers error
* @handlers alreadyExists
*/
module.exports = function ( options, handlers ) {
// Provide default values for handlers
handlers = reportback.extend(handlers, {
alreadyExists: 'error'
});
// Provide defaults and validate required options
_.defaults(options, {
force: false
});
var missingOpts = _.difference([
'rootPath',
'data'
], Object.keys(options));
if ( missingOpts.length ) return handlers.invalid(missingOpts);
var rootPath = path.resolve( process.cwd() , options.rootPath );
// Only override an existing file if `options.force` is true
fs.exists(rootPath, function (exists) {
if (exists && !options.force) {
return handlers.alreadyExists('Something else already exists at ::'+rootPath);
}
if ( exists ) {
fs.remove(rootPath, function deletedOldINode (err) {
if (err) return handlers.error(err);
_afterwards_();
});
}
else _afterwards_();
function _afterwards_ () {
fs.outputJSON(rootPath, options.data, function (err){
if (err) return handlers.error(err);
else handlers.success();
});
}
});
};
| harindaka/node-mvc-starter | node_modules/sails/node_modules/sails-generate/lib/helpers/jsonfile/index.js | JavaScript | mit | 1,395 |
/*!
* angular-translate - v2.18.0 - 2018-05-17
*
* Copyright (c) 2018 The angular-translate team, Pascal Precht; Licensed MIT
*/
!function(e,t){"function"==typeof define&&define.amd?define([],function(){return t()}):"object"==typeof module&&module.exports?module.exports=t():t()}(0,function(){function e(r,n){"use strict";return function(e){if(!e||!e.url)throw new Error("Couldn't use urlLoader since no url is given!");var t={};return t[e.queryParameter||"lang"]=e.key,n(angular.extend({url:e.url,params:t,method:"GET"},e.$http)).then(function(e){return e.data},function(){return r.reject(e.key)})}}return e.$inject=["$q","$http"],angular.module("pascalprecht.translate").factory("$translateUrlLoader",e),e.displayName="$translateUrlLoader","pascalprecht.translate"}); | sashberd/cdnjs | ajax/libs/angular-translate/2.18.0/angular-translate-loader-url/angular-translate-loader-url.min.js | JavaScript | mit | 774 |
/*
* 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.
*/
({
doInit: function(component, event, helper) {
// Add some data to the "data" attribute to show in the iteration
var mapdata = {
items: [
{ "label": "0"},
{ "label": "1"},
{ "label": "2"},
{ "label": "3"},
{ "label": "4"}
]
};
component.set("v.mapdata", mapdata);
},
}) | forcedotcom/aura | aura-components/src/test/components/iterationTest/iterationArrayValueChange_ObjectFromAttribute_PassThroughValue/iterationArrayValueChange_ObjectFromAttribute_PassThroughValueController.js | JavaScript | apache-2.0 | 919 |
// Copyright 2009 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Test that getters can be defined and called with an index as a parameter.
var o = {};
o.x = 42;
o.__defineGetter__('0', function() { return o.x; });
assertEquals(o.x, o[0]);
assertEquals(o.x, o.__lookupGetter__('0')());
o.__defineSetter__('0', function(y) { o.x = y; });
assertEquals(o.x, o[0]);
assertEquals(o.x, o.__lookupGetter__('0')());
o[0] = 21;
assertEquals(21, o.x);
o.__lookupSetter__(0)(7);
assertEquals(7, o.x);
function Pair(x, y) {
this.x = x;
this.y = y;
};
Pair.prototype.__defineGetter__('0', function() { return this.x; });
Pair.prototype.__defineGetter__('1', function() { return this.y; });
Pair.prototype.__defineSetter__('0', function(x) { this.x = x; });
Pair.prototype.__defineSetter__('1', function(y) { this.y = y; });
var p = new Pair(2, 3);
assertEquals(2, p[0]);
assertEquals(3, p[1]);
p.x = 7;
p[1] = 8;
assertEquals(7, p[0]);
assertEquals(7, p.x);
assertEquals(8, p[1]);
assertEquals(8, p.y);
// Testing that a defined getter doesn't get lost due to inline caching.
var expected = {};
var actual = {};
for (var i = 0; i < 10; i++) {
expected[i] = actual[i] = i;
}
function testArray() {
for (var i = 0; i < 10; i++) {
assertEquals(expected[i], actual[i]);
}
}
actual[1000000] = -1;
testArray();
testArray();
actual.__defineGetter__('0', function() { return expected[0]; });
expected[0] = 42;
testArray();
expected[0] = 111;
testArray();
// Using a setter where only a getter is defined does not throw an exception,
// unless we are in strict mode.
var q = {};
q.__defineGetter__('0', function() { return 42; });
assertDoesNotThrow('q[0] = 7');
// Using a getter where only a setter is defined returns undefined.
var q1 = {};
q1.__defineSetter__('0', function() {q1.b = 17;});
assertEquals(q1[0], undefined);
// Setter works
q1[0] = 3;
assertEquals(q1[0], undefined);
assertEquals(q1.b, 17);
// Complex case of using an undefined getter.
// From http://code.google.com/p/v8/issues/detail?id=298
// Reported by nth10sd.
a = function() {};
this.__defineSetter__("0", function() {});
if (a |= '') {};
assertThrows('this[a].__parent__');
assertEquals(a, 0);
assertEquals(this[a], undefined);
| zero-rp/miniblink49 | v8_7_5/test/mjsunit/indexed-accessors.js | JavaScript | apache-2.0 | 3,743 |
/**
* An assortment of Windows Store app-related tools.
*
* @module winstore
*
* @copyright
* Copyright (c) 2014 by Appcelerator, Inc. All Rights Reserved.
*
* @license
* Licensed under the terms of the Apache Public License.
* Please see the LICENSE included with this distribution for details.
*/
const
appc = require('node-appc'),
async = require('async'),
fs = require('fs'),
magik = require('./utilities').magik,
path = require('path'),
visualstudio = require('./visualstudio'),
__ = appc.i18n(__dirname).__;
var architectures = [ 'arm', 'x86', 'x64' ];
var detectCache,
deviceCache = {};
exports.install = install;
exports.launch = launch;
exports.uninstall = uninstall;
exports.detect = detect;
/**
* Installs a Windows Store application.
*
* @param {Object} [options] - An object containing various settings.
* @param {String} [options.buildConfiguration='Release'] - The type of configuration to build using. Example: "Release" or "Debug".
* @param {Function} [callback(err)] - A function to call after installing the Windows Store app.
*
* @emits module:winstore#error
* @emits module:winstore#installed
*
* @returns {EventEmitter}
*/
function install(projectDir, options, callback) {
return magik(options, callback, function (emitter, options, callback) {
var scripts = [],
packageScript = 'Add-AppDevPackage.ps1';
// find the Add-AppDevPackage.ps1
(function walk(dir) {
fs.readdirSync(dir).forEach(function (name) {
var file = path.join(dir, name);
if (fs.statSync(file).isDirectory()) {
walk(file);
} else if (name === packageScript && (!options.buildConfiguration || path.basename(dir).indexOf('_' + options.buildConfiguration) !== -1)) {
scripts.push(file);
}
});
}(projectDir));
if (!scripts.length) {
var err = new Error(__('Unable to find built application. Please rebuild the project.'));
emitter.emit('error', err);
return callback(err);
}
// let's grab the first match
appc.subprocess.getRealName(scripts[0], function (err, psScript) {
if (err) {
emitter.emit('error', err);
return callback(err);
}
appc.subprocess.run(options.powershell || 'powershell', ['-ExecutionPolicy', 'Bypass', '-NoLogo', '-NoProfile', '-File', psScript, '-Force'], function (code, out, err) {
if (!code) {
emitter.emit('installed');
return callback();
}
// I'm seeing "Please run this script without the -Force parameter" for Win 8.1 store apps.
// This originally was "Please rerun the script without the -Force parameter" (for Win 8 hybrid apps?)
// It's a hack to check for the common substring. Hopefully use of the exact error codes works better first
// Error codes 9 and 14 mean rerun without -Force
if ((code && (code == 9 || code == 14)) ||
out.indexOf('script without the -Force parameter') !== -1) {
appc.subprocess.run(options.powershell || 'powershell', ['-ExecutionPolicy', 'Bypass', '-NoLogo', '-NoProfile', '-File', psScript], function (code, out, err) {
if (err) {
emitter.emit('error', err);
callback(err);
} else {
emitter.emit('installed');
callback();
}
});
return;
}
// must have been some other issue, error out
var ex = new Error(__('Failed to install app: %s', out));
emitter.emit('error', ex);
callback(ex);
});
});
});
}
/**
* Uninstalls a Windows Store application.
*
* @param {String} appId - The application id.
* @param {Object} [options] - An object containing various settings.
* @param {String} [options.powershell='powershell'] - Path to the 'powershell' executable.
* @param {Function} [callback(err)] - A function to call after uninstalling the Windows Store app.
*
* @emits module:winstore#error
* @emits module:winstore#uninstalled
*
* @returns {EventEmitter}
*/
function uninstall(appId, options, callback) {
return magik(options, callback, function (emitter, options, callback) {
appc.subprocess.run(options.powershell || 'powershell', ['-command', 'Get-AppxPackage'], function (code, out, err) {
if (code) {
var ex = new Error(__('Could not query the list of installed Windows Store apps: %s', err || code));
emitter.emit('error', ex);
return callback(ex);
}
var packageNameRegExp = new RegExp('PackageFullName[\\s]*:[\\s]*(' + appId + '.*)'),
packageName;
out.split(/\r\n|\n/).some(function (line) {
var m = line.trim().match(packageNameRegExp);
if (m) {
packageName = m[1];
return true;
}
});
if (packageName) {
appc.subprocess.run(options.powershell || 'powershell', ['-command', 'Remove-AppxPackage', packageName], function (code, out, err) {
if (err) {
emitter.emit('error', err);
callback(err);
} else {
emitter.emit('uninstalled');
callback();
}
});
} else {
emitter.emit('uninstalled');
callback();
}
});
});
}
/**
* Launches a Windows Store application.
*
* @param {String} appId - The application id.
* @param {String} version - The application version.
* @param {Object} [options] - An object containing various settings.
* @param {String} [options.powershell='powershell'] - Path to the 'powershell' executable.
* @param {String} [options.version] - The specific version of the app to launch. If empty, picks the largest version.
* @param {Function} [callback(err)] - A function to call after uninstalling the Windows Store app.
*
* @emits module:winstore#error
* @emits module:winstore#launched
*
* @returns {EventEmitter}
*/
function launch(appId, options, callback) {
return magik(options, callback, function (emitter, options, callback) {
var wstool = path.resolve(__dirname, '..', 'bin', 'wstool.exe');
function runTool() {
var args = ['launch', appId];
options.version && args.push(options.version);
appc.subprocess.run(wstool, args, function (code, out, err) {
if (code) {
var ex = new Error(__('Erroring running wstool (code %s)', code) + '\n' + out);
emitter.emit('error', ex);
callback(ex);
} else {
emitter.emit('installed');
callback();
}
});
}
if (fs.existsSync(wstool)) {
runTool();
} else {
visualstudio.build(appc.util.mix({
buildConfiguration: 'Release',
project: path.resolve(__dirname, '..', 'wstool', 'wstool.csproj')
}, options), function (err, result) {
if (err) {
emitter.emit('error', err);
return callback(err);
}
var src = path.resolve(__dirname, '..', 'wstool', 'bin', 'Release', 'wstool.exe');
if (!fs.existsSync(src)) {
var ex = new Error(__('Failed to build the wstool executable.') + (result ? '\n' + result.out : ''));
emitter.emit('error', ex);
return callback(ex);
}
// sanity check that the wstool.exe wasn't copied by another async task in windowslib
if (!fs.existsSync(wstool)) {
fs.writeFileSync(wstool, fs.readFileSync(src));
}
runTool();
});
}
});
}
/**
* Detects Windows Store SDKs.
*
* @param {Object} [options] - An object containing various settings.
* @param {Boolean} [options.bypassCache=false] - When true, re-detects the Windows SDKs.
* @param {String} [options.preferredWindowsSDK] - The preferred version of the Windows SDK to use by default. Example "8.0".
* @param {String} [options.supportedWindowsSDKVersions] - A string with a version number or range to check if a Windows SDK is supported.
* @param {Function} [callback(err, results)] - A function to call with the Windows SDK information.
*
* @emits module:windowsphone#detected
* @emits module:windowsphone#error
*
* @returns {EventEmitter}
*/
function detect(options, callback) {
return magik(options, callback, function (emitter, options, callback) {
if (detectCache && !options.bypassCache) {
emitter.emit('detected', detectCache);
return callback(null, detectCache);
}
var results = {
windows: {},
issues: []
},
searchPaths = [
'HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Microsoft SDKs\\Windows', // probably nothing here
'HKEY_LOCAL_MACHINE\\Software\\Wow6432Node\\Microsoft\\Microsoft SDKs\\Windows' // this is most likely where Windows SDK will be found
];
function finalize() {
detectCache = results;
emitter.emit('detected', results);
callback(null, results);
}
async.each(searchPaths, function (keyPath, next) {
appc.subprocess.run('reg', ['query', keyPath], function (code, out, err) {
var keyRegExp = /.+\\(v\d+\.\d)$/;
if (!code) {
out.trim().split(/\r\n|\n/).forEach(function (key) {
key = key.trim();
var m = key.match(keyRegExp);
if (!m) {
return;
}
var version = m[1].replace(/^v/, '');
if (m) {
results.windows || (results.windows = {});
results.windows[version] = {
version: version,
registryKey: keyPath + '\\' + m[1],
supported: !options.supportedWindowsSDKVersions || appc.version.satisfies(version, options.supportedWindowsSDKVersions, false), // no maybes
path: null,
signTool: null,
makeCert: null,
pvk2pfx: null,
selected: false
};
}
});
}
next();
});
}, function () {
// check if we didn't find any Windows SDKs, then we're done
if (!Object.keys(results.windows).length) {
results.issues.push({
id: 'WINDOWS_STORE_SDK_NOT_INSTALLED',
type: 'error',
message: __('Microsoft Windows Store SDK not found.') + '\n' +
__('You will be unable to build Windows Store apps.')
});
return finalize();
}
// fetch Windows SDK install information
async.each(Object.keys(results.windows), function (ver, next) {
appc.subprocess.run('reg', ['query', results.windows[ver].registryKey, '/v', '*'], function (code, out, err) {
if (code) {
// bad key? either way, remove this version
delete results.windows[ver];
} else {
// get only the values we are interested in
out.trim().split(/\r\n|\n/).forEach(function (line) {
var parts = line.trim().split(' ').map(function (p) { return p.trim(); });
if (parts.length == 3) {
if (parts[0] == 'InstallationFolder') {
results.windows[ver].path = parts[2];
function addIfExists(key, exe) {
for (var i = 0; i < architectures.length; i++) {
var arch = architectures[i],
tool = path.join(parts[2], 'bin', arch, exe);
if (fs.existsSync(tool)) {
!results.windows[ver][key] && (results.windows[ver][key] = {});
results.windows[ver][key][arch] = tool;
}
}
}
addIfExists('signTool', 'SignTool.exe');
addIfExists('makeCert', 'MakeCert.exe');
addIfExists('pvk2pfx', 'pvk2pfx.exe');
}
}
});
}
next();
});
}, function () {
// double check if we didn't find any Windows SDKs, then we're done
if (Object.keys(results.windows).every(function (v) { return !results.windows[v].path; })) {
results.issues.push({
id: 'WINDOWS_STORE_SDK_NOT_INSTALLED',
type: 'error',
message: __('Microsoft Windows Store SDK not found.') + '\n' +
__('You will be unable to build Windows Store apps.')
});
return finalize();
}
if (Object.keys(results.windows).every(function (v) { return !results.windows[v].deployCmd; })) {
results.issues.push({
id: 'WINDOWS_STORE_SDK_MISSING_DEPLOY_CMD',
type: 'error',
message: __('Microsoft Windows Store SDK is missing the deploy command.') + '\n' +
__('You will be unable to build Windows Store apps.')
});
return finalize();
}
var preferred = options.preferred;
if (!results.windows[preferred] || !results.windows[preferred].supported) {
preferred = Object.keys(results.windows).filter(function (v) { return results.windows[v].supported; }).sort().pop();
}
if (preferred) {
results.windows[preferred].selected = true;
}
finalize();
});
});
});
} | prop/titanium_mobile | node_modules/windowslib/lib/winstore.js | JavaScript | apache-2.0 | 12,463 |
/*jslint node:true, vars:true, bitwise:true, unparam:true */
/*jshint unused:true */
/*global */
/*
* Author: Zion Orent <[email protected]>
* Copyright (c) 2014 Intel Corporation.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
//Load Grove Moisture module
var grove_moisture = require('jsupm_grovemoisture');
// Instantiate a Grove Moisture sensor on analog pin A0
var myMoistureObj = new grove_moisture.GroveMoisture(0);
// Values (approximate):
// 0-300, sensor in air or dry soil
// 300-600, sensor in humid soil
// 600+, sensor in wet soil or submerged in water
// Read the value every second and print the corresponding moisture level
setInterval(function()
{
var result;
var moisture_val = parseInt(myMoistureObj.value());
if (moisture_val >= 0 && moisture_val < 300)
result = "Dry";
else if (moisture_val >= 300 && moisture_val < 600)
result = "Moist";
else
result = "Wet";
console.log("Moisture value: " + moisture_val + ", " + result);
}, 1000);
// Print message when exiting
process.on('SIGINT', function()
{
console.log("Exiting...");
process.exit(0);
});
| yoyojacky/upm | examples/javascript/grovemoisture.js | JavaScript | mit | 2,103 |
module.exports={"title":"CSS3","hex":"1572B6","source":"http://www.w3.org/html/logo/","svg":"<svg aria-labelledby=\"simpleicons-css3-icon\" role=\"img\" viewBox=\"0 0 24 24\" xmlns=\"http://www.w3.org/2000/svg\"><title id=\"simpleicons-css3-icon\">CSS3 icon</title><path d=\"M1.5 0h21l-1.91 21.563L11.977 24l-8.565-2.438L1.5 0zm17.09 4.413L5.41 4.41l.213 2.622 10.125.002-.255 2.716h-6.64l.24 2.573h6.182l-.366 3.523-2.91.804-2.956-.81-.188-2.11h-2.61l.29 3.855L12 19.288l5.373-1.53L18.59 4.414z\"/></svg>"}; | cdnjs/cdnjs | ajax/libs/simple-icons/1.9.9/css3.js | JavaScript | mit | 508 |
/* eslint no-console: 0 */
var _ = require('underscore');
var files = require('./files.js');
var Console = require('./console.js').Console;
// This file implements "upgraders" --- functions which upgrade a Meteor app to
// a new version. Each upgrader has a name (registered in upgradersByName).
//
// You can test upgraders by running "meteor admin run-upgrader myupgradername".
//
// Upgraders are run automatically by "meteor update". It looks at the
// .meteor/.finished-upgraders file in the app and runs every upgrader listed
// here that is not in that file; then it appends their names to that file.
// Upgraders are run in the order they are listed in upgradersByName below.
//
// Upgraders receive a projectContext that has been fully prepared for build.
var printedNoticeHeaderThisProcess = false;
var maybePrintNoticeHeader = function () {
if (printedNoticeHeaderThisProcess)
return;
console.log();
console.log("-- Notice --");
console.log();
printedNoticeHeaderThisProcess = true;
};
// How to do package-specific notices:
// (a) A notice that occurs if a package is used indirectly or directly.
// if (projectContext.packageMap.getInfo('accounts-ui')) {
// console.log(
// "\n" +
// " Accounts UI has totally changed, yo.");
// }
//
// (b) A notice that occurs if a package is used directly.
// if (projectContext.projectConstraintsFile.getConstraint('accounts-ui')) {
// console.log(
// "\n" +
// " Accounts UI has totally changed, yo.");
// }
var upgradersByName = {
"notices-for-0.9.0": function (projectContext) {
maybePrintNoticeHeader();
var smartJsonPath =
files.pathJoin(projectContext.projectDir, 'smart.json');
if (files.exists(smartJsonPath)) {
// Meteorite apps:
console.log(
"0.9.0: Welcome to the new Meteor package system! You can now add any Meteor\n" +
" package to your app (from more than 1800 packages available on the\n" +
" Meteor Package Server) just by typing 'meteor add <packagename>', no\n" +
" Meteorite required.\n" +
"\n" +
" It looks like you have been using Meteorite with this project. To\n" +
" migrate your project automatically to the new system:\n" +
" (1) upgrade your Meteorite with 'npm install -g meteorite', then\n" +
" (2) run 'mrt migrate-app' inside the project.\n" +
" Having done this, you no longer need 'mrt' and can just use 'meteor'.\n");
} else {
// Non-Meteorite apps:
console.log(
"0.9.0: Welcome to the new Meteor package system! You can now add any Meteor\n" +
" package to your app (from more than 1800 packages available on the\n" +
" Meteor Package Server) just by typing 'meteor add <packagename>'. Check\n" +
" out the available packages by typing 'meteor search <term>' or by\n" +
" visiting atmospherejs.com.\n");
}
console.log();
},
"notices-for-0.9.1": function () {
maybePrintNoticeHeader();
console.log(
"0.9.1: Meteor 0.9.1 includes changes to the Blaze API, in preparation for 1.0.\n" +
" Many previously undocumented APIs are now public and documented. Most\n" +
" changes are backwards compatible, except that templates can no longer\n" +
" be named \"body\" or \"instance\".\n");
console.log();
},
// In 0.9.4, the platforms file contains "server" and "browser" as platforms,
// and before it only had "ios" and/or "android". We auto-fix that in
// PlatformList anyway, but we also need to pull platforms from the old
// cordova-platforms filename.
"0.9.4-platform-file": function (projectContext) {
var oldPlatformsPath =
files.pathJoin(projectContext.projectDir, ".meteor", "cordova-platforms");
try {
var oldPlatformsFile = files.readFile(oldPlatformsPath);
} catch (e) {
// If the file doesn't exist, there's no transition to do.
if (e && e.code === 'ENOENT')
return;
throw e;
}
var oldPlatforms = _.compact(_.map(
files.splitBufferToLines(oldPlatformsFile), files.trimSpaceAndComments));
// This method will automatically add "server" and "browser" and sort, etc.
projectContext.platformList.write(oldPlatforms);
files.unlink(oldPlatformsPath);
},
"notices-for-facebook-graph-api-2": function (projectContext) {
// Note: this will print if the app has facebook as a dependency, whether
// direct or indirect. (This is good, since most apps will be pulling it in
// indirectly via accounts-facebook.)
if (projectContext.packageMap.getInfo('facebook')) {
maybePrintNoticeHeader();
Console.info(
"This version of Meteor now uses version 2.2 of the Facebook API",
"for authentication, instead of 1.0. If you use additional Facebook",
"API methods beyond login, you may need to request new",
"permissions.\n\n",
"Facebook will automatically switch all apps to API",
"version 2.0 on April 30th, 2015. Please make sure to update your",
"application's permissions and API calls by that date.\n\n",
"For more details, see",
"https://github.com/meteor/meteor/wiki/Facebook-Graph-API-Upgrade",
Console.options({ bulletPoint: "1.0.5: " })
);
}
},
"1.2.0-standard-minifiers-package": function (projectContext) {
// Minifiers are extracted into a new package called "standard-minifiers"
projectContext.projectConstraintsFile.addConstraints(
['standard-minifiers']);
projectContext.projectConstraintsFile.writeIfModified();
}
////////////
// PLEASE. When adding new upgraders that print mesasges, follow the
// examples for 0.9.0 and 0.9.1 above. Specifically, formatting
// should be:
//
// 1.x.y: Lorem ipsum messages go here...
// ...and linewrapped on the right column
//
// (Or just use Console.info with bulletPoint)
////////////
};
exports.runUpgrader = function (projectContext, upgraderName) {
// This should only be called from the hidden run-upgrader command or by
// "meteor update" with an upgrader from one of our releases, so it's OK if
// error handling is just an exception.
if (! _.has(upgradersByName, upgraderName))
throw new Error("Unknown upgrader: " + upgraderName);
upgradersByName[upgraderName](projectContext);
};
exports.upgradersToRun = function (projectContext) {
var ret = [];
var finishedUpgraders = projectContext.finishedUpgraders.readUpgraders();
// This relies on the fact that Node guarantees object iteration ordering.
_.each(upgradersByName, function (func, name) {
if (! _.contains(finishedUpgraders, name)) {
ret.push(name);
}
});
return ret;
};
exports.allUpgraders = function () {
return _.keys(upgradersByName);
};
| arunoda/meteor | tools/upgraders.js | JavaScript | mit | 6,784 |
module.exports={title:"Fortinet",slug:"fortinet",svg:'<svg role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><title>Fortinet icon</title><path d="M0 9.785h6.788v4.454H0zm8.666-6.33h6.668v4.453H8.666zm0 12.637h6.668v4.454H8.666zm8.522-6.307H24v4.454h-6.812zM2.792 3.455C1.372 3.814.265 5.404 0 7.425v.506h6.788V3.454zM0 16.091v.554c.24 1.926 1.276 3.466 2.624 3.9h4.188v-4.454zm24-8.184v-.506c-.265-1.998-1.372-3.587-2.792-3.972h-4.02v4.454H24zM21.376 20.57c1.324-.458 2.36-1.974 2.624-3.9v-.554h-6.812v4.454Z"/></svg>',get path(){return this.svg.match(/<path\s+d="([^"]*)/)[1]},source:"http://www.fortinet.com/",hex:"EE3124",guidelines:void 0,license:void 0}; | cdnjs/cdnjs | ajax/libs/simple-icons/4.25.0/fortinet.min.js | JavaScript | mit | 675 |
var _ = require('underscore');
var os = require('os');
var utils = require('./utils.js');
/* Meteor's current architecture scheme defines the following virtual
* machine types, which are defined by specifying what is promised by
* the host enviroment:
*
* browser.w3c
* A web browser compliant with modern standards. This is
* intentionally a broad definition. In the coming years, as web
* standards evolve, we will likely tighten it up.
*
* browser.ie[678]
* Old versions of Internet Explorer (not sure yet exactly which
* versions to distinguish -- maybe 6 and 8?)
*
* os.linux.x86_32
* os.linux.x86_64
* Linux on Intel x86 architecture. x86_64 means a system that can
* run 64-bit images, furnished with 64-bit builds of shared
* libraries (there is no guarantee that 32-bit builds of shared
* libraries will be available). x86_32 means a system that can run
* 32-bit images, furnished with 32-bit builds of shared libraries.
* Additionally, if a package contains shared libraries (for use by
* other packages), then if the package is built for x86_64, it
* should contain a 64-bit version of the library, and likewise for
* 32-bit.
*
* Operationally speaking, if you worked at it, under this
* definition it would be possible to build a Linux system that can
* run both x86_64 and x86_32 images (eg, by using a 64-bit kernel
* and making sure that both versions of all relevant libraries were
* installed). But we require such a host to decide whether it is
* x86_64 or x86_32, and stick with it. You can't load a combination
* of packages from each and expect them to work together, because
* if they contain shared libraries they all need to have the same
* architecture.
*
* Basically the punchline is: if you installed the 32-bit version
* of Ubuntu, you've got a os.linux.x86_32 system and you will
* use exclusively os.linux.x86_32 packages, and likewise
* 64-bit. They are two parallel universes and which one you're in
* is determined by which version of Red Hat or Ubuntu you
* installed.
*
* os.osx.x86_64
* OS X (technically speaking, Darwin) on Intel x86 architecture,
* with a kernel capable of loading 64-bit images, and 64-bit builds
* of shared libraries available. If a os.osx.x86_64 package
* contains a shared library, it is only required to provide a
* 64-bit version of the library (it is not required to provide a
* fat binary with both 32-bit and 64-bit builds).
*
* Note that in modern Darwin, both the 32 and 64 bit versions of
* the kernel can load 64-bit images, and the Apple-supplied shared
* libraries are fat binaries that include both 32-bit and 64-bit
* builds in a single file. So it is technically fine (but
* discouraged) for a os.osx.x86_64 to include a 32-bit
* executable, if it only uses the system's shared libraries, but
* you'll run into problems if shared libraries from other packages
* are used.
*
* There is no os.osx.x86_32. Our experience is that such
* hardware is virtually extinct. Meteor has never supported it and
* nobody has asked for it.
*
* os.windows.x86_32
* This is 32 and 64 bit Windows. It seems like there is not much of
* a benefit to using 64 bit Node on Windows, and 32 bit works properly
* even on 64 bit systems.
*
* To be (more but far from completely) precise, the ABI for os.*
* architectures includes a CPU type, a mode in which the code will be
* run (eg, 64 bit), an executable file format (eg, ELF), a promise to
* make any shared libraries available in a particular architecture,
* and promise to set up the shared library search path
* "appropriately". In the future it will also include some guarantees
* about the directory layout in the environment, eg, location of a
* directory where temporary files may be freely written. It does not
* include any syscalls (beyond those used by code that customarily is
* statically linked into every executable built on a platform, eg,
* exit(2)). It does not guarantee the presence of any particular
* shared libraries or programs (including any particular shell or
* traditional tools like 'grep' or 'find').
*
* To model the shared libraries that are required on a system (and
* the particular versions that are required), and to model
* dependencies on command-line programs like 'bash' and 'grep', the
* idea is to have a package named something like 'posix-base' that
* rolls up a reasonable base environment (including such modern
* niceties as libopenssl) and is supplied by the container. This
* allows it to be versioned, unlike architectures, which we hope to
* avoid versioning.
*
* Q: What does "x86" mean?
* A: It refers to the traditional Intel architecture, which
* originally surfaced in CPUs such as the 8086 and the 80386. Those
* of us who are older should remember that the last time that Intel
* used this branding was the 80486, introduced in 1989, and that
* today, parts that use this architecture bear names like "Core",
* "Atom", and "Phenom", with no "86" it sight. We use it in the
* architecture name anyway because we don't want to depart too far
* from Linux's architecture names.
*
* Q: Why do we call it "x86_32" instead of the customary "i386" or
* "i686"?
* A: We wanted to have one name for 32-bit and one name for 64-bit,
* rather than several names for each that are virtual synonyms for
* each (eg, x86_64 vs amd64 vs ia64, i386 vs i686 vs x86). For the
* moment anyway, we're willing to adopt a "one size fits all"
* attitude to get there (no ability to have separate builds for 80386
* CPUs that don't support Pentium Pro extensions, for example --
* you'll have to do runtime detection if you need that). And as long
* as we have to pick a name, we wanted to pick one that was super
* clear (it is not obvious to many people that "i686" means "32-bit
* Intel", because why should it be?) and didn't imply too close of an
* equivalence to the precise meanings that other platforms may assign
* to some of these strings.
*/
// Returns the fully qualified arch of this host -- something like
// "os.linux.x86_32" or "os.osx.x86_64". Must be called inside
// a fiber. Throws an error if it's not a supported architecture.
//
// If you change this, also change scripts/admin/launch-meteor
var _host = null; // memoize
var host = function () {
if (! _host) {
var run = function (...args) {
var result = utils.execFileSync(args[0], args.slice(1)).stdout;
if (! result) {
throw new Error("can't get arch with " + args.join(" ") + "?");
}
return result.replace(/\s*$/, ''); // trailing whitespace
};
var platform = os.platform();
if (platform === "darwin") {
// Can't just test uname -m = x86_64, because Snow Leopard can
// return other values.
if (run('uname', '-p') !== "i386" ||
run('sysctl', '-n', 'hw.cpu64bit_capable') !== "1") {
throw new Error("Only 64-bit Intel processors are supported on OS X");
}
_host = "os.osx.x86_64";
}
else if (platform === "linux") {
var machine = run('uname', '-m');
if (_.contains(["i386", "i686", "x86"], machine)) {
_host = "os.linux.x86_32";
} else if (_.contains(["x86_64", "amd64", "ia64"], machine)) {
_host = "os.linux.x86_64";
} else {
throw new Error("Unsupported architecture: " + machine);
}
}
else if (platform === "win32") {
// We also use 32 bit builds on 64 bit Windows architectures.
_host = "os.windows.x86_32";
} else {
throw new Error("Unsupported operating system: " + platform);
}
}
return _host;
};
// True if `host` (an architecture name such as 'os.linux.x86_64') can run
// programs of architecture `program` (which might be something like 'os',
// 'os.linux', or 'os.linux.x86_64').
//
// `host` and `program` are just mnemonics -- `host` does not
// necessariy have to be a fully qualified architecture name. This
// function just checks to see if `program` describes a set of
// enviroments that is a (non-strict) superset of `host`.
var matches = function (host, program) {
return host.substr(0, program.length) === program &&
(host.length === program.length ||
host.substr(program.length, 1) === ".");
};
// Like `supports`, but instead taken an array of possible
// architectures as its second argument. Returns the most specific
// match, or null if none match. Throws an error if `programs`
// contains exact duplicates.
var mostSpecificMatch = function (host, programs) {
var seen = {};
var best = null;
_.each(programs, function (p) {
if (seen[p]) {
throw new Error("Duplicate architecture: " + p);
}
seen[p] = true;
if (archinfo.matches(host, p) &&
(! best || p.length > best.length)) {
best = p;
}
});
return best;
};
// `programs` is a set of architectures (as an array of string, which
// may contain duplicates). Determine if there exists any architecture
// that is compatible with all of the architectures in the set. If so,
// returns the least specific such architecture. Otherwise (the
// architectures are disjoin) raise an exception.
//
// For example, for 'os' and 'os.osx', return 'os.osx'. For 'os' and
// 'os.linux.x86_64', return 'os.linux.x86_64'. For 'os' and 'browser', throw an
// exception.
var leastSpecificDescription = function (programs) {
if (programs.length === 0) {
return '';
}
// Find the longest string
var longest = _.max(programs, function (p) { return p.length; });
// If everything else in the list is compatible with the longest,
// then it must be the most specific, and if everything is
// compatible with the most specific then it must be the least
// specific compatible description.
_.each(programs, function (p) {
if (! archinfo.matches(longest, p)) {
throw new Error("Incompatible architectures: '" + p + "' and '" +
longest + "'");
}
});
return longest;
};
var withoutSpecificOs = function (arch) {
if (arch.substr(0, 3) === 'os.') {
return 'os';
}
return arch;
};
var archinfo = exports;
_.extend(archinfo, {
host: host,
matches: matches,
mostSpecificMatch: mostSpecificMatch,
leastSpecificDescription: leastSpecificDescription,
withoutSpecificOs: withoutSpecificOs
});
| lpinto93/meteor | tools/utils/archinfo.js | JavaScript | mit | 10,422 |
module.exports = {
justNow: "ligenu",
secondsAgo: "{{time}} sekunder siden",
aMinuteAgo: "et minut siden",
minutesAgo: "{{time}} minutter siden",
anHourAgo: "en time siden",
hoursAgo: "{{time}} timer siden",
aDayAgo: "i går",
daysAgo: "{{time}} dage siden",
aWeekAgo: "en uge siden",
weeksAgo: "{{time}} uger siden",
aMonthAgo: "en måned siden",
monthsAgo: "{{time}} måneder siden",
aYearAgo: "et år siden",
yearsAgo: "{{time}} år siden",
overAYearAgo: "over et år siden",
secondsFromNow: "om {{time}} sekunder",
aMinuteFromNow: "om et minut",
minutesFromNow: "om {{time}} minutter",
anHourFromNow: "om en time",
hoursFromNow: "om {{time}} timer",
aDayFromNow: "i morgen",
daysFromNow: "om {{time}} dage",
aWeekFromNow: "om en uge",
weeksFromNow: "om {{time}} uger",
aMonthFromNow: "om en måned",
monthsFromNow: "om {{time}} måneder",
aYearFromNow: "om et år",
yearsFromNow: "om {{time}} år",
overAYearFromNow: "om over et år"
}
| joegesualdo/dotfiles | npm-global/lib/node_modules/npm/node_modules/tiny-relative-date/translations/da.js | JavaScript | mit | 998 |
( function ( mw, $ ) {
mw.page = {};
// Client profile classes for <html>
// Allows for easy hiding/showing of JS or no-JS-specific UI elements
$( 'html' )
.addClass( 'client-js' )
.removeClass( 'client-nojs' );
$( function () {
// Initialize utilities as soon as the document is ready (mw.util.$content,
// messageBoxNew, profile, tooltip access keys, Table of contents toggle, ..).
// In the domready here instead of in mediawiki.page.ready to ensure that it gets enqueued
// before other modules hook into domready, so that mw.util.$content (defined by
// mw.util.init), is defined for them.
mw.util.init();
/**
* @event wikipage_content
* @member mw.hook
* @param {jQuery} $content
*/
mw.hook( 'wikipage.content' ).fire( $( '#mw-content-text' ) );
} );
}( mediaWiki, jQuery ) );
| BRL-CAD/web | wiki/resources/mediawiki.page/mediawiki.page.startup.js | JavaScript | bsd-2-clause | 826 |
/// Copyright (c) 2012 Ecma International. All rights reserved.
/**
* @path ch15/15.3/15.3.5/15.3.5.4/15.3.5.4_2-77gs.js
* @description Strict mode - checking access to strict function caller from non-strict function (non-strict function declaration called by strict Function constructor)
* @noStrict
*/
function f() {return gNonStrict();};
(function () {"use strict"; return Function("return f();")(); })();
function gNonStrict() {
return gNonStrict.caller;
}
| Oceanswave/NiL.JS | Tests/tests/sputnik/ch15/15.3/15.3.5/15.3.5.4/15.3.5.4_2-77gs.js | JavaScript | bsd-3-clause | 476 |
/// Copyright (c) 2012 Ecma International. All rights reserved.
/**
* @path ch10/10.6/10.6-11-b-1.js
* @description Arguments Object has index property '0' as its own property, it shoulde be writable, enumerable, configurable and does not invoke the setter defined on Object.prototype[0] (Step 11.b)
*/
function testcase() {
try {
var data = "data";
var getFunc = function () {
return data;
};
var setFunc = function (value) {
data = value;
};
Object.defineProperty(Object.prototype, "0", {
get: getFunc,
set: setFunc,
configurable: true
});
var argObj = (function () { return arguments })(1);
var verifyValue = false;
verifyValue = (argObj[0] === 1);
var verifyEnumerable = false;
for (var p in argObj) {
if (p === "0" && argObj.hasOwnProperty("0")) {
verifyEnumerable = true;
}
}
var verifyWritable = false;
argObj[0] = 1001;
verifyWritable = (argObj[0] === 1001);
var verifyConfigurable = false;
delete argObj[0];
verifyConfigurable = argObj.hasOwnProperty("0");
return verifyValue && verifyWritable && verifyEnumerable && !verifyConfigurable && data === "data";
} finally {
delete Object.prototype[0];
}
}
runTestCase(testcase);
| Oceanswave/NiL.JS | Tests/tests/sputnik/ch10/10.6/10.6-11-b-1.js | JavaScript | bsd-3-clause | 1,560 |
// Copyright 2009 the Sputnik authors. All rights reserved.
/**
* The [[Value]] property of the newly constructed object
* is set by following steps:
* 1. Call ToNumber(year)
* 2. Call ToNumber(month)
* 3. If date is supplied use ToNumber(date)
* 4. If hours is supplied use ToNumber(hours)
* 5. If minutes is supplied use ToNumber(minutes)
* 6. If seconds is supplied use ToNumber(seconds)
* 7. If ms is supplied use ToNumber(ms)
*
* @path ch15/15.9/15.9.3/S15.9.3.1_A4_T4.js
* @description 5 arguments, (year, month, date, hours, minutes)
*/
var myObj = function(val){
this.value = val;
this.valueOf = function(){throw "valueOf-"+this.value;};
this.toString = function(){throw "toString-"+this.value;};
};
//CHECK#1
try{
var x1 = new Date(new myObj(1), new myObj(2), new myObj(3), new myObj(4), new myObj(5));
$ERROR("#1: The 1st step is calling ToNumber(year)");
}
catch(e){
if(e !== "valueOf-1"){
$ERROR("#1: The 1st step is calling ToNumber(year)");
}
}
//CHECK#2
try{
var x2 = new Date(1, new myObj(2), new myObj(3), new myObj(4), new myObj(5));
$ERROR("#2: The 2nd step is calling ToNumber(month)");
}
catch(e){
if(e !== "valueOf-2"){
$ERROR("#2: The 2nd step is calling ToNumber(month)");
}
}
//CHECK#3
try{
var x3 = new Date(1, 2, new myObj(3), new myObj(4), new myObj(5));
$ERROR("#3: The 3rd step is calling ToNumber(date)");
}
catch(e){
if(e !== "valueOf-3"){
$ERROR("#3: The 3rd step is calling ToNumber(date)");
}
}
//CHECK#4
try{
var x4 = new Date(1, 2, 3, new myObj(4), new myObj(5));
$ERROR("#4: The 4th step is calling ToNumber(hours)");
}
catch(e){
if(e !== "valueOf-4"){
$ERROR("#4: The 4th step is calling ToNumber(hours)");
}
}
//CHECK#5
try{
var x5 = new Date(1, 2, 3, 4, new myObj(5));
$ERROR("#5: The 5th step is calling ToNumber(minutes)");
}
catch(e){
if(e !== "valueOf-5"){
$ERROR("#5: The 5th step is calling ToNumber(minutes)");
}
}
| Oceanswave/NiL.JS | Tests/tests/sputnik/ch15/15.9/15.9.3/S15.9.3.1_A4_T4.js | JavaScript | bsd-3-clause | 1,950 |
// Copyright 2009 the Sputnik authors. All rights reserved.
/**
* Number.MIN_VALUE has the attribute DontEnum
*
* @path ch15/15.7/15.7.3/15.7.3.3/S15.7.3.3_A4.js
* @description Checking if enumerating Number.MIN_VALUE fails
*/
//CHECK#1
for(var x in Number) {
if(x === "MIN_VALUE") {
$ERROR('#1: Number.MIN_VALUE has the attribute DontEnum');
}
}
if (Number.propertyIsEnumerable('MIN_VALUE')) {
$ERROR('#2: Number.MIN_VALUE has the attribute DontEnum');
}
| Oceanswave/NiL.JS | Tests/tests/sputnik/ch15/15.7/15.7.3/15.7.3.3/S15.7.3.3_A4.js | JavaScript | bsd-3-clause | 475 |
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // identity function for calling harmony imports with the correct context
/******/ __webpack_require__.i = function(value) { return value; };
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 96);
/******/ })
/************************************************************************/
/******/ ({
/***/ 0:
/***/ (function(module, exports) {
module.exports = jQuery;
/***/ }),
/***/ 1:
/***/ (function(module, exports) {
module.exports = {Foundation: window.Foundation};
/***/ }),
/***/ 2:
/***/ (function(module, exports) {
module.exports = {Plugin: window.Foundation.Plugin};
/***/ }),
/***/ 3:
/***/ (function(module, exports) {
module.exports = {rtl: window.Foundation.rtl, GetYoDigits: window.Foundation.GetYoDigits, transitionend: window.Foundation.transitionend};
/***/ }),
/***/ 30:
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__foundation_core__ = __webpack_require__(1);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__foundation_core___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0__foundation_core__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__foundation_sticky__ = __webpack_require__(60);
__WEBPACK_IMPORTED_MODULE_0__foundation_core__["Foundation"].plugin(__WEBPACK_IMPORTED_MODULE_1__foundation_sticky__["a" /* Sticky */], 'Sticky');
/***/ }),
/***/ 4:
/***/ (function(module, exports) {
module.exports = {Motion: window.Foundation.Motion, Move: window.Foundation.Move};
/***/ }),
/***/ 6:
/***/ (function(module, exports) {
module.exports = {MediaQuery: window.Foundation.MediaQuery};
/***/ }),
/***/ 60:
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Sticky; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_jquery__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__foundation_util_core__ = __webpack_require__(3);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__foundation_util_core___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_1__foundation_util_core__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__foundation_util_mediaQuery__ = __webpack_require__(6);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__foundation_util_mediaQuery___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_2__foundation_util_mediaQuery__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__foundation_plugin__ = __webpack_require__(2);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__foundation_plugin___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_3__foundation_plugin__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__foundation_util_triggers__ = __webpack_require__(7);
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
/**
* Sticky module.
* @module foundation.sticky
* @requires foundation.util.triggers
* @requires foundation.util.mediaQuery
*/
var Sticky = function (_Plugin) {
_inherits(Sticky, _Plugin);
function Sticky() {
_classCallCheck(this, Sticky);
return _possibleConstructorReturn(this, (Sticky.__proto__ || Object.getPrototypeOf(Sticky)).apply(this, arguments));
}
_createClass(Sticky, [{
key: '_setup',
/**
* Creates a new instance of a sticky thing.
* @class
* @param {jQuery} element - jQuery object to make sticky.
* @param {Object} options - options object passed when creating the element programmatically.
*/
value: function _setup(element, options) {
this.$element = element;
this.options = __WEBPACK_IMPORTED_MODULE_0_jquery___default.a.extend({}, Sticky.defaults, this.$element.data(), options);
// Triggers init is idempotent, just need to make sure it is initialized
__WEBPACK_IMPORTED_MODULE_4__foundation_util_triggers__["a" /* Triggers */].init(__WEBPACK_IMPORTED_MODULE_0_jquery___default.a);
this._init();
}
/**
* Initializes the sticky element by adding classes, getting/setting dimensions, breakpoints and attributes
* @function
* @private
*/
}, {
key: '_init',
value: function _init() {
__WEBPACK_IMPORTED_MODULE_2__foundation_util_mediaQuery__["MediaQuery"]._init();
var $parent = this.$element.parent('[data-sticky-container]'),
id = this.$element[0].id || __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__foundation_util_core__["GetYoDigits"])(6, 'sticky'),
_this = this;
if ($parent.length) {
this.$container = $parent;
} else {
this.wasWrapped = true;
this.$element.wrap(this.options.container);
this.$container = this.$element.parent();
}
this.$container.addClass(this.options.containerClass);
this.$element.addClass(this.options.stickyClass).attr({ 'data-resize': id, 'data-mutate': id });
if (this.options.anchor !== '') {
__WEBPACK_IMPORTED_MODULE_0_jquery___default()('#' + _this.options.anchor).attr({ 'data-mutate': id });
}
this.scrollCount = this.options.checkEvery;
this.isStuck = false;
__WEBPACK_IMPORTED_MODULE_0_jquery___default()(window).one('load.zf.sticky', function () {
//We calculate the container height to have correct values for anchor points offset calculation.
_this.containerHeight = _this.$element.css("display") == "none" ? 0 : _this.$element[0].getBoundingClientRect().height;
_this.$container.css('height', _this.containerHeight);
_this.elemHeight = _this.containerHeight;
if (_this.options.anchor !== '') {
_this.$anchor = __WEBPACK_IMPORTED_MODULE_0_jquery___default()('#' + _this.options.anchor);
} else {
_this._parsePoints();
}
_this._setSizes(function () {
var scroll = window.pageYOffset;
_this._calc(false, scroll);
//Unstick the element will ensure that proper classes are set.
if (!_this.isStuck) {
_this._removeSticky(scroll >= _this.topPoint ? false : true);
}
});
_this._events(id.split('-').reverse().join('-'));
});
}
/**
* If using multiple elements as anchors, calculates the top and bottom pixel values the sticky thing should stick and unstick on.
* @function
* @private
*/
}, {
key: '_parsePoints',
value: function _parsePoints() {
var top = this.options.topAnchor == "" ? 1 : this.options.topAnchor,
btm = this.options.btmAnchor == "" ? document.documentElement.scrollHeight : this.options.btmAnchor,
pts = [top, btm],
breaks = {};
for (var i = 0, len = pts.length; i < len && pts[i]; i++) {
var pt;
if (typeof pts[i] === 'number') {
pt = pts[i];
} else {
var place = pts[i].split(':'),
anchor = __WEBPACK_IMPORTED_MODULE_0_jquery___default()('#' + place[0]);
pt = anchor.offset().top;
if (place[1] && place[1].toLowerCase() === 'bottom') {
pt += anchor[0].getBoundingClientRect().height;
}
}
breaks[i] = pt;
}
this.points = breaks;
return;
}
/**
* Adds event handlers for the scrolling element.
* @private
* @param {String} id - pseudo-random id for unique scroll event listener.
*/
}, {
key: '_events',
value: function _events(id) {
var _this = this,
scrollListener = this.scrollListener = 'scroll.zf.' + id;
if (this.isOn) {
return;
}
if (this.canStick) {
this.isOn = true;
__WEBPACK_IMPORTED_MODULE_0_jquery___default()(window).off(scrollListener).on(scrollListener, function (e) {
if (_this.scrollCount === 0) {
_this.scrollCount = _this.options.checkEvery;
_this._setSizes(function () {
_this._calc(false, window.pageYOffset);
});
} else {
_this.scrollCount--;
_this._calc(false, window.pageYOffset);
}
});
}
this.$element.off('resizeme.zf.trigger').on('resizeme.zf.trigger', function (e, el) {
_this._eventsHandler(id);
});
this.$element.on('mutateme.zf.trigger', function (e, el) {
_this._eventsHandler(id);
});
if (this.$anchor) {
this.$anchor.on('mutateme.zf.trigger', function (e, el) {
_this._eventsHandler(id);
});
}
}
/**
* Handler for events.
* @private
* @param {String} id - pseudo-random id for unique scroll event listener.
*/
}, {
key: '_eventsHandler',
value: function _eventsHandler(id) {
var _this = this,
scrollListener = this.scrollListener = 'scroll.zf.' + id;
_this._setSizes(function () {
_this._calc(false);
if (_this.canStick) {
if (!_this.isOn) {
_this._events(id);
}
} else if (_this.isOn) {
_this._pauseListeners(scrollListener);
}
});
}
/**
* Removes event handlers for scroll and change events on anchor.
* @fires Sticky#pause
* @param {String} scrollListener - unique, namespaced scroll listener attached to `window`
*/
}, {
key: '_pauseListeners',
value: function _pauseListeners(scrollListener) {
this.isOn = false;
__WEBPACK_IMPORTED_MODULE_0_jquery___default()(window).off(scrollListener);
/**
* Fires when the plugin is paused due to resize event shrinking the view.
* @event Sticky#pause
* @private
*/
this.$element.trigger('pause.zf.sticky');
}
/**
* Called on every `scroll` event and on `_init`
* fires functions based on booleans and cached values
* @param {Boolean} checkSizes - true if plugin should recalculate sizes and breakpoints.
* @param {Number} scroll - current scroll position passed from scroll event cb function. If not passed, defaults to `window.pageYOffset`.
*/
}, {
key: '_calc',
value: function _calc(checkSizes, scroll) {
if (checkSizes) {
this._setSizes();
}
if (!this.canStick) {
if (this.isStuck) {
this._removeSticky(true);
}
return false;
}
if (!scroll) {
scroll = window.pageYOffset;
}
if (scroll >= this.topPoint) {
if (scroll <= this.bottomPoint) {
if (!this.isStuck) {
this._setSticky();
}
} else {
if (this.isStuck) {
this._removeSticky(false);
}
}
} else {
if (this.isStuck) {
this._removeSticky(true);
}
}
}
/**
* Causes the $element to become stuck.
* Adds `position: fixed;`, and helper classes.
* @fires Sticky#stuckto
* @function
* @private
*/
}, {
key: '_setSticky',
value: function _setSticky() {
var _this = this,
stickTo = this.options.stickTo,
mrgn = stickTo === 'top' ? 'marginTop' : 'marginBottom',
notStuckTo = stickTo === 'top' ? 'bottom' : 'top',
css = {};
css[mrgn] = this.options[mrgn] + 'em';
css[stickTo] = 0;
css[notStuckTo] = 'auto';
this.isStuck = true;
this.$element.removeClass('is-anchored is-at-' + notStuckTo).addClass('is-stuck is-at-' + stickTo).css(css)
/**
* Fires when the $element has become `position: fixed;`
* Namespaced to `top` or `bottom`, e.g. `sticky.zf.stuckto:top`
* @event Sticky#stuckto
*/
.trigger('sticky.zf.stuckto:' + stickTo);
this.$element.on("transitionend webkitTransitionEnd oTransitionEnd otransitionend MSTransitionEnd", function () {
_this._setSizes();
});
}
/**
* Causes the $element to become unstuck.
* Removes `position: fixed;`, and helper classes.
* Adds other helper classes.
* @param {Boolean} isTop - tells the function if the $element should anchor to the top or bottom of its $anchor element.
* @fires Sticky#unstuckfrom
* @private
*/
}, {
key: '_removeSticky',
value: function _removeSticky(isTop) {
var stickTo = this.options.stickTo,
stickToTop = stickTo === 'top',
css = {},
anchorPt = (this.points ? this.points[1] - this.points[0] : this.anchorHeight) - this.elemHeight,
mrgn = stickToTop ? 'marginTop' : 'marginBottom',
notStuckTo = stickToTop ? 'bottom' : 'top',
topOrBottom = isTop ? 'top' : 'bottom';
css[mrgn] = 0;
css['bottom'] = 'auto';
if (isTop) {
css['top'] = 0;
} else {
css['top'] = anchorPt;
}
this.isStuck = false;
this.$element.removeClass('is-stuck is-at-' + stickTo).addClass('is-anchored is-at-' + topOrBottom).css(css)
/**
* Fires when the $element has become anchored.
* Namespaced to `top` or `bottom`, e.g. `sticky.zf.unstuckfrom:bottom`
* @event Sticky#unstuckfrom
*/
.trigger('sticky.zf.unstuckfrom:' + topOrBottom);
}
/**
* Sets the $element and $container sizes for plugin.
* Calls `_setBreakPoints`.
* @param {Function} cb - optional callback function to fire on completion of `_setBreakPoints`.
* @private
*/
}, {
key: '_setSizes',
value: function _setSizes(cb) {
this.canStick = __WEBPACK_IMPORTED_MODULE_2__foundation_util_mediaQuery__["MediaQuery"].is(this.options.stickyOn);
if (!this.canStick) {
if (cb && typeof cb === 'function') {
cb();
}
}
var _this = this,
newElemWidth = this.$container[0].getBoundingClientRect().width,
comp = window.getComputedStyle(this.$container[0]),
pdngl = parseInt(comp['padding-left'], 10),
pdngr = parseInt(comp['padding-right'], 10);
if (this.$anchor && this.$anchor.length) {
this.anchorHeight = this.$anchor[0].getBoundingClientRect().height;
} else {
this._parsePoints();
}
this.$element.css({
'max-width': newElemWidth - pdngl - pdngr + 'px'
});
var newContainerHeight = this.$element[0].getBoundingClientRect().height || this.containerHeight;
if (this.$element.css("display") == "none") {
newContainerHeight = 0;
}
this.containerHeight = newContainerHeight;
this.$container.css({
height: newContainerHeight
});
this.elemHeight = newContainerHeight;
if (!this.isStuck) {
if (this.$element.hasClass('is-at-bottom')) {
var anchorPt = (this.points ? this.points[1] - this.$container.offset().top : this.anchorHeight) - this.elemHeight;
this.$element.css('top', anchorPt);
}
}
this._setBreakPoints(newContainerHeight, function () {
if (cb && typeof cb === 'function') {
cb();
}
});
}
/**
* Sets the upper and lower breakpoints for the element to become sticky/unsticky.
* @param {Number} elemHeight - px value for sticky.$element height, calculated by `_setSizes`.
* @param {Function} cb - optional callback function to be called on completion.
* @private
*/
}, {
key: '_setBreakPoints',
value: function _setBreakPoints(elemHeight, cb) {
if (!this.canStick) {
if (cb && typeof cb === 'function') {
cb();
} else {
return false;
}
}
var mTop = emCalc(this.options.marginTop),
mBtm = emCalc(this.options.marginBottom),
topPoint = this.points ? this.points[0] : this.$anchor.offset().top,
bottomPoint = this.points ? this.points[1] : topPoint + this.anchorHeight,
// topPoint = this.$anchor.offset().top || this.points[0],
// bottomPoint = topPoint + this.anchorHeight || this.points[1],
winHeight = window.innerHeight;
if (this.options.stickTo === 'top') {
topPoint -= mTop;
bottomPoint -= elemHeight + mTop;
} else if (this.options.stickTo === 'bottom') {
topPoint -= winHeight - (elemHeight + mBtm);
bottomPoint -= winHeight - mBtm;
} else {
//this would be the stickTo: both option... tricky
}
this.topPoint = topPoint;
this.bottomPoint = bottomPoint;
if (cb && typeof cb === 'function') {
cb();
}
}
/**
* Destroys the current sticky element.
* Resets the element to the top position first.
* Removes event listeners, JS-added css properties and classes, and unwraps the $element if the JS added the $container.
* @function
*/
}, {
key: '_destroy',
value: function _destroy() {
this._removeSticky(true);
this.$element.removeClass(this.options.stickyClass + ' is-anchored is-at-top').css({
height: '',
top: '',
bottom: '',
'max-width': ''
}).off('resizeme.zf.trigger').off('mutateme.zf.trigger');
if (this.$anchor && this.$anchor.length) {
this.$anchor.off('change.zf.sticky');
}
__WEBPACK_IMPORTED_MODULE_0_jquery___default()(window).off(this.scrollListener);
if (this.wasWrapped) {
this.$element.unwrap();
} else {
this.$container.removeClass(this.options.containerClass).css({
height: ''
});
}
}
}]);
return Sticky;
}(__WEBPACK_IMPORTED_MODULE_3__foundation_plugin__["Plugin"]);
Sticky.defaults = {
/**
* Customizable container template. Add your own classes for styling and sizing.
* @option
* @type {string}
* @default '<div data-sticky-container></div>'
*/
container: '<div data-sticky-container></div>',
/**
* Location in the view the element sticks to. Can be `'top'` or `'bottom'`.
* @option
* @type {string}
* @default 'top'
*/
stickTo: 'top',
/**
* If anchored to a single element, the id of that element.
* @option
* @type {string}
* @default ''
*/
anchor: '',
/**
* If using more than one element as anchor points, the id of the top anchor.
* @option
* @type {string}
* @default ''
*/
topAnchor: '',
/**
* If using more than one element as anchor points, the id of the bottom anchor.
* @option
* @type {string}
* @default ''
*/
btmAnchor: '',
/**
* Margin, in `em`'s to apply to the top of the element when it becomes sticky.
* @option
* @type {number}
* @default 1
*/
marginTop: 1,
/**
* Margin, in `em`'s to apply to the bottom of the element when it becomes sticky.
* @option
* @type {number}
* @default 1
*/
marginBottom: 1,
/**
* Breakpoint string that is the minimum screen size an element should become sticky.
* @option
* @type {string}
* @default 'medium'
*/
stickyOn: 'medium',
/**
* Class applied to sticky element, and removed on destruction. Foundation defaults to `sticky`.
* @option
* @type {string}
* @default 'sticky'
*/
stickyClass: 'sticky',
/**
* Class applied to sticky container. Foundation defaults to `sticky-container`.
* @option
* @type {string}
* @default 'sticky-container'
*/
containerClass: 'sticky-container',
/**
* Number of scroll events between the plugin's recalculating sticky points. Setting it to `0` will cause it to recalc every scroll event, setting it to `-1` will prevent recalc on scroll.
* @option
* @type {number}
* @default -1
*/
checkEvery: -1
};
/**
* Helper function to calculate em values
* @param Number {em} - number of em's to calculate into pixels
*/
function emCalc(em) {
return parseInt(window.getComputedStyle(document.body, null).fontSize, 10) * em;
}
/***/ }),
/***/ 7:
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Triggers; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_jquery__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__foundation_util_motion__ = __webpack_require__(4);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__foundation_util_motion___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_1__foundation_util_motion__);
var MutationObserver = function () {
var prefixes = ['WebKit', 'Moz', 'O', 'Ms', ''];
for (var i = 0; i < prefixes.length; i++) {
if (prefixes[i] + 'MutationObserver' in window) {
return window[prefixes[i] + 'MutationObserver'];
}
}
return false;
}();
var triggers = function (el, type) {
el.data(type).split(' ').forEach(function (id) {
__WEBPACK_IMPORTED_MODULE_0_jquery___default()('#' + id)[type === 'close' ? 'trigger' : 'triggerHandler'](type + '.zf.trigger', [el]);
});
};
var Triggers = {
Listeners: {
Basic: {},
Global: {}
},
Initializers: {}
};
Triggers.Listeners.Basic = {
openListener: function () {
triggers(__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this), 'open');
},
closeListener: function () {
var id = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).data('close');
if (id) {
triggers(__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this), 'close');
} else {
__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).trigger('close.zf.trigger');
}
},
toggleListener: function () {
var id = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).data('toggle');
if (id) {
triggers(__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this), 'toggle');
} else {
__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).trigger('toggle.zf.trigger');
}
},
closeableListener: function (e) {
e.stopPropagation();
var animation = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).data('closable');
if (animation !== '') {
Foundation.Motion.animateOut(__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this), animation, function () {
__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).trigger('closed.zf');
});
} else {
__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).fadeOut().trigger('closed.zf');
}
},
toggleFocusListener: function () {
var id = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).data('toggle-focus');
__WEBPACK_IMPORTED_MODULE_0_jquery___default()('#' + id).triggerHandler('toggle.zf.trigger', [__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this)]);
}
};
// Elements with [data-open] will reveal a plugin that supports it when clicked.
Triggers.Initializers.addOpenListener = function ($elem) {
$elem.off('click.zf.trigger', Triggers.Listeners.Basic.openListener);
$elem.on('click.zf.trigger', '[data-open]', Triggers.Listeners.Basic.openListener);
};
// Elements with [data-close] will close a plugin that supports it when clicked.
// If used without a value on [data-close], the event will bubble, allowing it to close a parent component.
Triggers.Initializers.addCloseListener = function ($elem) {
$elem.off('click.zf.trigger', Triggers.Listeners.Basic.closeListener);
$elem.on('click.zf.trigger', '[data-close]', Triggers.Listeners.Basic.closeListener);
};
// Elements with [data-toggle] will toggle a plugin that supports it when clicked.
Triggers.Initializers.addToggleListener = function ($elem) {
$elem.off('click.zf.trigger', Triggers.Listeners.Basic.toggleListener);
$elem.on('click.zf.trigger', '[data-toggle]', Triggers.Listeners.Basic.toggleListener);
};
// Elements with [data-closable] will respond to close.zf.trigger events.
Triggers.Initializers.addCloseableListener = function ($elem) {
$elem.off('close.zf.trigger', Triggers.Listeners.Basic.closeableListener);
$elem.on('close.zf.trigger', '[data-closeable]', Triggers.Listeners.Basic.closeableListener);
};
// Elements with [data-toggle-focus] will respond to coming in and out of focus
Triggers.Initializers.addToggleFocusListener = function ($elem) {
$elem.off('focus.zf.trigger blur.zf.trigger', Triggers.Listeners.Basic.toggleFocusListener);
$elem.on('focus.zf.trigger blur.zf.trigger', '[data-toggle-focus]', Triggers.Listeners.Basic.toggleFocusListener);
};
// More Global/complex listeners and triggers
Triggers.Listeners.Global = {
resizeListener: function ($nodes) {
if (!MutationObserver) {
//fallback for IE 9
$nodes.each(function () {
__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).triggerHandler('resizeme.zf.trigger');
});
}
//trigger all listening elements and signal a resize event
$nodes.attr('data-events', "resize");
},
scrollListener: function ($nodes) {
if (!MutationObserver) {
//fallback for IE 9
$nodes.each(function () {
__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).triggerHandler('scrollme.zf.trigger');
});
}
//trigger all listening elements and signal a scroll event
$nodes.attr('data-events', "scroll");
},
closeMeListener: function (e, pluginId) {
var plugin = e.namespace.split('.')[0];
var plugins = __WEBPACK_IMPORTED_MODULE_0_jquery___default()('[data-' + plugin + ']').not('[data-yeti-box="' + pluginId + '"]');
plugins.each(function () {
var _this = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this);
_this.triggerHandler('close.zf.trigger', [_this]);
});
}
};
// Global, parses whole document.
Triggers.Initializers.addClosemeListener = function (pluginName) {
var yetiBoxes = __WEBPACK_IMPORTED_MODULE_0_jquery___default()('[data-yeti-box]'),
plugNames = ['dropdown', 'tooltip', 'reveal'];
if (pluginName) {
if (typeof pluginName === 'string') {
plugNames.push(pluginName);
} else if (typeof pluginName === 'object' && typeof pluginName[0] === 'string') {
plugNames.concat(pluginName);
} else {
console.error('Plugin names must be strings');
}
}
if (yetiBoxes.length) {
var listeners = plugNames.map(function (name) {
return 'closeme.zf.' + name;
}).join(' ');
__WEBPACK_IMPORTED_MODULE_0_jquery___default()(window).off(listeners).on(listeners, Triggers.Listeners.Global.closeMeListener);
}
};
function debounceGlobalListener(debounce, trigger, listener) {
var timer = void 0,
args = Array.prototype.slice.call(arguments, 3);
__WEBPACK_IMPORTED_MODULE_0_jquery___default()(window).off(trigger).on(trigger, function (e) {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(function () {
listener.apply(null, args);
}, debounce || 10); //default time to emit scroll event
});
}
Triggers.Initializers.addResizeListener = function (debounce) {
var $nodes = __WEBPACK_IMPORTED_MODULE_0_jquery___default()('[data-resize]');
if ($nodes.length) {
debounceGlobalListener(debounce, 'resize.zf.trigger', Triggers.Listeners.Global.resizeListener, $nodes);
}
};
Triggers.Initializers.addScrollListener = function (debounce) {
var $nodes = __WEBPACK_IMPORTED_MODULE_0_jquery___default()('[data-scroll]');
if ($nodes.length) {
debounceGlobalListener(debounce, 'scroll.zf.trigger', Triggers.Listeners.Global.scrollListener, $nodes);
}
};
Triggers.Initializers.addMutationEventsListener = function ($elem) {
if (!MutationObserver) {
return false;
}
var $nodes = $elem.find('[data-resize], [data-scroll], [data-mutate]');
//element callback
var listeningElementsMutation = function (mutationRecordsList) {
var $target = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(mutationRecordsList[0].target);
//trigger the event handler for the element depending on type
switch (mutationRecordsList[0].type) {
case "attributes":
if ($target.attr("data-events") === "scroll" && mutationRecordsList[0].attributeName === "data-events") {
$target.triggerHandler('scrollme.zf.trigger', [$target, window.pageYOffset]);
}
if ($target.attr("data-events") === "resize" && mutationRecordsList[0].attributeName === "data-events") {
$target.triggerHandler('resizeme.zf.trigger', [$target]);
}
if (mutationRecordsList[0].attributeName === "style") {
$target.closest("[data-mutate]").attr("data-events", "mutate");
$target.closest("[data-mutate]").triggerHandler('mutateme.zf.trigger', [$target.closest("[data-mutate]")]);
}
break;
case "childList":
$target.closest("[data-mutate]").attr("data-events", "mutate");
$target.closest("[data-mutate]").triggerHandler('mutateme.zf.trigger', [$target.closest("[data-mutate]")]);
break;
default:
return false;
//nothing
}
};
if ($nodes.length) {
//for each element that needs to listen for resizing, scrolling, or mutation add a single observer
for (var i = 0; i <= $nodes.length - 1; i++) {
var elementObserver = new MutationObserver(listeningElementsMutation);
elementObserver.observe($nodes[i], { attributes: true, childList: true, characterData: false, subtree: true, attributeFilter: ["data-events", "style"] });
}
}
};
Triggers.Initializers.addSimpleListeners = function () {
var $document = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(document);
Triggers.Initializers.addOpenListener($document);
Triggers.Initializers.addCloseListener($document);
Triggers.Initializers.addToggleListener($document);
Triggers.Initializers.addCloseableListener($document);
Triggers.Initializers.addToggleFocusListener($document);
};
Triggers.Initializers.addGlobalListeners = function () {
var $document = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(document);
Triggers.Initializers.addMutationEventsListener($document);
Triggers.Initializers.addResizeListener();
Triggers.Initializers.addScrollListener();
Triggers.Initializers.addClosemeListener();
};
Triggers.init = function ($, Foundation) {
if (typeof $.triggersInitialized === 'undefined') {
var $document = $(document);
if (document.readyState === "complete") {
Triggers.Initializers.addSimpleListeners();
Triggers.Initializers.addGlobalListeners();
} else {
$(window).on('load', function () {
Triggers.Initializers.addSimpleListeners();
Triggers.Initializers.addGlobalListeners();
});
}
$.triggersInitialized = true;
}
if (Foundation) {
Foundation.Triggers = Triggers;
// Legacy included to be backwards compatible for now.
Foundation.IHearYou = Triggers.Initializers.addGlobalListeners;
}
};
/***/ }),
/***/ 96:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(30);
/***/ })
/******/ }); | jeromelebleu/foundation-sites | dist/js/plugins/foundation.sticky.js | JavaScript | mit | 34,861 |
//
// [The "BSD license"]
// Copyright (c) 2012 Terence Parr
// Copyright (c) 2012 Sam Harwell
// Copyright (c) 2014 Eric Vergnaud
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// 3. The name of the author may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//
// The embodiment of the adaptive LL(*), ALL(*), parsing strategy.
//
// <p>
// The basic complexity of the adaptive strategy makes it harder to understand.
// We begin with ATN simulation to build paths in a DFA. Subsequent prediction
// requests go through the DFA first. If they reach a state without an edge for
// the current symbol, the algorithm fails over to the ATN simulation to
// complete the DFA path for the current input (until it finds a conflict state
// or uniquely predicting state).</p>
//
// <p>
// All of that is done without using the outer context because we want to create
// a DFA that is not dependent upon the rule invocation stack when we do a
// prediction. One DFA works in all contexts. We avoid using context not
// necessarily because it's slower, although it can be, but because of the DFA
// caching problem. The closure routine only considers the rule invocation stack
// created during prediction beginning in the decision rule. For example, if
// prediction occurs without invoking another rule's ATN, there are no context
// stacks in the configurations. When lack of context leads to a conflict, we
// don't know if it's an ambiguity or a weakness in the strong LL(*) parsing
// strategy (versus full LL(*)).</p>
//
// <p>
// When SLL yields a configuration set with conflict, we rewind the input and
// retry the ATN simulation, this time using full outer context without adding
// to the DFA. Configuration context stacks will be the full invocation stacks
// from the start rule. If we get a conflict using full context, then we can
// definitively say we have a true ambiguity for that input sequence. If we
// don't get a conflict, it implies that the decision is sensitive to the outer
// context. (It is not context-sensitive in the sense of context-sensitive
// grammars.)</p>
//
// <p>
// The next time we reach this DFA state with an SLL conflict, through DFA
// simulation, we will again retry the ATN simulation using full context mode.
// This is slow because we can't save the results and have to "interpret" the
// ATN each time we get that input.</p>
//
// <p>
// <strong>CACHING FULL CONTEXT PREDICTIONS</strong></p>
//
// <p>
// We could cache results from full context to predicted alternative easily and
// that saves a lot of time but doesn't work in presence of predicates. The set
// of visible predicates from the ATN start state changes depending on the
// context, because closure can fall off the end of a rule. I tried to cache
// tuples (stack context, semantic context, predicted alt) but it was slower
// than interpreting and much more complicated. Also required a huge amount of
// memory. The goal is not to create the world's fastest parser anyway. I'd like
// to keep this algorithm simple. By launching multiple threads, we can improve
// the speed of parsing across a large number of files.</p>
//
// <p>
// There is no strict ordering between the amount of input used by SLL vs LL,
// which makes it really hard to build a cache for full context. Let's say that
// we have input A B C that leads to an SLL conflict with full context X. That
// implies that using X we might only use A B but we could also use A B C D to
// resolve conflict. Input A B C D could predict alternative 1 in one position
// in the input and A B C E could predict alternative 2 in another position in
// input. The conflicting SLL configurations could still be non-unique in the
// full context prediction, which would lead us to requiring more input than the
// original A B C. To make a prediction cache work, we have to track the exact
// input used during the previous prediction. That amounts to a cache that maps
// X to a specific DFA for that context.</p>
//
// <p>
// Something should be done for left-recursive expression predictions. They are
// likely LL(1) + pred eval. Easier to do the whole SLL unless error and retry
// with full LL thing Sam does.</p>
//
// <p>
// <strong>AVOIDING FULL CONTEXT PREDICTION</strong></p>
//
// <p>
// We avoid doing full context retry when the outer context is empty, we did not
// dip into the outer context by falling off the end of the decision state rule,
// or when we force SLL mode.</p>
//
// <p>
// As an example of the not dip into outer context case, consider as super
// constructor calls versus function calls. One grammar might look like
// this:</p>
//
// <pre>
// ctorBody
// : '{' superCall? stat* '}'
// ;
// </pre>
//
// <p>
// Or, you might see something like</p>
//
// <pre>
// stat
// : superCall ';'
// | expression ';'
// | ...
// ;
// </pre>
//
// <p>
// In both cases I believe that no closure operations will dip into the outer
// context. In the first case ctorBody in the worst case will stop at the '}'.
// In the 2nd case it should stop at the ';'. Both cases should stay within the
// entry rule and not dip into the outer context.</p>
//
// <p>
// <strong>PREDICATES</strong></p>
//
// <p>
// Predicates are always evaluated if present in either SLL or LL both. SLL and
// LL simulation deals with predicates differently. SLL collects predicates as
// it performs closure operations like ANTLR v3 did. It delays predicate
// evaluation until it reaches and accept state. This allows us to cache the SLL
// ATN simulation whereas, if we had evaluated predicates on-the-fly during
// closure, the DFA state configuration sets would be different and we couldn't
// build up a suitable DFA.</p>
//
// <p>
// When building a DFA accept state during ATN simulation, we evaluate any
// predicates and return the sole semantically valid alternative. If there is
// more than 1 alternative, we report an ambiguity. If there are 0 alternatives,
// we throw an exception. Alternatives without predicates act like they have
// true predicates. The simple way to think about it is to strip away all
// alternatives with false predicates and choose the minimum alternative that
// remains.</p>
//
// <p>
// When we start in the DFA and reach an accept state that's predicated, we test
// those and return the minimum semantically viable alternative. If no
// alternatives are viable, we throw an exception.</p>
//
// <p>
// During full LL ATN simulation, closure always evaluates predicates and
// on-the-fly. This is crucial to reducing the configuration set size during
// closure. It hits a landmine when parsing with the Java grammar, for example,
// without this on-the-fly evaluation.</p>
//
// <p>
// <strong>SHARING DFA</strong></p>
//
// <p>
// All instances of the same parser share the same decision DFAs through a
// static field. Each instance gets its own ATN simulator but they share the
// same {@link //decisionToDFA} field. They also share a
// {@link PredictionContextCache} object that makes sure that all
// {@link PredictionContext} objects are shared among the DFA states. This makes
// a big size difference.</p>
//
// <p>
// <strong>THREAD SAFETY</strong></p>
//
// <p>
// The {@link ParserATNSimulator} locks on the {@link //decisionToDFA} field when
// it adds a new DFA object to that array. {@link //addDFAEdge}
// locks on the DFA for the current decision when setting the
// {@link DFAState//edges} field. {@link //addDFAState} locks on
// the DFA for the current decision when looking up a DFA state to see if it
// already exists. We must make sure that all requests to add DFA states that
// are equivalent result in the same shared DFA object. This is because lots of
// threads will be trying to update the DFA at once. The
// {@link //addDFAState} method also locks inside the DFA lock
// but this time on the shared context cache when it rebuilds the
// configurations' {@link PredictionContext} objects using cached
// subgraphs/nodes. No other locking occurs, even during DFA simulation. This is
// safe as long as we can guarantee that all threads referencing
// {@code s.edge[t]} get the same physical target {@link DFAState}, or
// {@code null}. Once into the DFA, the DFA simulation does not reference the
// {@link DFA//states} map. It follows the {@link DFAState//edges} field to new
// targets. The DFA simulator will either find {@link DFAState//edges} to be
// {@code null}, to be non-{@code null} and {@code dfa.edges[t]} null, or
// {@code dfa.edges[t]} to be non-null. The
// {@link //addDFAEdge} method could be racing to set the field
// but in either case the DFA simulator works; if {@code null}, and requests ATN
// simulation. It could also race trying to get {@code dfa.edges[t]}, but either
// way it will work because it's not doing a test and set operation.</p>
//
// <p>
// <strong>Starting with SLL then failing to combined SLL/LL (Two-Stage
// Parsing)</strong></p>
//
// <p>
// Sam pointed out that if SLL does not give a syntax error, then there is no
// point in doing full LL, which is slower. We only have to try LL if we get a
// syntax error. For maximum speed, Sam starts the parser set to pure SLL
// mode with the {@link BailErrorStrategy}:</p>
//
// <pre>
// parser.{@link Parser//getInterpreter() getInterpreter()}.{@link //setPredictionMode setPredictionMode}{@code (}{@link PredictionMode//SLL}{@code )};
// parser.{@link Parser//setErrorHandler setErrorHandler}(new {@link BailErrorStrategy}());
// </pre>
//
// <p>
// If it does not get a syntax error, then we're done. If it does get a syntax
// error, we need to retry with the combined SLL/LL strategy.</p>
//
// <p>
// The reason this works is as follows. If there are no SLL conflicts, then the
// grammar is SLL (at least for that input set). If there is an SLL conflict,
// the full LL analysis must yield a set of viable alternatives which is a
// subset of the alternatives reported by SLL. If the LL set is a singleton,
// then the grammar is LL but not SLL. If the LL set is the same size as the SLL
// set, the decision is SLL. If the LL set has size > 1, then that decision
// is truly ambiguous on the current input. If the LL set is smaller, then the
// SLL conflict resolution might choose an alternative that the full LL would
// rule out as a possibility based upon better context information. If that's
// the case, then the SLL parse will definitely get an error because the full LL
// analysis says it's not viable. If SLL conflict resolution chooses an
// alternative within the LL set, them both SLL and LL would choose the same
// alternative because they both choose the minimum of multiple conflicting
// alternatives.</p>
//
// <p>
// Let's say we have a set of SLL conflicting alternatives {@code {1, 2, 3}} and
// a smaller LL set called <em>s</em>. If <em>s</em> is {@code {2, 3}}, then SLL
// parsing will get an error because SLL will pursue alternative 1. If
// <em>s</em> is {@code {1, 2}} or {@code {1, 3}} then both SLL and LL will
// choose the same alternative because alternative one is the minimum of either
// set. If <em>s</em> is {@code {2}} or {@code {3}} then SLL will get a syntax
// error. If <em>s</em> is {@code {1}} then SLL will succeed.</p>
//
// <p>
// Of course, if the input is invalid, then we will get an error for sure in
// both SLL and LL parsing. Erroneous input will therefore require 2 passes over
// the input.</p>
//
var Utils = require('./../Utils');
var Set = Utils.Set;
var BitSet = Utils.BitSet;
var DoubleDict = Utils.DoubleDict;
var ATN = require('./ATN').ATN;
var ATNConfig = require('./ATNConfig').ATNConfig;
var ATNConfigSet = require('./ATNConfigSet').ATNConfigSet;
var Token = require('./../Token').Token;
var DFAState = require('./../dfa/DFAState').DFAState;
var PredPrediction = require('./../dfa/DFAState').PredPrediction;
var ATNSimulator = require('./ATNSimulator').ATNSimulator;
var PredictionMode = require('./PredictionMode').PredictionMode;
var RuleContext = require('./../RuleContext').RuleContext;
var ParserRuleContext = require('./../ParserRuleContext').ParserRuleContext;
var SemanticContext = require('./SemanticContext').SemanticContext;
var StarLoopEntryState = require('./ATNState').StarLoopEntryState;
var RuleStopState = require('./ATNState').RuleStopState;
var PredictionContext = require('./../PredictionContext').PredictionContext;
var Interval = require('./../IntervalSet').Interval;
var Transitions = require('./Transition');
var Transition = Transitions.Transition;
var SetTransition = Transitions.SetTransition;
var NotSetTransition = Transitions.NotSetTransition;
var RuleTransition = Transitions.RuleTransition;
var ActionTransition = Transitions.ActionTransition;
var NoViableAltException = require('./../error/Errors').NoViableAltException;
var SingletonPredictionContext = require('./../PredictionContext').SingletonPredictionContext;
var predictionContextFromRuleContext = require('./../PredictionContext').predictionContextFromRuleContext;
function ParserATNSimulator(parser, atn, decisionToDFA, sharedContextCache) {
ATNSimulator.call(this, atn, sharedContextCache);
this.parser = parser;
this.decisionToDFA = decisionToDFA;
// SLL, LL, or LL + exact ambig detection?//
this.predictionMode = PredictionMode.LL;
// LAME globals to avoid parameters!!!!! I need these down deep in predTransition
this._input = null;
this._startIndex = 0;
this._outerContext = null;
this._dfa = null;
// Each prediction operation uses a cache for merge of prediction contexts.
// Don't keep around as it wastes huge amounts of memory. DoubleKeyMap
// isn't synchronized but we're ok since two threads shouldn't reuse same
// parser/atnsim object because it can only handle one input at a time.
// This maps graphs a and b to merged result c. (a,b)→c. We can avoid
// the merge if we ever see a and b again. Note that (b,a)→c should
// also be examined during cache lookup.
//
this.mergeCache = null;
return this;
}
ParserATNSimulator.prototype = Object.create(ATNSimulator.prototype);
ParserATNSimulator.prototype.constructor = ParserATNSimulator;
ParserATNSimulator.prototype.debug = false;
ParserATNSimulator.prototype.debug_list_atn_decisions = false;
ParserATNSimulator.prototype.dfa_debug = false;
ParserATNSimulator.prototype.retry_debug = false;
ParserATNSimulator.prototype.reset = function() {
};
ParserATNSimulator.prototype.adaptivePredict = function(input, decision, outerContext) {
if (this.debug || this.debug_list_atn_decisions) {
console.log("adaptivePredict decision " + decision +
" exec LA(1)==" + this.getLookaheadName(input) +
" line " + input.LT(1).line + ":" +
input.LT(1).column);
}
this._input = input;
this._startIndex = input.index;
this._outerContext = outerContext;
var dfa = this.decisionToDFA[decision];
this._dfa = dfa;
var m = input.mark();
var index = input.index;
// Now we are certain to have a specific decision's DFA
// But, do we still need an initial state?
try {
var s0;
if (dfa.precedenceDfa) {
// the start state for a precedence DFA depends on the current
// parser precedence, and is provided by a DFA method.
s0 = dfa.getPrecedenceStartState(this.parser.getPrecedence());
} else {
// the start state for a "regular" DFA is just s0
s0 = dfa.s0;
}
if (s0===null) {
if (outerContext===null) {
outerContext = RuleContext.EMPTY;
}
if (this.debug || this.debug_list_atn_decisions) {
console.log("predictATN decision " + dfa.decision +
" exec LA(1)==" + this.getLookaheadName(input) +
", outerContext=" + outerContext.toString(this.parser.ruleNames));
}
// If this is not a precedence DFA, we check the ATN start state
// to determine if this ATN start state is the decision for the
// closure block that determines whether a precedence rule
// should continue or complete.
//
if (!dfa.precedenceDfa && (dfa.atnStartState instanceof StarLoopEntryState)) {
if (dfa.atnStartState.precedenceRuleDecision) {
dfa.setPrecedenceDfa(true);
}
}
var fullCtx = false;
var s0_closure = this.computeStartState(dfa.atnStartState, RuleContext.EMPTY, fullCtx);
if( dfa.precedenceDfa) {
// If this is a precedence DFA, we use applyPrecedenceFilter
// to convert the computed start state to a precedence start
// state. We then use DFA.setPrecedenceStartState to set the
// appropriate start state for the precedence level rather
// than simply setting DFA.s0.
//
s0_closure = this.applyPrecedenceFilter(s0_closure);
s0 = this.addDFAState(dfa, new DFAState(null, s0_closure));
dfa.setPrecedenceStartState(this.parser.getPrecedence(), s0);
} else {
s0 = this.addDFAState(dfa, new DFAState(null, s0_closure));
dfa.s0 = s0;
}
}
var alt = this.execATN(dfa, s0, input, index, outerContext);
if (this.debug) {
console.log("DFA after predictATN: " + dfa.toString(this.parser.literalNames));
}
return alt;
} finally {
this._dfa = null;
this.mergeCache = null; // wack cache after each prediction
input.seek(index);
input.release(m);
}
};
// Performs ATN simulation to compute a predicted alternative based
// upon the remaining input, but also updates the DFA cache to avoid
// having to traverse the ATN again for the same input sequence.
// There are some key conditions we're looking for after computing a new
// set of ATN configs (proposed DFA state):
// if the set is empty, there is no viable alternative for current symbol
// does the state uniquely predict an alternative?
// does the state have a conflict that would prevent us from
// putting it on the work list?
// We also have some key operations to do:
// add an edge from previous DFA state to potentially new DFA state, D,
// upon current symbol but only if adding to work list, which means in all
// cases except no viable alternative (and possibly non-greedy decisions?)
// collecting predicates and adding semantic context to DFA accept states
// adding rule context to context-sensitive DFA accept states
// consuming an input symbol
// reporting a conflict
// reporting an ambiguity
// reporting a context sensitivity
// reporting insufficient predicates
// cover these cases:
// dead end
// single alt
// single alt + preds
// conflict
// conflict + preds
//
ParserATNSimulator.prototype.execATN = function(dfa, s0, input, startIndex, outerContext ) {
if (this.debug || this.debug_list_atn_decisions) {
console.log("execATN decision " + dfa.decision +
" exec LA(1)==" + this.getLookaheadName(input) +
" line " + input.LT(1).line + ":" + input.LT(1).column);
}
var alt;
var previousD = s0;
if (this.debug) {
console.log("s0 = " + s0);
}
var t = input.LA(1);
while(true) { // while more work
var D = this.getExistingTargetState(previousD, t);
if(D===null) {
D = this.computeTargetState(dfa, previousD, t);
}
if(D===ATNSimulator.ERROR) {
// if any configs in previous dipped into outer context, that
// means that input up to t actually finished entry rule
// at least for SLL decision. Full LL doesn't dip into outer
// so don't need special case.
// We will get an error no matter what so delay until after
// decision; better error message. Also, no reachable target
// ATN states in SLL implies LL will also get nowhere.
// If conflict in states that dip out, choose min since we
// will get error no matter what.
var e = this.noViableAlt(input, outerContext, previousD.configs, startIndex);
input.seek(startIndex);
alt = this.getSynValidOrSemInvalidAltThatFinishedDecisionEntryRule(previousD.configs, outerContext);
if(alt!==ATN.INVALID_ALT_NUMBER) {
return alt;
} else {
throw e;
}
}
if(D.requiresFullContext && this.predictionMode !== PredictionMode.SLL) {
// IF PREDS, MIGHT RESOLVE TO SINGLE ALT => SLL (or syntax error)
var conflictingAlts = null;
if (D.predicates!==null) {
if (this.debug) {
console.log("DFA state has preds in DFA sim LL failover");
}
var conflictIndex = input.index;
if(conflictIndex !== startIndex) {
input.seek(startIndex);
}
conflictingAlts = this.evalSemanticContext(D.predicates, outerContext, true);
if (conflictingAlts.length===1) {
if(this.debug) {
console.log("Full LL avoided");
}
return conflictingAlts.minValue();
}
if (conflictIndex !== startIndex) {
// restore the index so reporting the fallback to full
// context occurs with the index at the correct spot
input.seek(conflictIndex);
}
}
if (this.dfa_debug) {
console.log("ctx sensitive state " + outerContext +" in " + D);
}
var fullCtx = true;
var s0_closure = this.computeStartState(dfa.atnStartState, outerContext, fullCtx);
this.reportAttemptingFullContext(dfa, conflictingAlts, D.configs, startIndex, input.index);
alt = this.execATNWithFullContext(dfa, D, s0_closure, input, startIndex, outerContext);
return alt;
}
if (D.isAcceptState) {
if (D.predicates===null) {
return D.prediction;
}
var stopIndex = input.index;
input.seek(startIndex);
var alts = this.evalSemanticContext(D.predicates, outerContext, true);
if (alts.length===0) {
throw this.noViableAlt(input, outerContext, D.configs, startIndex);
} else if (alts.length===1) {
return alts.minValue();
} else {
// report ambiguity after predicate evaluation to make sure the correct set of ambig alts is reported.
this.reportAmbiguity(dfa, D, startIndex, stopIndex, false, alts, D.configs);
return alts.minValue();
}
}
previousD = D;
if (t !== Token.EOF) {
input.consume();
t = input.LA(1);
}
}
};
//
// Get an existing target state for an edge in the DFA. If the target state
// for the edge has not yet been computed or is otherwise not available,
// this method returns {@code null}.
//
// @param previousD The current DFA state
// @param t The next input symbol
// @return The existing target DFA state for the given input symbol
// {@code t}, or {@code null} if the target state for this edge is not
// already cached
//
ParserATNSimulator.prototype.getExistingTargetState = function(previousD, t) {
var edges = previousD.edges;
if (edges===null) {
return null;
} else {
return edges[t + 1] || null;
}
};
//
// Compute a target state for an edge in the DFA, and attempt to add the
// computed state and corresponding edge to the DFA.
//
// @param dfa The DFA
// @param previousD The current DFA state
// @param t The next input symbol
//
// @return The computed target DFA state for the given input symbol
// {@code t}. If {@code t} does not lead to a valid DFA state, this method
// returns {@link //ERROR}.
//
ParserATNSimulator.prototype.computeTargetState = function(dfa, previousD, t) {
var reach = this.computeReachSet(previousD.configs, t, false);
if(reach===null) {
this.addDFAEdge(dfa, previousD, t, ATNSimulator.ERROR);
return ATNSimulator.ERROR;
}
// create new target state; we'll add to DFA after it's complete
var D = new DFAState(null, reach);
var predictedAlt = this.getUniqueAlt(reach);
if (this.debug) {
var altSubSets = PredictionMode.getConflictingAltSubsets(reach);
console.log("SLL altSubSets=" + Utils.arrayToString(altSubSets) +
", previous=" + previousD.configs +
", configs=" + reach +
", predict=" + predictedAlt +
", allSubsetsConflict=" +
PredictionMode.allSubsetsConflict(altSubSets) + ", conflictingAlts=" +
this.getConflictingAlts(reach));
}
if (predictedAlt!==ATN.INVALID_ALT_NUMBER) {
// NO CONFLICT, UNIQUELY PREDICTED ALT
D.isAcceptState = true;
D.configs.uniqueAlt = predictedAlt;
D.prediction = predictedAlt;
} else if (PredictionMode.hasSLLConflictTerminatingPrediction(this.predictionMode, reach)) {
// MORE THAN ONE VIABLE ALTERNATIVE
D.configs.conflictingAlts = this.getConflictingAlts(reach);
D.requiresFullContext = true;
// in SLL-only mode, we will stop at this state and return the minimum alt
D.isAcceptState = true;
D.prediction = D.configs.conflictingAlts.minValue();
}
if (D.isAcceptState && D.configs.hasSemanticContext) {
this.predicateDFAState(D, this.atn.getDecisionState(dfa.decision));
if( D.predicates!==null) {
D.prediction = ATN.INVALID_ALT_NUMBER;
}
}
// all adds to dfa are done after we've created full D state
D = this.addDFAEdge(dfa, previousD, t, D);
return D;
};
ParserATNSimulator.prototype.predicateDFAState = function(dfaState, decisionState) {
// We need to test all predicates, even in DFA states that
// uniquely predict alternative.
var nalts = decisionState.transitions.length;
// Update DFA so reach becomes accept state with (predicate,alt)
// pairs if preds found for conflicting alts
var altsToCollectPredsFrom = this.getConflictingAltsOrUniqueAlt(dfaState.configs);
var altToPred = this.getPredsForAmbigAlts(altsToCollectPredsFrom, dfaState.configs, nalts);
if (altToPred!==null) {
dfaState.predicates = this.getPredicatePredictions(altsToCollectPredsFrom, altToPred);
dfaState.prediction = ATN.INVALID_ALT_NUMBER; // make sure we use preds
} else {
// There are preds in configs but they might go away
// when OR'd together like {p}? || NONE == NONE. If neither
// alt has preds, resolve to min alt
dfaState.prediction = altsToCollectPredsFrom.minValue();
}
};
// comes back with reach.uniqueAlt set to a valid alt
ParserATNSimulator.prototype.execATNWithFullContext = function(dfa, D, // how far we got before failing over
s0,
input,
startIndex,
outerContext) {
if (this.debug || this.debug_list_atn_decisions) {
console.log("execATNWithFullContext "+s0);
}
var fullCtx = true;
var foundExactAmbig = false;
var reach = null;
var previous = s0;
input.seek(startIndex);
var t = input.LA(1);
var predictedAlt = -1;
while (true) { // while more work
reach = this.computeReachSet(previous, t, fullCtx);
if (reach===null) {
// if any configs in previous dipped into outer context, that
// means that input up to t actually finished entry rule
// at least for LL decision. Full LL doesn't dip into outer
// so don't need special case.
// We will get an error no matter what so delay until after
// decision; better error message. Also, no reachable target
// ATN states in SLL implies LL will also get nowhere.
// If conflict in states that dip out, choose min since we
// will get error no matter what.
var e = this.noViableAlt(input, outerContext, previous, startIndex);
input.seek(startIndex);
var alt = this.getSynValidOrSemInvalidAltThatFinishedDecisionEntryRule(previous, outerContext);
if(alt!==ATN.INVALID_ALT_NUMBER) {
return alt;
} else {
throw e;
}
}
var altSubSets = PredictionMode.getConflictingAltSubsets(reach);
if(this.debug) {
console.log("LL altSubSets=" + altSubSets + ", predict=" +
PredictionMode.getUniqueAlt(altSubSets) + ", resolvesToJustOneViableAlt=" +
PredictionMode.resolvesToJustOneViableAlt(altSubSets));
}
reach.uniqueAlt = this.getUniqueAlt(reach);
// unique prediction?
if(reach.uniqueAlt!==ATN.INVALID_ALT_NUMBER) {
predictedAlt = reach.uniqueAlt;
break;
} else if (this.predictionMode !== PredictionMode.LL_EXACT_AMBIG_DETECTION) {
predictedAlt = PredictionMode.resolvesToJustOneViableAlt(altSubSets);
if(predictedAlt !== ATN.INVALID_ALT_NUMBER) {
break;
}
} else {
// In exact ambiguity mode, we never try to terminate early.
// Just keeps scarfing until we know what the conflict is
if (PredictionMode.allSubsetsConflict(altSubSets) && PredictionMode.allSubsetsEqual(altSubSets)) {
foundExactAmbig = true;
predictedAlt = PredictionMode.getSingleViableAlt(altSubSets);
break;
}
// else there are multiple non-conflicting subsets or
// we're not sure what the ambiguity is yet.
// So, keep going.
}
previous = reach;
if( t !== Token.EOF) {
input.consume();
t = input.LA(1);
}
}
// If the configuration set uniquely predicts an alternative,
// without conflict, then we know that it's a full LL decision
// not SLL.
if (reach.uniqueAlt !== ATN.INVALID_ALT_NUMBER ) {
this.reportContextSensitivity(dfa, predictedAlt, reach, startIndex, input.index);
return predictedAlt;
}
// We do not check predicates here because we have checked them
// on-the-fly when doing full context prediction.
//
// In non-exact ambiguity detection mode, we might actually be able to
// detect an exact ambiguity, but I'm not going to spend the cycles
// needed to check. We only emit ambiguity warnings in exact ambiguity
// mode.
//
// For example, we might know that we have conflicting configurations.
// But, that does not mean that there is no way forward without a
// conflict. It's possible to have nonconflicting alt subsets as in:
// altSubSets=[{1, 2}, {1, 2}, {1}, {1, 2}]
// from
//
// [(17,1,[5 $]), (13,1,[5 10 $]), (21,1,[5 10 $]), (11,1,[$]),
// (13,2,[5 10 $]), (21,2,[5 10 $]), (11,2,[$])]
//
// In this case, (17,1,[5 $]) indicates there is some next sequence that
// would resolve this without conflict to alternative 1. Any other viable
// next sequence, however, is associated with a conflict. We stop
// looking for input because no amount of further lookahead will alter
// the fact that we should predict alternative 1. We just can't say for
// sure that there is an ambiguity without looking further.
this.reportAmbiguity(dfa, D, startIndex, input.index, foundExactAmbig, null, reach);
return predictedAlt;
};
ParserATNSimulator.prototype.computeReachSet = function(closure, t, fullCtx) {
if (this.debug) {
console.log("in computeReachSet, starting closure: " + closure);
}
if( this.mergeCache===null) {
this.mergeCache = new DoubleDict();
}
var intermediate = new ATNConfigSet(fullCtx);
// Configurations already in a rule stop state indicate reaching the end
// of the decision rule (local context) or end of the start rule (full
// context). Once reached, these configurations are never updated by a
// closure operation, so they are handled separately for the performance
// advantage of having a smaller intermediate set when calling closure.
//
// For full-context reach operations, separate handling is required to
// ensure that the alternative matching the longest overall sequence is
// chosen when multiple such configurations can match the input.
var skippedStopStates = null;
// First figure out where we can reach on input t
for (var i=0; i<closure.items.length;i++) {
var c = closure.items[i];
if(this.debug) {
console.log("testing " + this.getTokenName(t) + " at " + c);
}
if (c.state instanceof RuleStopState) {
if (fullCtx || t === Token.EOF) {
if (skippedStopStates===null) {
skippedStopStates = [];
}
skippedStopStates.push(c);
if(this.debug) {
console.log("added " + c + " to skippedStopStates");
}
}
continue;
}
for(var j=0;j<c.state.transitions.length;j++) {
var trans = c.state.transitions[j];
var target = this.getReachableTarget(trans, t);
if (target!==null) {
var cfg = new ATNConfig({state:target}, c);
intermediate.add(cfg, this.mergeCache);
if(this.debug) {
console.log("added " + cfg + " to intermediate");
}
}
}
}
// Now figure out where the reach operation can take us...
var reach = null;
// This block optimizes the reach operation for intermediate sets which
// trivially indicate a termination state for the overall
// adaptivePredict operation.
//
// The conditions assume that intermediate
// contains all configurations relevant to the reach set, but this
// condition is not true when one or more configurations have been
// withheld in skippedStopStates, or when the current symbol is EOF.
//
if (skippedStopStates===null && t!==Token.EOF) {
if (intermediate.items.length===1) {
// Don't pursue the closure if there is just one state.
// It can only have one alternative; just add to result
// Also don't pursue the closure if there is unique alternative
// among the configurations.
reach = intermediate;
} else if (this.getUniqueAlt(intermediate)!==ATN.INVALID_ALT_NUMBER) {
// Also don't pursue the closure if there is unique alternative
// among the configurations.
reach = intermediate;
}
}
// If the reach set could not be trivially determined, perform a closure
// operation on the intermediate set to compute its initial value.
//
if (reach===null) {
reach = new ATNConfigSet(fullCtx);
var closureBusy = new Set();
var treatEofAsEpsilon = t === Token.EOF;
for (var k=0; k<intermediate.items.length;k++) {
this.closure(intermediate.items[k], reach, closureBusy, false, fullCtx, treatEofAsEpsilon);
}
}
if (t === Token.EOF) {
// After consuming EOF no additional input is possible, so we are
// only interested in configurations which reached the end of the
// decision rule (local context) or end of the start rule (full
// context). Update reach to contain only these configurations. This
// handles both explicit EOF transitions in the grammar and implicit
// EOF transitions following the end of the decision or start rule.
//
// When reach==intermediate, no closure operation was performed. In
// this case, removeAllConfigsNotInRuleStopState needs to check for
// reachable rule stop states as well as configurations already in
// a rule stop state.
//
// This is handled before the configurations in skippedStopStates,
// because any configurations potentially added from that list are
// already guaranteed to meet this condition whether or not it's
// required.
//
reach = this.removeAllConfigsNotInRuleStopState(reach, reach === intermediate);
}
// If skippedStopStates!==null, then it contains at least one
// configuration. For full-context reach operations, these
// configurations reached the end of the start rule, in which case we
// only add them back to reach if no configuration during the current
// closure operation reached such a state. This ensures adaptivePredict
// chooses an alternative matching the longest overall sequence when
// multiple alternatives are viable.
//
if (skippedStopStates!==null && ( (! fullCtx) || (! PredictionMode.hasConfigInRuleStopState(reach)))) {
for (var l=0; l<skippedStopStates.length;l++) {
reach.add(skippedStopStates[l], this.mergeCache);
}
}
if (reach.items.length===0) {
return null;
} else {
return reach;
}
};
//
// Return a configuration set containing only the configurations from
// {@code configs} which are in a {@link RuleStopState}. If all
// configurations in {@code configs} are already in a rule stop state, this
// method simply returns {@code configs}.
//
// <p>When {@code lookToEndOfRule} is true, this method uses
// {@link ATN//nextTokens} for each configuration in {@code configs} which is
// not already in a rule stop state to see if a rule stop state is reachable
// from the configuration via epsilon-only transitions.</p>
//
// @param configs the configuration set to update
// @param lookToEndOfRule when true, this method checks for rule stop states
// reachable by epsilon-only transitions from each configuration in
// {@code configs}.
//
// @return {@code configs} if all configurations in {@code configs} are in a
// rule stop state, otherwise return a new configuration set containing only
// the configurations from {@code configs} which are in a rule stop state
//
ParserATNSimulator.prototype.removeAllConfigsNotInRuleStopState = function(configs, lookToEndOfRule) {
if (PredictionMode.allConfigsInRuleStopStates(configs)) {
return configs;
}
var result = new ATNConfigSet(configs.fullCtx);
for(var i=0; i<configs.items.length;i++) {
var config = configs.items[i];
if (config.state instanceof RuleStopState) {
result.add(config, this.mergeCache);
continue;
}
if (lookToEndOfRule && config.state.epsilonOnlyTransitions) {
var nextTokens = this.atn.nextTokens(config.state);
if (nextTokens.contains(Token.EPSILON)) {
var endOfRuleState = this.atn.ruleToStopState[config.state.ruleIndex];
result.add(new ATNConfig({state:endOfRuleState}, config), this.mergeCache);
}
}
}
return result;
};
ParserATNSimulator.prototype.computeStartState = function(p, ctx, fullCtx) {
// always at least the implicit call to start rule
var initialContext = predictionContextFromRuleContext(this.atn, ctx);
var configs = new ATNConfigSet(fullCtx);
for(var i=0;i<p.transitions.length;i++) {
var target = p.transitions[i].target;
var c = new ATNConfig({ state:target, alt:i+1, context:initialContext }, null);
var closureBusy = new Set();
this.closure(c, configs, closureBusy, true, fullCtx, false);
}
return configs;
};
//
// This method transforms the start state computed by
// {@link //computeStartState} to the special start state used by a
// precedence DFA for a particular precedence value. The transformation
// process applies the following changes to the start state's configuration
// set.
//
// <ol>
// <li>Evaluate the precedence predicates for each configuration using
// {@link SemanticContext//evalPrecedence}.</li>
// <li>Remove all configurations which predict an alternative greater than
// 1, for which another configuration that predicts alternative 1 is in the
// same ATN state with the same prediction context. This transformation is
// valid for the following reasons:
// <ul>
// <li>The closure block cannot contain any epsilon transitions which bypass
// the body of the closure, so all states reachable via alternative 1 are
// part of the precedence alternatives of the transformed left-recursive
// rule.</li>
// <li>The "primary" portion of a left recursive rule cannot contain an
// epsilon transition, so the only way an alternative other than 1 can exist
// in a state that is also reachable via alternative 1 is by nesting calls
// to the left-recursive rule, with the outer calls not being at the
// preferred precedence level.</li>
// </ul>
// </li>
// </ol>
//
// <p>
// The prediction context must be considered by this filter to address
// situations like the following.
// </p>
// <code>
// <pre>
// grammar TA;
// prog: statement* EOF;
// statement: letterA | statement letterA 'b' ;
// letterA: 'a';
// </pre>
// </code>
// <p>
// If the above grammar, the ATN state immediately before the token
// reference {@code 'a'} in {@code letterA} is reachable from the left edge
// of both the primary and closure blocks of the left-recursive rule
// {@code statement}. The prediction context associated with each of these
// configurations distinguishes between them, and prevents the alternative
// which stepped out to {@code prog} (and then back in to {@code statement}
// from being eliminated by the filter.
// </p>
//
// @param configs The configuration set computed by
// {@link //computeStartState} as the start state for the DFA.
// @return The transformed configuration set representing the start state
// for a precedence DFA at a particular precedence level (determined by
// calling {@link Parser//getPrecedence}).
//
ParserATNSimulator.prototype.applyPrecedenceFilter = function(configs) {
var config;
var statesFromAlt1 = [];
var configSet = new ATNConfigSet(configs.fullCtx);
for(var i=0; i<configs.items.length; i++) {
config = configs.items[i];
// handle alt 1 first
if (config.alt !== 1) {
continue;
}
var updatedContext = config.semanticContext.evalPrecedence(this.parser, this._outerContext);
if (updatedContext===null) {
// the configuration was eliminated
continue;
}
statesFromAlt1[config.state.stateNumber] = config.context;
if (updatedContext !== config.semanticContext) {
configSet.add(new ATNConfig({semanticContext:updatedContext}, config), this.mergeCache);
} else {
configSet.add(config, this.mergeCache);
}
}
for(i=0; i<configs.items.length; i++) {
config = configs.items[i];
if (config.alt === 1) {
// already handled
continue;
}
// In the future, this elimination step could be updated to also
// filter the prediction context for alternatives predicting alt>1
// (basically a graph subtraction algorithm).
if (!config.precedenceFilterSuppressed) {
var context = statesFromAlt1[config.state.stateNumber] || null;
if (context!==null && context.equals(config.context)) {
// eliminated
continue;
}
}
configSet.add(config, this.mergeCache);
}
return configSet;
};
ParserATNSimulator.prototype.getReachableTarget = function(trans, ttype) {
if (trans.matches(ttype, 0, this.atn.maxTokenType)) {
return trans.target;
} else {
return null;
}
};
ParserATNSimulator.prototype.getPredsForAmbigAlts = function(ambigAlts, configs, nalts) {
// REACH=[1|1|[]|0:0, 1|2|[]|0:1]
// altToPred starts as an array of all null contexts. The entry at index i
// corresponds to alternative i. altToPred[i] may have one of three values:
// 1. null: no ATNConfig c is found such that c.alt==i
// 2. SemanticContext.NONE: At least one ATNConfig c exists such that
// c.alt==i and c.semanticContext==SemanticContext.NONE. In other words,
// alt i has at least one unpredicated config.
// 3. Non-NONE Semantic Context: There exists at least one, and for all
// ATNConfig c such that c.alt==i, c.semanticContext!=SemanticContext.NONE.
//
// From this, it is clear that NONE||anything==NONE.
//
var altToPred = [];
for(var i=0;i<configs.items.length;i++) {
var c = configs.items[i];
if(ambigAlts.contains( c.alt )) {
altToPred[c.alt] = SemanticContext.orContext(altToPred[c.alt] || null, c.semanticContext);
}
}
var nPredAlts = 0;
for (i =1;i< nalts+1;i++) {
var pred = altToPred[i] || null;
if (pred===null) {
altToPred[i] = SemanticContext.NONE;
} else if (pred !== SemanticContext.NONE) {
nPredAlts += 1;
}
}
// nonambig alts are null in altToPred
if (nPredAlts===0) {
altToPred = null;
}
if (this.debug) {
console.log("getPredsForAmbigAlts result " + Utils.arrayToString(altToPred));
}
return altToPred;
};
ParserATNSimulator.prototype.getPredicatePredictions = function(ambigAlts, altToPred) {
var pairs = [];
var containsPredicate = false;
for (var i=1; i<altToPred.length;i++) {
var pred = altToPred[i];
// unpredicated is indicated by SemanticContext.NONE
if( ambigAlts!==null && ambigAlts.contains( i )) {
pairs.push(new PredPrediction(pred, i));
}
if (pred !== SemanticContext.NONE) {
containsPredicate = true;
}
}
if (! containsPredicate) {
return null;
}
return pairs;
};
//
// This method is used to improve the localization of error messages by
// choosing an alternative rather than throwing a
// {@link NoViableAltException} in particular prediction scenarios where the
// {@link //ERROR} state was reached during ATN simulation.
//
// <p>
// The default implementation of this method uses the following
// algorithm to identify an ATN configuration which successfully parsed the
// decision entry rule. Choosing such an alternative ensures that the
// {@link ParserRuleContext} returned by the calling rule will be complete
// and valid, and the syntax error will be reported later at a more
// localized location.</p>
//
// <ul>
// <li>If a syntactically valid path or paths reach the end of the decision rule and
// they are semantically valid if predicated, return the min associated alt.</li>
// <li>Else, if a semantically invalid but syntactically valid path exist
// or paths exist, return the minimum associated alt.
// </li>
// <li>Otherwise, return {@link ATN//INVALID_ALT_NUMBER}.</li>
// </ul>
//
// <p>
// In some scenarios, the algorithm described above could predict an
// alternative which will result in a {@link FailedPredicateException} in
// the parser. Specifically, this could occur if the <em>only</em> configuration
// capable of successfully parsing to the end of the decision rule is
// blocked by a semantic predicate. By choosing this alternative within
// {@link //adaptivePredict} instead of throwing a
// {@link NoViableAltException}, the resulting
// {@link FailedPredicateException} in the parser will identify the specific
// predicate which is preventing the parser from successfully parsing the
// decision rule, which helps developers identify and correct logic errors
// in semantic predicates.
// </p>
//
// @param configs The ATN configurations which were valid immediately before
// the {@link //ERROR} state was reached
// @param outerContext The is the \gamma_0 initial parser context from the paper
// or the parser stack at the instant before prediction commences.
//
// @return The value to return from {@link //adaptivePredict}, or
// {@link ATN//INVALID_ALT_NUMBER} if a suitable alternative was not
// identified and {@link //adaptivePredict} should report an error instead.
//
ParserATNSimulator.prototype.getSynValidOrSemInvalidAltThatFinishedDecisionEntryRule = function(configs, outerContext) {
var cfgs = this.splitAccordingToSemanticValidity(configs, outerContext);
var semValidConfigs = cfgs[0];
var semInvalidConfigs = cfgs[1];
var alt = this.getAltThatFinishedDecisionEntryRule(semValidConfigs);
if (alt!==ATN.INVALID_ALT_NUMBER) { // semantically/syntactically viable path exists
return alt;
}
// Is there a syntactically valid path with a failed pred?
if (semInvalidConfigs.items.length>0) {
alt = this.getAltThatFinishedDecisionEntryRule(semInvalidConfigs);
if (alt!==ATN.INVALID_ALT_NUMBER) { // syntactically viable path exists
return alt;
}
}
return ATN.INVALID_ALT_NUMBER;
};
ParserATNSimulator.prototype.getAltThatFinishedDecisionEntryRule = function(configs) {
var alts = [];
for(var i=0;i<configs.items.length; i++) {
var c = configs.items[i];
if (c.reachesIntoOuterContext>0 || ((c.state instanceof RuleStopState) && c.context.hasEmptyPath())) {
if(alts.indexOf(c.alt)<0) {
alts.push(c.alt);
}
}
}
if (alts.length===0) {
return ATN.INVALID_ALT_NUMBER;
} else {
return Math.min.apply(null, alts);
}
};
// Walk the list of configurations and split them according to
// those that have preds evaluating to true/false. If no pred, assume
// true pred and include in succeeded set. Returns Pair of sets.
//
// Create a new set so as not to alter the incoming parameter.
//
// Assumption: the input stream has been restored to the starting point
// prediction, which is where predicates need to evaluate.
//
ParserATNSimulator.prototype.splitAccordingToSemanticValidity = function( configs, outerContext) {
var succeeded = new ATNConfigSet(configs.fullCtx);
var failed = new ATNConfigSet(configs.fullCtx);
for(var i=0;i<configs.items.length; i++) {
var c = configs.items[i];
if (c.semanticContext !== SemanticContext.NONE) {
var predicateEvaluationResult = c.semanticContext.evaluate(this.parser, outerContext);
if (predicateEvaluationResult) {
succeeded.add(c);
} else {
failed.add(c);
}
} else {
succeeded.add(c);
}
}
return [succeeded, failed];
};
// Look through a list of predicate/alt pairs, returning alts for the
// pairs that win. A {@code NONE} predicate indicates an alt containing an
// unpredicated config which behaves as "always true." If !complete
// then we stop at the first predicate that evaluates to true. This
// includes pairs with null predicates.
//
ParserATNSimulator.prototype.evalSemanticContext = function(predPredictions, outerContext, complete) {
var predictions = new BitSet();
for(var i=0;i<predPredictions.length;i++) {
var pair = predPredictions[i];
if (pair.pred === SemanticContext.NONE) {
predictions.add(pair.alt);
if (! complete) {
break;
}
continue;
}
var predicateEvaluationResult = pair.pred.evaluate(this.parser, outerContext);
if (this.debug || this.dfa_debug) {
console.log("eval pred " + pair + "=" + predicateEvaluationResult);
}
if (predicateEvaluationResult) {
if (this.debug || this.dfa_debug) {
console.log("PREDICT " + pair.alt);
}
predictions.add(pair.alt);
if (! complete) {
break;
}
}
}
return predictions;
};
// TODO: If we are doing predicates, there is no point in pursuing
// closure operations if we reach a DFA state that uniquely predicts
// alternative. We will not be caching that DFA state and it is a
// waste to pursue the closure. Might have to advance when we do
// ambig detection thought :(
//
ParserATNSimulator.prototype.closure = function(config, configs, closureBusy, collectPredicates, fullCtx, treatEofAsEpsilon) {
var initialDepth = 0;
this.closureCheckingStopState(config, configs, closureBusy, collectPredicates,
fullCtx, initialDepth, treatEofAsEpsilon);
};
ParserATNSimulator.prototype.closureCheckingStopState = function(config, configs, closureBusy, collectPredicates, fullCtx, depth, treatEofAsEpsilon) {
if (this.debug) {
console.log("closure(" + config.toString(this.parser,true) + ")");
console.log("configs(" + configs.toString() + ")");
if(config.reachesIntoOuterContext>50) {
throw "problem";
}
}
if (config.state instanceof RuleStopState) {
// We hit rule end. If we have context info, use it
// run thru all possible stack tops in ctx
if (! config.context.isEmpty()) {
for ( var i =0; i<config.context.length; i++) {
if (config.context.getReturnState(i) === PredictionContext.EMPTY_RETURN_STATE) {
if (fullCtx) {
configs.add(new ATNConfig({state:config.state, context:PredictionContext.EMPTY}, config), this.mergeCache);
continue;
} else {
// we have no context info, just chase follow links (if greedy)
if (this.debug) {
console.log("FALLING off rule " + this.getRuleName(config.state.ruleIndex));
}
this.closure_(config, configs, closureBusy, collectPredicates,
fullCtx, depth, treatEofAsEpsilon);
}
continue;
}
returnState = this.atn.states[config.context.getReturnState(i)];
newContext = config.context.getParent(i); // "pop" return state
var parms = {state:returnState, alt:config.alt, context:newContext, semanticContext:config.semanticContext};
c = new ATNConfig(parms, null);
// While we have context to pop back from, we may have
// gotten that context AFTER having falling off a rule.
// Make sure we track that we are now out of context.
c.reachesIntoOuterContext = config.reachesIntoOuterContext;
this.closureCheckingStopState(c, configs, closureBusy, collectPredicates, fullCtx, depth - 1, treatEofAsEpsilon);
}
return;
} else if( fullCtx) {
// reached end of start rule
configs.add(config, this.mergeCache);
return;
} else {
// else if we have no context info, just chase follow links (if greedy)
if (this.debug) {
console.log("FALLING off rule " + this.getRuleName(config.state.ruleIndex));
}
}
}
this.closure_(config, configs, closureBusy, collectPredicates, fullCtx, depth, treatEofAsEpsilon);
};
// Do the actual work of walking epsilon edges//
ParserATNSimulator.prototype.closure_ = function(config, configs, closureBusy, collectPredicates, fullCtx, depth, treatEofAsEpsilon) {
var p = config.state;
// optimization
if (! p.epsilonOnlyTransitions) {
configs.add(config, this.mergeCache);
// make sure to not return here, because EOF transitions can act as
// both epsilon transitions and non-epsilon transitions.
}
for(var i = 0;i<p.transitions.length; i++) {
var t = p.transitions[i];
var continueCollecting = collectPredicates && !(t instanceof ActionTransition);
var c = this.getEpsilonTarget(config, t, continueCollecting, depth === 0, fullCtx, treatEofAsEpsilon);
if (c!==null) {
if (!t.isEpsilon && closureBusy.add(c)!==c){
// avoid infinite recursion for EOF* and EOF+
continue;
}
var newDepth = depth;
if ( config.state instanceof RuleStopState) {
// target fell off end of rule; mark resulting c as having dipped into outer context
// We can't get here if incoming config was rule stop and we had context
// track how far we dip into outer context. Might
// come in handy and we avoid evaluating context dependent
// preds if this is > 0.
if (closureBusy.add(c)!==c) {
// avoid infinite recursion for right-recursive rules
continue;
}
if (this._dfa !== null && this._dfa.precedenceDfa) {
if (t.outermostPrecedenceReturn === this._dfa.atnStartState.ruleIndex) {
c.precedenceFilterSuppressed = true;
}
}
c.reachesIntoOuterContext += 1;
configs.dipsIntoOuterContext = true; // TODO: can remove? only care when we add to set per middle of this method
newDepth -= 1;
if (this.debug) {
console.log("dips into outer ctx: " + c);
}
} else if (t instanceof RuleTransition) {
// latch when newDepth goes negative - once we step out of the entry context we can't return
if (newDepth >= 0) {
newDepth += 1;
}
}
this.closureCheckingStopState(c, configs, closureBusy, continueCollecting, fullCtx, newDepth, treatEofAsEpsilon);
}
}
};
ParserATNSimulator.prototype.getRuleName = function( index) {
if (this.parser!==null && index>=0) {
return this.parser.ruleNames[index];
} else {
return "<rule " + index + ">";
}
};
ParserATNSimulator.prototype.getEpsilonTarget = function(config, t, collectPredicates, inContext, fullCtx, treatEofAsEpsilon) {
switch(t.serializationType) {
case Transition.RULE:
return this.ruleTransition(config, t);
case Transition.PRECEDENCE:
return this.precedenceTransition(config, t, collectPredicates, inContext, fullCtx);
case Transition.PREDICATE:
return this.predTransition(config, t, collectPredicates, inContext, fullCtx);
case Transition.ACTION:
return this.actionTransition(config, t);
case Transition.EPSILON:
return new ATNConfig({state:t.target}, config);
case Transition.ATOM:
case Transition.RANGE:
case Transition.SET:
// EOF transitions act like epsilon transitions after the first EOF
// transition is traversed
if (treatEofAsEpsilon) {
if (t.matches(Token.EOF, 0, 1)) {
return new ATNConfig({state: t.target}, config);
}
}
return null;
default:
return null;
}
};
ParserATNSimulator.prototype.actionTransition = function(config, t) {
if (this.debug) {
console.log("ACTION edge " + t.ruleIndex + ":" + t.actionIndex);
}
return new ATNConfig({state:t.target}, config);
};
ParserATNSimulator.prototype.precedenceTransition = function(config, pt, collectPredicates, inContext, fullCtx) {
if (this.debug) {
console.log("PRED (collectPredicates=" + collectPredicates + ") " +
pt.precedence + ">=_p, ctx dependent=true");
if (this.parser!==null) {
console.log("context surrounding pred is " + Utils.arrayToString(this.parser.getRuleInvocationStack()));
}
}
var c = null;
if (collectPredicates && inContext) {
if (fullCtx) {
// In full context mode, we can evaluate predicates on-the-fly
// during closure, which dramatically reduces the size of
// the config sets. It also obviates the need to test predicates
// later during conflict resolution.
var currentPosition = this._input.index;
this._input.seek(this._startIndex);
var predSucceeds = pt.getPredicate().evaluate(this.parser, this._outerContext);
this._input.seek(currentPosition);
if (predSucceeds) {
c = new ATNConfig({state:pt.target}, config); // no pred context
}
} else {
newSemCtx = SemanticContext.andContext(config.semanticContext, pt.getPredicate());
c = new ATNConfig({state:pt.target, semanticContext:newSemCtx}, config);
}
} else {
c = new ATNConfig({state:pt.target}, config);
}
if (this.debug) {
console.log("config from pred transition=" + c);
}
return c;
};
ParserATNSimulator.prototype.predTransition = function(config, pt, collectPredicates, inContext, fullCtx) {
if (this.debug) {
console.log("PRED (collectPredicates=" + collectPredicates + ") " + pt.ruleIndex +
":" + pt.predIndex + ", ctx dependent=" + pt.isCtxDependent);
if (this.parser!==null) {
console.log("context surrounding pred is " + Utils.arrayToString(this.parser.getRuleInvocationStack()));
}
}
var c = null;
if (collectPredicates && ((pt.isCtxDependent && inContext) || ! pt.isCtxDependent)) {
if (fullCtx) {
// In full context mode, we can evaluate predicates on-the-fly
// during closure, which dramatically reduces the size of
// the config sets. It also obviates the need to test predicates
// later during conflict resolution.
var currentPosition = this._input.index;
this._input.seek(this._startIndex);
var predSucceeds = pt.getPredicate().evaluate(this.parser, this._outerContext);
this._input.seek(currentPosition);
if (predSucceeds) {
c = new ATNConfig({state:pt.target}, config); // no pred context
}
} else {
var newSemCtx = SemanticContext.andContext(config.semanticContext, pt.getPredicate());
c = new ATNConfig({state:pt.target, semanticContext:newSemCtx}, config);
}
} else {
c = new ATNConfig({state:pt.target}, config);
}
if (this.debug) {
console.log("config from pred transition=" + c);
}
return c;
};
ParserATNSimulator.prototype.ruleTransition = function(config, t) {
if (this.debug) {
console.log("CALL rule " + this.getRuleName(t.target.ruleIndex) + ", ctx=" + config.context);
}
var returnState = t.followState;
var newContext = SingletonPredictionContext.create(config.context, returnState.stateNumber);
return new ATNConfig({state:t.target, context:newContext}, config );
};
ParserATNSimulator.prototype.getConflictingAlts = function(configs) {
var altsets = PredictionMode.getConflictingAltSubsets(configs);
return PredictionMode.getAlts(altsets);
};
// Sam pointed out a problem with the previous definition, v3, of
// ambiguous states. If we have another state associated with conflicting
// alternatives, we should keep going. For example, the following grammar
//
// s : (ID | ID ID?) ';' ;
//
// When the ATN simulation reaches the state before ';', it has a DFA
// state that looks like: [12|1|[], 6|2|[], 12|2|[]]. Naturally
// 12|1|[] and 12|2|[] conflict, but we cannot stop processing this node
// because alternative to has another way to continue, via [6|2|[]].
// The key is that we have a single state that has config's only associated
// with a single alternative, 2, and crucially the state transitions
// among the configurations are all non-epsilon transitions. That means
// we don't consider any conflicts that include alternative 2. So, we
// ignore the conflict between alts 1 and 2. We ignore a set of
// conflicting alts when there is an intersection with an alternative
// associated with a single alt state in the state→config-list map.
//
// It's also the case that we might have two conflicting configurations but
// also a 3rd nonconflicting configuration for a different alternative:
// [1|1|[], 1|2|[], 8|3|[]]. This can come about from grammar:
//
// a : A | A | A B ;
//
// After matching input A, we reach the stop state for rule A, state 1.
// State 8 is the state right before B. Clearly alternatives 1 and 2
// conflict and no amount of further lookahead will separate the two.
// However, alternative 3 will be able to continue and so we do not
// stop working on this state. In the previous example, we're concerned
// with states associated with the conflicting alternatives. Here alt
// 3 is not associated with the conflicting configs, but since we can continue
// looking for input reasonably, I don't declare the state done. We
// ignore a set of conflicting alts when we have an alternative
// that we still need to pursue.
//
ParserATNSimulator.prototype.getConflictingAltsOrUniqueAlt = function(configs) {
var conflictingAlts = null;
if (configs.uniqueAlt!== ATN.INVALID_ALT_NUMBER) {
conflictingAlts = new BitSet();
conflictingAlts.add(configs.uniqueAlt);
} else {
conflictingAlts = configs.conflictingAlts;
}
return conflictingAlts;
};
ParserATNSimulator.prototype.getTokenName = function( t) {
if (t===Token.EOF) {
return "EOF";
}
if( this.parser!==null && this.parser.literalNames!==null) {
if (t >= this.parser.literalNames.length) {
console.log("" + t + " ttype out of range: " + this.parser.literalNames);
console.log("" + this.parser.getInputStream().getTokens());
} else {
return this.parser.literalNames[t] + "<" + t + ">";
}
}
return "" + t;
};
ParserATNSimulator.prototype.getLookaheadName = function(input) {
return this.getTokenName(input.LA(1));
};
// Used for debugging in adaptivePredict around execATN but I cut
// it out for clarity now that alg. works well. We can leave this
// "dead" code for a bit.
//
ParserATNSimulator.prototype.dumpDeadEndConfigs = function(nvae) {
console.log("dead end configs: ");
var decs = nvae.getDeadEndConfigs();
for(var i=0; i<decs.length; i++) {
var c = decs[i];
var trans = "no edges";
if (c.state.transitions.length>0) {
var t = c.state.transitions[0];
if (t instanceof AtomTransition) {
trans = "Atom "+ this.getTokenName(t.label);
} else if (t instanceof SetTransition) {
var neg = (t instanceof NotSetTransition);
trans = (neg ? "~" : "") + "Set " + t.set;
}
}
console.error(c.toString(this.parser, true) + ":" + trans);
}
};
ParserATNSimulator.prototype.noViableAlt = function(input, outerContext, configs, startIndex) {
return new NoViableAltException(this.parser, input, input.get(startIndex), input.LT(1), configs, outerContext);
};
ParserATNSimulator.prototype.getUniqueAlt = function(configs) {
var alt = ATN.INVALID_ALT_NUMBER;
for(var i=0;i<configs.items.length;i++) {
var c = configs.items[i];
if (alt === ATN.INVALID_ALT_NUMBER) {
alt = c.alt // found first alt
} else if( c.alt!==alt) {
return ATN.INVALID_ALT_NUMBER;
}
}
return alt;
};
//
// Add an edge to the DFA, if possible. This method calls
// {@link //addDFAState} to ensure the {@code to} state is present in the
// DFA. If {@code from} is {@code null}, or if {@code t} is outside the
// range of edges that can be represented in the DFA tables, this method
// returns without adding the edge to the DFA.
//
// <p>If {@code to} is {@code null}, this method returns {@code null}.
// Otherwise, this method returns the {@link DFAState} returned by calling
// {@link //addDFAState} for the {@code to} state.</p>
//
// @param dfa The DFA
// @param from The source state for the edge
// @param t The input symbol
// @param to The target state for the edge
//
// @return If {@code to} is {@code null}, this method returns {@code null};
// otherwise this method returns the result of calling {@link //addDFAState}
// on {@code to}
//
ParserATNSimulator.prototype.addDFAEdge = function(dfa, from_, t, to) {
if( this.debug) {
console.log("EDGE " + from_ + " -> " + to + " upon " + this.getTokenName(t));
}
if (to===null) {
return null;
}
to = this.addDFAState(dfa, to); // used existing if possible not incoming
if (from_===null || t < -1 || t > this.atn.maxTokenType) {
return to;
}
if (from_.edges===null) {
from_.edges = [];
}
from_.edges[t+1] = to; // connect
if (this.debug) {
var names = this.parser===null ? null : this.parser.literalNames;
console.log("DFA=\n" + dfa.toString(names));
}
return to;
};
//
// Add state {@code D} to the DFA if it is not already present, and return
// the actual instance stored in the DFA. If a state equivalent to {@code D}
// is already in the DFA, the existing state is returned. Otherwise this
// method returns {@code D} after adding it to the DFA.
//
// <p>If {@code D} is {@link //ERROR}, this method returns {@link //ERROR} and
// does not change the DFA.</p>
//
// @param dfa The dfa
// @param D The DFA state to add
// @return The state stored in the DFA. This will be either the existing
// state if {@code D} is already in the DFA, or {@code D} itself if the
// state was not already present.
//
ParserATNSimulator.prototype.addDFAState = function(dfa, D) {
if (D == ATNSimulator.ERROR) {
return D;
}
var hash = D.hashString();
var existing = dfa.states[hash] || null;
if(existing!==null) {
return existing;
}
D.stateNumber = dfa.states.length;
if (! D.configs.readonly) {
D.configs.optimizeConfigs(this);
D.configs.setReadonly(true);
}
dfa.states[hash] = D;
if (this.debug) {
console.log("adding new DFA state: " + D);
}
return D;
};
ParserATNSimulator.prototype.reportAttemptingFullContext = function(dfa, conflictingAlts, configs, startIndex, stopIndex) {
if (this.debug || this.retry_debug) {
var interval = new Interval(startIndex, stopIndex + 1);
console.log("reportAttemptingFullContext decision=" + dfa.decision + ":" + configs +
", input=" + this.parser.getTokenStream().getText(interval));
}
if (this.parser!==null) {
this.parser.getErrorListenerDispatch().reportAttemptingFullContext(this.parser, dfa, startIndex, stopIndex, conflictingAlts, configs);
}
};
ParserATNSimulator.prototype.reportContextSensitivity = function(dfa, prediction, configs, startIndex, stopIndex) {
if (this.debug || this.retry_debug) {
var interval = new Interval(startIndex, stopIndex + 1);
console.log("reportContextSensitivity decision=" + dfa.decision + ":" + configs +
", input=" + this.parser.getTokenStream().getText(interval));
}
if (this.parser!==null) {
this.parser.getErrorListenerDispatch().reportContextSensitivity(this.parser, dfa, startIndex, stopIndex, prediction, configs);
}
};
// If context sensitive parsing, we know it's ambiguity not conflict//
ParserATNSimulator.prototype.reportAmbiguity = function(dfa, D, startIndex, stopIndex,
exact, ambigAlts, configs ) {
if (this.debug || this.retry_debug) {
var interval = new Interval(startIndex, stopIndex + 1);
console.log("reportAmbiguity " + ambigAlts + ":" + configs +
", input=" + this.parser.getTokenStream().getText(interval));
}
if (this.parser!==null) {
this.parser.getErrorListenerDispatch().reportAmbiguity(this.parser, dfa, startIndex, stopIndex, exact, ambigAlts, configs);
}
};
exports.ParserATNSimulator = ParserATNSimulator; | alberto-chiesa/grunt-jsl10n | tasks/antlr4/atn/ParserATNSimulator.js | JavaScript | mit | 74,098 |
(function() {
'use strict';
Polymer({
is: 'iron-overlay-backdrop',
properties: {
/**
* Returns true if the backdrop is opened.
*/
opened: {
reflectToAttribute: true,
type: Boolean,
value: false,
observer: '_openedChanged'
}
},
listeners: {
'transitionend': '_onTransitionend'
},
created: function() {
// Used to cancel previous requestAnimationFrame calls when opened changes.
this.__openedRaf = null;
},
attached: function() {
this.opened && this._openedChanged(this.opened);
},
/**
* Appends the backdrop to document body if needed.
*/
prepare: function() {
if (this.opened && !this.parentNode) {
Polymer.dom(document.body).appendChild(this);
}
},
/**
* Shows the backdrop.
*/
open: function() {
this.opened = true;
},
/**
* Hides the backdrop.
*/
close: function() {
this.opened = false;
},
/**
* Removes the backdrop from document body if needed.
*/
complete: function() {
if (!this.opened && this.parentNode === document.body) {
Polymer.dom(this.parentNode).removeChild(this);
}
},
_onTransitionend: function(event) {
if (event && event.target === this) {
this.complete();
}
},
/**
* @param {boolean} opened
* @private
*/
_openedChanged: function(opened) {
if (opened) {
// Auto-attach.
this.prepare();
} else {
// Animation might be disabled via the mixin or opacity custom property.
// If it is disabled in other ways, it's up to the user to call complete.
var cs = window.getComputedStyle(this);
if (cs.transitionDuration === '0s' || cs.opacity == 0) {
this.complete();
}
}
if (!this.isAttached) {
return;
}
// Always cancel previous requestAnimationFrame.
if (this.__openedRaf) {
window.cancelAnimationFrame(this.__openedRaf);
this.__openedRaf = null;
}
// Force relayout to ensure proper transitions.
this.scrollTop = this.scrollTop;
this.__openedRaf = window.requestAnimationFrame(function() {
this.__openedRaf = null;
this.toggleClass('opened', this.opened);
}.bind(this));
}
});
})(); | axinging/chromium-crosswalk | third_party/polymer/v1_0/components-chromium/iron-overlay-behavior/iron-overlay-backdrop-extracted.js | JavaScript | bsd-3-clause | 2,415 |
'use strict';
$(function () {
//Simple implementation of direct chat contact pane toggle (TEMPORARY)
$('[data-widget="chat-pane-toggle"]').click(function(){
$("#myDirectChat").toggleClass('direct-chat-contacts-open');
});
/* ChartJS
* -------
* Here we will create a few charts using ChartJS
*/
//-----------------------
//- MONTHLY SALES CHART -
//-----------------------
// Get context with jQuery - using jQuery's .get() method.
var salesChartCanvas = $("#salesChart").get(0).getContext("2d");
// This will get the first returned node in the jQuery collection.
var salesChart = new Chart(salesChartCanvas);
var salesChartData = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "Electronics",
fillColor: "rgb(210, 214, 222)",
strokeColor: "rgb(210, 214, 222)",
pointColor: "rgb(210, 214, 222)",
pointStrokeColor: "#c1c7d1",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgb(220,220,220)",
data: [65, 59, 80, 81, 56, 55, 40]
},
{
label: "Digital Goods",
fillColor: "rgba(60,141,188,0.9)",
strokeColor: "rgba(60,141,188,0.8)",
pointColor: "#3b8bba",
pointStrokeColor: "rgba(60,141,188,1)",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(60,141,188,1)",
data: [28, 48, 40, 19, 86, 27, 90]
}
]
};
var salesChartOptions = {
//Boolean - If we should show the scale at all
showScale: true,
//Boolean - Whether grid lines are shown across the chart
scaleShowGridLines: false,
//String - Colour of the grid lines
scaleGridLineColor: "rgba(0,0,0,.05)",
//Number - Width of the grid lines
scaleGridLineWidth: 1,
//Boolean - Whether to show horizontal lines (except X axis)
scaleShowHorizontalLines: true,
//Boolean - Whether to show vertical lines (except Y axis)
scaleShowVerticalLines: true,
//Boolean - Whether the line is curved between points
bezierCurve: true,
//Number - Tension of the bezier curve between points
bezierCurveTension: 0.3,
//Boolean - Whether to show a dot for each point
pointDot: false,
//Number - Radius of each point dot in pixels
pointDotRadius: 4,
//Number - Pixel width of point dot stroke
pointDotStrokeWidth: 1,
//Number - amount extra to add to the radius to cater for hit detection outside the drawn point
pointHitDetectionRadius: 20,
//Boolean - Whether to show a stroke for datasets
datasetStroke: true,
//Number - Pixel width of dataset stroke
datasetStrokeWidth: 2,
//Boolean - Whether to fill the dataset with a color
datasetFill: true,
//String - A legend template
legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].lineColor%>\"></span><%=datasets[i].label%></li><%}%></ul>",
//Boolean - whether to maintain the starting aspect ratio or not when responsive, if set to false, will take up entire container
maintainAspectRatio: false,
//Boolean - whether to make the chart responsive to window resizing
responsive: true
};
//Create the line chart
salesChart.Line(salesChartData, salesChartOptions);
//---------------------------
//- END MONTHLY SALES CHART -
//---------------------------
//-------------
//- PIE CHART -
//-------------
// Get context with jQuery - using jQuery's .get() method.
var pieChartCanvas = $("#pieChart").get(0).getContext("2d");
var pieChart = new Chart(pieChartCanvas);
var PieData = [
{
value: 700,
color: "#f56954",
highlight: "#f56954",
label: "Chrome"
},
{
value: 500,
color: "#00a65a",
highlight: "#00a65a",
label: "IE"
},
{
value: 400,
color: "#f39c12",
highlight: "#f39c12",
label: "FireFox"
},
{
value: 600,
color: "#00c0ef",
highlight: "#00c0ef",
label: "Safari"
},
{
value: 300,
color: "#3c8dbc",
highlight: "#3c8dbc",
label: "Opera"
},
{
value: 100,
color: "#d2d6de",
highlight: "#d2d6de",
label: "Navigator"
}
];
var pieOptions = {
//Boolean - Whether we should show a stroke on each segment
segmentShowStroke: true,
//String - The colour of each segment stroke
segmentStrokeColor: "#fff",
//Number - The width of each segment stroke
segmentStrokeWidth: 2,
//Number - The percentage of the chart that we cut out of the middle
percentageInnerCutout: 50, // This is 0 for Pie charts
//Number - Amount of animation steps
animationSteps: 100,
//String - Animation easing effect
animationEasing: "easeOutBounce",
//Boolean - Whether we animate the rotation of the Doughnut
animateRotate: true,
//Boolean - Whether we animate scaling the Doughnut from the centre
animateScale: false,
//Boolean - whether to make the chart responsive to window resizing
responsive: true,
// Boolean - whether to maintain the starting aspect ratio or not when responsive, if set to false, will take up entire container
maintainAspectRatio: false,
//String - A legend template
legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<segments.length; i++){%><li><span style=\"background-color:<%=segments[i].fillColor%>\"></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>",
//String - A tooltip template
tooltipTemplate: "<%=value %> <%=label%> users"
};
//Create pie or douhnut chart
// You can switch between pie and douhnut using the method below.
pieChart.Doughnut(PieData, pieOptions);
//-----------------
//- END PIE CHART -
//-----------------
/* jVector Maps
* ------------
* Create a world map with markers
*/
$('#world-map-markers').vectorMap({
map: 'world_mill_en',
normalizeFunction: 'polynomial',
hoverOpacity: 0.7,
hoverColor: false,
backgroundColor: 'transparent',
regionStyle: {
initial: {
fill: 'rgba(210, 214, 222, 1)',
"fill-opacity": 1,
stroke: 'none',
"stroke-width": 0,
"stroke-opacity": 1
},
hover: {
"fill-opacity": 0.7,
cursor: 'pointer'
},
selected: {
fill: 'yellow'
},
selectedHover: {
}
},
markerStyle: {
initial: {
fill: '#00a65a',
stroke: '#111'
}
},
markers: [
{latLng: [41.90, 12.45], name: 'Vatican City'},
{latLng: [43.73, 7.41], name: 'Monaco'},
{latLng: [-0.52, 166.93], name: 'Nauru'},
{latLng: [-8.51, 179.21], name: 'Tuvalu'},
{latLng: [43.93, 12.46], name: 'San Marino'},
{latLng: [47.14, 9.52], name: 'Liechtenstein'},
{latLng: [7.11, 171.06], name: 'Marshall Islands'},
{latLng: [17.3, -62.73], name: 'Saint Kitts and Nevis'},
{latLng: [3.2, 73.22], name: 'Maldives'},
{latLng: [35.88, 14.5], name: 'Malta'},
{latLng: [12.05, -61.75], name: 'Grenada'},
{latLng: [13.16, -61.23], name: 'Saint Vincent and the Grenadines'},
{latLng: [13.16, -59.55], name: 'Barbados'},
{latLng: [17.11, -61.85], name: 'Antigua and Barbuda'},
{latLng: [-4.61, 55.45], name: 'Seychelles'},
{latLng: [7.35, 134.46], name: 'Palau'},
{latLng: [42.5, 1.51], name: 'Andorra'},
{latLng: [14.01, -60.98], name: 'Saint Lucia'},
{latLng: [6.91, 158.18], name: 'Federated States of Micronesia'},
{latLng: [1.3, 103.8], name: 'Singapore'},
{latLng: [1.46, 173.03], name: 'Kiribati'},
{latLng: [-21.13, -175.2], name: 'Tonga'},
{latLng: [15.3, -61.38], name: 'Dominica'},
{latLng: [-20.2, 57.5], name: 'Mauritius'},
{latLng: [26.02, 50.55], name: 'Bahrain'},
{latLng: [0.33, 6.73], name: 'São Tomé and Príncipe'}
]
});
/* SPARKLINE CHARTS
* ----------------
* Create a inline charts with spark line
*/
//-----------------
//- SPARKLINE BAR -
//-----------------
$('.sparkbar').each(function () {
var $this = $(this);
$this.sparkline('html', {
type: 'bar',
height: $this.data('height') ? $this.data('height') : '30',
barColor: $this.data('color')
});
});
//-----------------
//- SPARKLINE PIE -
//-----------------
$('.sparkpie').each(function () {
var $this = $(this);
$this.sparkline('html', {
type: 'pie',
height: $this.data('height') ? $this.data('height') : '90',
sliceColors: $this.data('color')
});
});
//------------------
//- SPARKLINE LINE -
//------------------
$('.sparkline').each(function () {
var $this = $(this);
$this.sparkline('html', {
type: 'line',
height: $this.data('height') ? $this.data('height') : '90',
width: '100%',
lineColor: $this.data('linecolor'),
fillColor: $this.data('fillcolor'),
spotColor: $this.data('spotcolor')
});
});
}); | johan--/ember-admin-dashboards | vendor/AdminLTE/dist/js/pages/dashboard2.js | JavaScript | mit | 9,137 |
/*!
* Bootstrap v3.2.0 (http://getbootstrap.com)
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
*/
if (typeof jQuery === 'undefined') { throw new Error('Bootstrap\'s JavaScript requires jQuery') }
/* ========================================================================
* Bootstrap: transition.js v3.2.0
* http://getbootstrap.com/javascript/#transitions
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/)
// ============================================================
function transitionEnd() {
var el = document.createElement('bootstrap')
var transEndEventNames = {
WebkitTransition : 'webkitTransitionEnd',
MozTransition : 'transitionend',
OTransition : 'oTransitionEnd otransitionend',
transition : 'transitionend'
}
for (var name in transEndEventNames) {
if (el.style[name] !== undefined) {
return { end: transEndEventNames[name] }
}
}
return false // explicit for ie8 ( ._.)
}
// http://blog.alexmaccaw.com/css-transitions
$.fn.emulateTransitionEnd = function (duration) {
var called = false
var $el = this
$(this).one('bsTransitionEnd', function () { called = true })
var callback = function () { if (!called) $($el).trigger($.support.transition.end) }
setTimeout(callback, duration)
return this
}
$(function () {
$.support.transition = transitionEnd()
if (!$.support.transition) return
$.event.special.bsTransitionEnd = {
bindType: $.support.transition.end,
delegateType: $.support.transition.end,
handle: function (e) {
if ($(e.target).is(this)) return e.handleObj.handler.apply(this, arguments)
}
}
})
}(jQuery);
/* ========================================================================
* Bootstrap: alert.js v3.2.0
* http://getbootstrap.com/javascript/#alerts
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// ALERT CLASS DEFINITION
// ======================
var dismiss = '[data-dismiss="alert"]'
var Alert = function (el) {
$(el).on('click', dismiss, this.close)
}
Alert.VERSION = '3.2.0'
Alert.TRANSITION_DURATION = 150
Alert.prototype.close = function (e) {
var $this = $(this)
var selector = $this.attr('data-target')
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
}
var $parent = $(selector)
if (e) e.preventDefault()
if (!$parent.length) {
$parent = $this.hasClass('alert') ? $this : $this.parent()
}
$parent.trigger(e = $.Event('close.bs.alert'))
if (e.isDefaultPrevented()) return
$parent.removeClass('in')
function removeElement() {
// detach from parent, fire event then clean up data
$parent.detach().trigger('closed.bs.alert').remove()
}
$.support.transition && $parent.hasClass('fade') ?
$parent
.one('bsTransitionEnd', removeElement)
.emulateTransitionEnd(Alert.TRANSITION_DURATION) :
removeElement()
}
// ALERT PLUGIN DEFINITION
// =======================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.alert')
if (!data) $this.data('bs.alert', (data = new Alert(this)))
if (typeof option == 'string') data[option].call($this)
})
}
var old = $.fn.alert
$.fn.alert = Plugin
$.fn.alert.Constructor = Alert
// ALERT NO CONFLICT
// =================
$.fn.alert.noConflict = function () {
$.fn.alert = old
return this
}
// ALERT DATA-API
// ==============
$(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close)
}(jQuery);
/* ========================================================================
* Bootstrap: button.js v3.2.0
* http://getbootstrap.com/javascript/#buttons
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// BUTTON PUBLIC CLASS DEFINITION
// ==============================
var Button = function (element, options) {
this.$element = $(element)
this.options = $.extend({}, Button.DEFAULTS, options)
this.isLoading = false
}
Button.VERSION = '3.2.0'
Button.DEFAULTS = {
loadingText: 'loading...'
}
Button.prototype.setState = function (state) {
var d = 'disabled'
var $el = this.$element
var val = $el.is('input') ? 'val' : 'html'
var data = $el.data()
state = state + 'Text'
if (data.resetText == null) $el.data('resetText', $el[val]())
$el[val](data[state] == null ? this.options[state] : data[state])
// push to event loop to allow forms to submit
setTimeout($.proxy(function () {
if (state == 'loadingText') {
this.isLoading = true
$el.addClass(d).attr(d, d)
} else if (this.isLoading) {
this.isLoading = false
$el.removeClass(d).removeAttr(d)
}
}, this), 0)
}
Button.prototype.toggle = function () {
var changed = true
var $parent = this.$element.closest('[data-toggle="buttons"]')
if ($parent.length) {
var $input = this.$element.find('input')
if ($input.prop('type') == 'radio') {
if ($input.prop('checked') && this.$element.hasClass('active')) changed = false
else $parent.find('.active').removeClass('active')
}
if (changed) $input.prop('checked', !this.$element.hasClass('active')).trigger('change')
}
if (changed) this.$element.toggleClass('active')
}
// BUTTON PLUGIN DEFINITION
// ========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.button')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.button', (data = new Button(this, options)))
if (option == 'toggle') data.toggle()
else if (option) data.setState(option)
})
}
var old = $.fn.button
$.fn.button = Plugin
$.fn.button.Constructor = Button
// BUTTON NO CONFLICT
// ==================
$.fn.button.noConflict = function () {
$.fn.button = old
return this
}
// BUTTON DATA-API
// ===============
$(document)
.on('click.bs.button.data-api', '[data-toggle^="button"]', function (e) {
var $btn = $(e.target)
if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn')
Plugin.call($btn, 'toggle')
e.preventDefault()
})
.on('focus.bs.button.data-api blur.bs.button.data-api', '[data-toggle^="button"]', function (e) {
$(e.target).closest('.btn').toggleClass('focus', e.type == 'focus')
})
}(jQuery);
/* ========================================================================
* Bootstrap: carousel.js v3.2.0
* http://getbootstrap.com/javascript/#carousel
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// CAROUSEL CLASS DEFINITION
// =========================
var Carousel = function (element, options) {
this.$element = $(element).on('keydown.bs.carousel', $.proxy(this.keydown, this))
this.$indicators = this.$element.find('.carousel-indicators')
this.options = options
this.paused =
this.sliding =
this.interval =
this.$active =
this.$items = null
this.options.pause == 'hover' && this.$element
.on('mouseenter.bs.carousel', $.proxy(this.pause, this))
.on('mouseleave.bs.carousel', $.proxy(this.cycle, this))
}
Carousel.VERSION = '3.2.0'
Carousel.TRANSITION_DURATION = 600
Carousel.DEFAULTS = {
interval: 5000,
pause: 'hover',
wrap: true
}
Carousel.prototype.keydown = function (e) {
switch (e.which) {
case 37: this.prev(); break
case 39: this.next(); break
default: return
}
e.preventDefault()
}
Carousel.prototype.cycle = function (e) {
e || (this.paused = false)
this.interval && clearInterval(this.interval)
this.options.interval
&& !this.paused
&& (this.interval = setInterval($.proxy(this.next, this), this.options.interval))
return this
}
Carousel.prototype.getItemIndex = function (item) {
this.$items = item.parent().children('.item')
return this.$items.index(item || this.$active)
}
Carousel.prototype.getItemForDirection = function (direction, active) {
var delta = direction == 'prev' ? -1 : 1
var activeIndex = this.getItemIndex(active)
var itemIndex = (activeIndex + delta) % this.$items.length
return this.$items.eq(itemIndex)
}
Carousel.prototype.to = function (pos) {
var that = this
var activeIndex = this.getItemIndex(this.$active = this.$element.find('.item.active'))
if (pos > (this.$items.length - 1) || pos < 0) return
if (this.sliding) return this.$element.one('slid.bs.carousel', function () { that.to(pos) }) // yes, "slid"
if (activeIndex == pos) return this.pause().cycle()
return this.slide(pos > activeIndex ? 'next' : 'prev', this.$items.eq(pos))
}
Carousel.prototype.pause = function (e) {
e || (this.paused = true)
if (this.$element.find('.next, .prev').length && $.support.transition) {
this.$element.trigger($.support.transition.end)
this.cycle(true)
}
this.interval = clearInterval(this.interval)
return this
}
Carousel.prototype.next = function () {
if (this.sliding) return
return this.slide('next')
}
Carousel.prototype.prev = function () {
if (this.sliding) return
return this.slide('prev')
}
Carousel.prototype.slide = function (type, next) {
var $active = this.$element.find('.item.active')
var $next = next || this.getItemForDirection(type, $active)
var isCycling = this.interval
var direction = type == 'next' ? 'left' : 'right'
var fallback = type == 'next' ? 'first' : 'last'
var that = this
if (!$next.length) {
if (!this.options.wrap) return
$next = this.$element.find('.item')[fallback]()
}
if ($next.hasClass('active')) return (this.sliding = false)
var relatedTarget = $next[0]
var slideEvent = $.Event('slide.bs.carousel', {
relatedTarget: relatedTarget,
direction: direction
})
this.$element.trigger(slideEvent)
if (slideEvent.isDefaultPrevented()) return
this.sliding = true
isCycling && this.pause()
if (this.$indicators.length) {
this.$indicators.find('.active').removeClass('active')
var $nextIndicator = $(this.$indicators.children()[this.getItemIndex($next)])
$nextIndicator && $nextIndicator.addClass('active')
}
var slidEvent = $.Event('slid.bs.carousel', { relatedTarget: relatedTarget, direction: direction }) // yes, "slid"
if ($.support.transition && this.$element.hasClass('slide')) {
$next.addClass(type)
$next[0].offsetWidth // force reflow
$active.addClass(direction)
$next.addClass(direction)
$active
.one('bsTransitionEnd', function () {
$next.removeClass([type, direction].join(' ')).addClass('active')
$active.removeClass(['active', direction].join(' '))
that.sliding = false
setTimeout(function () {
that.$element.trigger(slidEvent)
}, 0)
})
.emulateTransitionEnd(Carousel.TRANSITION_DURATION)
} else {
$active.removeClass('active')
$next.addClass('active')
this.sliding = false
this.$element.trigger(slidEvent)
}
isCycling && this.cycle()
return this
}
// CAROUSEL PLUGIN DEFINITION
// ==========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.carousel')
var options = $.extend({}, Carousel.DEFAULTS, $this.data(), typeof option == 'object' && option)
var action = typeof option == 'string' ? option : options.slide
if (!data) $this.data('bs.carousel', (data = new Carousel(this, options)))
if (typeof option == 'number') data.to(option)
else if (action) data[action]()
else if (options.interval) data.pause().cycle()
})
}
var old = $.fn.carousel
$.fn.carousel = Plugin
$.fn.carousel.Constructor = Carousel
// CAROUSEL NO CONFLICT
// ====================
$.fn.carousel.noConflict = function () {
$.fn.carousel = old
return this
}
// CAROUSEL DATA-API
// =================
$(document).on('click.bs.carousel.data-api', '[data-slide], [data-slide-to]', function (e) {
var href
var $this = $(this)
var $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) // strip for ie7
if (!$target.hasClass('carousel')) return
var options = $.extend({}, $target.data(), $this.data())
var slideIndex = $this.attr('data-slide-to')
if (slideIndex) options.interval = false
Plugin.call($target, options)
if (slideIndex) {
$target.data('bs.carousel').to(slideIndex)
}
e.preventDefault()
})
$(window).on('load', function () {
$('[data-ride="carousel"]').each(function () {
var $carousel = $(this)
Plugin.call($carousel, $carousel.data())
})
})
}(jQuery);
/* ========================================================================
* Bootstrap: collapse.js v3.2.0
* http://getbootstrap.com/javascript/#collapse
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// COLLAPSE PUBLIC CLASS DEFINITION
// ================================
var Collapse = function (element, options) {
this.$element = $(element)
this.options = $.extend({}, Collapse.DEFAULTS, options)
this.transitioning = null
if (this.options.parent) this.$parent = $(this.options.parent)
if (this.options.toggle) this.toggle()
}
Collapse.VERSION = '3.2.0'
Collapse.TRANSITION_DURATION = 350
Collapse.DEFAULTS = {
toggle: true
}
Collapse.prototype.dimension = function () {
var hasWidth = this.$element.hasClass('width')
return hasWidth ? 'width' : 'height'
}
Collapse.prototype.show = function () {
if (this.transitioning || this.$element.hasClass('in')) return
var startEvent = $.Event('show.bs.collapse')
this.$element.trigger(startEvent)
if (startEvent.isDefaultPrevented()) return
var actives = this.$parent && this.$parent.find('> .panel > .in')
if (actives && actives.length) {
var hasData = actives.data('bs.collapse')
if (hasData && hasData.transitioning) return
Plugin.call(actives, 'hide')
hasData || actives.data('bs.collapse', null)
}
var dimension = this.dimension()
this.$element
.removeClass('collapse')
.addClass('collapsing')[dimension](0)
this.transitioning = 1
var complete = function () {
this.$element
.removeClass('collapsing')
.addClass('collapse in')[dimension]('')
this.transitioning = 0
this.$element
.trigger('shown.bs.collapse')
}
if (!$.support.transition) return complete.call(this)
var scrollSize = $.camelCase(['scroll', dimension].join('-'))
this.$element
.one('bsTransitionEnd', $.proxy(complete, this))
.emulateTransitionEnd(Collapse.TRANSITION_DURATION)[dimension](this.$element[0][scrollSize])
}
Collapse.prototype.hide = function () {
if (this.transitioning || !this.$element.hasClass('in')) return
var startEvent = $.Event('hide.bs.collapse')
this.$element.trigger(startEvent)
if (startEvent.isDefaultPrevented()) return
var dimension = this.dimension()
this.$element[dimension](this.$element[dimension]())[0].offsetHeight
this.$element
.addClass('collapsing')
.removeClass('collapse in')
this.transitioning = 1
var complete = function () {
this.transitioning = 0
this.$element
.trigger('hidden.bs.collapse')
.removeClass('collapsing')
.addClass('collapse')
}
if (!$.support.transition) return complete.call(this)
this.$element
[dimension](0)
.one('bsTransitionEnd', $.proxy(complete, this))
.emulateTransitionEnd(Collapse.TRANSITION_DURATION)
}
Collapse.prototype.toggle = function () {
this[this.$element.hasClass('in') ? 'hide' : 'show']()
}
// COLLAPSE PLUGIN DEFINITION
// ==========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.collapse')
var options = $.extend({}, Collapse.DEFAULTS, $this.data(), typeof option == 'object' && option)
if (!data && options.toggle && option == 'show') option = !option
if (!data) $this.data('bs.collapse', (data = new Collapse(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.collapse
$.fn.collapse = Plugin
$.fn.collapse.Constructor = Collapse
// COLLAPSE NO CONFLICT
// ====================
$.fn.collapse.noConflict = function () {
$.fn.collapse = old
return this
}
// COLLAPSE DATA-API
// =================
$(document).on('click.bs.collapse.data-api', '[data-toggle="collapse"]', function (e) {
var href
var $this = $(this)
var target = $this.attr('data-target')
|| e.preventDefault()
|| (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') // strip for ie7
var $target = $(target)
var data = $target.data('bs.collapse')
var option = data ? 'toggle' : $this.data()
var parent = $this.attr('data-parent')
var $parent = parent && $(parent)
if (!data || !data.transitioning) {
if ($parent) $parent.find('[data-toggle="collapse"][data-parent="' + parent + '"]').not($this).addClass('collapsed')
$this.toggleClass('collapsed', $target.hasClass('in'))
}
Plugin.call($target, option)
})
}(jQuery);
/* ========================================================================
* Bootstrap: dropdown.js v3.2.0
* http://getbootstrap.com/javascript/#dropdowns
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// DROPDOWN CLASS DEFINITION
// =========================
var backdrop = '.dropdown-backdrop'
var toggle = '[data-toggle="dropdown"]'
var Dropdown = function (element) {
$(element).on('click.bs.dropdown', this.toggle)
}
Dropdown.VERSION = '3.2.0'
Dropdown.prototype.toggle = function (e) {
var $this = $(this)
if ($this.is('.disabled, :disabled')) return
var $parent = getParent($this)
var isActive = $parent.hasClass('open')
clearMenus()
if (!isActive) {
if ('ontouchstart' in document.documentElement && !$parent.closest('.navbar-nav').length) {
// if mobile we use a backdrop because click events don't delegate
$('<div class="dropdown-backdrop"/>').insertAfter($(this)).on('click', clearMenus)
}
var relatedTarget = { relatedTarget: this }
$parent.trigger(e = $.Event('show.bs.dropdown', relatedTarget))
if (e.isDefaultPrevented()) return
$this
.trigger('focus')
.attr('aria-expanded', 'true')
$parent
.toggleClass('open')
.trigger('shown.bs.dropdown', relatedTarget)
}
return false
}
Dropdown.prototype.keydown = function (e) {
if (!/(38|40|27)/.test(e.keyCode)) return
var $this = $(this)
e.preventDefault()
e.stopPropagation()
if ($this.is('.disabled, :disabled')) return
var $parent = getParent($this)
var isActive = $parent.hasClass('open')
if (!isActive || (isActive && e.keyCode == 27)) {
if (e.which == 27) $parent.find(toggle).trigger('focus')
return $this.trigger('click')
}
var desc = ' li:not(.divider):visible a'
var $items = $parent.find('[role="menu"]' + desc + ', [role="listbox"]' + desc)
if (!$items.length) return
var index = $items.index($items.filter(':focus'))
if (e.keyCode == 38 && index > 0) index-- // up
if (e.keyCode == 40 && index < $items.length - 1) index++ // down
if (!~index) index = 0
$items.eq(index).trigger('focus')
}
function clearMenus(e) {
if (e && e.which === 3) return
$(backdrop).remove()
$(toggle).each(function () {
var $this = $(this)
var $parent = getParent($this)
var relatedTarget = { relatedTarget: this }
if (!$parent.hasClass('open')) return
$parent.trigger(e = $.Event('hide.bs.dropdown', relatedTarget))
if (e.isDefaultPrevented()) return
$this.attr('aria-expanded', 'false')
$parent.removeClass('open').trigger('hidden.bs.dropdown', relatedTarget)
})
}
function getParent($this) {
var selector = $this.attr('data-target')
if (!selector) {
selector = $this.attr('href')
selector = selector && /#[A-Za-z]/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
}
var $parent = selector && $(selector)
return $parent && $parent.length ? $parent : $this.parent()
}
// DROPDOWN PLUGIN DEFINITION
// ==========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.dropdown')
if (!data) $this.data('bs.dropdown', (data = new Dropdown(this)))
if (typeof option == 'string') data[option].call($this)
})
}
var old = $.fn.dropdown
$.fn.dropdown = Plugin
$.fn.dropdown.Constructor = Dropdown
// DROPDOWN NO CONFLICT
// ====================
$.fn.dropdown.noConflict = function () {
$.fn.dropdown = old
return this
}
// APPLY TO STANDARD DROPDOWN ELEMENTS
// ===================================
$(document)
.on('click.bs.dropdown.data-api', clearMenus)
.on('click.bs.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() })
.on('click.bs.dropdown.data-api', toggle, Dropdown.prototype.toggle)
.on('keydown.bs.dropdown.data-api', toggle + ', [role="menu"], [role="listbox"]', Dropdown.prototype.keydown)
}(jQuery);
/* ========================================================================
* Bootstrap: modal.js v3.2.0
* http://getbootstrap.com/javascript/#modals
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// MODAL CLASS DEFINITION
// ======================
var Modal = function (element, options) {
this.options = options
this.$body = $(document.body)
this.$element = $(element)
this.$backdrop =
this.isShown = null
this.scrollbarWidth = 0
if (this.options.remote) {
this.$element
.find('.modal-content')
.load(this.options.remote, $.proxy(function () {
this.$element.trigger('loaded.bs.modal')
}, this))
}
}
Modal.VERSION = '3.2.0'
Modal.TRANSITION_DURATION = 300
Modal.BACKDROP_TRANSITION_DURATION = 150
Modal.DEFAULTS = {
backdrop: true,
keyboard: true,
show: true
}
Modal.prototype.toggle = function (_relatedTarget) {
return this.isShown ? this.hide() : this.show(_relatedTarget)
}
Modal.prototype.show = function (_relatedTarget) {
var that = this
var e = $.Event('show.bs.modal', { relatedTarget: _relatedTarget })
this.$element.trigger(e)
if (this.isShown || e.isDefaultPrevented()) return
this.isShown = true
this.checkScrollbar()
this.$body.addClass('modal-open')
this.setScrollbar()
this.escape()
this.$element.on('click.dismiss.bs.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this))
this.backdrop(function () {
var transition = $.support.transition && that.$element.hasClass('fade')
if (!that.$element.parent().length) {
that.$element.appendTo(that.$body) // don't move modals dom position
}
that.$element
.show()
.scrollTop(0)
if (transition) {
that.$element[0].offsetWidth // force reflow
}
that.$element
.addClass('in')
.attr('aria-hidden', false)
that.enforceFocus()
var e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget })
transition ?
that.$element.find('.modal-dialog') // wait for modal to slide in
.one('bsTransitionEnd', function () {
that.$element.trigger('focus').trigger(e)
})
.emulateTransitionEnd(Modal.TRANSITION_DURATION) :
that.$element.trigger('focus').trigger(e)
})
}
Modal.prototype.hide = function (e) {
if (e) e.preventDefault()
e = $.Event('hide.bs.modal')
this.$element.trigger(e)
if (!this.isShown || e.isDefaultPrevented()) return
this.isShown = false
this.$body.removeClass('modal-open')
this.resetScrollbar()
this.escape()
$(document).off('focusin.bs.modal')
this.$element
.removeClass('in')
.attr('aria-hidden', true)
.off('click.dismiss.bs.modal')
$.support.transition && this.$element.hasClass('fade') ?
this.$element
.one('bsTransitionEnd', $.proxy(this.hideModal, this))
.emulateTransitionEnd(Modal.TRANSITION_DURATION) :
this.hideModal()
}
Modal.prototype.enforceFocus = function () {
$(document)
.off('focusin.bs.modal') // guard against infinite focus loop
.on('focusin.bs.modal', $.proxy(function (e) {
if (this.$element[0] !== e.target && !this.$element.has(e.target).length) {
this.$element.trigger('focus')
}
}, this))
}
Modal.prototype.escape = function () {
if (this.isShown && this.options.keyboard) {
this.$element.on('keydown.dismiss.bs.modal', $.proxy(function (e) {
e.which == 27 && this.hide()
}, this))
} else if (!this.isShown) {
this.$element.off('keydown.dismiss.bs.modal')
}
}
Modal.prototype.hideModal = function () {
var that = this
this.$element.hide()
this.backdrop(function () {
that.$element.trigger('hidden.bs.modal')
})
}
Modal.prototype.removeBackdrop = function () {
this.$backdrop && this.$backdrop.remove()
this.$backdrop = null
}
Modal.prototype.backdrop = function (callback) {
var that = this
var animate = this.$element.hasClass('fade') ? 'fade' : ''
if (this.isShown && this.options.backdrop) {
var doAnimate = $.support.transition && animate
this.$backdrop = $('<div class="modal-backdrop ' + animate + '" />')
.appendTo(this.$body)
this.$element.on('mousedown.dismiss.bs.modal', $.proxy(function (e) {
if (e.target !== e.currentTarget) return
this.options.backdrop == 'static'
? this.$element[0].focus.call(this.$element[0])
: this.hide.call(this)
}, this))
if (doAnimate) this.$backdrop[0].offsetWidth // force reflow
this.$backdrop.addClass('in')
if (!callback) return
doAnimate ?
this.$backdrop
.one('bsTransitionEnd', callback)
.emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) :
callback()
} else if (!this.isShown && this.$backdrop) {
this.$backdrop.removeClass('in')
var callbackRemove = function () {
that.removeBackdrop()
callback && callback()
}
$.support.transition && this.$element.hasClass('fade') ?
this.$backdrop
.one('bsTransitionEnd', callbackRemove)
.emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) :
callbackRemove()
} else if (callback) {
callback()
}
}
Modal.prototype.checkScrollbar = function () {
if (document.body.clientWidth >= window.innerWidth) return
this.scrollbarWidth = this.scrollbarWidth || this.measureScrollbar()
}
Modal.prototype.setScrollbar = function () {
var bodyPad = parseInt((this.$body.css('padding-right') || 0), 10)
if (this.scrollbarWidth) this.$body.css('padding-right', bodyPad + this.scrollbarWidth)
}
Modal.prototype.resetScrollbar = function () {
this.$body.css('padding-right', '')
}
Modal.prototype.measureScrollbar = function () { // thx walsh
var scrollDiv = document.createElement('div')
scrollDiv.className = 'modal-scrollbar-measure'
this.$body.append(scrollDiv)
var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth
this.$body[0].removeChild(scrollDiv)
return scrollbarWidth
}
// MODAL PLUGIN DEFINITION
// =======================
function Plugin(option, _relatedTarget) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.modal')
var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option)
if (!data) $this.data('bs.modal', (data = new Modal(this, options)))
if (typeof option == 'string') data[option](_relatedTarget)
else if (options.show) data.show(_relatedTarget)
})
}
var old = $.fn.modal
$.fn.modal = Plugin
$.fn.modal.Constructor = Modal
// MODAL NO CONFLICT
// =================
$.fn.modal.noConflict = function () {
$.fn.modal = old
return this
}
// MODAL DATA-API
// ==============
$(document).on('click.bs.modal.data-api', '[data-toggle="modal"]', function (e) {
var $this = $(this)
var href = $this.attr('href')
var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) // strip for ie7
var option = $target.data('bs.modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data())
if ($this.is('a')) e.preventDefault()
$target.one('show.bs.modal', function (showEvent) {
if (showEvent.isDefaultPrevented()) return // only register focus restorer if modal will actually get shown
$target.one('hidden.bs.modal', function () {
$this.is(':visible') && $this.trigger('focus')
})
})
Plugin.call($target, option, this)
})
}(jQuery);
/* ========================================================================
* Bootstrap: tooltip.js v3.2.0
* http://getbootstrap.com/javascript/#tooltip
* Inspired by the original jQuery.tipsy by Jason Frame
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// TOOLTIP PUBLIC CLASS DEFINITION
// ===============================
var Tooltip = function (element, options) {
this.type =
this.options =
this.enabled =
this.timeout =
this.hoverState =
this.$element = null
this.init('tooltip', element, options)
}
Tooltip.VERSION = '3.2.0'
Tooltip.TRANSITION_DURATION = 150
Tooltip.DEFAULTS = {
animation: true,
placement: 'top',
selector: false,
template: '<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',
trigger: 'hover focus',
title: '',
delay: 0,
html: false,
container: false,
viewport: {
selector: 'body',
padding: 0
}
}
Tooltip.prototype.init = function (type, element, options) {
this.enabled = true
this.type = type
this.$element = $(element)
this.options = this.getOptions(options)
this.$viewport = this.options.viewport && $(this.options.viewport.selector || this.options.viewport)
var triggers = this.options.trigger.split(' ')
for (var i = triggers.length; i--;) {
var trigger = triggers[i]
if (trigger == 'click') {
this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this))
} else if (trigger != 'manual') {
var eventIn = trigger == 'hover' ? 'mouseenter' : 'focusin'
var eventOut = trigger == 'hover' ? 'mouseleave' : 'focusout'
this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this))
this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this))
}
}
this.options.selector ?
(this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) :
this.fixTitle()
}
Tooltip.prototype.getDefaults = function () {
return Tooltip.DEFAULTS
}
Tooltip.prototype.getOptions = function (options) {
options = $.extend({}, this.getDefaults(), this.$element.data(), options)
if (options.delay && typeof options.delay == 'number') {
options.delay = {
show: options.delay,
hide: options.delay
}
}
return options
}
Tooltip.prototype.getDelegateOptions = function () {
var options = {}
var defaults = this.getDefaults()
this._options && $.each(this._options, function (key, value) {
if (defaults[key] != value) options[key] = value
})
return options
}
Tooltip.prototype.enter = function (obj) {
var self = obj instanceof this.constructor ?
obj : $(obj.currentTarget).data('bs.' + this.type)
if (!self) {
self = new this.constructor(obj.currentTarget, this.getDelegateOptions())
$(obj.currentTarget).data('bs.' + this.type, self)
}
clearTimeout(self.timeout)
self.hoverState = 'in'
if (!self.options.delay || !self.options.delay.show) return self.show()
self.timeout = setTimeout(function () {
if (self.hoverState == 'in') self.show()
}, self.options.delay.show)
}
Tooltip.prototype.leave = function (obj) {
var self = obj instanceof this.constructor ?
obj : $(obj.currentTarget).data('bs.' + this.type)
if (!self) {
self = new this.constructor(obj.currentTarget, this.getDelegateOptions())
$(obj.currentTarget).data('bs.' + this.type, self)
}
clearTimeout(self.timeout)
self.hoverState = 'out'
if (!self.options.delay || !self.options.delay.hide) return self.hide()
self.timeout = setTimeout(function () {
if (self.hoverState == 'out') self.hide()
}, self.options.delay.hide)
}
Tooltip.prototype.show = function () {
var e = $.Event('show.bs.' + this.type)
if (this.hasContent() && this.enabled) {
this.$element.trigger(e)
var inDom = $.contains(document.documentElement, this.$element[0])
if (e.isDefaultPrevented() || !inDom) return
var that = this
var $tip = this.tip()
var tipId = this.getUID(this.type)
this.setContent()
$tip.attr('id', tipId)
this.$element.attr('aria-describedby', tipId)
if (this.options.animation) $tip.addClass('fade')
var placement = typeof this.options.placement == 'function' ?
this.options.placement.call(this, $tip[0], this.$element[0]) :
this.options.placement
var autoToken = /\s?auto?\s?/i
var autoPlace = autoToken.test(placement)
if (autoPlace) placement = placement.replace(autoToken, '') || 'top'
$tip
.detach()
.css({ top: 0, left: 0, display: 'block' })
.addClass(placement)
.data('bs.' + this.type, this)
this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element)
var pos = this.getPosition()
var actualWidth = $tip[0].offsetWidth
var actualHeight = $tip[0].offsetHeight
if (autoPlace) {
var orgPlacement = placement
var $parent = this.$element.parent()
var parentDim = this.getPosition($parent)
placement = placement == 'bottom' && pos.top + pos.height + actualHeight - parentDim.scroll > parentDim.height ? 'top' :
placement == 'top' && pos.top - parentDim.scroll - actualHeight < 0 ? 'bottom' :
placement == 'right' && pos.right + actualWidth > parentDim.width ? 'left' :
placement == 'left' && pos.left - actualWidth < parentDim.left ? 'right' :
placement
$tip
.removeClass(orgPlacement)
.addClass(placement)
}
var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight)
this.applyPlacement(calculatedOffset, placement)
var complete = function () {
that.$element.trigger('shown.bs.' + that.type)
that.hoverState = null
}
$.support.transition && this.$tip.hasClass('fade') ?
$tip
.one('bsTransitionEnd', complete)
.emulateTransitionEnd(Tooltip.TRANSITION_DURATION) :
complete()
}
}
Tooltip.prototype.applyPlacement = function (offset, placement) {
var $tip = this.tip()
var width = $tip[0].offsetWidth
var height = $tip[0].offsetHeight
// manually read margins because getBoundingClientRect includes difference
var marginTop = parseInt($tip.css('margin-top'), 10)
var marginLeft = parseInt($tip.css('margin-left'), 10)
// we must check for NaN for ie 8/9
if (isNaN(marginTop)) marginTop = 0
if (isNaN(marginLeft)) marginLeft = 0
offset.top = offset.top + marginTop
offset.left = offset.left + marginLeft
// $.fn.offset doesn't round pixel values
// so we use setOffset directly with our own function B-0
$.offset.setOffset($tip[0], $.extend({
using: function (props) {
$tip.css({
top: Math.round(props.top),
left: Math.round(props.left)
})
}
}, offset), 0)
$tip.addClass('in')
// check to see if placing tip in new offset caused the tip to resize itself
var actualWidth = $tip[0].offsetWidth
var actualHeight = $tip[0].offsetHeight
if (placement == 'top' && actualHeight != height) {
offset.top = offset.top + height - actualHeight
}
var delta = this.getViewportAdjustedDelta(placement, offset, actualWidth, actualHeight)
if (delta.left) offset.left += delta.left
else offset.top += delta.top
var arrowDelta = delta.left ? delta.left * 2 - width + actualWidth : delta.top * 2 - height + actualHeight
var arrowPosition = delta.left ? 'left' : 'top'
var arrowOffsetPosition = delta.left ? 'offsetWidth' : 'offsetHeight'
$tip.offset(offset)
this.replaceArrow(arrowDelta, $tip[0][arrowOffsetPosition], arrowPosition)
}
Tooltip.prototype.replaceArrow = function (delta, dimension, position) {
this.arrow().css(position, delta ? (50 * (1 - delta / dimension) + '%') : '')
}
Tooltip.prototype.setContent = function () {
var $tip = this.tip()
var title = this.getTitle()
$tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title)
$tip.removeClass('fade in top bottom left right')
}
Tooltip.prototype.hide = function () {
var that = this
var $tip = this.tip()
var e = $.Event('hide.bs.' + this.type)
this.$element.removeAttr('aria-describedby')
function complete() {
if (that.hoverState != 'in') $tip.detach()
that.$element.trigger('hidden.bs.' + that.type)
}
this.$element.trigger(e)
if (e.isDefaultPrevented()) return
$tip.removeClass('in')
$.support.transition && this.$tip.hasClass('fade') ?
$tip
.one('bsTransitionEnd', complete)
.emulateTransitionEnd(Tooltip.TRANSITION_DURATION) :
complete()
this.hoverState = null
return this
}
Tooltip.prototype.fixTitle = function () {
var $e = this.$element
if ($e.attr('title') || typeof ($e.attr('data-original-title')) != 'string') {
$e.attr('data-original-title', $e.attr('title') || '').attr('title', '')
}
}
Tooltip.prototype.hasContent = function () {
return this.getTitle()
}
Tooltip.prototype.getPosition = function ($element) {
$element = $element || this.$element
var el = $element[0]
var isBody = el.tagName == 'BODY'
var isSvg = window.SVGElement && el instanceof window.SVGElement
var elRect = el.getBoundingClientRect ? el.getBoundingClientRect() : null
var elOffset = isBody ? { top: 0, left: 0 } : $element.offset()
var scroll = { scroll: isBody ? document.documentElement.scrollTop || document.body.scrollTop : $element.scrollTop() }
var outerDims = isSvg ? {} : {
width: isBody ? $(window).width() : $element.outerWidth(),
height: isBody ? $(window).height() : $element.outerHeight()
}
return $.extend({}, elRect, scroll, outerDims, elOffset)
}
Tooltip.prototype.getCalculatedOffset = function (placement, pos, actualWidth, actualHeight) {
return placement == 'bottom' ? { top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2 } :
placement == 'top' ? { top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2 } :
placement == 'left' ? { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth } :
/* placement == 'right' */ { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width }
}
Tooltip.prototype.getViewportAdjustedDelta = function (placement, pos, actualWidth, actualHeight) {
var delta = { top: 0, left: 0 }
if (!this.$viewport) return delta
var viewportPadding = this.options.viewport && this.options.viewport.padding || 0
var viewportDimensions = this.getPosition(this.$viewport)
if (/right|left/.test(placement)) {
var topEdgeOffset = pos.top - viewportPadding - viewportDimensions.scroll
var bottomEdgeOffset = pos.top + viewportPadding - viewportDimensions.scroll + actualHeight
if (topEdgeOffset < viewportDimensions.top) { // top overflow
delta.top = viewportDimensions.top - topEdgeOffset
} else if (bottomEdgeOffset > viewportDimensions.top + viewportDimensions.height) { // bottom overflow
delta.top = viewportDimensions.top + viewportDimensions.height - bottomEdgeOffset
}
} else {
var leftEdgeOffset = pos.left - viewportPadding
var rightEdgeOffset = pos.left + viewportPadding + actualWidth
if (leftEdgeOffset < viewportDimensions.left) { // left overflow
delta.left = viewportDimensions.left - leftEdgeOffset
} else if (rightEdgeOffset > viewportDimensions.width) { // right overflow
delta.left = viewportDimensions.left + viewportDimensions.width - rightEdgeOffset
}
}
return delta
}
Tooltip.prototype.getTitle = function () {
var title
var $e = this.$element
var o = this.options
title = $e.attr('data-original-title')
|| (typeof o.title == 'function' ? o.title.call($e[0]) : o.title)
return title
}
Tooltip.prototype.getUID = function (prefix) {
do prefix += ~~(Math.random() * 1000000)
while (document.getElementById(prefix))
return prefix
}
Tooltip.prototype.tip = function () {
return (this.$tip = this.$tip || $(this.options.template))
}
Tooltip.prototype.arrow = function () {
return (this.$arrow = this.$arrow || this.tip().find('.tooltip-arrow'))
}
Tooltip.prototype.validate = function () {
if (!this.$element[0].parentNode) {
this.hide()
this.$element = null
this.options = null
}
}
Tooltip.prototype.enable = function () {
this.enabled = true
}
Tooltip.prototype.disable = function () {
this.enabled = false
}
Tooltip.prototype.toggleEnabled = function () {
this.enabled = !this.enabled
}
Tooltip.prototype.toggle = function (e) {
var self = this
if (e) {
self = $(e.currentTarget).data('bs.' + this.type)
if (!self) {
self = new this.constructor(e.currentTarget, this.getDelegateOptions())
$(e.currentTarget).data('bs.' + this.type, self)
}
}
self.tip().hasClass('in') ? self.leave(self) : self.enter(self)
}
Tooltip.prototype.destroy = function () {
clearTimeout(this.timeout)
this.hide().$element.off('.' + this.type).removeData('bs.' + this.type)
}
// TOOLTIP PLUGIN DEFINITION
// =========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.tooltip')
var options = typeof option == 'object' && option
if (!data && option == 'destroy') return
if (!data) $this.data('bs.tooltip', (data = new Tooltip(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.tooltip
$.fn.tooltip = Plugin
$.fn.tooltip.Constructor = Tooltip
// TOOLTIP NO CONFLICT
// ===================
$.fn.tooltip.noConflict = function () {
$.fn.tooltip = old
return this
}
}(jQuery);
/* ========================================================================
* Bootstrap: popover.js v3.2.0
* http://getbootstrap.com/javascript/#popovers
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// POPOVER PUBLIC CLASS DEFINITION
// ===============================
var Popover = function (element, options) {
this.init('popover', element, options)
}
if (!$.fn.tooltip) throw new Error('Popover requires tooltip.js')
Popover.VERSION = '3.2.0'
Popover.DEFAULTS = $.extend({}, $.fn.tooltip.Constructor.DEFAULTS, {
placement: 'right',
trigger: 'click',
content: '',
template: '<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'
})
// NOTE: POPOVER EXTENDS tooltip.js
// ================================
Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype)
Popover.prototype.constructor = Popover
Popover.prototype.getDefaults = function () {
return Popover.DEFAULTS
}
Popover.prototype.setContent = function () {
var $tip = this.tip()
var title = this.getTitle()
var content = this.getContent()
$tip.find('.popover-title')[this.options.html ? 'html' : 'text'](title)
$tip.find('.popover-content').empty()[ // we use append for html objects to maintain js events
this.options.html ? (typeof content == 'string' ? 'html' : 'append') : 'text'
](content)
$tip.removeClass('fade top bottom left right in')
// IE8 doesn't accept hiding via the `:empty` pseudo selector, we have to do
// this manually by checking the contents.
if (!$tip.find('.popover-title').html()) $tip.find('.popover-title').hide()
}
Popover.prototype.hasContent = function () {
return this.getTitle() || this.getContent()
}
Popover.prototype.getContent = function () {
var $e = this.$element
var o = this.options
return $e.attr('data-content')
|| (typeof o.content == 'function' ?
o.content.call($e[0]) :
o.content)
}
Popover.prototype.arrow = function () {
return (this.$arrow = this.$arrow || this.tip().find('.arrow'))
}
Popover.prototype.tip = function () {
if (!this.$tip) this.$tip = $(this.options.template)
return this.$tip
}
// POPOVER PLUGIN DEFINITION
// =========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.popover')
var options = typeof option == 'object' && option
if (!data && option == 'destroy') return
if (!data) $this.data('bs.popover', (data = new Popover(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.popover
$.fn.popover = Plugin
$.fn.popover.Constructor = Popover
// POPOVER NO CONFLICT
// ===================
$.fn.popover.noConflict = function () {
$.fn.popover = old
return this
}
}(jQuery);
/* ========================================================================
* Bootstrap: scrollspy.js v3.2.0
* http://getbootstrap.com/javascript/#scrollspy
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// SCROLLSPY CLASS DEFINITION
// ==========================
function ScrollSpy(element, options) {
var process = $.proxy(this.process, this)
this.$body = $('body')
this.$scrollElement = $(element).is('body') ? $(window) : $(element)
this.options = $.extend({}, ScrollSpy.DEFAULTS, options)
this.selector = (this.options.target || '') + ' .nav li > a'
this.offsets = []
this.targets = []
this.activeTarget = null
this.scrollHeight = 0
this.$scrollElement.on('scroll.bs.scrollspy', process)
this.refresh()
this.process()
}
ScrollSpy.VERSION = '3.2.0'
ScrollSpy.DEFAULTS = {
offset: 10
}
ScrollSpy.prototype.getScrollHeight = function () {
return this.$scrollElement[0].scrollHeight || Math.max(this.$body[0].scrollHeight, document.documentElement.scrollHeight)
}
ScrollSpy.prototype.refresh = function () {
var offsetMethod = 'offset'
var offsetBase = 0
if (!$.isWindow(this.$scrollElement[0])) {
offsetMethod = 'position'
offsetBase = this.$scrollElement.scrollTop()
}
this.offsets = []
this.targets = []
this.scrollHeight = this.getScrollHeight()
var self = this
this.$body
.find(this.selector)
.map(function () {
var $el = $(this)
var href = $el.data('target') || $el.attr('href')
var $href = /^#./.test(href) && $(href)
return ($href
&& $href.length
&& $href.is(':visible')
&& [[$href[offsetMethod]().top + offsetBase, href]]) || null
})
.sort(function (a, b) { return a[0] - b[0] })
.each(function () {
self.offsets.push(this[0])
self.targets.push(this[1])
})
}
ScrollSpy.prototype.process = function () {
var scrollTop = this.$scrollElement.scrollTop() + this.options.offset
var scrollHeight = this.getScrollHeight()
var maxScroll = this.options.offset + scrollHeight - this.$scrollElement.height()
var offsets = this.offsets
var targets = this.targets
var activeTarget = this.activeTarget
var i
if (this.scrollHeight != scrollHeight) {
this.refresh()
}
if (scrollTop >= maxScroll) {
return activeTarget != (i = targets[targets.length - 1]) && this.activate(i)
}
if (activeTarget && scrollTop <= offsets[0]) {
return activeTarget != (i = targets[0]) && this.activate(i)
}
for (i = offsets.length; i--;) {
activeTarget != targets[i]
&& scrollTop >= offsets[i]
&& (!offsets[i + 1] || scrollTop <= offsets[i + 1])
&& this.activate(targets[i])
}
}
ScrollSpy.prototype.activate = function (target) {
this.activeTarget = target
$(this.selector)
.parentsUntil(this.options.target, '.active')
.removeClass('active')
var selector = this.selector +
'[data-target="' + target + '"],' +
this.selector + '[href="' + target + '"]'
var active = $(selector)
.parents('li')
.addClass('active')
if (active.parent('.dropdown-menu').length) {
active = active
.closest('li.dropdown')
.addClass('active')
}
active.trigger('activate.bs.scrollspy')
}
// SCROLLSPY PLUGIN DEFINITION
// ===========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.scrollspy')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.scrollspy', (data = new ScrollSpy(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.scrollspy
$.fn.scrollspy = Plugin
$.fn.scrollspy.Constructor = ScrollSpy
// SCROLLSPY NO CONFLICT
// =====================
$.fn.scrollspy.noConflict = function () {
$.fn.scrollspy = old
return this
}
// SCROLLSPY DATA-API
// ==================
$(window).on('load.bs.scrollspy.data-api', function () {
$('[data-spy="scroll"]').each(function () {
var $spy = $(this)
Plugin.call($spy, $spy.data())
})
})
}(jQuery);
/* ========================================================================
* Bootstrap: tab.js v3.2.0
* http://getbootstrap.com/javascript/#tabs
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// TAB CLASS DEFINITION
// ====================
var Tab = function (element) {
this.element = $(element)
}
Tab.VERSION = '3.2.0'
Tab.TRANSITION_DURATION = 150
Tab.prototype.show = function () {
var $this = this.element
var $ul = $this.closest('ul:not(.dropdown-menu)')
var selector = $this.data('target')
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
}
if ($this.parent('li').hasClass('active')) return
var previous = $ul.find('.active:last a')[0]
var e = $.Event('show.bs.tab', {
relatedTarget: previous
})
$this.trigger(e)
if (e.isDefaultPrevented()) return
var $target = $(selector)
this.activate($this.closest('li'), $ul)
this.activate($target, $target.parent(), function () {
$this.trigger({
type: 'shown.bs.tab',
relatedTarget: previous
})
})
}
Tab.prototype.activate = function (element, container, callback) {
var $active = container.find('> .active')
var transition = callback
&& $.support.transition
&& (($active.length && $active.hasClass('fade')) || !!container.find('> .fade').length)
function next() {
$active
.removeClass('active')
.find('> .dropdown-menu > .active')
.removeClass('active')
element.addClass('active')
if (transition) {
element[0].offsetWidth // reflow for transition
element.addClass('in')
} else {
element.removeClass('fade')
}
if (element.parent('.dropdown-menu')) {
element.closest('li.dropdown').addClass('active')
}
callback && callback()
}
$active.length && transition ?
$active
.one('bsTransitionEnd', next)
.emulateTransitionEnd(Tab.TRANSITION_DURATION) :
next()
$active.removeClass('in')
}
// TAB PLUGIN DEFINITION
// =====================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.tab')
if (!data) $this.data('bs.tab', (data = new Tab(this)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.tab
$.fn.tab = Plugin
$.fn.tab.Constructor = Tab
// TAB NO CONFLICT
// ===============
$.fn.tab.noConflict = function () {
$.fn.tab = old
return this
}
// TAB DATA-API
// ============
$(document).on('click.bs.tab.data-api', '[data-toggle="tab"], [data-toggle="pill"]', function (e) {
e.preventDefault()
Plugin.call($(this), 'show')
})
}(jQuery);
/* ========================================================================
* Bootstrap: affix.js v3.2.0
* http://getbootstrap.com/javascript/#affix
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// AFFIX CLASS DEFINITION
// ======================
var Affix = function (element, options) {
this.options = $.extend({}, Affix.DEFAULTS, options)
this.$target = $(this.options.target)
.on('scroll.bs.affix.data-api', $.proxy(this.checkPosition, this))
.on('click.bs.affix.data-api', $.proxy(this.checkPositionWithEventLoop, this))
this.$element = $(element)
this.affixed =
this.unpin =
this.pinnedOffset = null
this.checkPosition()
}
Affix.VERSION = '3.2.0'
Affix.RESET = 'affix affix-top affix-bottom'
Affix.DEFAULTS = {
offset: 0,
target: window
}
Affix.prototype.getState = function (scrollHeight, height, offsetTop, offsetBottom) {
var scrollTop = this.$target.scrollTop()
var position = this.$element.offset()
var targetHeight = this.$target.height()
if (offsetTop != null && this.affixed == 'top') return scrollTop < offsetTop ? 'top' : false
if (this.affixed == 'bottom') {
if (offsetTop != null) return (scrollTop + this.unpin <= position.top) ? false : 'bottom'
return (scrollTop + targetHeight <= scrollHeight - offsetBottom) ? false : 'bottom'
}
var initializing = this.affixed == null
var colliderTop = initializing ? scrollTop : position.top
var colliderHeight = initializing ? targetHeight : height
if (offsetTop != null && colliderTop <= offsetTop) return 'top'
if (offsetBottom != null && (colliderTop + colliderHeight >= scrollHeight - offsetBottom)) return 'bottom'
return false
}
Affix.prototype.getPinnedOffset = function () {
if (this.pinnedOffset) return this.pinnedOffset
this.$element.removeClass(Affix.RESET).addClass('affix')
var scrollTop = this.$target.scrollTop()
var position = this.$element.offset()
return (this.pinnedOffset = position.top - scrollTop)
}
Affix.prototype.checkPositionWithEventLoop = function () {
setTimeout($.proxy(this.checkPosition, this), 1)
}
Affix.prototype.checkPosition = function () {
if (!this.$element.is(':visible')) return
var height = this.$element.height()
var offset = this.options.offset
var offsetTop = offset.top
var offsetBottom = offset.bottom
var scrollHeight = $('body').height()
if (typeof offset != 'object') offsetBottom = offsetTop = offset
if (typeof offsetTop == 'function') offsetTop = offset.top(this.$element)
if (typeof offsetBottom == 'function') offsetBottom = offset.bottom(this.$element)
var affix = this.getState(scrollHeight, height, offsetTop, offsetBottom)
if (this.affixed != affix) {
if (this.unpin != null) this.$element.css('top', '')
var affixType = 'affix' + (affix ? '-' + affix : '')
var e = $.Event(affixType + '.bs.affix')
this.$element.trigger(e)
if (e.isDefaultPrevented()) return
this.affixed = affix
this.unpin = affix == 'bottom' ? this.getPinnedOffset() : null
this.$element
.removeClass(Affix.RESET)
.addClass(affixType)
.trigger(affixType.replace('affix', 'affixed') + '.bs.affix')
}
if (affix == 'bottom') {
this.$element.offset({
top: scrollHeight - height - offsetBottom
})
}
}
// AFFIX PLUGIN DEFINITION
// =======================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.affix')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.affix', (data = new Affix(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.affix
$.fn.affix = Plugin
$.fn.affix.Constructor = Affix
// AFFIX NO CONFLICT
// =================
$.fn.affix.noConflict = function () {
$.fn.affix = old
return this
}
// AFFIX DATA-API
// ==============
$(window).on('load', function () {
$('[data-spy="affix"]').each(function () {
var $spy = $(this)
var data = $spy.data()
data.offset = data.offset || {}
if (data.offsetBottom) data.offset.bottom = data.offsetBottom
if (data.offsetTop) data.offset.top = data.offsetTop
Plugin.call($spy, data)
})
})
}(jQuery);
| Czarnodziej/final-omnislash | web/assetic/bootstrap_js.js | JavaScript | mit | 62,681 |
/*global $:false*/
define([
"manager",
"constants",
"lang",
"generator"
], function(manager, C, L, generator) {
"use strict";
/**
* @name Composite
* @description JS code for the Composite Data Type.
* @see DataType
* @namespace
*/
/* @private */
var MODULE_ID = "data-type-Composite";
var LANG = L.dataTypePlugins.Composite;
var _validate = function(rows) {
var visibleProblemRows = [];
var problemFields = [];
for (var i=0; i<rows.length; i++) {
if ($("#dtOption_" + rows[i]).val() === "") {
var visibleRowNum = generator.getVisibleRowOrderByRowNum(rows[i]);
visibleProblemRows.push(visibleRowNum);
problemFields.push($("#option_" + rows[i]));
}
}
var errors = [];
if (visibleProblemRows.length) {
errors.push({ els: problemFields, error: L.AlphaNumeric_incomplete_fields + " <b>" + visibleProblemRows.join(", ") + "</b>"});
}
return errors;
};
var _loadRow = function(rowNum, data) {
return {
execute: function() {
$("#dtExample_" + rowNum).val(data.example);
$("#dtOption_" + rowNum).val(data.option);
},
isComplete: function() { return $("#dtOption_" + rowNum).length > 0; }
};
};
var _saveRow = function(rowNum) {
return {
"example": $("#dtExample_" + rowNum).val(),
"option": $("#dtOption_" + rowNum).val()
};
};
manager.registerDataType(MODULE_ID, {
validate: _validate,
loadRow: _loadRow,
saveRow: _saveRow
});
});
| vivekmalikymca/generatedata | plugins/dataTypes/Composite/Composite.js | JavaScript | gpl-3.0 | 1,444 |
define(["../SimpleTheme", "./common"], function(SimpleTheme, themes){
themes.Minty = new SimpleTheme({
colors: [
"#80ccbb",
"#539e8b",
"#335f54",
"#8dd1c2",
"#68c5ad"
]
});
return themes.Minty;
});
| avz-cmf/zaboy-middleware | www/js/dojox/charting/themes/Minty.js | JavaScript | gpl-3.0 | 220 |
define(
({
"preview": "Anteprima"
})
);
| avz-cmf/zaboy-middleware | www/js/dojox/editor/plugins/nls/it/Preview.js | JavaScript | gpl-3.0 | 41 |
// Copyright 2016 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
class MyArray extends Array { }
Object.prototype[Symbol.species] = MyArray;
delete Array[Symbol.species];
__v_1 = Math.pow(2, 31);
__v_2 = [];
__v_2[__v_1] = 31;
__v_4 = [];
__v_4[__v_1 - 2] = 33;
assertThrows(() => __v_2.concat(__v_4), RangeError);
| weolar/miniblink49 | v8_7_5/test/mjsunit/regress/regress-crbug-592340.js | JavaScript | apache-2.0 | 418 |
import Vue from 'vue'
describe('Options render', () => {
it('basic usage', () => {
const vm = new Vue({
render (h) {
const children = []
for (let i = 0; i < this.items.length; i++) {
children.push(h('li', { staticClass: 'task' }, [this.items[i].name]))
}
return h('ul', { staticClass: 'tasks' }, children)
},
data: {
items: [{ id: 1, name: 'task1' }, { id: 2, name: 'task2' }]
}
}).$mount()
expect(vm.$el.tagName).toBe('UL')
for (let i = 0; i < vm.$el.children.length; i++) {
const li = vm.$el.children[i]
expect(li.tagName).toBe('LI')
expect(li.textContent).toBe(vm.items[i].name)
}
})
it('allow null data', () => {
const vm = new Vue({
render (h) {
return h('div', null, 'hello' /* string as children*/)
}
}).$mount()
expect(vm.$el.tagName).toBe('DIV')
expect(vm.$el.textContent).toBe('hello')
})
it('should warn non `render` option and non `template` option', () => {
new Vue().$mount()
expect('Failed to mount component: template or render function not defined.').toHaveBeenWarned()
})
})
| new4/Vue4Fun | vue-2.5.16/test/unit/features/options/render.spec.js | JavaScript | mit | 1,164 |
/*
Copyright (c) 2003-2021, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang("easyimage","it",{commands:{fullImage:"Immagine a dimensione intera",sideImage:"Immagine laterale",altText:"Cambia testo alternativo dell'immagine",upload:"Carica immagine"},uploadFailed:"L'immagine non può essere caricata a causa di un errore di rete."}); | stweil/TYPO3.CMS | typo3/sysext/rte_ckeditor/Resources/Public/JavaScript/Contrib/plugins/easyimage/lang/it.js | JavaScript | gpl-2.0 | 450 |
/*! jQuery UI - v1.9.2 - 2014-06-04
* http://jqueryui.com
* Copyright 2014 jQuery Foundation and other contributors; Licensed MIT */
jQuery(function(e){e.datepicker.regional.hu={closeText:"bezár",prevText:"vissza",nextText:"előre",currentText:"ma",monthNames:["Január","Február","Március","Április","Május","Június","Július","Augusztus","Szeptember","Október","November","December"],monthNamesShort:["Jan","Feb","Már","Ápr","Máj","Jún","Júl","Aug","Szep","Okt","Nov","Dec"],dayNames:["Vasárnap","Hétfő","Kedd","Szerda","Csütörtök","Péntek","Szombat"],dayNamesShort:["Vas","Hét","Ked","Sze","Csü","Pén","Szo"],dayNamesMin:["V","H","K","Sze","Cs","P","Szo"],weekHeader:"Hét",dateFormat:"yy.mm.dd.",firstDay:1,isRTL:!1,showMonthAfterYear:!0,yearSuffix:""},e.datepicker.setDefaults(e.datepicker.regional.hu)}); | haakonsk/O2-Framework | var/www/js/jquery-ui/jquery-ui-1.9.2/vader/development-bundle/ui/minified/i18n/jquery.ui.datepicker-hu.min.js | JavaScript | mit | 833 |
var test = require("testling")
, sinon = require("sinon")
, some = require("../../").someSync
, createItem = require("..").createItem
test("some calls each iterator", function (t) {
var item = createItem()
, iterator = sinon.spy(function (v) {
if (v === "b1") {
return v
}
})
var result = some(item, iterator)
t.ok(iterator.calledTwice, "iterator is not called two times")
t.deepEqual(iterator.args[0], ["a1", "a", item],
"iterator called with wrong arguments")
t.deepEqual(iterator.args[1], ["b1", "b", item],
"iterator called with wrong arguments")
t.equal(result, "b1", "result is incorrect")
t.end()
})
test("some returns false if all fail", function (t) {
var item = createItem()
, iterator = sinon.spy(function (v) {
return null
})
var result = some(item, iterator)
t.ok(iterator.calledThrice, "iterator was not called three times")
t.equal(result, null, "result is not false")
t.end()
})
test("some calls iterator with correct this value", function (t) {
var item = createItem()
, iterator = sinon.spy()
, thisValue = {}
some(item, iterator, thisValue)
t.ok(iterator.calledOn(thisValue), "this value is incorrect")
t.end()
}) | xinyzhang9/xinyzhang9.github.io | spirits2/node_modules/iterators/test/sync/some.js | JavaScript | mit | 1,336 |
ej.addCulture( "ug", {
name: "ug",
englishName: "Uyghur",
nativeName: "ئۇيغۇرچە",
language: "ug",
isRTL: true,
numberFormat: {
"NaN": "سان ئەمەس",
negativeInfinity: "مەنپىي چەكسىزلىك",
positiveInfinity: "مۇسبەت چەكسىزلىك",
percent: {
pattern: ["-n%","n%"]
},
currency: {
pattern: ["$-n","$n"],
symbol: "¥"
}
},
calendars: {
standard: {
"/": "-",
firstDay: 1,
days: {
names: ["يەكشەنبە","دۈشەنبە","سەيشەنبە","چارشەنبە","پەيشەنبە","جۈمە","شەنبە"],
namesAbbr: ["يە","دۈ","سە","چا","پە","جۈ","شە"],
namesShort: ["ي","د","س","چ","پ","ج","ش"]
},
months: {
names: ["يانۋار","فېۋرال","مارت","ئاپرېل","ماي","ئىيۇن","ئىيۇل","ئاۋغۇست","سېنتەبىر","ئۆكتەبىر","نويابىر","دېكابىر",""],
namesAbbr: ["1-ئاي","2-ئاي","3-ئاي","4-ئاي","5-ئاي","6-ئاي","7-ئاي","8-ئاي","9-ئاي","10-ئاي","11-ئاي","12-ئاي",""]
},
AM: ["چۈشتىن بۇرۇن","چۈشتىن بۇرۇن","چۈشتىن بۇرۇن"],
PM: ["چۈشتىن كېيىن","چۈشتىن كېيىن","چۈشتىن كېيىن"],
patterns: {
d: "yyyy-M-d",
D: "yyyy-'يىل' d-MMMM",
t: "H:mm",
T: "H:mm:ss",
f: "yyyy-'يىل' d-MMMM H:mm",
F: "yyyy-'يىل' d-MMMM H:mm:ss",
M: "d-MMMM",
Y: "yyyy-'يىلى' MMMM"
}
},
Hijri: {
name: "Hijri",
"/": "-",
firstDay: 1,
days: {
names: ["يەكشەنبە","دۈشەنبە","سەيشەنبە","چارشەنبە","پەيشەنبە","جۈمە","شەنبە"],
namesAbbr: ["يە","دۈ","سە","چا","پە","جۈ","شە"],
namesShort: ["ي","د","س","چ","پ","ج","ش"]
},
months: {
names: ["مۇھەررەم","سەپەر","رەبىئۇلئەۋۋەل","رەبىئۇلئاخىر","جەمادىيەلئەۋۋەل","جەمادىيەلئاخىر","رەجەب","شەئبان","رامىزان","شەۋۋال","زۇلقەئدە","زۇلھەججە",""],
namesAbbr: ["مۇھەررەم","سەپەر","رەبىئۇلئەۋۋەل","رەبىئۇلئاخىر","جەمادىيەلئەۋۋەل","جەمادىيەلئاخىر","رەجەب","شەئبان","رامىزان","شەۋۋال","زۇلقەئدە","زۇلھەججە",""]
},
AM: ["چۈشتىن بۇرۇن","چۈشتىن بۇرۇن","چۈشتىن بۇرۇن"],
PM: ["چۈشتىن كېيىن","چۈشتىن كېيىن","چۈشتىن كېيىن"],
twoDigitYearMax: 1451,
patterns: {
d: "yyyy-M-d",
D: "yyyy-'يىل' d-MMMM",
t: "H:mm",
T: "H:mm:ss",
f: "yyyy-'يىل' d-MMMM H:mm",
F: "yyyy-'يىل' d-MMMM H:mm:ss",
M: "d-MMMM",
Y: "yyyy-'يىلى' MMMM"
},
convert: {
// Adapted to Script from System.Globalization.HijriCalendar
ticks1970: 62135596800000,
// number of days leading up to each month
monthDays: [0, 30, 59, 89, 118, 148, 177, 207, 236, 266, 295, 325, 355],
minDate: -42521673600000,
maxDate: 253402300799999,
// The number of days to add or subtract from the calendar to accommodate the variances
// in the start and the end of Ramadan and to accommodate the date difference between
// countries/regions. May be dynamically adjusted based on user preference, but should
// remain in the range of -2 to 2, inclusive.
hijriAdjustment: 0,
toGregorian: function(hyear, hmonth, hday) {
var daysSinceJan0101 = this.daysToYear(hyear) + this.monthDays[hmonth] + hday - 1 - this.hijriAdjustment;
// 86400000 = ticks per day
var gdate = new Date(daysSinceJan0101 * 86400000 - this.ticks1970);
// adjust for timezone, because we are interested in the gregorian date for the same timezone
// but ticks in javascript is always from GMT, unlike the server were ticks counts from the base
// date in the current timezone.
gdate.setMinutes(gdate.getMinutes() + gdate.getTimezoneOffset());
return gdate;
},
fromGregorian: function(gdate) {
if ((gdate < this.minDate) || (gdate > this.maxDate)) return null;
var ticks = this.ticks1970 + (gdate-0) - gdate.getTimezoneOffset() * 60000,
daysSinceJan0101 = Math.floor(ticks / 86400000) + 1 + this.hijriAdjustment;
// very particular formula determined by someone smart, adapted from the server-side implementation.
// it approximates the hijri year.
var hday, hmonth, hyear = Math.floor(((daysSinceJan0101 - 227013) * 30) / 10631) + 1,
absDays = this.daysToYear(hyear),
daysInYear = this.isLeapYear(hyear) ? 355 : 354;
// hyear is just approximate, it may need adjustment up or down by 1.
if (daysSinceJan0101 < absDays) {
hyear--;
absDays -= daysInYear;
}
else if (daysSinceJan0101 === absDays) {
hyear--;
absDays = this.daysToYear(hyear);
}
else {
if (daysSinceJan0101 > (absDays + daysInYear)) {
absDays += daysInYear;
hyear++;
}
}
// determine month by looking at how many days into the hyear we are
// monthDays contains the number of days up to each month.
hmonth = 0;
var daysIntoYear = daysSinceJan0101 - absDays;
while (hmonth <= 11 && daysIntoYear > this.monthDays[hmonth]) {
hmonth++;
}
hmonth--;
hday = daysIntoYear - this.monthDays[hmonth];
return [hyear, hmonth, hday];
},
daysToYear: function(year) {
// calculates how many days since Jan 1, 0001
var yearsToYear30 = Math.floor((year - 1) / 30) * 30,
yearsInto30 = year - yearsToYear30 - 1,
days = Math.floor((yearsToYear30 * 10631) / 30) + 227013;
while (yearsInto30 > 0) {
days += (this.isLeapYear(yearsInto30) ? 355 : 354);
yearsInto30--;
}
return days;
},
isLeapYear: function(year) {
return ((((year * 11) + 14) % 30) < 11);
}
}
}
}
});
| Asaf-S/jsdelivr | files/syncfusion-ej-global/15.1.41/i18n/ej.culture.ug.js | JavaScript | mit | 7,278 |
/**
* Copyright (c) Microsoft. 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.
*/
'use strict';
var util = require('util');
var validate = require('../validation');
function AccessTokenCloudCredentials(accessToken, subscriptionId) {
validate.validateArgs('AccessTokenCloudCredentials', function (v) {
v.object(accessToken, 'accessToken');
v.function(accessToken.authenticateRequest, 'accessToken.authenticateRequest');
});
this.accessToken = accessToken;
this.subscriptionId = subscriptionId;
}
AccessTokenCloudCredentials.prototype.signRequest = function (webResource, callback) {
this.accessToken.authenticateRequest(function (err, scheme, token) {
if (err) { return callback(err); }
webResource.headers['Authorization'] = util.format('%s %s', scheme, token);
callback(null);
});
};
module.exports = AccessTokenCloudCredentials;
| oaastest/azure-xplat-cli | lib/util/authentication/accessTokenCloudCredentials.js | JavaScript | apache-2.0 | 1,385 |
//// [optionalPropertiesInClasses.ts]
interface ifoo {
x?:number;
y:number;
}
class C1 implements ifoo {
public y:number;
}
class C2 implements ifoo { // ERROR - still need 'y'
public x:number;
}
class C3 implements ifoo {
public x:number;
public y:number;
}
//// [optionalPropertiesInClasses.js]
var C1 = (function () {
function C1() {
}
return C1;
}());
var C2 = (function () {
function C2() {
}
return C2;
}());
var C3 = (function () {
function C3() {
}
return C3;
}());
| AbubakerB/TypeScript | tests/baselines/reference/optionalPropertiesInClasses.js | JavaScript | apache-2.0 | 539 |
import * as module from './export-referrer-checker.py';
if ('DedicatedWorkerGlobalScope' in self &&
self instanceof DedicatedWorkerGlobalScope) {
postMessage(module.referrer);
} else if (
'SharedWorkerGlobalScope' in self &&
self instanceof SharedWorkerGlobalScope) {
onconnect = e => {
e.ports[0].postMessage(module.referrer);
};
}
| scheib/chromium | third_party/blink/web_tests/external/wpt/workers/modules/resources/static-import-same-origin-referrer-checker-worker.js | JavaScript | bsd-3-clause | 355 |
/*! UIkit 3.0.0-beta.6 | http://www.getuikit.com | (c) 2014 - 2016 YOOtheme | MIT License */
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('jquery')) :
typeof define === 'function' && define.amd ? define(['jquery'], factory) :
(global.UIkit = factory(global.jQuery));
}(this, (function ($) { 'use strict';
var $__default = 'default' in $ ? $['default'] : $;
var win = $__default(window);
var doc = $__default(document);
var doc$1 = $__default(document.documentElement);
var langDirection = $__default('html').attr('dir') == 'rtl' ? 'right' : 'left';
function isReady() {
return document.readyState === 'complete' || document.readyState !== 'loading' && !document.documentElement.doScroll;
}
function ready(fn) {
var handle = function () {
off(document, 'DOMContentLoaded', handle);
off(window, 'load', handle);
fn();
};
if (isReady()) {
fn();
} else {
on(document, 'DOMContentLoaded', handle);
on(window, 'load', handle);
}
}
function on(el, type, listener, useCapture) {
$__default(el)[0].addEventListener(type, listener, useCapture)
}
function off(el, type, listener, useCapture) {
$__default(el)[0].removeEventListener(type, listener, useCapture)
}
function transition(element, props, duration, transition) {
if ( duration === void 0 ) duration = 400;
if ( transition === void 0 ) transition = 'linear';
var d = $__default.Deferred();
element = $__default(element);
for (var name in props) {
element.css(name, element.css(name));
}
var timer = setTimeout(function () { return element.trigger(transitionend || 'transitionend'); }, duration);
element
.one(transitionend || 'transitionend', function (e, cancel) {
clearTimeout(timer);
element.removeClass('uk-transition').css('transition', '');
if (!cancel) {
d.resolve();
} else {
d.reject();
}
})
.addClass('uk-transition')
.css('transition', ("all " + duration + "ms " + transition))
.css(props);
return d.promise();
}
var Transition = {
start: transition,
stop: function stop(element) {
$__default(element).trigger(transitionend || 'transitionend');
return this;
},
cancel: function cancel(element) {
$__default(element).trigger(transitionend || 'transitionend', [true]);
return this;
},
inProgress: function inProgress(element) {
return $__default(element).hasClass('uk-transition');
}
};
function animate(element, animation, duration, origin, out) {
if ( duration === void 0 ) duration = 200;
var d = $__default.Deferred(), cls = out ? 'uk-animation-leave' : 'uk-animation-enter';
element = $__default(element);
if (animation.lastIndexOf('uk-animation-', 0) === 0) {
if (origin) {
animation += " uk-animation-" + origin;
}
if (out) {
animation += ' uk-animation-reverse';
}
}
reset();
element
.one(animationend || 'animationend', function () { return d.resolve().then(reset); })
.css('animation-duration', (duration + "ms"))
.addClass(animation)
.addClass(cls);
if (!animationend) {
requestAnimationFrame(function () { return Animation.cancel(element); });
}
return d.promise();
function reset() {
element.css('animation-duration', '').removeClass((cls + " " + animation));
}
}
var Animation = {
in: function in$1(element, animation, duration, origin) {
return animate(element, animation, duration, origin, false);
},
out: function out(element, animation, duration, origin) {
return animate(element, animation, duration, origin, true);
},
inProgress: function inProgress(element) {
return $__default(element).hasClass('uk-animation-enter') || $__default(element).hasClass('uk-animation-leave');
},
cancel: function cancel(element) {
$__default(element).trigger(animationend || 'animationend');
return $__default.Deferred().resolve();
}
};
function isWithin(element, selector) {
element = $__default(element);
return element.is(selector) || !!(isString(selector) ? element.parents(selector).length : $__default.contains(selector instanceof $__default ? selector[0] : selector, element[0]));
}
function attrFilter(element, attr, pattern, replacement) {
element = $__default(element);
return element.attr(attr, function (i, value) { return value ? value.replace(pattern, replacement) : value; });
}
function removeClass(element, cls) {
return attrFilter(element, 'class', new RegExp(("(^|\\s)" + cls + "(?!\\S)"), 'g'), '');
}
function createEvent(e, bubbles, cancelable, data) {
if ( bubbles === void 0 ) bubbles = true;
if ( cancelable === void 0 ) cancelable = false;
if ( data === void 0 ) data = false;
if (isString(e)) {
var event = document.createEvent('Event');
event.initEvent(e, bubbles, cancelable);
e = event;
}
if (data) {
$__default.extend(e, data);
}
return e;
}
function isInView(element, offsetTop, offsetLeft) {
if ( offsetTop === void 0 ) offsetTop = 0;
if ( offsetLeft === void 0 ) offsetLeft = 0;
element = $__default(element);
if (!element.is(':visible')) {
return false;
}
var scrollLeft = win.scrollLeft(), scrollTop = win.scrollTop();
var ref = element.offset();
var top = ref.top;
var left = ref.left;
return top + element.height() >= scrollTop
&& top - offsetTop <= scrollTop + win.height()
&& left + element.width() >= scrollLeft
&& left - offsetLeft <= scrollLeft + win.width();
}
function getIndex(index, elements, current) {
if ( current === void 0 ) current = 0;
elements = $__default(elements);
var length = $__default(elements).length;
index = (isNumber(index)
? index
: index === 'next'
? current + 1
: index === 'previous'
? current - 1
: isString(index)
? parseInt(index, 10)
: elements.index(index)
) % length;
return index < 0 ? index + length : index;
}
var voidElements = {
area: true,
base: true,
br: true,
col: true,
embed: true,
hr: true,
img: true,
input: true,
keygen: true,
link: true,
menuitem: true,
meta: true,
param: true,
source: true,
track: true,
wbr: true
};
function isVoidElement(element) {
element = $__default(element);
return voidElements[element[0].tagName.toLowerCase()];
}
var Dimensions = {
ratio: function ratio(dimensions, prop, value) {
var aProp = prop === 'width' ? 'height' : 'width';
return ( obj = {}, obj[aProp] = Math.round(value * dimensions[aProp] / dimensions[prop]), obj[prop] = value, obj );
var obj;
},
fit: function fit(dimensions, maxDimensions) {
var this$1 = this;
dimensions = $.extend({}, dimensions);
$.each(dimensions, function (prop) { return dimensions = dimensions[prop] > maxDimensions[prop] ? this$1.ratio(dimensions, prop, maxDimensions[prop]) : dimensions; });
return dimensions;
},
cover: function cover(dimensions, maxDimensions) {
var this$1 = this;
dimensions = this.fit(dimensions, maxDimensions);
$.each(dimensions, function (prop) { return dimensions = dimensions[prop] < maxDimensions[prop] ? this$1.ratio(dimensions, prop, maxDimensions[prop]) : dimensions; });
return dimensions;
}
};
function query(selector, context) {
var selectors = getContextSelectors(selector);
return selectors ? selectors.reduce(function (context, selector) { return toJQuery(selector, context); }, context) : toJQuery(selector);
}
var Observer = window.MutationObserver || window.WebKitMutationObserver;
var requestAnimationFrame = window.requestAnimationFrame || function (fn) { return setTimeout(fn, 1000 / 60); };
var cancelAnimationFrame = window.cancelAnimationFrame || window.clearTimeout;
var hasTouch = 'ontouchstart' in window
|| window.DocumentTouch && document instanceof DocumentTouch
|| navigator.msPointerEnabled && navigator.msMaxTouchPoints > 0 // IE 10
|| navigator.pointerEnabled && navigator.maxTouchPoints > 0; // IE >=11
var pointerDown = !hasTouch ? 'mousedown' : window.PointerEvent ? 'pointerdown' : 'touchstart';
var pointerMove = !hasTouch ? 'mousemove' : window.PointerEvent ? 'pointermove' : 'touchmove';
var pointerUp = !hasTouch ? 'mouseup' : window.PointerEvent ? 'pointerup' : 'touchend';
var transitionend = (function () {
var element = document.body || document.documentElement,
names = {
WebkitTransition: 'webkitTransitionEnd',
MozTransition: 'transitionend',
OTransition: 'oTransitionEnd otransitionend',
transition: 'transitionend'
}, name;
for (name in names) {
if (element.style[name] !== undefined) {
return names[name];
}
}
})();
var animationend = (function () {
var element = document.body || document.documentElement,
names = {
WebkitAnimation: 'webkitAnimationEnd',
MozAnimation: 'animationend',
OAnimation: 'oAnimationEnd oanimationend',
animation: 'animationend'
}, name;
for (name in names) {
if (element.style[name] !== undefined) {
return names[name];
}
}
})();
function getStyle(element, property, pseudoElt) {
return (window.getComputedStyle(element, pseudoElt) || {})[property];
}
function getCssVar(name) {
/* usage in css: .var-name:before { content:"xyz" } */
var val, doc = document.documentElement,
element = doc.appendChild(document.createElement('div'));
element.classList.add(("var-" + name));
try {
val = getStyle(element, 'content', ':before').replace(/^["'](.*)["']$/, '$1');
val = JSON.parse(val);
} catch (e) {}
doc.removeChild(element);
return val || undefined;
}
// Copyright (c) 2016 Wilson Page [email protected]
// https://github.com/wilsonpage/fastdom
/**
* Initialize a `FastDom`.
*
* @constructor
*/
function FastDom() {
var self = this;
self.reads = [];
self.writes = [];
self.raf = requestAnimationFrame.bind(window); // test hook
}
FastDom.prototype = {
constructor: FastDom,
/**
* Adds a job to the read batch and
* schedules a new frame if need be.
*
* @param {Function} fn
* @public
*/
measure: function(fn, ctx) {
var task = !ctx ? fn : fn.bind(ctx);
this.reads.push(task);
scheduleFlush(this);
return task;
},
/**
* Adds a job to the
* write batch and schedules
* a new frame if need be.
*
* @param {Function} fn
* @public
*/
mutate: function(fn, ctx) {
var task = !ctx ? fn : fn.bind(ctx);
this.writes.push(task);
scheduleFlush(this);
return task;
},
/**
* Clears a scheduled 'read' or 'write' task.
*
* @param {Object} task
* @return {Boolean} success
* @public
*/
clear: function(task) {
return remove(this.reads, task) || remove(this.writes, task);
},
/**
* Extend this FastDom with some
* custom functionality.
*
* Because fastdom must *always* be a
* singleton, we're actually extending
* the fastdom instance. This means tasks
* scheduled by an extension still enter
* fastdom's global task queue.
*
* The 'super' instance can be accessed
* from `this.fastdom`.
*
* @example
*
* var myFastdom = fastdom.extend({
* initialize: function() {
* // runs on creation
* },
*
* // override a method
* measure: function(fn) {
* // do extra stuff ...
*
* // then call the original
* return this.fastdom.measure(fn);
* },
*
* ...
* });
*
* @param {Object} props properties to mixin
* @return {FastDom}
*/
extend: function(props) {
if (typeof props != 'object') { throw new Error('expected object'); }
var child = Object.create(this);
mixin(child, props);
child.fastdom = this;
// run optional creation hook
if (child.initialize) { child.initialize(); }
return child;
},
// override this with a function
// to prevent Errors in console
// when tasks throw
catch: null
};
/**
* Schedules a new read/write
* batch if one isn't pending.
*
* @private
*/
function scheduleFlush(fastdom) {
if (!fastdom.scheduled) {
fastdom.scheduled = true;
fastdom.raf(flush.bind(null, fastdom));
}
}
/**
* Runs queued `read` and `write` tasks.
*
* Errors are caught and thrown by default.
* If a `.catch` function has been defined
* it is called instead.
*
* @private
*/
function flush(fastdom) {
var reads = fastdom.reads.splice(0, fastdom.reads.length),
writes = fastdom.writes.splice(0, fastdom.writes.length),
error;
try {
runTasks(reads);
runTasks(writes);
} catch (e) { error = e; }
fastdom.scheduled = false;
// If the batch errored we may still have tasks queued
if (fastdom.reads.length || fastdom.writes.length) { scheduleFlush(fastdom); }
if (error) {
if (fastdom.catch) { fastdom.catch(error); }
else { throw error; }
}
}
/**
* We run this inside a try catch
* so that if any jobs error, we
* are able to recover and continue
* to flush the batch until it's empty.
*
* @private
*/
function runTasks(tasks) {
var task; while (task = tasks.shift()) { task(); }
}
/**
* Remove an item from an Array.
*
* @param {Array} array
* @param {*} item
* @return {Boolean}
*/
function remove(array, item) {
var index = array.indexOf(item);
return !!~index && !!array.splice(index, 1);
}
/**
* Mixin own properties of source
* object into the target.
*
* @param {Object} target
* @param {Object} source
*/
function mixin(target, source) {
for (var key in source) {
if (source.hasOwnProperty(key)) { target[key] = source[key]; }
}
}
var fastdom = new FastDom();
function bind(fn, context) {
return function (a) {
var l = arguments.length;
return l ? l > 1 ? fn.apply(context, arguments) : fn.call(context, a) : fn.call(context);
};
}
var hasOwnProperty = Object.prototype.hasOwnProperty;
function hasOwn(obj, key) {
return hasOwnProperty.call(obj, key);
}
function classify(str) {
return str.replace(/(?:^|[-_\/])(\w)/g, function (_, c) { return c ? c.toUpperCase() : ''; });
}
function hyphenate(str) {
return str
.replace(/([a-z\d])([A-Z])/g, '$1-$2')
.toLowerCase()
}
var camelizeRE = /-(\w)/g;
function camelize(str) {
return str.replace(camelizeRE, toUpper)
}
function toUpper(_, c) {
return c ? c.toUpperCase() : ''
}
function isString(value) {
return typeof value === 'string';
}
function isNumber(value) {
return typeof value === 'number';
}
function isUndefined(value) {
return value === undefined;
}
function isContextSelector(selector) {
return isString(selector) && selector.match(/^(!|>|\+|-)/);
}
function getContextSelectors(selector) {
return isContextSelector(selector) && selector.split(/(?=\s(?:!|>|\+|-))/g).map(function (value) { return value.trim(); });
}
var contextSelectors = {'!': 'closest', '+': 'nextAll', '-': 'prevAll'};
function toJQuery(element, context) {
if (element === true) {
return null;
}
try {
if (context && isContextSelector(element) && element[0] !== '>') {
element = $__default(context)[contextSelectors[element[0]]](element.substr(1));
} else {
element = $__default(element, context);
}
} catch (e) {
return null;
}
return element.length ? element : null;
}
function toBoolean(value) {
return typeof value === 'boolean'
? value
: value === 'true' || value == '1' || value === ''
? true
: value === 'false' || value == '0'
? false
: value;
}
function toNumber(value) {
var number = Number(value);
return !isNaN(number) ? number : false;
}
var vars = {};
function toMedia(value) {
if (isString(value) && value[0] == '@') {
var name = "media-" + (value.substr(1));
value = vars[name] || (vars[name] = parseFloat(getCssVar(name)));
}
return value && !isNaN(value) ? ("(min-width: " + value + "px)") : false;
}
function coerce(type, value, context) {
if (type === Boolean) {
return toBoolean(value);
} else if (type === Number) {
return toNumber(value);
} else if (type === 'jQuery') {
return query(value, context);
} else if (type === 'media') {
return toMedia(value);
}
return type ? type(value) : value;
}
var strats = {};
// concat strategy
strats.args =
strats.created =
strats.init =
strats.ready =
strats.connected =
strats.disconnected =
strats.destroy = function (parentVal, childVal) {
return childVal
? parentVal
? parentVal.concat(childVal)
: $.isArray(childVal)
? childVal
: [childVal]
: parentVal;
};
strats.update = function (parentVal, childVal) {
return strats.args(parentVal, $.isFunction(childVal) ? {write: childVal} : childVal);
};
// events strategy
strats.events = function (parentVal, childVal) {
if (!childVal) {
return parentVal;
}
if (!parentVal) {
return childVal;
}
var ret = $.extend({}, parentVal);
for (var key in childVal) {
var parent = ret[key], child = childVal[key];
if (parent && !$.isArray(parent)) {
parent = [parent]
}
ret[key] = parent
? parent.concat(child)
: [child]
}
return ret;
};
// property strategy
strats.props = function (parentVal, childVal) {
if ($.isArray(childVal)) {
var ret = {};
childVal.forEach(function (val) {
ret[val] = String;
});
childVal = ret;
}
return strats.methods(parentVal, childVal);
};
// extend strategy
strats.defaults =
strats.methods = function (parentVal, childVal) {
return childVal
? parentVal
? $.extend(true, {}, parentVal, childVal)
: childVal
: parentVal;
};
// default strategy
var defaultStrat = function (parentVal, childVal) {
return isUndefined(childVal) ? parentVal : childVal;
};
function mergeOptions (parent, child, thisArg) {
var options = {}, key;
if (child.mixins) {
for (var i = 0, l = child.mixins.length; i < l; i++) {
parent = mergeOptions(parent, child.mixins[i], thisArg);
}
}
for (key in parent) {
mergeKey(key);
}
for (key in child) {
if (!hasOwn(parent, key)) {
mergeKey(key);
}
}
function mergeKey (key) {
options[key] = (strats[key] || defaultStrat)(parent[key], child[key], thisArg, key);
}
return options;
}
var dirs = {
x: ['width', 'left', 'right'],
y: ['height', 'top', 'bottom']
};
function position(element, target, attach, targetAttach, offset, targetOffset, flip, boundary) {
element = $__default(element);
target = $__default(target);
boundary = boundary && $__default(boundary);
attach = getPos(attach);
targetAttach = getPos(targetAttach);
var dim = getDimensions(element),
targetDim = getDimensions(target),
position = targetDim;
moveTo(position, attach, dim, -1);
moveTo(position, targetAttach, targetDim, 1);
offset = getOffsets(offset, dim.width, dim.height);
targetOffset = getOffsets(targetOffset, targetDim.width, targetDim.height);
offset['x'] += targetOffset['x'];
offset['y'] += targetOffset['y'];
position.left += offset['x'];
position.top += offset['y'];
boundary = getDimensions(boundary || window);
var flipped = {element: attach, target: targetAttach};
if (flip) {
$__default.each(dirs, function (dir, ref) {
var prop = ref[0];
var align = ref[1];
var alignFlip = ref[2];
if (!(flip === true || ~flip.indexOf(dir))) {
return;
}
var elemOffset = attach[dir] === align ? -dim[prop] : attach[dir] === alignFlip ? dim[prop] : 0,
targetOffset = targetAttach[dir] === align ? targetDim[prop] : targetAttach[dir] === alignFlip ? -targetDim[prop] : 0;
if (position[align] < boundary[align] || position[align] + dim[prop] > boundary[alignFlip]) {
var newVal = position[align] + elemOffset + targetOffset - offset[dir] * 2;
if (newVal >= boundary[align] && newVal + dim[prop] <= boundary[alignFlip]) {
position[align] = newVal;
['element', 'target'].forEach(function (el) {
flipped[el][dir] = !elemOffset
? flipped[el][dir]
: flipped[el][dir] === dirs[dir][1]
? dirs[dir][2]
: dirs[dir][1];
});
}
}
});
}
element.offset({left: position.left, top: position.top});
return flipped;
}
function getDimensions(elem) {
elem = $__default(elem);
var width = Math.round(elem.outerWidth()),
height = Math.round(elem.outerHeight()),
offset = elem[0].getClientRects ? elem.offset() : null,
left = offset ? Math.round(offset.left) : elem.scrollLeft(),
top = offset ? Math.round(offset.top) : elem.scrollTop();
return {width: width, height: height, left: left, top: top, right: left + width, bottom: top + height};
}
function moveTo(position, attach, dim, factor) {
$__default.each(dirs, function (dir, ref) {
var prop = ref[0];
var align = ref[1];
var alignFlip = ref[2];
if (attach[dir] === alignFlip) {
position[align] += dim[prop] * factor;
} else if (attach[dir] === 'center') {
position[align] += dim[prop] * factor / 2;
}
});
}
function getPos(pos) {
var x = /left|center|right/, y = /top|center|bottom/;
pos = (pos || '').split(' ');
if (pos.length === 1) {
pos = x.test(pos[0])
? pos.concat(['center'])
: y.test(pos[0])
? ['center'].concat(pos)
: ['center', 'center'];
}
return {
x: x.test(pos[0]) ? pos[0] : 'center',
y: y.test(pos[1]) ? pos[1] : 'center'
};
}
function getOffsets(offsets, width, height) {
offsets = (offsets || '').split(' ');
return {
x: offsets[0] ? parseFloat(offsets[0]) * (offsets[0][offsets[0].length - 1] === '%' ? width / 100 : 1) : 0,
y: offsets[1] ? parseFloat(offsets[1]) * (offsets[1][offsets[1].length - 1] === '%' ? height / 100 : 1) : 0
};
}
function flipPosition(pos) {
switch (pos) {
case 'left':
return 'right';
case 'right':
return 'left';
case 'top':
return 'bottom';
case 'bottom':
return 'top';
default:
return pos;
}
}
// Copyright (c) 2010-2016 Thomas Fuchs
// http://zeptojs.com/
var touch = {};
var touchTimeout;
var tapTimeout;
var swipeTimeout;
var longTapTimeout;
var longTapDelay = 750;
var gesture;
var clicked;
function swipeDirection(x1, x2, y1, y2) {
return Math.abs(x1 - x2) >= Math.abs(y1 - y2) ? (x1 - x2 > 0 ? 'Left' : 'Right') : (y1 - y2 > 0 ? 'Up' : 'Down');
}
function longTap() {
longTapTimeout = null;
if (touch.last) {
if (touch.el !== undefined) { touch.el.trigger('longTap'); }
touch = {};
}
}
function cancelLongTap() {
if (longTapTimeout) { clearTimeout(longTapTimeout); }
longTapTimeout = null;
}
function cancelAll() {
if (touchTimeout) { clearTimeout(touchTimeout); }
if (tapTimeout) { clearTimeout(tapTimeout); }
if (swipeTimeout) { clearTimeout(swipeTimeout); }
if (longTapTimeout) { clearTimeout(longTapTimeout); }
touchTimeout = tapTimeout = swipeTimeout = longTapTimeout = null;
touch = {};
}
ready(function () {
var now, delta, deltaX = 0, deltaY = 0, firstTouch;
if ('MSGesture' in window) {
gesture = new MSGesture();
gesture.target = document.body;
}
document.addEventListener('click', function () { return clicked = true; }, true);
doc
.on('MSGestureEnd gestureend', function (e) {
var swipeDirectionFromVelocity = e.originalEvent.velocityX > 1 ? 'Right' : e.originalEvent.velocityX < -1 ? 'Left' : e.originalEvent.velocityY > 1 ? 'Down' : e.originalEvent.velocityY < -1 ? 'Up' : null;
if (swipeDirectionFromVelocity && touch.el !== undefined) {
touch.el.trigger('swipe');
touch.el.trigger('swipe' + swipeDirectionFromVelocity);
}
})
.on(pointerDown, function (e) {
firstTouch = e.originalEvent.touches ? e.originalEvent.touches[0] : e;
now = Date.now();
delta = now - (touch.last || now);
touch.el = $__default('tagName' in firstTouch.target ? firstTouch.target : firstTouch.target.parentNode);
if (touchTimeout) { clearTimeout(touchTimeout); }
touch.x1 = firstTouch.pageX;
touch.y1 = firstTouch.pageY;
if (delta > 0 && delta <= 250) { touch.isDoubleTap = true; }
touch.last = now;
longTapTimeout = setTimeout(longTap, longTapDelay);
// adds the current touch contact for IE gesture recognition
if (gesture && ( e.type == 'pointerdown' || e.type == 'touchstart' )) {
gesture.addPointer(e.originalEvent.pointerId);
}
clicked = false;
})
.on(pointerMove, function (e) {
firstTouch = e.originalEvent.touches ? e.originalEvent.touches[0] : e;
cancelLongTap();
touch.x2 = firstTouch.pageX;
touch.y2 = firstTouch.pageY;
deltaX += Math.abs(touch.x1 - touch.x2);
deltaY += Math.abs(touch.y1 - touch.y2);
})
.on(pointerUp, function () {
cancelLongTap();
// swipe
if ((touch.x2 && Math.abs(touch.x1 - touch.x2) > 30) || (touch.y2 && Math.abs(touch.y1 - touch.y2) > 30)) {
swipeTimeout = setTimeout(function () {
if (touch.el !== undefined) {
touch.el.trigger('swipe');
touch.el.trigger('swipe' + (swipeDirection(touch.x1, touch.x2, touch.y1, touch.y2)));
}
touch = {};
}, 0);
// normal tap
} else if ('last' in touch) {
// don't fire tap when delta position changed by more than 30 pixels,
// for instance when moving to a point and back to origin
if (isNaN(deltaX) || (deltaX < 30 && deltaY < 30)) {
// delay by one tick so we can cancel the 'tap' event if 'scroll' fires
// ('tap' fires before 'scroll')
tapTimeout = setTimeout(function () {
// trigger universal 'tap' with the option to cancelTouch()
// (cancelTouch cancels processing of single vs double taps for faster 'tap' response)
var event = $__default.Event('tap');
event.cancelTouch = cancelAll;
if (touch.el !== undefined) {
touch.el.trigger(event);
}
// trigger double tap immediately
if (touch.isDoubleTap) {
if (touch.el !== undefined) { touch.el.trigger('doubleTap'); }
touch = {};
}
// trigger single tap after 300ms of inactivity
else {
touchTimeout = setTimeout(function () {
touchTimeout = null;
if (touch.el !== undefined) {
touch.el.trigger('singleTap');
if (!clicked) {
touch.el.trigger('click');
}
}
touch = {};
}, 300);
}
});
} else {
touch = {};
}
deltaX = deltaY = 0;
}
})
// when the browser window loses focus,
// for example when a modal dialog is shown,
// cancel all ongoing events
.on('touchcancel pointercancel', cancelAll);
// scrolling the window indicates intention of the user
// to scroll, not tap or swipe, so cancel all ongoing events
win.on('scroll', cancelAll);
});
var util = Object.freeze({
win: win,
doc: doc,
docElement: doc$1,
langDirection: langDirection,
isReady: isReady,
ready: ready,
on: on,
off: off,
transition: transition,
Transition: Transition,
animate: animate,
Animation: Animation,
isWithin: isWithin,
attrFilter: attrFilter,
removeClass: removeClass,
createEvent: createEvent,
isInView: isInView,
getIndex: getIndex,
isVoidElement: isVoidElement,
Dimensions: Dimensions,
query: query,
Observer: Observer,
requestAnimationFrame: requestAnimationFrame,
cancelAnimationFrame: cancelAnimationFrame,
hasTouch: hasTouch,
pointerDown: pointerDown,
pointerMove: pointerMove,
pointerUp: pointerUp,
transitionend: transitionend,
animationend: animationend,
getStyle: getStyle,
getCssVar: getCssVar,
fastdom: fastdom,
$: $__default,
bind: bind,
hasOwn: hasOwn,
classify: classify,
hyphenate: hyphenate,
camelize: camelize,
isString: isString,
isNumber: isNumber,
isUndefined: isUndefined,
isContextSelector: isContextSelector,
getContextSelectors: getContextSelectors,
toJQuery: toJQuery,
toBoolean: toBoolean,
toNumber: toNumber,
toMedia: toMedia,
coerce: coerce,
ajax: $.ajax,
each: $.each,
extend: $.extend,
map: $.map,
merge: $.merge,
isArray: $.isArray,
isNumeric: $.isNumeric,
isFunction: $.isFunction,
isPlainObject: $.isPlainObject,
mergeOptions: mergeOptions,
position: position,
getDimensions: getDimensions,
flipPosition: flipPosition
});
function globalAPI (UIkit) {
var DATA = UIkit.data;
UIkit.use = function (plugin) {
if (plugin.installed) {
return;
}
plugin.call(null, this);
plugin.installed = true;
return this;
};
UIkit.mixin = function (mixin, component) {
component = (isString(component) ? UIkit.components[component] : component) || this;
component.options = mergeOptions(component.options, mixin);
};
UIkit.extend = function (options) {
options = options || {};
var Super = this, name = options.name || Super.options.name;
var Sub = createClass(name || 'UIkitComponent');
Sub.prototype = Object.create(Super.prototype);
Sub.prototype.constructor = Sub;
Sub.options = mergeOptions(Super.options, options);
Sub['super'] = Super;
Sub.extend = Super.extend;
return Sub;
};
UIkit.update = function (e, element, parents) {
if ( parents === void 0 ) parents = false;
e = createEvent(e || 'update');
if (!element) {
update(UIkit.instances, e);
return;
}
element = $__default(element)[0];
if (parents) {
do {
update(element[DATA], e);
element = element.parentNode;
} while (element)
} else {
apply(element, function (element) { return update(element[DATA], e); });
}
};
var container;
Object.defineProperty(UIkit, 'container', {
get: function get() {
return container || document.body;
},
set: function set(element) {
container = element;
}
});
}
function createClass(name) {
return new Function(("return function " + (classify(name)) + " (options) { this._init(options); }"))();
}
function apply(node, fn) {
if (node.nodeType !== Node.ELEMENT_NODE) {
return;
}
fn(node);
node = node.firstChild;
while (node) {
apply(node, fn);
node = node.nextSibling;
}
}
function update(data, e) {
if (!data) {
return;
}
for (var name in data) {
if (data[name]._isReady) {
data[name]._callUpdate(e);
}
}
}
function internalAPI (UIkit) {
var uid = 0;
UIkit.prototype.props = {};
UIkit.prototype._init = function (options) {
options = options || {};
options = this.$options = mergeOptions(this.constructor.options, options, this);
UIkit.instances[uid] = this;
this.$el = null;
this.$name = UIkit.prefix + hyphenate(this.$options.name);
this._uid = uid++;
this._initData();
this._initMethods();
this._callHook('created');
this._frames = {reads: {}, writes: {}};
if (options.el) {
this.$mount(options.el);
}
};
UIkit.prototype._initData = function () {
var this$1 = this;
var defaults = $.extend(true, {}, this.$options.defaults),
data = this.$options.data || {},
args = this.$options.args || [],
props = this.$options.props || {};
if (!defaults) {
return;
}
if (args.length && $.isArray(data)) {
data = data.slice(0, args.length).reduce(function (data, value, index) {
data[args[index]] = value;
return data;
}, {});
}
for (var key in defaults) {
this$1[key] = hasOwn(data, key) ? coerce(props[key], data[key], this$1.$options.el) : defaults[key];
}
};
UIkit.prototype._initProps = function () {
var this$1 = this;
var el = this.$el[0],
args = this.$options.args || [],
props = this.$options.props || {},
options = el.getAttribute(this.$name) || el.getAttribute(("data-" + (this.$name))),
key, prop;
if (!props) {
return;
}
for (key in props) {
prop = hyphenate(key);
if (el.hasAttribute(prop)) {
var value = coerce(props[key], el.getAttribute(prop), el);
if (prop === 'target' && (!value || value.lastIndexOf('_', 0) === 0)) {
continue;
}
this$1[key] = value;
}
}
if (!options) {
return;
}
if (options[0] === '{') {
try {
options = JSON.parse(options);
} catch (e) {
console.warn("Invalid JSON.");
options = {};
}
} else if (args.length && !~options.indexOf(':')) {
options = (( obj = {}, obj[args[0]] = options, obj ));
var obj;
} else {
var tmp = {};
options.split(';').forEach(function (option) {
var ref = option.split(/:(.+)/);
var key = ref[0];
var value = ref[1];
if (key && value) {
tmp[key.trim()] = value.trim();
}
});
options = tmp;
}
for (key in options || {}) {
prop = camelize(key);
if (props[prop] !== undefined) {
this$1[prop] = coerce(props[prop], options[key], el);
}
}
};
UIkit.prototype._initMethods = function () {
var this$1 = this;
var methods = this.$options.methods;
if (methods) {
for (var key in methods) {
this$1[key] = bind(methods[key], this$1);
}
}
};
UIkit.prototype._initEvents = function () {
var this$1 = this;
var events = this.$options.events,
register = function (name, fn) { return this$1.$el.on(name, isString(fn) ? this$1[fn] : bind(fn, this$1)); };
if (events) {
for (var key in events) {
if ($.isArray(events[key])) {
events[key].forEach(function (event) { return register(key, event); });
} else {
register(key, events[key]);
}
}
}
};
UIkit.prototype._callReady = function () {
this._isReady = true;
this._callHook('ready');
this._callUpdate();
};
UIkit.prototype._callHook = function (hook) {
var this$1 = this;
var handlers = this.$options[hook];
if (handlers) {
handlers.forEach(function (handler) { return handler.call(this$1); });
}
};
UIkit.prototype._callUpdate = function (e) {
var this$1 = this;
e = createEvent(e || 'update');
var updates = this.$options.update;
if (!updates) {
return;
}
updates.forEach(function (update, i) {
if (e.type !== 'update' && (!update.events || !~update.events.indexOf(e.type))) {
return;
}
if (e.sync) {
if (update.read) {
update.read.call(this$1, e);
}
if (update.write) {
update.write.call(this$1, e);
}
return;
}
if (update.read && !~fastdom.reads.indexOf(this$1._frames.reads[i])) {
this$1._frames.reads[i] = fastdom.measure(function () { return update.read.call(this$1, e); });
}
if (update.write && !~fastdom.writes.indexOf(this$1._frames.writes[i])) {
this$1._frames.writes[i] = fastdom.mutate(function () { return update.write.call(this$1, e); });
}
});
};
}
function instanceAPI (UIkit) {
var DATA = UIkit.data;
UIkit.prototype.$mount = function (el) {
var this$1 = this;
var name = this.$options.name;
if (!el[DATA]) {
el[DATA] = {};
UIkit.elements.push(el);
}
if (el[DATA][name]) {
console.warn(("Component \"" + name + "\" is already mounted on element: "), el);
return;
}
el[DATA][name] = this;
this.$el = $__default(el);
this._initProps();
this._callHook('init');
this._initEvents();
if (document.documentElement.contains(this.$el[0])) {
this._callHook('connected');
}
ready(function () { return this$1._callReady(); });
};
UIkit.prototype.$emit = function (e) {
this._callUpdate(e);
};
UIkit.prototype.$emitSync = function (e) {
this._callUpdate(createEvent(e || 'update', true, false, {sync: true}));
};
UIkit.prototype.$update = function (e, parents) {
UIkit.update(e, this.$el, parents);
};
UIkit.prototype.$updateSync = function (e, parents) {
UIkit.update(createEvent(e || 'update', true, false, {sync: true}), this.$el, parents);
};
UIkit.prototype.$destroy = function (remove) {
if ( remove === void 0 ) remove = false;
this._callHook('destroy');
delete UIkit.instances[this._uid];
var el = this.$options.el;
if (!el || !el[DATA]) {
return;
}
delete el[DATA][this.$options.name];
if (!Object.keys(el[DATA]).length) {
delete el[DATA];
var index = UIkit.elements.indexOf(el);
if (~index) {
UIkit.elements.splice(index, 1);
}
}
if (remove) {
this.$el.remove();
}
};
}
function componentAPI (UIkit) {
var DATA = UIkit.data;
UIkit.components = {};
UIkit.component = function (id, options) {
var name = camelize(id);
if ($.isPlainObject(options)) {
options.name = name;
options = UIkit.extend(options);
} else {
options.options.name = name;
}
UIkit.components[name] = options;
UIkit[name] = function (element, data) {
var i = arguments.length, argsArray = Array(i);
while ( i-- ) argsArray[i] = arguments[i];
if ($.isPlainObject(element)) {
return new UIkit.components[name]({data: element});
}
if (UIkit.components[name].options.functional) {
return new UIkit.components[name]({data: [].concat( argsArray )});
}
var result = [];
data = data || {};
$__default(element).each(function (i, el) { return result.push(el[DATA] && el[DATA][name] || new UIkit.components[name]({el: el, data: data})); });
return result;
};
if (document.body && !options.options.functional) {
UIkit[name](("[uk-" + id + "],[data-uk-" + id + "]"));
}
return UIkit.components[name];
};
UIkit.getComponents = function (element) { return element && element[DATA] || {}; };
UIkit.getComponent = function (element, name) { return UIkit.getComponents(element)[name]; };
UIkit.connect = function (node) {
var name;
if (node[DATA]) {
if (!~UIkit.elements.indexOf(node)) {
UIkit.elements.push(node);
}
for (name in node[DATA]) {
var component = node[DATA][name];
if (!(component._uid in UIkit.instances)) {
UIkit.instances[component._uid] = component;
}
component._callHook('connected');
}
}
for (var i = 0; i < node.attributes.length; i++) {
name = node.attributes[i].name;
if (name.lastIndexOf('uk-', 0) === 0 || name.lastIndexOf('data-uk-', 0) === 0) {
name = camelize(name.replace('data-uk-', '').replace('uk-', ''));
if (UIkit[name]) {
UIkit[name](node);
}
}
}
};
UIkit.disconnect = function (node) {
var index = UIkit.elements.indexOf(node);
if (~index) {
UIkit.elements.splice(index, 1);
}
for (var name in node[DATA]) {
var component = node[DATA][name];
if (component._uid in UIkit.instances) {
delete UIkit.instances[component._uid];
component._callHook('disconnected');
}
}
}
}
var UIkit$1 = function (options) {
this._init(options);
};
UIkit$1.util = util;
UIkit$1.data = '__uikit__';
UIkit$1.prefix = 'uk-';
UIkit$1.options = {};
UIkit$1.instances = {};
UIkit$1.elements = [];
globalAPI(UIkit$1);
internalAPI(UIkit$1);
instanceAPI(UIkit$1);
componentAPI(UIkit$1);
var Class = {
init: function init() {
this.$el.addClass(this.$name);
}
}
var Toggable = {
props: {
cls: Boolean,
animation: Boolean,
duration: Number,
origin: String,
transition: String,
queued: Boolean
},
defaults: {
cls: false,
animation: false,
duration: 200,
origin: false,
transition: 'linear',
queued: false,
initProps: {
overflow: '',
height: '',
paddingTop: '',
paddingBottom: '',
marginTop: '',
marginBottom: ''
},
hideProps: {
overflow: 'hidden',
height: 0,
paddingTop: 0,
paddingBottom: 0,
marginTop: 0,
marginBottom: 0
}
},
ready: function ready() {
if (isString(this.animation)) {
this.animation = this.animation.split(',');
if (this.animation.length === 1) {
this.animation[1] = this.animation[0];
}
this.animation = this.animation.map(function (animation) { return animation.trim(); });
}
this.queued = this.queued && !!this.animation;
},
methods: {
toggleElement: function toggleElement(targets, show, animate) {
var this$1 = this;
var toggles, body = document.body, scroll = body.scrollTop,
all = function (targets) { return $__default.when.apply($__default, targets.toArray().map(function (el) { return this$1._toggleElement(el, show, animate); })); },
delay = function (targets) {
var def = all(targets);
this$1.queued = true;
body.scrollTop = scroll;
return def;
};
targets = $__default(targets);
if (!this.queued || targets.length < 2) {
return all(targets);
}
if (this.queued !== true) {
return delay(targets.not(this.queued));
}
this.queued = targets.not(toggles = targets.filter(function (_, el) { return this$1.isToggled(el); }));
return all(toggles).then(function () { return this$1.queued !== true && delay(this$1.queued); });
},
toggleNow: function toggleNow(targets, show) {
var this$1 = this;
$__default(targets).each(function (_, el) { return this$1._toggleElement(el, show, false); });
},
isToggled: function isToggled(el) {
el = $__default(el);
return this.cls ? el.hasClass(this.cls.split(' ')[0]) : !el.attr('hidden');
},
updateAria: function updateAria(el) {
if (this.cls === false) {
el.attr('aria-hidden', !this.isToggled(el));
}
},
_toggleElement: function _toggleElement(el, show, animate) {
var this$1 = this;
el = $__default(el);
var deferred;
if (Animation.inProgress(el)) {
return Animation.cancel(el).then(function () { return this$1._toggleElement(el, show, animate); });
}
show = typeof show === 'boolean' ? show : !this.isToggled(el);
var event = $__default.Event(("before" + (show ? 'show' : 'hide')));
el.trigger(event, [this]);
if (event.result === false) {
return $__default.Deferred().reject();
}
deferred = (this.animation === true && animate !== false
? this._toggleHeight
: this.animation && animate !== false
? this._toggleAnimation
: this._toggleImmediate
)(el, show);
el.trigger(show ? 'show' : 'hide', [this]);
return deferred.then(function () { return el.trigger(show ? 'shown' : 'hidden', [this$1]); });
},
_toggle: function _toggle(el, toggled) {
el = $__default(el);
if (this.cls) {
el.toggleClass(this.cls, ~this.cls.indexOf(' ') ? undefined : toggled);
} else {
el.attr('hidden', !toggled);
}
el.find('[autofocus]:visible').focus();
this.updateAria(el);
UIkit.update(null, el);
},
_toggleImmediate: function _toggleImmediate(el, show) {
this._toggle(el, show);
return $__default.Deferred().resolve();
},
_toggleHeight: function _toggleHeight(el, show) {
var this$1 = this;
var inProgress = Transition.inProgress(el),
inner = parseFloat(el.children().first().css('margin-top')) + parseFloat(el.children().last().css('margin-bottom')),
height = el[0].offsetHeight ? el.height() + (inProgress ? 0 : inner) : 0,
endHeight;
Transition.cancel(el);
if (!this.isToggled(el)) {
this._toggle(el, true);
}
el.css('height', '');
endHeight = el.height() + (inProgress ? 0 : inner);
el.height(height);
return show
? Transition.start(el, $.extend(this.initProps, {overflow: 'hidden', height: endHeight}), Math.round(this.duration * (1 - height / endHeight)), this.transition)
: Transition.start(el, this.hideProps, Math.round(this.duration * (height / endHeight)), this.transition).then(function () {
this$1._toggle(el, false);
el.css(this$1.initProps);
});
},
_toggleAnimation: function _toggleAnimation(el, show) {
var this$1 = this;
if (show) {
this._toggle(el, true);
return Animation.in(el, this.animation[0], this.duration, this.origin);
}
return Animation.out(el, this.animation[1], this.duration, this.origin).then(function () { return this$1._toggle(el, false); });
}
}
};
var active;
doc.on({
click: function click(e) {
if (active && active.bgClose && !e.isDefaultPrevented() && !isWithin(e.target, active.panel)) {
active.hide();
}
},
keydown: function keydown(e) {
if (e.keyCode === 27 && active && active.escClose) {
e.preventDefault();
active.hide();
}
}
});
var Modal = {
mixins: [Class, Toggable],
props: {
clsPanel: String,
selClose: String,
escClose: Boolean,
bgClose: Boolean,
stack: Boolean
},
defaults: {
cls: 'uk-open',
escClose: true,
bgClose: true,
overlay: true,
stack: false
},
ready: function ready() {
var this$1 = this;
this.page = $__default(document.documentElement);
this.body = $__default(document.body);
this.panel = toJQuery(("." + (this.clsPanel)), this.$el);
this.$el.on('click', this.selClose, function (e) {
e.preventDefault();
this$1.hide();
});
},
events: {
toggle: function toggle(e) {
e.preventDefault();
this.toggleNow(this.$el);
},
beforeshow: function beforeshow(e) {
var this$1 = this;
if (!this.$el.is(e.target)) {
return;
}
if (this.isActive()) {
return false;
}
var prev = active && active !== this && active;
if (!active) {
this.body.css('overflow-y', this.getScrollbarWidth() && this.overlay ? 'scroll' : '');
}
active = this;
if (prev) {
if (this.stack) {
this.prev = prev;
} else {
prev.hide();
}
}
this.panel.one(transitionend, function () {
var event = $__default.Event('show');
event.isShown = true;
this$1.$el.trigger(event, [this$1]);
});
},
show: function show(e) {
if (!this.$el.is(e.target)) {
return;
}
if (!e.isShown) {
e.stopImmediatePropagation();
}
},
beforehide: function beforehide(e) {
var this$1 = this;
if (!this.$el.is(e.target)) {
return;
}
active = active && active !== this && active || this.prev;
var hide = function () {
var event = $__default.Event('hide');
event.isHidden = true;
this$1.$el.trigger(event, [this$1]);
};
if (parseFloat(this.panel.css('transition-duration'))) {
this.panel.one(transitionend, hide);
} else {
hide();
}
},
hide: function hide(e) {
if (!this.$el.is(e.target)) {
return;
}
if (!e.isHidden) {
e.stopImmediatePropagation();
return;
}
if (!active) {
this.body.css('overflow-y', '');
}
}
},
methods: {
isActive: function isActive() {
return this.$el.hasClass(this.cls);
},
toggle: function toggle() {
return this.isActive() ? this.hide() : this.show();
},
show: function show() {
var deferred = $__default.Deferred();
this.$el.one('show', function () { return deferred.resolve(); });
this.toggleNow(this.$el, true);
return deferred.promise();
},
hide: function hide() {
var deferred = $__default.Deferred();
this.$el.one('hide', function () { return deferred.resolve(); });
this.toggleNow(this.$el, false);
return deferred.promise();
},
getActive: function getActive() {
return active;
},
getScrollbarWidth: function getScrollbarWidth() {
var width = this.page[0].style.width;
this.page.css('width', '');
var scrollbarWidth = window.innerWidth - this.page.outerWidth(true);
if (width) {
this.page.width(width);
}
return scrollbarWidth;
}
}
}
var Mouse = {
defaults: {
positions: [],
position: null
},
methods: {
initMouseTracker: function initMouseTracker() {
var this$1 = this;
this.positions = [];
this.position = null;
this.mouseHandler = function (e) {
this$1.positions.push({x: e.pageX, y: e.pageY});
if (this$1.positions.length > 5) {
this$1.positions.shift();
}
};
doc.on('mousemove', this.mouseHandler);
},
cancelMouseTracker: function cancelMouseTracker() {
if (this.mouseHandler) {
doc.off('mousemove', this.mouseHandler);
}
},
movesTo: function movesTo(target) {
var p = getDimensions(target),
points = [
[{x: p.left, y: p.top}, {x: p.right, y: p.bottom}],
[{x: p.right, y: p.top}, {x: p.left, y: p.bottom}]
],
position = this.positions[this.positions.length - 1],
prevPos = this.positions[0] || position;
if (!position) {
return false;
}
if (p.right <= position.x) {
} else if (p.left >= position.x) {
points[0].reverse();
points[1].reverse();
} else if (p.bottom <= position.y) {
points[0].reverse();
} else if (p.top >= position.y) {
points[1].reverse();
}
var delay = position
&& !(this.position && position.x === this.position.x && position.y === this.position.y)
&& points.reduce(function (result, point) {
return result + (slope(prevPos, point[0]) < slope(position, point[0]) && slope(prevPos, point[1]) > slope(position, point[1]));
}, 0);
this.position = delay ? position : null;
return delay;
}
}
}
function slope(a, b) {
return (b.y - a.y) / (b.x - a.x);
}
var Position = {
props: {
pos: String,
offset: null,
flip: Boolean,
clsPos: String
},
defaults: {
pos: 'bottom-left',
flip: true,
offset: false,
clsPos: ''
},
init: function init() {
this.pos = (this.pos + (!~this.pos.indexOf('-') ? '-center' : '')).split('-');
this.dir = this.pos[0];
this.align = this.pos[1];
},
methods: {
positionAt: function positionAt(element, target, boundary) {
removeClass(element, this.clsPos + '-(top|bottom|left|right)(-[a-z]+)?').css({top: '', left: ''});
this.dir = this.pos[0];
this.align = this.pos[1];
var offset = toNumber(this.offset) || 0,
axis = this.getAxis(),
flipped = position(
element,
target,
axis === 'x' ? ((flipPosition(this.dir)) + " " + (this.align)) : ((this.align) + " " + (flipPosition(this.dir))),
axis === 'x' ? ((this.dir) + " " + (this.align)) : ((this.align) + " " + (this.dir)),
axis === 'x' ? ("" + (this.dir === 'left' ? -1 * offset : offset)) : (" " + (this.dir === 'top' ? -1 * offset : offset)),
null,
this.flip,
boundary
);
this.dir = axis === 'x' ? flipped.target.x : flipped.target.y;
this.align = axis === 'x' ? flipped.target.y : flipped.target.x;
element.css('display', '').toggleClass(((this.clsPos) + "-" + (this.dir) + "-" + (this.align)), this.offset === false);
},
getAxis: function getAxis() {
return this.pos[0] === 'top' || this.pos[0] === 'bottom' ? 'y' : 'x';
}
}
}
function mixin$1 (UIkit) {
UIkit.mixin.class = Class;
UIkit.mixin.modal = Modal;
UIkit.mixin.mouse = Mouse;
UIkit.mixin.position = Position;
UIkit.mixin.toggable = Toggable;
}
function Accordion (UIkit) {
UIkit.component('accordion', {
mixins: [Class, Toggable],
props: {
targets: String,
active: null,
collapsible: Boolean,
multiple: Boolean,
toggle: String,
content: String,
transition: String
},
defaults: {
targets: '> *',
active: false,
animation: true,
collapsible: true,
multiple: false,
clsOpen: 'uk-open',
toggle: '.uk-accordion-title',
content: '.uk-accordion-content',
transition: 'ease'
},
ready: function ready() {
var this$1 = this;
this.$el.on('click', ((this.targets) + " " + (this.toggle)), function (e) {
e.preventDefault();
this$1.show(this$1.items.find(this$1.toggle).index(e.currentTarget));
});
},
update: function update() {
var this$1 = this;
var items = $__default(this.targets, this.$el),
changed = !this.items || items.length !== this.items.length || items.toArray().some(function (el, i) { return el !== this$1.items.get(i); });
this.items = items;
if (!changed) {
return;
}
this.items.each(function (i, el) {
el = $__default(el);
this$1.toggleNow(el.find(this$1.content), el.hasClass(this$1.clsOpen));
});
var active = this.active !== false && toJQuery(this.items.eq(Number(this.active))) || !this.collapsible && toJQuery(this.items.eq(0));
if (active && !active.hasClass(this.clsOpen)) {
this.show(active, false);
}
},
methods: {
show: function show(item, animate) {
var this$1 = this;
if (!this.items) {
this.$emitSync();
}
var index = getIndex(item, this.items),
active = this.items.filter(("." + (this.clsOpen)));
item = this.items.eq(index);
item.add(!this.multiple && active).each(function (i, el) {
el = $__default(el);
var content = el.find(this$1.content), isItem = el.is(item), state = isItem && !el.hasClass(this$1.clsOpen);
if (!state && isItem && !this$1.collapsible && active.length < 2) {
return;
}
el.toggleClass(this$1.clsOpen, state);
if (!Transition.inProgress(content.parent())) {
content.wrap('<div>').parent().attr('hidden', state);
}
this$1.toggleNow(content, true);
this$1.toggleElement(content.parent(), state, animate).then(function () {
if (el.hasClass(this$1.clsOpen) === state) {
if (!state) {
this$1.toggleNow(content, false);
}
content.unwrap();
}
});
})
}
}
});
}
function Alert (UIkit) {
UIkit.component('alert', {
mixins: [Class, Toggable],
args: 'animation',
props: {
animation: Boolean,
close: String
},
defaults: {
animation: true,
close: '.uk-alert-close',
duration: 150,
hideProps: {opacity: 0}
},
ready: function ready() {
var this$1 = this;
this.$el.on('click', this.close, function (e) {
e.preventDefault();
this$1.closeAlert();
});
},
methods: {
closeAlert: function closeAlert() {
var this$1 = this;
this.toggleElement(this.$el).then(function () { return this$1.$destroy(true); });
}
}
});
}
function Cover (UIkit) {
UIkit.component('cover', {
props: {
automute: Boolean,
width: Number,
height: Number
},
defaults: {automute: true},
ready: function ready() {
if (!this.$el.is('iframe')) {
return;
}
this.$el.css('pointerEvents', 'none');
if (this.automute) {
var src = this.$el.attr('src');
this.$el
.attr('src', ("" + src + (~src.indexOf('?') ? '&' : '?') + "enablejsapi=1&api=1"))
.on('load', function (ref) {
var target = ref.target;
return target.contentWindow.postMessage('{"event": "command", "func": "mute", "method":"setVolume", "value":0}', '*');
});
}
},
update: {
write: function write() {
if (this.$el[0].offsetHeight === 0) {
return;
}
this.$el
.css({width: '', height: ''})
.css(Dimensions.cover(
{width: this.width || this.$el.width(), height: this.height || this.$el.height()},
{width: this.$el.parent().width(), height: this.$el.parent().height()}
));
},
events: ['load', 'resize', 'orientationchange']
},
events: {
loadedmetadata: function loadedmetadata() {
this.$emit();
}
}
});
}
function Drop (UIkit) {
var active;
doc.on('click', function (e) {
if (active && !isWithin(e.target, active.$el) && (!active.toggle || !isWithin(e.target, active.toggle.$el))) {
active.hide(false);
}
});
UIkit.component('drop', {
mixins: [Mouse, Position, Toggable],
args: 'pos',
props: {
mode: String,
toggle: Boolean,
boundary: 'jQuery',
boundaryAlign: Boolean,
delayShow: Number,
delayHide: Number,
clsDrop: String
},
defaults: {
mode: 'hover',
toggle: '- :first',
boundary: window,
boundaryAlign: false,
delayShow: 0,
delayHide: 800,
clsDrop: false,
hoverIdle: 200,
animation: 'uk-animation-fade',
cls: 'uk-open'
},
init: function init() {
this.clsDrop = this.clsDrop || ("uk-" + (this.$options.name));
this.clsPos = this.clsDrop;
this.$el.addClass(this.clsDrop);
},
ready: function ready() {
var this$1 = this;
this.updateAria(this.$el);
this.$el.on('click', ("." + (this.clsDrop) + "-close"), function (e) {
e.preventDefault();
this$1.hide(false);
});
if (this.toggle) {
this.toggle = query(this.toggle, this.$el);
if (this.toggle) {
this.toggle = UIkit.toggle(this.toggle, {target: this.$el, mode: this.mode})[0];
}
}
},
update: {
write: function write() {
if (!this.$el.hasClass(this.cls)) {
return;
}
removeClass(this.$el, ((this.clsDrop) + "-(stack|boundary)")).css({top: '', left: ''});
this.$el.toggleClass(((this.clsDrop) + "-boundary"), this.boundaryAlign);
this.dir = this.pos[0];
this.align = this.pos[1];
var boundary = getDimensions(this.boundary), alignTo = this.boundaryAlign ? boundary : getDimensions(this.toggle.$el);
if (this.align === 'justify') {
var prop = this.getAxis() === 'y' ? 'width' : 'height';
this.$el.css(prop, alignTo[prop]);
} else if (this.$el.outerWidth() > Math.max(boundary.right - alignTo.left, alignTo.right - boundary.left)) {
this.$el.addClass(this.clsDrop + '-stack');
this.$el.trigger('stack', [this]);
}
this.positionAt(this.$el, this.boundaryAlign ? this.boundary : this.toggle.$el, this.boundary);
},
events: ['resize', 'orientationchange']
},
events: {
toggle: function toggle(e, toggle$1) {
e.preventDefault();
if (this.isToggled(this.$el)) {
this.hide(false);
} else {
this.show(toggle$1, false);
}
},
'toggleShow mouseenter': function toggleShowmouseenter(e, toggle) {
e.preventDefault();
this.show(toggle || this.toggle);
},
'toggleHide mouseleave': function toggleHidemouseleave(e) {
e.preventDefault();
if (this.toggle && this.toggle.mode === 'hover') {
this.hide();
}
}
},
methods: {
show: function show(toggle, delay) {
var this$1 = this;
if ( delay === void 0 ) delay = true;
if (toggle && this.toggle && !this.toggle.$el.is(toggle.$el)) {
this.hide(false);
}
this.toggle = toggle || this.toggle;
this.clearTimers();
if (this.isActive()) {
return;
} else if (delay && active && active !== this && active.isDelaying) {
this.showTimer = setTimeout(this.show, 75);
return;
} else if (active) {
active.hide(false);
}
var show = function () {
if (this$1.toggleElement(this$1.$el, true).state() !== 'rejected') {
this$1.initMouseTracker();
this$1.toggle.$el.addClass(this$1.cls).attr('aria-expanded', 'true');
this$1.clearTimers();
}
};
if (delay && this.delayShow) {
this.showTimer = setTimeout(show, this.delayShow);
} else {
show();
}
active = this;
},
hide: function hide(delay) {
var this$1 = this;
if ( delay === void 0 ) delay = true;
this.clearTimers();
var hide = function () {
if (this$1.toggleElement(this$1.$el, false, false).state() !== 'rejected') {
active = this$1.isActive() ? null : active;
this$1.toggle.$el.removeClass(this$1.cls).attr('aria-expanded', 'false').blur().find('a, button').blur();
this$1.cancelMouseTracker();
this$1.clearTimers();
}
};
this.isDelaying = this.movesTo(this.$el);
if (delay && this.isDelaying) {
this.hideTimer = setTimeout(this.hide, this.hoverIdle);
} else if (delay && this.delayHide) {
this.hideTimer = setTimeout(hide, this.delayHide);
} else {
hide();
}
},
clearTimers: function clearTimers() {
clearTimeout(this.showTimer);
clearTimeout(this.hideTimer);
this.showTimer = null;
this.hideTimer = null;
},
isActive: function isActive() {
return active === this;
}
}
});
UIkit.drop.getActive = function () { return active; };
}
function Dropdown (UIkit) {
UIkit.component('dropdown', UIkit.components.drop.extend({name: 'dropdown'}));
}
function FormCustom (UIkit) {
UIkit.component('form-custom', {
mixins: [Class],
args: 'target',
props: {
target: Boolean
},
defaults: {
target: false
},
ready: function ready() {
this.input = this.$el.find(':input:first');
this.target = this.target && query(this.target === true ? '> :input:first + :first' : this.target, this.$el);
var state = this.input.next();
this.input.on({
focus: function (e) { return state.addClass('uk-focus'); },
blur: function (e) { return state.removeClass('uk-focus'); },
mouseenter: function (e) { return state.addClass('uk-hover'); },
mouseleave: function (e) { return state.removeClass('uk-hover'); }
});
this.input.trigger('change');
},
events: {
change: function change() {
this.target && this.target[this.target.is(':input') ? 'val' : 'text'](
this.input[0].files && this.input[0].files[0]
? this.input[0].files[0].name
: this.input.is('select')
? this.input.find('option:selected').text()
: this.input.val()
);
}
}
});
}
function Gif (UIkit) {
UIkit.component('gif', {
update: {
read: function read() {
var inview = isInView(this.$el);
if (!this.isInView && inview) {
this.$el[0].src = this.$el[0].src;
}
this.isInView = inview;
},
events: ['scroll', 'load', 'resize', 'orientationchange']
}
});
}
function Grid (UIkit) {
UIkit.component('grid', UIkit.components.margin.extend({
mixins: [Class],
name: 'grid',
defaults: {
margin: 'uk-grid-margin',
clsStack: 'uk-grid-stack'
},
update: {
write: function write() {
this.$el.toggleClass(this.clsStack, this.stacks);
},
events: ['load', 'resize', 'orientationchange']
}
}));
}
function HeightMatch (UIkit) {
UIkit.component('height-match', {
args: 'target',
props: {
target: String,
row: Boolean
},
defaults: {
target: '> *',
row: true
},
update: {
write: function write() {
var this$1 = this;
var elements = toJQuery(this.target, this.$el).css('min-height', '');
if (!this.row) {
this.match(elements);
return this;
}
var lastOffset = false, group = [];
elements.each(function (i, el) {
el = $__default(el);
var offset = el.offset().top;
if (offset != lastOffset && group.length) {
this$1.match($__default(group));
group = [];
offset = el.offset().top;
}
group.push(el);
lastOffset = offset;
});
if (group.length) {
this.match($__default(group));
}
},
events: ['resize', 'orientationchange']
},
methods: {
match: function match(elements) {
if (elements.length < 2) {
return;
}
var max = 0;
elements
.each(function (i, el) {
el = $__default(el);
var height;
if (el.css('display') === 'none') {
var style = el.attr('style');
el.attr('style', (style + ";display:block !important;"));
height = el.outerHeight();
el.attr('style', style || '');
} else {
height = el.outerHeight();
}
max = Math.max(max, height);
})
.each(function (i, el) {
el = $__default(el);
el.css('min-height', ((max - (el.outerHeight() - parseFloat(el.css('height')))) + "px"));
});
}
}
});
}
function HeightViewport (UIkit) {
UIkit.component('height-viewport', {
props: {
expand: Boolean,
offsetTop: Boolean,
offsetBottom: Boolean
},
defaults: {
expand: false,
offsetTop: false,
offsetBottom: false
},
init: function init() {
this.$emit();
},
update: {
write: function write() {
var viewport = window.innerHeight, height, offset = 0;
if (this.expand) {
this.$el.css({height: '', minHeight: ''});
var diff = viewport - document.documentElement.offsetHeight;
if (diff > 0) {
this.$el.css('min-height', height = this.$el.outerHeight() + diff)
}
} else {
var top = this.$el[0].offsetTop;
if (top < viewport) {
if (this.offsetTop) {
offset += top;
}
if (this.offsetBottom) {
offset += this.$el.next().outerHeight() || 0;
}
}
this.$el.css('min-height', height = offset ? ("calc(100vh - " + offset + "px)") : '100vh');
}
// IE 10-11 fix (min-height on a flex container won't apply to its flex items)
this.$el.css('height', '');
if (height && viewport - offset >= this.$el.outerHeight()) {
this.$el.css('height', height);
}
},
events: ['load', 'resize', 'orientationchange']
}
});
}
function Hover (UIkit) {
ready(function () {
if (!hasTouch) {
return;
}
var cls = 'uk-hover';
doc$1.on('tap', function (ref) {
var target = ref.target;
return $__default(("." + cls)).filter(function (_, el) { return !isWithin(target, el); }).removeClass(cls);
});
Object.defineProperty(UIkit, 'hoverSelector', {
set: function set(selector) {
doc$1.on('tap', selector, function () {
this.classList.add(cls);
});
}
});
UIkit.hoverSelector = '.uk-animation-toggle, .uk-transition-toggle, [uk-hover]';
});
}
function Icon (UIkit) {
UIkit.component('icon', UIkit.components.svg.extend({
mixins: [Class],
name: 'icon',
args: 'icon',
props: ['icon'],
defaults: {exclude: ['id', 'style', 'class', 'src']},
init: function init() {
this.$el.addClass('uk-icon');
}
}));
[
'close',
'navbar-toggle-icon',
'overlay-icon',
'pagination-previous',
'pagination-next',
'slidenav',
'search-icon',
'totop'
].forEach(function (name) { return UIkit.component(name, UIkit.components.icon.extend({name: name})); });
}
function Margin (UIkit) {
UIkit.component('margin', {
props: {
margin: String,
firstColumn: Boolean
},
defaults: {
margin: 'uk-margin-small-top',
firstColumn: 'uk-first-column'
},
connected: function connected() {
this.$emit();
},
update: {
read: function read() {
var this$1 = this;
if (this.$el[0].offsetHeight === 0) {
this.hidden = true;
return;
}
this.hidden = false;
this.stacks = true;
var columns = this.$el.children().filter(function (_, el) { return el.offsetHeight > 0; });
this.rows = [[columns.get(0)]];
columns.slice(1).each(function (_, el) {
var top = Math.ceil(el.offsetTop), bottom = top + el.offsetHeight;
for (var index = this$1.rows.length - 1; index >= 0; index--) {
var row = this$1.rows[index], rowTop = Math.ceil(row[0].offsetTop);
if (top >= rowTop + row[0].offsetHeight) {
this$1.rows.push([el]);
break;
}
if (bottom > rowTop) {
this$1.stacks = false;
if (el.offsetLeft < row[0].offsetLeft) {
row.unshift(el);
break;
}
row.push(el);
break;
}
if (index === 0) {
this$1.rows.splice(index, 0, [el]);
break;
}
}
});
},
write: function write() {
var this$1 = this;
if (this.hidden) {
return;
}
this.rows.forEach(function (row, i) { return row.forEach(function (el, j) { return $__default(el)
.toggleClass(this$1.margin, i !== 0)
.toggleClass(this$1.firstColumn, j === 0); }
); }
)
},
events: ['load', 'resize', 'orientationchange']
}
});
}
function Modal$1 (UIkit) {
UIkit.component('modal', {
mixins: [Modal],
props: {
center: Boolean,
container: Boolean
},
defaults: {
center: false,
clsPage: 'uk-modal-page',
clsPanel: 'uk-modal-dialog',
selClose: '.uk-modal-close, .uk-modal-close-default, .uk-modal-close-outside, .uk-modal-close-full',
container: true
},
ready: function ready() {
this.container = this.container === true && UIkit.container || this.container && toJQuery(this.container);
if (this.container && !this.$el.parent().is(this.container)) {
this.$el.appendTo(this.container);
}
},
update: {
write: function write() {
if (this.$el.css('display') === 'block' && this.center) {
this.$el
.removeClass('uk-flex uk-flex-center uk-flex-middle')
.css('display', 'block')
.toggleClass('uk-flex uk-flex-center uk-flex-middle', window.innerHeight > this.panel.outerHeight(true))
.css('display', this.$el.hasClass('uk-flex') ? '' : 'block');
}
},
events: ['resize', 'orientationchange']
},
events: {
beforeshow: function beforeshow(e) {
if (!this.$el.is(e.target)) {
return;
}
this.page.addClass(this.clsPage);
this.$el.css('display', 'block');
this.$el.height();
},
hide: function hide(e) {
if (!this.$el.is(e.target)) {
return;
}
if (!this.getActive()) {
this.page.removeClass(this.clsPage);
}
this.$el.css('display', '').removeClass('uk-flex uk-flex-center uk-flex-middle');
}
}
});
UIkit.component('overflow-auto', {
mixins: [Class],
ready: function ready() {
this.panel = query('!.uk-modal-dialog', this.$el);
this.$el.css('min-height', 150);
},
update: {
write: function write() {
var current = this.$el.css('max-height');
this.$el.css('max-height', 150).css('max-height', Math.max(150, 150 - (this.panel.outerHeight(true) - window.innerHeight)));
if (current !== this.$el.css('max-height')) {
this.$el.trigger('resize');
}
},
events: ['load', 'resize', 'orientationchange']
}
});
UIkit.modal.dialog = function (content, options) {
var dialog = UIkit.modal($__default(
("<div class=\"uk-modal\">\n <div class=\"uk-modal-dialog\">" + content + "</div>\n </div>")
), options)[0];
dialog.show();
dialog.$el.on('hide', function () { return dialog.$destroy(true); });
return dialog;
};
UIkit.modal.alert = function (message, options) {
options = $.extend({bgClose: false, escClose: false, labels: UIkit.modal.labels}, options);
var deferred = $__default.Deferred();
UIkit.modal.dialog(("\n <div class=\"uk-modal-body\">" + (isString(message) ? message : $__default(message).html()) + "</div>\n <div class=\"uk-modal-footer uk-text-right\">\n <button class=\"uk-button uk-button-primary uk-modal-close\" autofocus>" + (options.labels.ok) + "</button>\n </div>\n "), options).$el.on('hide', function () { return deferred.resolve(); });
return deferred.promise();
};
UIkit.modal.confirm = function (message, options) {
options = $.extend({bgClose: false, escClose: false, labels: UIkit.modal.labels}, options);
var deferred = $__default.Deferred();
UIkit.modal.dialog(("\n <div class=\"uk-modal-body\">" + (isString(message) ? message : $__default(message).html()) + "</div>\n <div class=\"uk-modal-footer uk-text-right\">\n <button class=\"uk-button uk-button-default uk-modal-close\">" + (options.labels.cancel) + "</button>\n <button class=\"uk-button uk-button-primary uk-modal-close\" autofocus>" + (options.labels.ok) + "</button>\n </div>\n "), options).$el.on('click', '.uk-modal-footer button', function (e) { return deferred[$__default(e.target).index() === 0 ? 'reject' : 'resolve'](); });
return deferred.promise();
};
UIkit.modal.prompt = function (message, value, options) {
options = $.extend({bgClose: false, escClose: false, labels: UIkit.modal.labels}, options);
var deferred = $__default.Deferred(),
prompt = UIkit.modal.dialog(("\n <form class=\"uk-form-stacked\">\n <div class=\"uk-modal-body\">\n <label>" + (isString(message) ? message : $__default(message).html()) + "</label>\n <input class=\"uk-input\" type=\"text\" autofocus>\n </div>\n <div class=\"uk-modal-footer uk-text-right\">\n <button class=\"uk-button uk-button-default uk-modal-close\" type=\"button\">" + (options.labels.cancel) + "</button>\n <button class=\"uk-button uk-button-primary\" type=\"submit\">" + (options.labels.ok) + "</button>\n </div>\n </form>\n "), options),
input = prompt.$el.find('input').val(value);
prompt.$el
.on('submit', 'form', function (e) {
e.preventDefault();
deferred.resolve(input.val());
prompt.hide()
})
.on('hide', function () {
if (deferred.state() === 'pending') {
deferred.resolve(null);
}
});
return deferred.promise();
};
UIkit.modal.labels = {
ok: 'Ok',
cancel: 'Cancel'
}
}
function Nav (UIkit) {
UIkit.component('nav', UIkit.components.accordion.extend({
name: 'nav',
defaults: {
targets: '> .uk-parent',
toggle: '> a',
content: 'ul:first'
}
}));
}
function Navbar (UIkit) {
UIkit.component('navbar', {
mixins: [Class],
props: {
dropdown: String,
mode: String,
align: String,
offset: Number,
boundary: Boolean,
boundaryAlign: Boolean,
clsDrop: String,
delayShow: Number,
delayHide: Number,
dropbar: Boolean,
dropbarMode: String,
dropbarAnchor: 'jQuery',
duration: Number
},
defaults: {
dropdown: '.uk-navbar-nav > li',
mode: 'hover',
align: 'left',
offset: false,
boundary: true,
boundaryAlign: false,
clsDrop: 'uk-navbar-dropdown',
delayShow: 0,
delayHide: 800,
flip: 'x',
dropbar: false,
dropbarMode: 'slide',
dropbarAnchor: false,
duration: 200,
},
init: function init() {
this.boundary = (this.boundary === true || this.boundaryAlign) ? this.$el : this.boundary;
this.pos = "bottom-" + (this.align);
},
ready: function ready() {
var this$1 = this;
this.$el.on('mouseenter', this.dropdown, function (ref) {
var target = ref.target;
var active = this$1.getActive();
if (active && !isWithin(target, active.toggle.$el) && !active.isDelaying) {
active.hide(false);
}
});
if (!this.dropbar) {
return;
}
this.dropbar = query(this.dropbar, this.$el) || $__default('<div class="uk-navbar-dropbar"></div>').insertAfter(this.dropbarAnchor || this.$el);
this.dropbar.on({
mouseleave: function () {
var active = this$1.getActive();
if (active && !this$1.dropbar.is(':hover')) {
active.hide();
}
},
beforeshow: function (e, ref) {
var $el = ref.$el;
$el.addClass(((this$1.clsDrop) + "-dropbar"));
this$1.transitionTo($el.outerHeight(true));
},
beforehide: function (e, ref) {
var $el = ref.$el;
var active = this$1.getActive();
if (this$1.dropbar.is(':hover') && active && active.$el.is($el)) {
return false;
}
},
hide: function (e, ref) {
var $el = ref.$el;
var active = this$1.getActive();
if (!active || active && active.$el.is($el)) {
this$1.transitionTo(0);
}
}
});
if (this.dropbarMode === 'slide') {
this.dropbar.addClass('uk-navbar-dropbar-slide');
}
},
update: function update() {
var this$1 = this;
$__default(this.dropdown, this.$el).each(function (i, el) {
var drop = toJQuery(("." + (this$1.clsDrop)), el);
if (drop && !UIkit.getComponent(drop, 'drop') && !UIkit.getComponent(drop, 'dropdown')) {
UIkit.drop(drop, $.extend({}, this$1));
}
});
},
events: {
beforeshow: function beforeshow(e, ref) {
var $el = ref.$el;
var dir = ref.dir;
if (this.dropbar && dir === 'bottom' && !isWithin($el, this.dropbar)) {
$el.appendTo(this.dropbar);
this.dropbar.trigger('beforeshow', [{$el: $el}]);
}
}
},
methods: {
getActive: function getActive() {
var active = UIkit.drop.getActive();
return active && active.mode !== 'click' && isWithin(active.toggle.$el, this.$el) && active;
},
transitionTo: function transitionTo(height) {
this.dropbar.height(this.dropbar[0].offsetHeight ? this.dropbar.height() : 0);
return Transition.cancel(this.dropbar).start(this.dropbar, {height: height}, this.duration);
}
}
});
}
function Offcanvas (UIkit) {
UIkit.component('offcanvas', {
mixins: [Modal],
args: 'mode',
props: {
mode: String,
flip: Boolean,
overlay: Boolean
},
defaults: {
mode: 'slide',
flip: false,
overlay: false,
clsPage: 'uk-offcanvas-page',
clsPanel: 'uk-offcanvas-bar',
clsFlip: 'uk-offcanvas-flip',
clsPageAnimation: 'uk-offcanvas-page-animation',
clsSidebarAnimation: 'uk-offcanvas-bar-animation',
clsMode: 'uk-offcanvas',
clsOverlay: 'uk-offcanvas-overlay',
clsPageOverlay: 'uk-offcanvas-page-overlay',
selClose: '.uk-offcanvas-close'
},
init: function init() {
this.clsFlip = this.flip ? this.clsFlip : '';
this.clsOverlay = this.overlay ? this.clsOverlay : '';
this.clsPageOverlay = this.overlay ? this.clsPageOverlay : '';
this.clsMode = (this.clsMode) + "-" + (this.mode);
if (this.mode === 'none' || this.mode === 'reveal') {
this.clsSidebarAnimation = '';
}
if (this.mode !== 'push' && this.mode !== 'reveal') {
this.clsPageAnimation = '';
}
},
update: {
write: function write() {
if (this.isActive()) {
this.page.width(window.innerWidth - this.getScrollbarWidth());
}
},
events: ['resize', 'orientationchange']
},
events: {
beforeshow: function beforeshow(e) {
if (!this.$el.is(e.target)) {
return;
}
this.page.addClass(((this.clsPage) + " " + (this.clsFlip) + " " + (this.clsPageAnimation) + " " + (this.clsPageOverlay)));
this.panel.addClass(((this.clsSidebarAnimation) + " " + (this.clsMode)));
this.$el.addClass(this.clsOverlay).css('display', 'block').height();
},
beforehide: function beforehide(e) {
if (!this.$el.is(e.target)) {
return;
}
this.page.removeClass(this.clsPageAnimation).css('margin-left', '');
if (this.mode === 'none' || this.getActive() && this.getActive() !== this) {
this.panel.trigger(transitionend);
}
},
hide: function hide(e) {
if (!this.$el.is(e.target)) {
return;
}
this.page.removeClass(((this.clsPage) + " " + (this.clsFlip) + " " + (this.clsPageOverlay))).width('');
this.panel.removeClass(((this.clsSidebarAnimation) + " " + (this.clsMode)));
this.$el.removeClass(this.clsOverlay).css('display', '');
}
}
});
}
function Responsive (UIkit) {
UIkit.component('responsive', {
props: ['width', 'height'],
update: {
write: function write() {
if (this.$el.is(':visible') && this.width && this.height) {
this.$el.height(Dimensions.fit(
{height: this.height, width: this.width},
{width: this.$el.parent().width(), height: this.height || this.$el.height()}
)['height']);
}
},
events: ['load', 'resize', 'orientationchange']
}
});
}
function Scroll (UIkit) {
UIkit.component('scroll', {
props: {
duration: Number,
transition: String,
offset: Number
},
defaults: {
duration: 1000,
transition: 'easeOutExpo',
offset: 0
},
methods: {
scrollToElement: function scrollToElement(el) {
var this$1 = this;
el = $__default(el);
// get / set parameters
var target = el.offset().top - this.offset,
docHeight = doc.height(),
winHeight = window.innerHeight;
if (target + winHeight > docHeight) {
target = docHeight - winHeight;
}
// animate to target, fire callback when done
$__default('html,body')
.stop()
.animate({scrollTop: parseInt(target, 10) || 1}, this.duration, this.transition)
.promise()
.then(function () { return this$1.$el.trigger('scrolled', [this$1]); });
}
},
events: {
click: function click(e) {
if (e.isDefaultPrevented()) {
return;
}
e.preventDefault();
this.scrollToElement($__default(this.$el[0].hash).length ? this.$el[0].hash : 'body');
}
}
});
if (!$__default.easing.easeOutExpo) {
$__default.easing.easeOutExpo = function (x, t, b, c, d) {
return (t == d) ? b + c : c * (-Math.pow(2, -10 * t / d) + 1) + b;
};
}
}
function Scrollspy (UIkit) {
UIkit.component('scrollspy', {
args: 'cls',
props: {
cls: String,
target: String,
hidden: Boolean,
offsetTop: Number,
offsetLeft: Number,
repeat: Boolean,
delay: Number
},
defaults: {
cls: 'uk-scrollspy-inview',
target: false,
hidden: true,
offsetTop: 0,
offsetLeft: 0,
repeat: false,
delay: 0,
inViewClass: 'uk-scrollspy-inview'
},
init: function init() {
this.$emit();
},
update: [
{
read: function read() {
this.elements = this.target && toJQuery(this.target, this.$el) || this.$el;
},
write: function write() {
if (this.hidden) {
this.elements.filter((":not(." + (this.inViewClass) + ")")).css('visibility', 'hidden');
}
}
},
{
read: function read() {
var this$1 = this;
this.elements.each(function (i, el) {
if (!el._scrollspy) {
el._scrollspy = {toggles: ($__default(el).attr('uk-scrollspy-class') || this$1.cls).split(',')};
}
el._scrollspy.show = isInView(el, this$1.offsetTop, this$1.offsetLeft);
});
},
write: function write() {
var this$1 = this;
var index = this.elements.length === 1 ? 1 : 0;
this.elements.each(function (i, el) {
var $el = $__default(el);
var data = el._scrollspy;
if (data.show) {
if (!data.inview && !data.timer) {
data.timer = setTimeout(function () {
$el.css('visibility', '')
.addClass(this$1.inViewClass)
.toggleClass(data.toggles[0])
.trigger('inview');
data.inview = true;
delete data.timer;
}, this$1.delay * index++);
}
} else {
if (data.inview && this$1.repeat) {
if (data.timer) {
clearTimeout(data.timer);
delete data.timer;
}
$el.removeClass(this$1.inViewClass)
.toggleClass(data.toggles[0])
.css('visibility', this$1.hidden ? 'hidden' : '')
.trigger('outview');
data.inview = false;
}
}
data.toggles.reverse();
});
},
events: ['scroll', 'load', 'resize', 'orientationchange']
}
]
});
}
function ScrollspyNav (UIkit) {
UIkit.component('scrollspy-nav', {
props: {
cls: String,
closest: String,
scroll: Boolean,
overflow: Boolean,
offset: Number
},
defaults: {
cls: 'uk-active',
closest: false,
scroll: false,
overflow: true,
offset: 0
},
update: [
{
read: function read() {
this.links = this.$el.find('a[href^="#"]').filter(function (i, el) { return el.hash; });
this.elements = (this.closest ? this.links.closest(this.closest) : this.links);
this.targets = $__default($__default.map(this.links, function (el) { return el.hash; }).join(','));
if (this.scroll) {
UIkit.scroll(this.links, {offset: this.offset || 0});
}
}
},
{
read: function read() {
var this$1 = this;
var scroll = win.scrollTop() + this.offset, max = document.documentElement.scrollHeight - window.innerHeight + this.offset;
this.active = false;
this.targets.each(function (i, el) {
el = $__default(el);
var offset = el.offset(), last = i + 1 === this$1.targets.length;
if (!this$1.overflow && (i === 0 && offset.top > scroll || last && offset.top + el.outerHeight() < scroll)) {
return false;
}
if (!last && this$1.targets.eq(i + 1).offset().top <= scroll) {
return;
}
if (scroll >= max) {
for (var j = this$1.targets.length; j > i; j--) {
if (isInView(this$1.targets.eq(j))) {
el = this$1.targets.eq(j);
break;
}
}
}
return !(this$1.active = toJQuery(this$1.links.filter(("[href=\"#" + (el.attr('id')) + "\"]"))));
});
},
write: function write() {
this.links.blur();
this.elements.removeClass(this.cls);
if (this.active) {
this.$el.trigger('active', [
this.active,
(this.closest ? this.active.closest(this.closest) : this.active).addClass(this.cls)
]);
}
},
events: ['scroll', 'load', 'resize', 'orientationchange']
}
]
});
}
function Spinner (UIkit) {
UIkit.component('spinner', UIkit.components.icon.extend({
name: 'spinner',
init: function init() {
this.height = this.width = this.$el.width();
},
ready: function ready() {
var this$1 = this;
this.svg.then(function (svg) {
var circle = svg.find('circle'),
diameter = Math.floor(this$1.width / 2);
svg[0].setAttribute('viewBox', ("0 0 " + (this$1.width) + " " + (this$1.width)));
circle.attr({cx: diameter, cy: diameter, r: diameter - parseInt(circle.css('stroke-width'), 10)});
});
}
}));
}
function Sticky (UIkit) {
UIkit.component('sticky', {
props: {
top: null,
bottom: Boolean,
offset: Number,
animation: String,
clsActive: String,
clsInactive: String,
widthElement: 'jQuery',
showOnUp: Boolean,
media: 'media',
target: Number
},
defaults: {
top: 0,
bottom: false,
offset: 0,
animation: '',
clsActive: 'uk-active',
clsInactive: '',
widthElement: false,
showOnUp: false,
media: false,
target: false
},
connected: function connected() {
this.placeholder = $__default('<div class="uk-sticky-placeholder"></div>').insertAfter(this.$el).attr('hidden', true);
this._widthElement = this.widthElement || this.placeholder;
},
ready: function ready() {
var this$1 = this;
this.topProp = this.top;
this.bottomProp = this.bottom;
if (this.target && location.hash && win.scrollTop() > 0) {
var target = query(location.hash);
if (target) {
requestAnimationFrame(function () {
var top = target.offset().top,
elTop = this$1.$el.offset().top,
elHeight = this$1.$el.outerHeight(),
elBottom = elTop + elHeight;
if (elBottom >= top && elTop <= top + target.outerHeight()) {
window.scrollTo(0, top - elHeight - this$1.target - this$1.offset);
}
});
}
}
},
update: [
{
write: function write() {
var this$1 = this;
var outerHeight = this.$el.outerHeight(), isActive = this.isActive(), el;
this.placeholder
.css('height', this.$el.css('position') !== 'absolute' ? outerHeight : '')
.css(this.$el.css(['marginTop', 'marginBottom', 'marginLeft', 'marginRight']));
this.topOffset = (isActive ? this.placeholder.offset() : this.$el.offset()).top;
this.bottomOffset = this.topOffset + outerHeight;
['top', 'bottom'].forEach(function (prop) {
this$1[prop] = this$1[(prop + "Prop")];
if (!this$1[prop]) {
return;
}
if ($.isNumeric(this$1[prop])) {
this$1[prop] = this$1[(prop + "Offset")] + parseFloat(this$1[prop]);
} else {
if (isString(this$1[prop]) && this$1[prop].match(/^-?\d+vh$/)) {
this$1[prop] = window.innerHeight * parseFloat(this$1[prop]) / 100;
} else {
el = this$1[prop] === true ? this$1.$el.parent() : query(this$1[prop], this$1.$el);
if (el) {
this$1[prop] = el.offset().top + el.outerHeight();
}
}
}
});
this.top = Math.max(parseFloat(this.top), this.topOffset) - this.offset;
this.bottom = this.bottom && this.bottom - outerHeight;
this.inactive = this.media && !window.matchMedia(this.media).matches;
if (isActive) {
this.update();
}
},
events: ['load', 'resize', 'orientationchange']
},
{
write: function write(ref) {
var this$1 = this;
if ( ref === void 0 ) ref = {};
var dir = ref.dir;
var isActive = this.isActive(), scroll = win.scrollTop();
if (scroll < 0 || !this.$el.is(':visible') || this.disabled) {
return;
}
if (this.inactive
|| scroll < this.top
|| this.showOnUp && (dir !== 'up' || dir === 'up' && !isActive && scroll <= this.bottomOffset)
) {
if (!isActive) {
return;
}
isActive = false;
if (this.animation && this.bottomOffset < this.$el.offset().top) {
Animation.cancel(this.$el).then(function () { return Animation.out(this$1.$el, this$1.animation).then(function () { return this$1.hide(); }); });
} else {
this.hide();
}
} else if (isActive) {
this.update();
} else if (this.animation) {
Animation.cancel(this.$el).then(function () {
this$1.show();
Animation.in(this$1.$el, this$1.animation);
});
} else {
this.show();
}
},
events: ['scroll']
} ],
methods: {
show: function show() {
this.update();
this.$el
.addClass(this.clsActive)
.removeClass(this.clsInactive)
.trigger('active');
},
hide: function hide() {
this.$el
.addClass(this.clsInactive)
.removeClass(this.clsActive)
.css({position: '', top: '', width: ''})
.trigger('inactive');
this.placeholder.attr('hidden', true);
},
update: function update() {
var top = Math.max(0, this.offset), scroll = win.scrollTop();
this.placeholder.attr('hidden', false);
if (this.bottom && scroll > this.bottom - this.offset) {
top = this.bottom - scroll;
}
this.$el.css({
position: 'fixed',
top: top + 'px',
width: this._widthElement[0].getBoundingClientRect().width
});
},
isActive: function isActive() {
return this.$el.hasClass(this.clsActive) && !(this.animation && this.$el.hasClass('uk-animation-leave'));
}
},
disconnected: function disconnected() {
this.placeholder.remove();
this.placeholder = null;
this._widthElement = null;
}
});
}
var storage = window.sessionStorage || {};
var svgs = {};
function Svg (UIkit) {
UIkit.component('svg', {
props: {
id: String,
icon: String,
src: String,
class: String,
style: String,
width: Number,
height: Number,
ratio: Number
},
defaults: {
ratio: 1,
id: false,
class: '',
exclude: ['src']
},
connected: function connected() {
this.svg = $__default.Deferred();
},
update: {
read: function read() {
var this$1 = this;
if (!this.src) {
this.src = getSrc(this.$el);
}
if (!this.src || this.isSet) {
return;
}
this.isSet = true;
if (!this.icon && ~this.src.indexOf('#')) {
var parts = this.src.split('#');
if (parts.length > 1) {
this.src = parts[0];
this.icon = parts[1];
}
}
this.get(this.src).then(function (svg) { return fastdom.mutate(function () {
var el;
el = !this$1.icon
? svg.clone()
: (el = toJQuery(("#" + (this$1.icon)), svg))
&& toJQuery((el[0].outerHTML || $__default('<div>').append(el.clone()).html()).replace(/symbol/g, 'svg')) // IE workaround, el[0].outerHTML
|| !toJQuery('symbol', svg) && svg.clone(); // fallback if SVG has no symbols
if (!el || !el.length) {
return $__default.Deferred().reject('SVG not found.');
}
var dimensions = el[0].getAttribute('viewBox'); // jQuery workaround, el.attr('viewBox')
if (dimensions) {
dimensions = dimensions.split(' ');
this$1.width = this$1.width || dimensions[2];
this$1.height = this$1.height || dimensions[3];
}
this$1.width *= this$1.ratio;
this$1.height *= this$1.ratio;
for (var prop in this$1.$options.props) {
if (this$1[prop] && !~this$1.exclude.indexOf(prop)) {
el.attr(prop, this$1[prop]);
}
}
if (!this$1.id) {
el.removeAttr('id');
}
if (this$1.width && !this$1.height) {
el.removeAttr('height');
}
if (this$1.height && !this$1.width) {
el.removeAttr('width');
}
if (isVoidElement(this$1.$el) || this$1.$el[0].tagName === 'CANVAS') {
this$1.$el.attr({hidden: true, id: null});
el.insertAfter(this$1.$el);
} else {
el.appendTo(this$1.$el);
}
this$1.svg.resolve(el);
}); }
);
},
events: ['load']
},
methods: {
get: function get(src) {
if (svgs[src]) {
return svgs[src];
}
svgs[src] = $__default.Deferred();
if (src.lastIndexOf('data:', 0) === 0) {
svgs[src].resolve(getSvg(decodeURIComponent(src.split(',')[1])));
} else {
var key = "uikit_" + (UIkit.version) + "_" + src;
if (storage[key]) {
svgs[src].resolve(getSvg(storage[key]));
} else {
$__default.get(src).then(function (doc, status, res) {
storage[key] = res.responseText;
svgs[src].resolve(getSvg(storage[key]));
});
}
}
return svgs[src];
function getSvg (doc) {
return $__default(doc).filter('svg');
}
}
},
destroy: function destroy() {
if (isVoidElement(this.$el)) {
this.$el.attr({hidden: null, id: this.id || null});
}
if (this.svg) {
this.svg.then(function (svg) { return svg.remove(); });
}
}
});
function getSrc(el) {
var image = getBackgroundImage(el);
if (!image) {
el = el.clone().empty()
.attr({'uk-no-boot': '', style: ((el.attr('style')) + ";display:block !important;")})
.appendTo(document.body);
image = getBackgroundImage(el);
// safari workaround
if (!image && el[0].tagName === 'CANVAS') {
var span = $__default(el[0].outerHTML.replace(/canvas/g, 'span')).insertAfter(el);
image = getBackgroundImage(span);
span.remove();
}
el.remove();
}
return image && image.slice(4, -1).replace(/"/g, '');
}
function getBackgroundImage(el) {
var image = getStyle(el[0], 'backgroundImage', '::before');
return image !== 'none' && image;
}
}
function Switcher (UIkit) {
UIkit.component('switcher', {
mixins: [Toggable],
args: 'connect',
props: {
connect: 'jQuery',
toggle: String,
active: Number,
swiping: Boolean
},
defaults: {
connect: false,
toggle: ' > *',
active: 0,
swiping: true,
cls: 'uk-active',
clsContainer: 'uk-switcher',
attrItem: 'uk-switcher-item',
queued: true
},
ready: function ready() {
var this$1 = this;
this.$el.on('click', ((this.toggle) + ":not(.uk-disabled)"), function (e) {
e.preventDefault();
this$1.show(e.currentTarget);
});
},
update: function update() {
var this$1 = this;
this.toggles = $__default(this.toggle, this.$el);
this.connects = this.connect || $__default(this.$el.next(("." + (this.clsContainer))));
this.connects.off('click', ("[" + (this.attrItem) + "]")).on('click', ("[" + (this.attrItem) + "]"), function (e) {
e.preventDefault();
this$1.show($__default(e.currentTarget).attr(this$1.attrItem));
});
if (this.swiping) {
this.connects.off('swipeRight swipeLeft').on('swipeRight swipeLeft', function (e) {
e.preventDefault();
if (!window.getSelection().toString()) {
this$1.show(e.type == 'swipeLeft' ? 'next' : 'previous');
}
});
}
this.updateAria(this.connects.children());
this.show(toJQuery(this.toggles.filter(("." + (this.cls) + ":first"))) || toJQuery(this.toggles.eq(this.active)) || this.toggles.first());
},
methods: {
show: function show(item) {
var this$1 = this;
if (!this.toggles) {
this.$emitSync();
}
var length = this.toggles.length,
prev = this.connects.children(("." + (this.cls))).index(),
hasPrev = prev >= 0,
index = getIndex(item, this.toggles, prev),
dir = item === 'previous' ? -1 : 1,
toggle;
for (var i = 0; i < length; i++, index = (index + dir + length) % length) {
if (!this$1.toggles.eq(index).is('.uk-disabled, [disabled]')) {
toggle = this$1.toggles.eq(index);
break;
}
}
if (!toggle || prev >= 0 && toggle.hasClass(this.cls) || prev === index) {
return;
}
this.toggles.removeClass(this.cls).attr('aria-expanded', false);
toggle.addClass(this.cls).attr('aria-expanded', true);
if (!hasPrev) {
this.toggleNow(this.connects.children((":nth-child(" + (index + 1) + ")")));
} else {
this.toggleElement(this.connects.children((":nth-child(" + (prev + 1) + "),:nth-child(" + (index + 1) + ")")));
}
}
}
});
}
function Tab (UIkit) {
UIkit.component('tab', UIkit.components.switcher.extend({
mixins: [Class],
name: 'tab',
defaults: {
media: 960,
attrItem: 'uk-tab-item'
},
init: function init() {
var cls = this.$el.hasClass('uk-tab-left') && 'uk-tab-left' || this.$el.hasClass('uk-tab-right') && 'uk-tab-right';
if (cls) {
UIkit.toggle(this.$el, {cls: cls, mode: 'media', media: this.media});
}
}
}));
}
function Toggle (UIkit) {
UIkit.component('toggle', {
mixins: [UIkit.mixin.toggable],
args: 'target',
props: {
href: 'jQuery',
target: 'jQuery',
mode: String,
media: 'media'
},
defaults: {
href: false,
target: false,
mode: 'click',
queued: true,
media: false
},
ready: function ready() {
var this$1 = this;
this.target = this.target || this.href || this.$el;
this.mode = hasTouch && this.mode == 'hover' ? 'click' : this.mode;
if (this.mode === 'media') {
return;
}
if (this.mode === 'hover') {
this.$el.on({
mouseenter: function () { return this$1.toggle('toggleShow'); },
mouseleave: function () { return this$1.toggle('toggleHide'); }
});
}
this.$el.on('click', function (e) {
// TODO better isToggled handling
if ($__default(e.target).closest('a[href="#"], button').length || $__default(e.target).closest('a[href]') && (this$1.cls || !this$1.target.is(':visible'))) {
e.preventDefault();
}
this$1.toggle();
});
},
update: {
write: function write() {
if (this.mode !== 'media' || !this.media) {
return;
}
var toggled = this.isToggled(this.target);
if (window.matchMedia(this.media).matches ? !toggled : toggled) {
this.toggle();
}
},
events: ['load', 'resize', 'orientationchange']
},
methods: {
toggle: function toggle(type) {
var event = $__default.Event(type || 'toggle');
this.target.triggerHandler(event, [this]);
if (!event.isDefaultPrevented()) {
this.toggleElement(this.target);
}
}
}
});
}
function core (UIkit) {
var scroll = null, dir, ticking, resizing;
win
.on('load', UIkit.update)
.on('resize orientationchange', function (e) {
if (!resizing) {
requestAnimationFrame(function () {
UIkit.update(e);
resizing = false;
});
resizing = true;
}
})
.on('scroll', function (e) {
if (scroll === null) {
scroll = 0;
}
dir = scroll < window.pageYOffset;
scroll = window.pageYOffset;
if (!ticking) {
requestAnimationFrame(function () {
e.dir = dir ? 'down' : 'up';
UIkit.update(e);
ticking = false;
});
ticking = true;
}
});
var started = 0;
on(document, 'animationstart', function (ref) {
var target = ref.target;
fastdom.measure(function () {
if (hasAnimation(target)) {
fastdom.mutate(function () {
document.body.style.overflowX = 'hidden';
started++;
});
}
});
}, true);
on(document, 'animationend', function (ref) {
var target = ref.target;
fastdom.measure(function () {
if (hasAnimation(target) && !--started) {
fastdom.mutate(function () { return document.body.style.overflowX = ''; })
}
});
}, true);
on(document.documentElement, 'webkitAnimationEnd', function (ref) {
var target = ref.target;
fastdom.measure(function () {
if (getStyle(target, 'webkitFontSmoothing') === 'antialiased') {
fastdom.mutate(function () {
target.style.webkitFontSmoothing = 'subpixel-antialiased';
setTimeout(function () { return target.style.webkitFontSmoothing = ''; });
})
}
});
}, true);
// core components
UIkit.use(Accordion);
UIkit.use(Alert);
UIkit.use(Cover);
UIkit.use(Drop);
UIkit.use(Dropdown);
UIkit.use(FormCustom);
UIkit.use(HeightMatch);
UIkit.use(HeightViewport);
UIkit.use(Hover);
UIkit.use(Margin);
UIkit.use(Gif);
UIkit.use(Grid);
UIkit.use(Modal$1);
UIkit.use(Nav);
UIkit.use(Navbar);
UIkit.use(Offcanvas);
UIkit.use(Responsive);
UIkit.use(Scroll);
UIkit.use(Scrollspy);
UIkit.use(ScrollspyNav);
UIkit.use(Sticky);
UIkit.use(Svg);
UIkit.use(Icon);
UIkit.use(Spinner);
UIkit.use(Switcher);
UIkit.use(Tab);
UIkit.use(Toggle);
function hasAnimation(target) {
return (getStyle(target, 'animationName') || '').lastIndexOf('uk-', 0) === 0;
}
}
function boot (UIkit) {
if (Observer) {
if (document.body) {
init();
} else {
(new Observer(function () {
if (document.body) {
this.disconnect();
init();
}
})).observe(document.documentElement, {childList: true, subtree: true});
}
} else {
ready(function () {
apply(document.body, UIkit.connect);
on(document.documentElement, 'DOMNodeInserted', function (e) { return apply(e.target, UIkit.connect); });
on(document.documentElement, 'DOMNodeRemoved', function (e) { return apply(e.target, UIkit.disconnect); });
});
}
function init() {
apply(document.body, UIkit.connect);
(new Observer(function (mutations) { return mutations.forEach(function (mutation) {
for (var i = 0; i < mutation.addedNodes.length; i++) {
apply(mutation.addedNodes[i], UIkit.connect)
}
for (i = 0; i < mutation.removedNodes.length; i++) {
apply(mutation.removedNodes[i], UIkit.disconnect)
}
UIkit.update('update', mutation.target, true);
}); }
)).observe(document.documentElement, {childList: true, subtree: true, characterData: true, attributes: true, attributeFilter: ['href']});
}
function apply(node, fn) {
if (node.nodeType !== Node.ELEMENT_NODE || node.hasAttribute('uk-no-boot')) {
return;
}
fn(node);
node = node.firstChild;
while (node) {
var next = node.nextSibling;
apply(node, fn);
node = next;
}
}
}
UIkit$1.version = '3.0.0';
mixin$1(UIkit$1);
core(UIkit$1);
boot(UIkit$1);
if (typeof module !== 'undefined') {
module.exports = UIkit$1;
}
return UIkit$1;
})));/*! UIkit 3.0.0-beta.6 | http://www.getuikit.com | (c) 2014 - 2016 YOOtheme | MIT License */
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('uikit')) :
typeof define === 'function' && define.amd ? define(['uikit'], factory) :
(factory(global.UIkit));
}(this, (function (uikit) { 'use strict';
var $ = uikit.util.$;
var doc = uikit.util.doc;
var extend = uikit.util.extend;
var Dimensions = uikit.util.Dimensions;
var getIndex = uikit.util.getIndex;
var Transition = uikit.util.Transition;
var active;
doc.on({
keydown: function (e) {
if (active) {
switch (e.keyCode) {
case 37:
active.show('previous');
break;
case 39:
active.show('next');
break;
}
}
}
});
UIkit.component('lightbox', {
name: 'lightbox',
props: {
toggle: String,
duration: Number,
inverse: Boolean
},
defaults: {
toggle: 'a',
duration: 400,
dark: false,
attrItem: 'uk-lightbox-item',
items: [],
index: 0
},
ready: function ready() {
var this$1 = this;
this.toggles = $(this.toggle, this.$el);
this.toggles.each(function (i, el) {
el = $(el);
this$1.items.push({
source: el.attr('href'),
title: el.attr('title'),
type: el.attr('type')
})
});
this.$el.on('click', ((this.toggle) + ":not(.uk-disabled)"), function (e) {
e.preventDefault();
this$1.show(this$1.toggles.index(e.currentTarget));
});
},
update: {
write: function write() {
var this$1 = this;
var item = this.getItem();
if (!this.modal || !item.content) {
return;
}
var panel = this.modal.panel,
dim = {width: panel.width(), height: panel.height()},
max = {
width: window.innerWidth - (panel.outerWidth(true) - dim.width),
height: window.innerHeight - (panel.outerHeight(true) - dim.height)
},
newDim = Dimensions.fit({width: item.width, height: item.height}, max);
Transition
.stop(panel)
.stop(this.modal.content);
if (this.modal.content) {
this.modal.content.remove();
}
this.modal.content = $(item.content).css('opacity', 0).appendTo(panel);
panel.css(dim);
Transition.start(panel, newDim, this.duration).then(function () {
Transition.start(this$1.modal.content, {opacity: 1}, 400).then(function () {
panel.find('[uk-transition-hide]').show();
panel.find('[uk-transition-show]').hide();
});
});
},
events: ['resize', 'orientationchange']
},
events: {
showitem: function showitem(e) {
var item = this.getItem();
if (item.content) {
this.$update();
e.stopImmediatePropagation();
}
}
},
methods: {
show: function show(index) {
var this$1 = this;
this.index = getIndex(index, this.items, this.index);
if (!this.modal) {
this.modal = UIkit.modal.dialog("\n <button class=\"uk-modal-close-outside\" uk-transition-hide type=\"button\" uk-close></button>\n <span class=\"uk-position-center\" uk-transition-show uk-icon=\"icon: trash\"></span>\n ", {center: true});
this.modal.$el.css('overflow', 'hidden').addClass('uk-modal-lightbox');
this.modal.panel.css({width: 200, height: 200});
this.modal.caption = $('<div class="uk-modal-caption" uk-transition-hide></div>').appendTo(this.modal.panel);
if (this.items.length > 1) {
$(("<div class=\"" + (this.dark ? 'uk-dark' : 'uk-light') + "\" uk-transition-hide>\n <a href=\"#\" class=\"uk-position-center-left\" uk-slidenav=\"previous\" uk-lightbox-item=\"previous\"></a>\n <a href=\"#\" class=\"uk-position-center-right\" uk-slidenav=\"next\" uk-lightbox-item=\"next\"></a>\n </div>\n ")).appendTo(this.modal.panel.addClass('uk-slidenav-position'));
}
this.modal.$el
.on('hide', this.hide)
.on('click', ("[" + (this.attrItem) + "]"), function (e) {
e.preventDefault();
this$1.show($(e.currentTarget).attr(this$1.attrItem));
}).on('swipeRight swipeLeft', function (e) {
e.preventDefault();
if (!window.getSelection().toString()) {
this$1.show(e.type == 'swipeLeft' ? 'next' : 'previous');
}
});
}
active = this;
this.modal.panel.find('[uk-transition-hide]').hide();
this.modal.panel.find('[uk-transition-show]').show();
this.modal.content && this.modal.content.remove();
this.modal.caption.text(this.getItem().title);
var event = $.Event('showitem');
this.$el.trigger(event);
if (!event.isImmediatePropagationStopped()) {
this.setError(this.getItem());
}
},
hide: function hide() {
var this$1 = this;
active = active && active !== this && active;
this.modal.hide().then(function () {
this$1.modal.$destroy(true);
this$1.modal = null;
});
},
getItem: function getItem() {
return this.items[this.index] || {source: '', title: '', type: ''};
},
setItem: function setItem(item, content, width, height) {
if ( width === void 0 ) width = 200;
if ( height === void 0 ) height = 200;
extend(item, {content: content, width: width, height: height});
this.$update();
},
setError: function setError(item) {
this.setItem(item, '<div class="uk-position-cover uk-flex uk-flex-middle uk-flex-center"><strong>Loading resource failed!</strong></div>', 400, 300);
}
}
});
UIkit.mixin({
events: {
showitem: function showitem(e) {
var this$1 = this;
var item = this.getItem();
if (item.type !== 'image' && item.source && !item.source.match(/\.(jp(e)?g|png|gif|svg)$/i)) {
return;
}
var img = new Image();
img.onerror = function () { return this$1.setError(item); };
img.onload = function () { return this$1.setItem(item, ("<img class=\"uk-responsive-width\" width=\"" + (img.width) + "\" height=\"" + (img.height) + "\" src =\"" + (item.source) + "\">"), img.width, img.height); };
img.src = item.source;
e.stopImmediatePropagation();
}
}
}, 'lightbox');
UIkit.mixin({
events: {
showitem: function showitem(e) {
var this$1 = this;
var item = this.getItem();
if (item.type !== 'video' && item.source && !item.source.match(/\.(mp4|webm|ogv)$/i)) {
return;
}
var vid = $('<video class="uk-responsive-width" controls></video>')
.on('loadedmetadata', function () { return this$1.setItem(item, vid.attr({width: vid[0].videoWidth, height: vid[0].videoHeight}), vid[0].videoWidth, vid[0].videoHeight); })
.attr('src', item.source);
e.stopImmediatePropagation();
}
}
}, 'lightbox');
UIkit.mixin({
events: {
showitem: function showitem(e) {
var this$1 = this;
var item = this.getItem(), matches;
if (!(matches = item.source.match(/\/\/.*?youtube\.[a-z]+\/watch\?v=([^&]+)&?(.*)/)) && !(item.source.match(/youtu\.be\/(.*)/))) {
return;
}
var id = matches[1],
img = new Image(),
lowres = false,
setIframe = function (width, height) { return this$1.setItem(item, ("<iframe src=\"//www.youtube.com/embed/" + id + "\" width=\"" + width + "\" height=\"" + height + "\" style=\"max-width:100%;box-sizing:border-box;\"></iframe>"), width, height); };
img.onerror = function () { return setIframe(640, 320); };
img.onload = function () {
//youtube default 404 thumb, fall back to lowres
if (img.width === 120 && img.height === 90) {
if (!lowres) {
lowres = true;
img.src = "//img.youtube.com/vi/" + id + "/0.jpg";
} else {
setIframe(640, 320);
}
} else {
setIframe(img.width, img.height);
}
};
img.src = "//img.youtube.com/vi/" + id + "/maxresdefault.jpg";
e.stopImmediatePropagation();
}
}
}, 'lightbox');
UIkit.mixin({
events: {
showitem: function showitem(e) {
var this$1 = this;
var item = this.getItem(), matches;
if (!(matches = item.source.match(/(\/\/.*?)vimeo\.[a-z]+\/([0-9]+).*?/))) {
return;
}
var id = matches[2],
setIframe = function (width, height) { return this$1.setItem(item, ("<iframe src=\"//player.vimeo.com/video/" + id + "\" width=\"" + width + "\" height=\"" + height + "\" style=\"max-width:100%;box-sizing:border-box;\"></iframe>"), width, height); };
$.ajax({type: 'GET', url: ("http://vimeo.com/api/oembed.json?url=" + (encodeURI(item.source))), jsonp: 'callback', dataType: 'jsonp'}).then(function (res) { return setIframe(res.width, res.height); });
e.stopImmediatePropagation();
}
}
}, 'lightbox');
})));/*! UIkit 3.0.0-beta.6 | http://www.getuikit.com | (c) 2014 - 2016 YOOtheme | MIT License */
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('uikit')) :
typeof define === 'function' && define.amd ? define(['uikit'], factory) :
(factory(global.UIkit));
}(this, (function (uikit) { 'use strict';
var $ = uikit.util.$;
var Transition = uikit.util.Transition;
var containers = {};
UIkit.component('notification', {
functional: true,
args: ['message', 'status'],
defaults: {
message: '',
status: '',
timeout: 5000,
group: null,
pos: 'top-center',
onClose: null
},
created: function created() {
if (!containers[this.pos]) {
containers[this.pos] = $(("<div class=\"uk-notification uk-notification-" + (this.pos) + "\"></div>")).appendTo(uikit.container);
}
this.$mount($(
("<div class=\"uk-notification-message" + (this.status ? (" uk-notification-message-" + (this.status)) : '') + "\">\n <a href=\"#\" class=\"uk-notification-close\" data-uk-close></a>\n <div>" + (this.message) + "</div>\n </div>")
).appendTo(containers[this.pos].show()));
},
ready: function ready() {
var this$1 = this;
var marginBottom = parseInt(this.$el.css('margin-bottom'), 10);
Transition.start(
this.$el.css({opacity: 0, marginTop: -1 * this.$el.outerHeight(), marginBottom: 0}),
{opacity: 1, marginTop: 0, marginBottom: marginBottom}
).then(function () {
if (this$1.timeout) {
this$1.timer = setTimeout(this$1.close, this$1.timeout);
this$1.$el
.on('mouseenter', function () { return clearTimeout(this$1.timer); })
.on('mouseleave', function () { return this$1.timer = setTimeout(this$1.close, this$1.timeout); });
}
});
},
events: {
click: function click(e) {
e.preventDefault();
this.close();
}
},
methods: {
close: function close(immediate) {
var this$1 = this;
var remove = function () {
this$1.onClose && this$1.onClose();
this$1.$el.trigger('close', [this$1]).remove();
if (!containers[this$1.pos].children().length) {
containers[this$1.pos].hide();
}
};
if (this.timer) {
clearTimeout(this.timer);
}
if (immediate) {
remove();
} else {
Transition.start(this.$el, {opacity: 0, marginTop: -1 * this.$el.outerHeight(), marginBottom: 0}).then(remove)
}
}
}
});
UIkit.notification.closeAll = function (group, immediate) {
var notification;
UIkit.elements.forEach(function (el) {
if ((notification = UIkit.getComponent(el, 'notification')) && (!group || group === notification.group)) {
notification.close(immediate);
}
});
};
})));/*! UIkit 3.0.0-beta.6 | http://www.getuikit.com | (c) 2014 - 2016 YOOtheme | MIT License */
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('uikit')) :
typeof define === 'function' && define.amd ? define(['uikit'], factory) :
(factory(global.UIkit));
}(this, (function (uikit) { 'use strict';
var $ = uikit.util.$;
var doc = uikit.util.docElement;
var extend = uikit.util.extend;
var isWithin = uikit.util.isWithin;
var Observer = uikit.util.Observer;
var on = uikit.util.on;
var off = uikit.util.off;
var pointerDown = uikit.util.pointerDown;
var pointerMove = uikit.util.pointerMove;
var pointerUp = uikit.util.pointerUp;
var win = uikit.util.win;
UIkit.component('sortable', {
mixins: [uikit.mixin.class],
props: {
group: String,
animation: Number,
threshold: Number,
clsItem: String,
clsPlaceholder: String,
clsDrag: String,
clsDragState: String,
clsBase: String,
clsNoDrag: String,
clsEmpty: String,
clsCustom: String,
handle: String
},
defaults: {
group: false,
animation: 150,
threshold: 5,
clsItem: 'uk-sortable-item',
clsPlaceholder: 'uk-sortable-placeholder',
clsDrag: 'uk-sortable-drag',
clsDragState: 'uk-drag',
clsBase: 'uk-sortable',
clsNoDrag: 'uk-sortable-nodrag',
clsEmpty: 'uk-sortable-empty',
clsCustom: '',
handle: false
},
init: function init() {
var this$1 = this;
['init', 'start', 'move', 'end'].forEach(function (key) {
var fn = this$1[key];
this$1[key] = function (e) {
e = e.originalEvent || e;
this$1.scrollY = window.scrollY;
var ref = e.touches && e.touches[0] || e;
var pageX = ref.pageX;
var pageY = ref.pageY;
this$1.pos = {x: pageX, y: pageY};
fn(e);
}
});
},
connected: function connected() {
var this$1 = this;
on(this.$el, pointerDown, this.init);
if (this.clsEmpty) {
var empty = function () { return this$1.$el.toggleClass(this$1.clsEmpty, !this$1.$el.children().length); };
(this._observer = new Observer(empty)).observe(this.$el[0], {childList: true});
empty();
}
},
update: {
write: function write() {
var this$1 = this;
if (!this.drag) {
return;
}
this.drag.offset({top: this.pos.y + this.origin.top, left: this.pos.x + this.origin.left});
var top = this.drag.offset().top, bottom = top + this.drag[0].offsetHeight;
if (top > 0 && top < this.scrollY) {
setTimeout(function () { return win.scrollTop(this$1.scrollY - 5); }, 5);
} else if (bottom < doc[0].offsetHeight && bottom > window.innerHeight + this.scrollY) {
setTimeout(function () { return win.scrollTop(this$1.scrollY + 5); }, 5);
}
}
},
methods: {
init: function init(e) {
var target = $(e.target), placeholder = this.$el.children().filter(function (i, el) { return isWithin(e.target, el); });
if (!placeholder.length
|| target.is(':input')
|| this.handle && !isWithin(target, this.handle)
|| e.button && e.button !== 0
|| isWithin(target, ("." + (this.clsNoDrag)))
) {
return;
}
e.preventDefault();
e.stopPropagation();
this.touched = [this];
this.placeholder = placeholder;
this.origin = extend({target: target, index: this.placeholder.index()}, this.pos);
doc.on(pointerMove, this.move);
doc.on(pointerUp, this.end);
win.on('scroll', this.scroll);
if (!this.threshold) {
this.start(e);
}
},
start: function start(e) {
this.drag = $(this.placeholder[0].outerHTML.replace(/^<li/i, '<div').replace(/li>$/i, 'div>'))
.attr('uk-no-boot', '')
.addClass(((this.clsDrag) + " " + (this.clsCustom)))
.css({
boxSizing: 'border-box',
width: this.placeholder.outerWidth(),
height: this.placeholder.outerHeight()
})
.css(this.placeholder.css(['paddingLeft', 'paddingRight', 'paddingTop', 'paddingBottom']))
.appendTo(uikit.container);
this.drag.children().first().height(this.placeholder.children().height());
var ref = this.placeholder.offset();
var left = ref.left;
var top = ref.top;
extend(this.origin, {left: left - this.pos.x, top: top - this.pos.y});
this.placeholder.addClass(this.clsPlaceholder);
this.$el.children().addClass(this.clsItem);
doc.addClass(this.clsDragState);
this.$el.trigger('start', [this, this.placeholder, this.drag]);
this.move(e);
},
move: function move(e) {
if (!this.drag) {
if (Math.abs(this.pos.x - this.origin.x) > this.threshold || Math.abs(this.pos.y - this.origin.y) > this.threshold) {
this.start(e);
}
return;
}
this.$emit();
var target = e.type === 'mousemove' ? e.target : document.elementFromPoint(this.pos.x - document.body.scrollLeft, this.pos.y - document.body.scrollTop),
sortable = getSortable(target),
previous = getSortable(this.placeholder[0]),
move = sortable !== previous;
if (!sortable || isWithin(target, this.placeholder) || move && (!sortable.group || sortable.group !== previous.group)) {
return;
}
target = sortable.$el.is(target.parentNode) && $(target) || sortable.$el.children().has(target);
if (move) {
previous.remove(this.placeholder);
} else if (!target.length) {
return;
}
sortable.insert(this.placeholder, target);
if (!~this.touched.indexOf(sortable)) {
this.touched.push(sortable);
}
},
scroll: function scroll() {
var scroll = window.scrollY;
if (scroll !== this.scrollY) {
this.pos.y += scroll - this.scrollY;
this.scrollY = scroll;
this.$emit();
}
},
end: function end(e) {
doc.off(pointerMove, this.move);
doc.off(pointerUp, this.end);
win.off('scroll', this.scroll);
if (!this.drag) {
if (e.type !== 'mouseup' && isWithin(e.target, 'a[href]')) {
location.href = $(e.target).closest('a[href]').attr('href');
}
return;
}
preventClick();
var sortable = getSortable(this.placeholder[0]);
if (this === sortable) {
if (this.origin.index !== this.placeholder.index()) {
this.$el.trigger('change', [this, this.placeholder, 'moved']);
}
} else {
sortable.$el.trigger('change', [sortable, this.placeholder, 'added']);
this.$el.trigger('change', [this, this.placeholder, 'removed']);
}
this.$el.trigger('stop', [this]);
this.drag.remove();
this.drag = null;
this.touched.forEach(function (sortable) { return sortable.$el.children().removeClass(((sortable.clsPlaceholder) + " " + (sortable.clsItem))); });
doc.removeClass(this.clsDragState);
},
insert: function insert(element, target) {
var this$1 = this;
this.$el.children().addClass(this.clsItem);
var insert = function () {
if (target.length) {
if (!this$1.$el.has(element).length || element.prevAll().filter(target).length) {
element.insertBefore(target);
} else {
element.insertAfter(target);
}
} else {
this$1.$el.append(element);
}
};
if (this.animation) {
this.animate(insert);
} else {
insert();
}
},
remove: function remove(element) {
if (!this.$el.has(element).length) {
return;
}
if (this.animation) {
this.animate(function () { return element.detach(); });
} else {
element.detach();
}
},
animate: function animate(action) {
var this$1 = this;
var props = [],
children = this.$el.children().toArray().map(function (el) {
el = $(el);
props.push(extend({
position: 'absolute',
pointerEvents: 'none',
width: el.outerWidth(),
height: el.outerHeight()
}, el.position()));
return el;
}),
reset = {position: '', width: '', height: '', pointerEvents: '', top: '', left: ''};
action();
children.forEach(function (el) { return el.stop(); });
this.$el.children().css(reset);
this.$updateSync('update', true);
this.$el.css('min-height', this.$el.height());
var positions = children.map(function (el) { return el.position(); });
$.when.apply($, children.map(function (el, i) { return el.css(props[i]).animate(positions[i], this$1.animation).promise(); }))
.then(function () {
this$1.$el.css('min-height', '').children().css(reset);
this$1.$updateSync('update', true);
});
}
},
disconnected: function disconnected() {
off(this.$el, pointerDown, this.init);
if (this._observer) {
this._observer.disconnect()
}
}
});
function getSortable(element) {
return UIkit.getComponent(element, 'sortable') || element.parentNode && getSortable(element.parentNode);
}
function preventClick() {
var timer = setTimeout(function () { return doc.trigger('click'); }, 0),
listener = function (e) {
e.preventDefault();
e.stopPropagation();
clearTimeout(timer);
off(doc, 'click', listener, true);
};
on(doc, 'click', listener, true);
}
})));/*! UIkit 3.0.0-beta.6 | http://www.getuikit.com | (c) 2014 - 2016 YOOtheme | MIT License */
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('uikit')) :
typeof define === 'function' && define.amd ? define(['uikit'], factory) :
(factory(global.UIkit));
}(this, (function (uikit) { 'use strict';
var $ = uikit.util.$;
var flipPosition = uikit.util.flipPosition;
UIkit.component('tooltip', {
mixins: [uikit.mixin.toggable, uikit.mixin.position],
props: {
delay: Number
},
defaults: {
pos: 'top',
delay: 0,
animation: 'uk-animation-scale-up',
duration: 100,
cls: 'uk-active',
clsPos: 'uk-tooltip'
},
ready: function ready() {
this.content = this.$el.attr('title');
this.$el
.removeAttr('title')
.attr('aria-expanded', false);
},
methods: {
show: function show() {
var this$1 = this;
clearTimeout(this.showTimer);
if (this.$el.attr('aria-expanded') === 'true') {
return;
}
this.tooltip = $(("<div class=\"" + (this.clsPos) + "\" aria-hidden=\"true\"><div class=\"" + (this.clsPos) + "-inner\">" + (this.content) + "</div></div>")).appendTo(uikit.container);
this.$el.attr('aria-expanded', true);
this.positionAt(this.tooltip, this.$el);
this.origin = this.getAxis() === 'y' ? ((flipPosition(this.dir)) + "-" + (this.align)) : ((this.align) + "-" + (flipPosition(this.dir)));
this.showTimer = setTimeout(function () {
this$1.toggleElement(this$1.tooltip, true);
this$1.hideTimer = setInterval(function () {
if (!this$1.$el.is(':visible')) {
this$1.hide();
}
}, 150);
}, this.delay);
},
hide: function hide() {
if (this.$el.is('input') && this.$el[0] === document.activeElement) {
return;
}
clearTimeout(this.showTimer);
clearInterval(this.hideTimer);
this.$el.attr('aria-expanded', false);
this.toggleElement(this.tooltip, false);
this.tooltip && this.tooltip.remove();
this.tooltip = false;
}
},
events: {
'focus mouseenter': 'show',
'blur mouseleave': 'hide'
}
});
})));/*! UIkit 3.0.0-beta.6 | http://www.getuikit.com | (c) 2014 - 2016 YOOtheme | MIT License */
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('uikit')) :
typeof define === 'function' && define.amd ? define(['uikit'], factory) :
(factory(global.UIkit));
}(this, (function (uikit) { 'use strict';
var $ = uikit.util.$;
var ajax = uikit.util.ajax;
var on = uikit.util.on;
UIkit.component('upload', {
props: {
allow: String,
clsDragover: String,
concurrent: Number,
dataType: String,
mime: String,
msgInvalidMime: String,
msgInvalidName: String,
multiple: Boolean,
name: String,
params: Object,
type: String,
url: String
},
defaults: {
allow: false,
clsDragover: 'uk-dragover',
concurrent: 1,
dataType: undefined,
mime: false,
msgInvalidMime: 'Invalid File Type: %s',
msgInvalidName: 'Invalid File Name: %s',
multiple: false,
name: 'files[]',
params: {},
type: 'POST',
url: '',
abort: null,
beforeAll: null,
beforeSend: null,
complete: null,
completeAll: null,
error: null,
fail: function fail(msg) {
alert(msg);
},
load: null,
loadEnd: null,
loadStart: null,
progress: null
},
events: {
change: function change(e) {
if (!$(e.target).is('input[type="file"]')) {
return;
}
e.preventDefault();
if (e.target.files) {
this.upload(e.target.files);
}
e.target.value = '';
},
drop: function drop(e) {
e.preventDefault();
e.stopPropagation();
var transfer = e.originalEvent.dataTransfer;
if (!transfer || !transfer.files) {
return;
}
this.$el.removeClass(this.clsDragover);
this.upload(transfer.files);
},
dragenter: function dragenter(e) {
e.preventDefault();
e.stopPropagation();
},
dragover: function dragover(e) {
e.preventDefault();
e.stopPropagation();
this.$el.addClass(this.clsDragover);
},
dragleave: function dragleave(e) {
e.preventDefault();
e.stopPropagation();
this.$el.removeClass(this.clsDragover);
}
},
methods: {
upload: function upload(files) {
var this$1 = this;
if (!files.length) {
return;
}
this.$el.trigger('upload', [files]);
for (var i = 0; i < files.length; i++) {
if (this$1.allow) {
if (!match(this$1.allow, files[i].name)) {
this$1.fail(this$1.msgInvalidName.replace(/%s/, this$1.allow));
return;
}
}
if (this$1.mime) {
if (!match(this$1.mime, files[i].type)) {
this$1.fail(this$1.msgInvalidMime.replace(/%s/, this$1.mime));
return;
}
}
}
if (!this.multiple) {
files = [files[0]];
}
this.beforeAll && this.beforeAll(this, files);
var chunks = chunk(files, this.concurrent),
upload = function (files) {
var data = new FormData();
files.forEach(function (file) { return data.append(this$1.name, file); });
for (var key in this$1.params) {
data.append(key, this$1.params[key]);
}
ajax({
data: data,
url: this$1.url,
type: this$1.type,
dataType: this$1.dataType,
beforeSend: this$1.beforeSend,
complete: [this$1.complete, function (xhr, status) {
if (chunks.length) {
upload(chunks.shift());
} else {
this$1.completeAll && this$1.completeAll(xhr);
}
if (status === 'abort') {
this$1.abort && this$1.abort(xhr);
}
}],
cache: false,
contentType: false,
processData: false,
xhr: function () {
var xhr = $.ajaxSettings.xhr();
xhr.upload && this$1.progress && on(xhr.upload, 'progress', this$1.progress);
['loadStart', 'load', 'loadEnd', 'error', 'abort'].forEach(function (type) { return this$1[type] && on(xhr, type.toLowerCase(), this$1[type]); });
return xhr;
}
})
};
upload(chunks.shift());
}
}
});
function match(pattern, path) {
return path.match(new RegExp(("^" + (pattern.replace(/\//g, '\\/').replace(/\*\*/g, '(\\/[^\\/]+)*').replace(/\*/g, '[^\\/]+').replace(/((?!\\))\?/g, '$1.')) + "$"), 'i'));
}
function chunk(files, size) {
var chunks = [];
for (var i = 0; i < files.length; i += size) {
var chunk = [];
for (var j = 0; j < size; j++) {
chunk.push(files[i+j]);
}
chunks.push(chunk);
}
return chunks;
}
}))); | ahocevar/cdnjs | ajax/libs/uikit/3.0.0-beta.6/js/uikit.js | JavaScript | mit | 161,667 |
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const Hook = require("./Hook");
const HookCodeFactory = require("./HookCodeFactory");
class AsyncSeriesWaterfallHookCodeFactory extends HookCodeFactory {
content({ onError, onResult, onDone }) {
return this.callTapsSeries({
onError: (i, err, next, doneBreak) => onError(err) + doneBreak(true),
onResult: (i, result, next) => {
let code = "";
code += `if(${result} !== undefined) {\n`;
code += `${this._args[0]} = ${result};\n`;
code += `}\n`;
code += next();
return code;
},
onDone: () => onResult(this._args[0])
});
}
}
const factory = new AsyncSeriesWaterfallHookCodeFactory();
class AsyncSeriesWaterfallHook extends Hook {
constructor(args) {
super(args);
if (args.length < 1)
throw new Error("Waterfall hooks must have at least one argument");
}
compile(options) {
factory.setup(this, options);
return factory.create(options);
}
}
Object.defineProperties(AsyncSeriesWaterfallHook.prototype, {
_call: { value: undefined, configurable: true, writable: true }
});
module.exports = AsyncSeriesWaterfallHook;
| convox/convox.github.io | webpack/node_modules/tapable/lib/AsyncSeriesWaterfallHook.js | JavaScript | apache-2.0 | 1,187 |
'use strict';
function create (env, entries, settings, treatments, profile, devicestatus) {
var express = require('express'),
app = express( )
;
var wares = require('../middleware/')(env);
// set up express app with our options
app.set('name', env.name);
app.set('version', env.version);
// app.set('head', env.head);
function get_head ( ) {
return env.head;
}
wares.get_head = get_head;
app.set('units', env.DISPLAY_UNITS);
// Only allow access to the API if API_SECRET is set on the server.
app.disable('api');
if (env.api_secret) {
console.log("API_SECRET", env.api_secret);
app.enable('api');
}
if (env.enable) {
app.enabledOptions = env.enable || '';
env.enable.toLowerCase().split(' ').forEach(function (value) {
var enable = value.trim();
console.info("enabling feature:", enable);
app.enable(enable);
});
}
app.defaults = env.defaults || '';
app.set('title', [app.get('name'), 'API', app.get('version')].join(' '));
app.thresholds = env.thresholds;
app.alarm_types = env.alarm_types;
// Start setting up routes
if (app.enabled('api')) {
// experiments
app.use('/experiments', require('./experiments/')(app, wares));
}
// Entries and settings
app.use('/', require('./entries/')(app, wares, entries));
app.use('/', require('./settings/')(app, wares, settings));
app.use('/', require('./treatments/')(app, wares, treatments));
app.use('/', require('./profile/')(app, wares, profile));
app.use('/', require('./devicestatus/')(app, wares, devicestatus));
// Status
app.use('/', require('./status')(app, wares));
return app;
}
module.exports = create;
| johnyburd/cgm-remote-monitor | lib/api/index.js | JavaScript | agpl-3.0 | 1,687 |
// 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 Datastructure: Circular Buffer.
*
* Implements a buffer with a maximum size. New entries override the oldest
* entries when the maximum size has been reached.
*
*/
goog.provide('goog.structs.CircularBuffer');
/**
* Class for CircularBuffer.
* @param {number=} opt_maxSize The maximum size of the buffer.
* @constructor
*/
goog.structs.CircularBuffer = function(opt_maxSize) {
/**
* Index of the next element in the circular array structure.
* @private {number}
*/
this.nextPtr_ = 0;
/**
* Maximum size of the the circular array structure.
* @private {number}
*/
this.maxSize_ = opt_maxSize || 100;
/**
* Underlying array for the CircularBuffer.
* @private {Array}
*/
this.buff_ = [];
};
/**
* Adds an item to the buffer. May remove the oldest item if the buffer is at
* max size.
* @param {*} item The item to add.
* @return {*} The removed old item, if the buffer is at max size.
* Return undefined, otherwise.
*/
goog.structs.CircularBuffer.prototype.add = function(item) {
var previousItem = this.buff_[this.nextPtr_];
this.buff_[this.nextPtr_] = item;
this.nextPtr_ = (this.nextPtr_ + 1) % this.maxSize_;
return previousItem;
};
/**
* Returns the item at the specified index.
* @param {number} index The index of the item. The index of an item can change
* after calls to {@code add()} if the buffer is at maximum size.
* @return {*} The item at the specified index.
*/
goog.structs.CircularBuffer.prototype.get = function(index) {
index = this.normalizeIndex_(index);
return this.buff_[index];
};
/**
* Sets the item at the specified index.
* @param {number} index The index of the item. The index of an item can change
* after calls to {@code add()} if the buffer is at maximum size.
* @param {*} item The item to add.
*/
goog.structs.CircularBuffer.prototype.set = function(index, item) {
index = this.normalizeIndex_(index);
this.buff_[index] = item;
};
/**
* Returns the current number of items in the buffer.
* @return {number} The current number of items in the buffer.
*/
goog.structs.CircularBuffer.prototype.getCount = function() {
return this.buff_.length;
};
/**
* @return {boolean} Whether the buffer is empty.
*/
goog.structs.CircularBuffer.prototype.isEmpty = function() {
return this.buff_.length == 0;
};
/**
* Empties the current buffer.
*/
goog.structs.CircularBuffer.prototype.clear = function() {
this.buff_.length = 0;
this.nextPtr_ = 0;
};
/**
* @return {Array} The values in the buffer.
*/
goog.structs.CircularBuffer.prototype.getValues = function() {
// getNewestValues returns all the values if the maxCount parameter is the
// count
return this.getNewestValues(this.getCount());
};
/**
* Returns the newest values in the buffer up to {@code count}.
* @param {number} maxCount The maximum number of values to get. Should be a
* positive number.
* @return {Array} The newest values in the buffer up to {@code count}.
*/
goog.structs.CircularBuffer.prototype.getNewestValues = function(maxCount) {
var l = this.getCount();
var start = this.getCount() - maxCount;
var rv = [];
for (var i = start; i < l; i++) {
rv.push(this.get(i));
}
return rv;
};
/**
* @return {Array} The indexes in the buffer.
*/
goog.structs.CircularBuffer.prototype.getKeys = function() {
var rv = [];
var l = this.getCount();
for (var i = 0; i < l; i++) {
rv[i] = i;
}
return rv;
};
/**
* Whether the buffer contains the key/index.
* @param {number} key The key/index to check for.
* @return {boolean} Whether the buffer contains the key/index.
*/
goog.structs.CircularBuffer.prototype.containsKey = function(key) {
return key < this.getCount();
};
/**
* Whether the buffer contains the given value.
* @param {*} value The value to check for.
* @return {boolean} Whether the buffer contains the given value.
*/
goog.structs.CircularBuffer.prototype.containsValue = function(value) {
var l = this.getCount();
for (var i = 0; i < l; i++) {
if (this.get(i) == value) {
return true;
}
}
return false;
};
/**
* Returns the last item inserted into the buffer.
* @return {*} The last item inserted into the buffer, or null if the buffer is
* empty.
*/
goog.structs.CircularBuffer.prototype.getLast = function() {
if (this.getCount() == 0) {
return null;
}
return this.get(this.getCount() - 1);
};
/**
* Helper function to convert an index in the number space of oldest to
* newest items in the array to the position that the element will be at in the
* underlying array.
* @param {number} index The index of the item in a list ordered from oldest to
* newest.
* @return {number} The index of the item in the CircularBuffer's underlying
* array.
* @private
*/
goog.structs.CircularBuffer.prototype.normalizeIndex_ = function(index) {
if (index >= this.buff_.length) {
throw Error('Out of bounds exception');
}
if (this.buff_.length < this.maxSize_) {
return index;
}
return (this.nextPtr_ + Number(index)) % this.maxSize_;
};
| metamolecular/closure-library | closure/goog/structs/circularbuffer.js | JavaScript | apache-2.0 | 5,746 |
// Copyright JS Foundation and other contributors, http://js.foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
var a = new String('example')
var c = 'length' in a
assert(c) | bsdelf/jerryscript | tests/jerry-test-suite/11/11.08/11.08.07/11.08.07-011.js | JavaScript | apache-2.0 | 691 |
/**
* 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.
*/
import DS from 'ember-data';
export default DS.Model.extend({
totalVmemAllocatedContainersMB: DS.attr('number'),
totalPmemAllocatedContainersMB: DS.attr('number'),
totalVCoresAllocatedContainers: DS.attr('number'),
vmemCheckEnabled: DS.attr('boolean'),
pmemCheckEnabled: DS.attr('boolean'),
nodeHealthy: DS.attr('boolean'),
lastNodeUpdateTime: DS.attr('string'),
healthReport: DS.attr('string'),
nmStartupTime: DS.attr('string'),
nodeManagerBuildVersion: DS.attr('string'),
hadoopBuildVersion: DS.attr('string'),
});
| dennishuo/hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-ui/src/main/webapp/app/models/yarn-node.js | JavaScript | apache-2.0 | 1,348 |
/*************************************************************
*
* MathJax/jax/output/HTML-CSS/optable/CombDiacritMarks.js
*
* Copyright (c) 2010-2017 The MathJax Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
(function (MML) {
var MO = MML.mo.OPTYPES;
var TEXCLASS = MML.TEXCLASS;
MathJax.Hub.Insert(MML.mo.prototype,{
OPTABLE: {
postfix: {
'\u0311': MO.ACCENT // combining inverted breve
}
}
});
MathJax.Ajax.loadComplete(MML.optableDir+"/CombDiacritMarks.js");
})(MathJax.ElementJax.mml);
| benjaminvialle/Markus | vendor/assets/javascripts/MathJax_lib/jax/element/mml/optable/CombDiacritMarks.js | JavaScript | mit | 1,080 |
/* ***** BEGIN LICENSE BLOCK *****
* Distributed under the BSD license:
*
* Copyright (c) 2010, Ajax.org B.V.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Ajax.org B.V. nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* ***** END LICENSE BLOCK ***** */
define('ace/theme/dreamweaver', ['require', 'exports', 'module' , 'ace/lib/dom'], function(require, exports, module) {
exports.isDark = false;
exports.cssClass = "ace-dreamweaver";
exports.cssText = ".ace-dreamweaver .ace_gutter {\
background: #e8e8e8;\
color: #333;\
}\
.ace-dreamweaver .ace_print-margin {\
width: 1px;\
background: #e8e8e8;\
}\
.ace-dreamweaver {\
background-color: #FFFFFF;\
}\
.ace-dreamweaver .ace_fold {\
background-color: #757AD8;\
}\
.ace-dreamweaver .ace_cursor {\
color: black;\
}\
.ace-dreamweaver .ace_invisible {\
color: rgb(191, 191, 191);\
}\
.ace-dreamweaver .ace_storage,\
.ace-dreamweaver .ace_keyword {\
color: blue;\
}\
.ace-dreamweaver .ace_constant.ace_buildin {\
color: rgb(88, 72, 246);\
}\
.ace-dreamweaver .ace_constant.ace_language {\
color: rgb(88, 92, 246);\
}\
.ace-dreamweaver .ace_constant.ace_library {\
color: rgb(6, 150, 14);\
}\
.ace-dreamweaver .ace_invalid {\
background-color: rgb(153, 0, 0);\
color: white;\
}\
.ace-dreamweaver .ace_support.ace_function {\
color: rgb(60, 76, 114);\
}\
.ace-dreamweaver .ace_support.ace_constant {\
color: rgb(6, 150, 14);\
}\
.ace-dreamweaver .ace_support.ace_type,\
.ace-dreamweaver .ace_support.ace_class {\
color: #009;\
}\
.ace-dreamweaver .ace_support.ace_php_tag {\
color: #f00;\
}\
.ace-dreamweaver .ace_keyword.ace_operator {\
color: rgb(104, 118, 135);\
}\
.ace-dreamweaver .ace_string {\
color: #00F;\
}\
.ace-dreamweaver .ace_comment {\
color: rgb(76, 136, 107);\
}\
.ace-dreamweaver .ace_comment.ace_doc {\
color: rgb(0, 102, 255);\
}\
.ace-dreamweaver .ace_comment.ace_doc.ace_tag {\
color: rgb(128, 159, 191);\
}\
.ace-dreamweaver .ace_constant.ace_numeric {\
color: rgb(0, 0, 205);\
}\
.ace-dreamweaver .ace_variable {\
color: #06F\
}\
.ace-dreamweaver .ace_xml-pe {\
color: rgb(104, 104, 91);\
}\
.ace-dreamweaver .ace_entity.ace_name.ace_function {\
color: #00F;\
}\
.ace-dreamweaver .ace_heading {\
color: rgb(12, 7, 255);\
}\
.ace-dreamweaver .ace_list {\
color:rgb(185, 6, 144);\
}\
.ace-dreamweaver .ace_marker-layer .ace_selection {\
background: rgb(181, 213, 255);\
}\
.ace-dreamweaver .ace_marker-layer .ace_step {\
background: rgb(252, 255, 0);\
}\
.ace-dreamweaver .ace_marker-layer .ace_stack {\
background: rgb(164, 229, 101);\
}\
.ace-dreamweaver .ace_marker-layer .ace_bracket {\
margin: -1px 0 0 -1px;\
border: 1px solid rgb(192, 192, 192);\
}\
.ace-dreamweaver .ace_marker-layer .ace_active-line {\
background: rgba(0, 0, 0, 0.07);\
}\
.ace-dreamweaver .ace_marker-layer .ace_selected-word {\
background: rgb(250, 250, 255);\
border: 1px solid rgb(200, 200, 250);\
}\
.ace-dreamweaver .ace_meta.ace_tag {\
color:#009;\
}\
.ace-dreamweaver .ace_meta.ace_tag.ace_anchor {\
color:#060;\
}\
.ace-dreamweaver .ace_meta.ace_tag.ace_form {\
color:#F90;\
}\
.ace-dreamweaver .ace_meta.ace_tag.ace_image {\
color:#909;\
}\
.ace-dreamweaver .ace_meta.ace_tag.ace_script {\
color:#900;\
}\
.ace-dreamweaver .ace_meta.ace_tag.ace_style {\
color:#909;\
}\
.ace-dreamweaver .ace_meta.ace_tag.ace_table {\
color:#099;\
}\
.ace-dreamweaver .ace_string.ace_regex {\
color: rgb(255, 0, 0)\
}\
.ace-dreamweaver .ace_indent-guide {\
background: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAE0lEQVQImWP4////f4bLly//BwAmVgd1/w11/gAAAABJRU5ErkJggg==\") right repeat-y;\
}";
var dom = require("../lib/dom");
dom.importCssString(exports.cssText, exports.cssClass);
});
| tancredi/draw | www/js/vendor/ace/theme-dreamweaver.js | JavaScript | mit | 5,077 |
function WPATH(s) {
var index = s.lastIndexOf("/");
var path = -1 === index ? "tony.section/" + s : s.substring(0, index) + "/tony.section/" + s.substring(index + 1);
return path;
}
module.exports = []; | brentonhouse/brentonhouse.alloy | test/apps/testing/ALOY-833/_generated/mobileweb/alloy/widgets/tony.section/styles/widget.js | JavaScript | apache-2.0 | 215 |
Subsets and Splits