code
stringlengths 2
1.05M
|
---|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "m22 6.92-1.41-1.41-2.85 3.21C15.68 6.4 12.83 5 9.61 5 6.72 5 4.07 6.16 2 8l1.42 1.42C5.12 7.93 7.27 7 9.61 7c2.74 0 5.09 1.26 6.77 3.24l-2.88 3.24-4-4L2 16.99l1.5 1.5 6-6.01 4 4 4.05-4.55c.75 1.35 1.25 2.9 1.44 4.55H21c-.22-2.3-.95-4.39-2.04-6.14L22 6.92z"
}), 'MultilineChartOutlined');
exports.default = _default; |
import dateformat from 'dateformat';
import { map } from "underscore";
import { getAccountById } from 'routes/root/routes/Banking/routes/Accounts/modules/accounts';
import { getCreditCardById, getPrepaidCardById } from 'routes/root/routes/Banking/routes/Cards/modules/cards';
import { getLoanById } from 'routes/root/routes/Banking/routes/Loans/modules/loans';
export const getDebitAccount = (debitAccountType, debitAccountId) => {
switch (debitAccountType) {
case "isAccount":
getAccountById(debitAccountId)
break;
case "isLoan":
getLoanById(debitAccountId)
break;
case "isCreditCard":
getCreditCardById(debitAccountId)
break;
case "isPrepaidCard":
getPrepaidCardById(debitAccountId)
break;
}
}
const findDebitAccount = (debitAccountType, debitAccountId, state) => {
let debitAccount = {};
switch (debitAccountType) {
case "isAccount":
debitAccount = state.accounts.accounts.filter((account) => account.id == debitAccountId)[0]
break;
case "isLoan":
debitAccount = state.loans.loans.filter((loan) => loan.id == debitAccountId)[0]
break;
case "isCreditCard":
debitAccount = state.cards.creditCards.filter((creditCard) => creditCard.id == debitAccountId)[0]
break;
case "isPrepaidCard":
debitAccount = state.cards.prepaidCards.filter((prepaidCard) => prepaidCard.id == debitAccountId)[0]
break;
}
return debitAccount;
}
export const getDebitAccountAvailableBalance = (debitAccountType, debitAccountId, state) => {
const debitAccount = findDebitAccount(debitAccountType, debitAccountId, state);
return getProductAvailableBalance(debitAccount, debitAccountType);
}
export const getProductAvailableBalance = (debitAccount, debitAccountType) => {
let availableBalance = 0;
switch (debitAccountType) {
case "isAccount":
availableBalance = debitAccount.ledgerBalance;
break;
case "isLoan":
case "isCreditCard":
case "isPrepaidCard":
availableBalance = debitAccount.availableBalance;
break;
}
return availableBalance;
}
export const getDebitAccountCurrency = (debitAccountType, debitAccountId, state) => {
return findDebitAccount(debitAccountType, debitAccountId, state).currency;
}
export const isValidDate = (date) => {
return new Date(date).setHours(0,0,0,0) >= new Date(dateformat()).setHours(0,0,0,0)
}
export const isValidInstallmentPaymentAmount = (product, amount, availableBalance) => {
return amount > 0 &&
(parseFloat(amount) <= product.nextInstallmentAmount ||
parseFloat(amount) <= product.debt) &&
parseFloat(amount) <= availableBalance
}
export const isValidInstallmentPaymentForm = (transactionForm) => {
return transactionForm.debitAccount.correct &&
transactionForm.amount.correct &&
transactionForm.date.correct
}
export const getPaymentType = (paymentMethod) => {
let paymentType = '';
switch (paymentMethod) {
case 'ΚΑΡΤΑ AGILE BANK':
paymentType = 'isCreditCardAgile';
break;
case 'ΚΑΡΤΑ ΑΛΛΗΣ ΤΡΑΠΕΖΗΣ':
paymentType = 'isCreditCardThirdParty';
break;
case 'ΔΑΝΕΙΟ AGILE BANK':
paymentType = 'isLoan';
break;
default:
paymentType = 'thirdPartyPayment';
}
return paymentType;
}
export const getCustomerName = (fullCustomerName) => {
return (fullCustomerName.firstName + ' ' + fullCustomerName.lastName)
.replace('ά', 'α')
.replace('έ', 'ε')
.replace('ί', 'ι')
.replace('ή', 'η')
.replace('ό', 'ο')
.replace('ύ', 'υ')
.replace('ώ', 'ω');
}
export const getActualFullName = (fullName, currentFullName) => {
const correctPattern = new RegExp("^[A-Za-zΑ-Ωα-ω ]+$");
return fullName = (correctPattern.test(fullName) || fullName == '' ? fullName : currentFullName).toUpperCase();
}
export const isValidFullName = (fullName) => fullName.split(' ').length == 2
export const isValidDebitAmount = (amount, availableBalance) => {
return amount > 0 && (parseFloat(amount)) <= availableBalance
}
export const isValidChargesBeneficiary = (beneficiary) => {
return beneficiary == 'both' || beneficiary == 'sender' || beneficiary == 'beneficiary'
}
export const findPaymentCharges = (paymentMethods, paymentName) => {
return map(paymentMethods, (paymentMethod) => paymentMethod.map(method => method))
.flatMap(paymentMethod => paymentMethod)
.filter(payment => payment.name == paymentName)[0].charges
}
export const findTransferCharges = (beneficiary) => {
let charges = 0;
switch (beneficiary) {
case 'both':
charges = 3;
break;
case 'sender':
charges = 6;
break;
case 'beneficiary':
charges = 0;
break;
}
return charges;
}
export const getImmediateText = (language) => {
let immediateText = '';
switch (language) {
case 'greek':
immediateText = 'ΑΜΕΣΑ';
break;
case 'english':
immediateText = 'IMMEDIATE';
break;
}
return immediateText;
}
export const formatCardNumber = (cardNumber) => {
return [...cardNumber].map(((num, key) => key % 4 == 0 && key != 0 ? ' ' + num : num ))
}
|
var assert = require('assert');
var num = require('../');
test('sub', function() {
assert.equal(num.sub(0, 0), '0');
assert.equal(num.sub('0', '-0'), '0');
assert.equal(num.sub('1.0', '-1.0'), '2.0');
assert.equal(num('987654321987654321.12345678901').sub(100.012), '987654321987654221.11145678901');
assert.equal(num(100.012).sub(num('987654321987654321.12345678901')), '-987654321987654221.11145678901');
});
test('sub#constness', function() {
var one = num(1.2);
var two = num(-1.2);
assert.equal(one, '1.2');
assert.equal(two, '-1.2');
one.sub(two);
assert.equal(one, '1.2');
assert.equal(two, '-1.2');
two.sub(one);
assert.equal(one, '1.2');
assert.equal(two, '-1.2');
});
|
/*!
* vue-resource v1.5.3
* https://github.com/pagekit/vue-resource
* Released under the MIT License.
*/
'use strict';
/**
* Promises/A+ polyfill v1.1.4 (https://github.com/bramstein/promis)
*/
var RESOLVED = 0;
var REJECTED = 1;
var PENDING = 2;
function Promise$1(executor) {
this.state = PENDING;
this.value = undefined;
this.deferred = [];
var promise = this;
try {
executor(function (x) {
promise.resolve(x);
}, function (r) {
promise.reject(r);
});
} catch (e) {
promise.reject(e);
}
}
Promise$1.reject = function (r) {
return new Promise$1(function (resolve, reject) {
reject(r);
});
};
Promise$1.resolve = function (x) {
return new Promise$1(function (resolve, reject) {
resolve(x);
});
};
Promise$1.all = function all(iterable) {
return new Promise$1(function (resolve, reject) {
var count = 0,
result = [];
if (iterable.length === 0) {
resolve(result);
}
function resolver(i) {
return function (x) {
result[i] = x;
count += 1;
if (count === iterable.length) {
resolve(result);
}
};
}
for (var i = 0; i < iterable.length; i += 1) {
Promise$1.resolve(iterable[i]).then(resolver(i), reject);
}
});
};
Promise$1.race = function race(iterable) {
return new Promise$1(function (resolve, reject) {
for (var i = 0; i < iterable.length; i += 1) {
Promise$1.resolve(iterable[i]).then(resolve, reject);
}
});
};
var p = Promise$1.prototype;
p.resolve = function resolve(x) {
var promise = this;
if (promise.state === PENDING) {
if (x === promise) {
throw new TypeError('Promise settled with itself.');
}
var called = false;
try {
var then = x && x['then'];
if (x !== null && typeof x === 'object' && typeof then === 'function') {
then.call(x, function (x) {
if (!called) {
promise.resolve(x);
}
called = true;
}, function (r) {
if (!called) {
promise.reject(r);
}
called = true;
});
return;
}
} catch (e) {
if (!called) {
promise.reject(e);
}
return;
}
promise.state = RESOLVED;
promise.value = x;
promise.notify();
}
};
p.reject = function reject(reason) {
var promise = this;
if (promise.state === PENDING) {
if (reason === promise) {
throw new TypeError('Promise settled with itself.');
}
promise.state = REJECTED;
promise.value = reason;
promise.notify();
}
};
p.notify = function notify() {
var promise = this;
nextTick(function () {
if (promise.state !== PENDING) {
while (promise.deferred.length) {
var deferred = promise.deferred.shift(),
onResolved = deferred[0],
onRejected = deferred[1],
resolve = deferred[2],
reject = deferred[3];
try {
if (promise.state === RESOLVED) {
if (typeof onResolved === 'function') {
resolve(onResolved.call(undefined, promise.value));
} else {
resolve(promise.value);
}
} else if (promise.state === REJECTED) {
if (typeof onRejected === 'function') {
resolve(onRejected.call(undefined, promise.value));
} else {
reject(promise.value);
}
}
} catch (e) {
reject(e);
}
}
}
});
};
p.then = function then(onResolved, onRejected) {
var promise = this;
return new Promise$1(function (resolve, reject) {
promise.deferred.push([onResolved, onRejected, resolve, reject]);
promise.notify();
});
};
p["catch"] = function (onRejected) {
return this.then(undefined, onRejected);
};
/**
* Promise adapter.
*/
if (typeof Promise === 'undefined') {
window.Promise = Promise$1;
}
function PromiseObj(executor, context) {
if (executor instanceof Promise) {
this.promise = executor;
} else {
this.promise = new Promise(executor.bind(context));
}
this.context = context;
}
PromiseObj.all = function (iterable, context) {
return new PromiseObj(Promise.all(iterable), context);
};
PromiseObj.resolve = function (value, context) {
return new PromiseObj(Promise.resolve(value), context);
};
PromiseObj.reject = function (reason, context) {
return new PromiseObj(Promise.reject(reason), context);
};
PromiseObj.race = function (iterable, context) {
return new PromiseObj(Promise.race(iterable), context);
};
var p$1 = PromiseObj.prototype;
p$1.bind = function (context) {
this.context = context;
return this;
};
p$1.then = function (fulfilled, rejected) {
if (fulfilled && fulfilled.bind && this.context) {
fulfilled = fulfilled.bind(this.context);
}
if (rejected && rejected.bind && this.context) {
rejected = rejected.bind(this.context);
}
return new PromiseObj(this.promise.then(fulfilled, rejected), this.context);
};
p$1["catch"] = function (rejected) {
if (rejected && rejected.bind && this.context) {
rejected = rejected.bind(this.context);
}
return new PromiseObj(this.promise["catch"](rejected), this.context);
};
p$1["finally"] = function (callback) {
return this.then(function (value) {
callback.call(this);
return value;
}, function (reason) {
callback.call(this);
return Promise.reject(reason);
});
};
/**
* Utility functions.
*/
var _ref = {},
hasOwnProperty = _ref.hasOwnProperty,
slice = [].slice,
debug = false,
ntick;
var inBrowser = typeof window !== 'undefined';
function Util (_ref2) {
var config = _ref2.config,
nextTick = _ref2.nextTick;
ntick = nextTick;
debug = config.debug || !config.silent;
}
function warn(msg) {
if (typeof console !== 'undefined' && debug) {
console.warn('[VueResource warn]: ' + msg);
}
}
function error(msg) {
if (typeof console !== 'undefined') {
console.error(msg);
}
}
function nextTick(cb, ctx) {
return ntick(cb, ctx);
}
function trim(str) {
return str ? str.replace(/^\s*|\s*$/g, '') : '';
}
function trimEnd(str, chars) {
if (str && chars === undefined) {
return str.replace(/\s+$/, '');
}
if (!str || !chars) {
return str;
}
return str.replace(new RegExp("[" + chars + "]+$"), '');
}
function toLower(str) {
return str ? str.toLowerCase() : '';
}
function toUpper(str) {
return str ? str.toUpperCase() : '';
}
var isArray = Array.isArray;
function isString(val) {
return typeof val === 'string';
}
function isFunction(val) {
return typeof val === 'function';
}
function isObject(obj) {
return obj !== null && typeof obj === 'object';
}
function isPlainObject(obj) {
return isObject(obj) && Object.getPrototypeOf(obj) == Object.prototype;
}
function isBlob(obj) {
return typeof Blob !== 'undefined' && obj instanceof Blob;
}
function isFormData(obj) {
return typeof FormData !== 'undefined' && obj instanceof FormData;
}
function when(value, fulfilled, rejected) {
var promise = PromiseObj.resolve(value);
if (arguments.length < 2) {
return promise;
}
return promise.then(fulfilled, rejected);
}
function options(fn, obj, opts) {
opts = opts || {};
if (isFunction(opts)) {
opts = opts.call(obj);
}
return merge(fn.bind({
$vm: obj,
$options: opts
}), fn, {
$options: opts
});
}
function each(obj, iterator) {
var i, key;
if (isArray(obj)) {
for (i = 0; i < obj.length; i++) {
iterator.call(obj[i], obj[i], i);
}
} else if (isObject(obj)) {
for (key in obj) {
if (hasOwnProperty.call(obj, key)) {
iterator.call(obj[key], obj[key], key);
}
}
}
return obj;
}
var assign = Object.assign || _assign;
function merge(target) {
var args = slice.call(arguments, 1);
args.forEach(function (source) {
_merge(target, source, true);
});
return target;
}
function defaults(target) {
var args = slice.call(arguments, 1);
args.forEach(function (source) {
for (var key in source) {
if (target[key] === undefined) {
target[key] = source[key];
}
}
});
return target;
}
function _assign(target) {
var args = slice.call(arguments, 1);
args.forEach(function (source) {
_merge(target, source);
});
return target;
}
function _merge(target, source, deep) {
for (var key in source) {
if (deep && (isPlainObject(source[key]) || isArray(source[key]))) {
if (isPlainObject(source[key]) && !isPlainObject(target[key])) {
target[key] = {};
}
if (isArray(source[key]) && !isArray(target[key])) {
target[key] = [];
}
_merge(target[key], source[key], deep);
} else if (source[key] !== undefined) {
target[key] = source[key];
}
}
}
/**
* Root Prefix Transform.
*/
function root (options$$1, next) {
var url = next(options$$1);
if (isString(options$$1.root) && !/^(https?:)?\//.test(url)) {
url = trimEnd(options$$1.root, '/') + '/' + url;
}
return url;
}
/**
* Query Parameter Transform.
*/
function query (options$$1, next) {
var urlParams = Object.keys(Url.options.params),
query = {},
url = next(options$$1);
each(options$$1.params, function (value, key) {
if (urlParams.indexOf(key) === -1) {
query[key] = value;
}
});
query = Url.params(query);
if (query) {
url += (url.indexOf('?') == -1 ? '?' : '&') + query;
}
return url;
}
/**
* URL Template v2.0.6 (https://github.com/bramstein/url-template)
*/
function expand(url, params, variables) {
var tmpl = parse(url),
expanded = tmpl.expand(params);
if (variables) {
variables.push.apply(variables, tmpl.vars);
}
return expanded;
}
function parse(template) {
var operators = ['+', '#', '.', '/', ';', '?', '&'],
variables = [];
return {
vars: variables,
expand: function expand(context) {
return template.replace(/\{([^{}]+)\}|([^{}]+)/g, function (_, expression, literal) {
if (expression) {
var operator = null,
values = [];
if (operators.indexOf(expression.charAt(0)) !== -1) {
operator = expression.charAt(0);
expression = expression.substr(1);
}
expression.split(/,/g).forEach(function (variable) {
var tmp = /([^:*]*)(?::(\d+)|(\*))?/.exec(variable);
values.push.apply(values, getValues(context, operator, tmp[1], tmp[2] || tmp[3]));
variables.push(tmp[1]);
});
if (operator && operator !== '+') {
var separator = ',';
if (operator === '?') {
separator = '&';
} else if (operator !== '#') {
separator = operator;
}
return (values.length !== 0 ? operator : '') + values.join(separator);
} else {
return values.join(',');
}
} else {
return encodeReserved(literal);
}
});
}
};
}
function getValues(context, operator, key, modifier) {
var value = context[key],
result = [];
if (isDefined(value) && value !== '') {
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
value = value.toString();
if (modifier && modifier !== '*') {
value = value.substring(0, parseInt(modifier, 10));
}
result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : null));
} else {
if (modifier === '*') {
if (Array.isArray(value)) {
value.filter(isDefined).forEach(function (value) {
result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : null));
});
} else {
Object.keys(value).forEach(function (k) {
if (isDefined(value[k])) {
result.push(encodeValue(operator, value[k], k));
}
});
}
} else {
var tmp = [];
if (Array.isArray(value)) {
value.filter(isDefined).forEach(function (value) {
tmp.push(encodeValue(operator, value));
});
} else {
Object.keys(value).forEach(function (k) {
if (isDefined(value[k])) {
tmp.push(encodeURIComponent(k));
tmp.push(encodeValue(operator, value[k].toString()));
}
});
}
if (isKeyOperator(operator)) {
result.push(encodeURIComponent(key) + '=' + tmp.join(','));
} else if (tmp.length !== 0) {
result.push(tmp.join(','));
}
}
}
} else {
if (operator === ';') {
result.push(encodeURIComponent(key));
} else if (value === '' && (operator === '&' || operator === '?')) {
result.push(encodeURIComponent(key) + '=');
} else if (value === '') {
result.push('');
}
}
return result;
}
function isDefined(value) {
return value !== undefined && value !== null;
}
function isKeyOperator(operator) {
return operator === ';' || operator === '&' || operator === '?';
}
function encodeValue(operator, value, key) {
value = operator === '+' || operator === '#' ? encodeReserved(value) : encodeURIComponent(value);
if (key) {
return encodeURIComponent(key) + '=' + value;
} else {
return value;
}
}
function encodeReserved(str) {
return str.split(/(%[0-9A-Fa-f]{2})/g).map(function (part) {
if (!/%[0-9A-Fa-f]/.test(part)) {
part = encodeURI(part);
}
return part;
}).join('');
}
/**
* URL Template (RFC 6570) Transform.
*/
function template (options) {
var variables = [],
url = expand(options.url, options.params, variables);
variables.forEach(function (key) {
delete options.params[key];
});
return url;
}
/**
* Service for URL templating.
*/
function Url(url, params) {
var self = this || {},
options$$1 = url,
transform;
if (isString(url)) {
options$$1 = {
url: url,
params: params
};
}
options$$1 = merge({}, Url.options, self.$options, options$$1);
Url.transforms.forEach(function (handler) {
if (isString(handler)) {
handler = Url.transform[handler];
}
if (isFunction(handler)) {
transform = factory(handler, transform, self.$vm);
}
});
return transform(options$$1);
}
/**
* Url options.
*/
Url.options = {
url: '',
root: null,
params: {}
};
/**
* Url transforms.
*/
Url.transform = {
template: template,
query: query,
root: root
};
Url.transforms = ['template', 'query', 'root'];
/**
* Encodes a Url parameter string.
*
* @param {Object} obj
*/
Url.params = function (obj) {
var params = [],
escape = encodeURIComponent;
params.add = function (key, value) {
if (isFunction(value)) {
value = value();
}
if (value === null) {
value = '';
}
this.push(escape(key) + '=' + escape(value));
};
serialize(params, obj);
return params.join('&').replace(/%20/g, '+');
};
/**
* Parse a URL and return its components.
*
* @param {String} url
*/
Url.parse = function (url) {
var el = document.createElement('a');
if (document.documentMode) {
el.href = url;
url = el.href;
}
el.href = url;
return {
href: el.href,
protocol: el.protocol ? el.protocol.replace(/:$/, '') : '',
port: el.port,
host: el.host,
hostname: el.hostname,
pathname: el.pathname.charAt(0) === '/' ? el.pathname : '/' + el.pathname,
search: el.search ? el.search.replace(/^\?/, '') : '',
hash: el.hash ? el.hash.replace(/^#/, '') : ''
};
};
function factory(handler, next, vm) {
return function (options$$1) {
return handler.call(vm, options$$1, next);
};
}
function serialize(params, obj, scope) {
var array = isArray(obj),
plain = isPlainObject(obj),
hash;
each(obj, function (value, key) {
hash = isObject(value) || isArray(value);
if (scope) {
key = scope + '[' + (plain || hash ? key : '') + ']';
}
if (!scope && array) {
params.add(value.name, value.value);
} else if (hash) {
serialize(params, value, key);
} else {
params.add(key, value);
}
});
}
/**
* XDomain client (Internet Explorer).
*/
function xdrClient (request) {
return new PromiseObj(function (resolve) {
var xdr = new XDomainRequest(),
handler = function handler(_ref) {
var type = _ref.type;
var status = 0;
if (type === 'load') {
status = 200;
} else if (type === 'error') {
status = 500;
}
resolve(request.respondWith(xdr.responseText, {
status: status
}));
};
request.abort = function () {
return xdr.abort();
};
xdr.open(request.method, request.getUrl());
if (request.timeout) {
xdr.timeout = request.timeout;
}
xdr.onload = handler;
xdr.onabort = handler;
xdr.onerror = handler;
xdr.ontimeout = handler;
xdr.onprogress = function () {};
xdr.send(request.getBody());
});
}
/**
* CORS Interceptor.
*/
var SUPPORTS_CORS = inBrowser && 'withCredentials' in new XMLHttpRequest();
function cors (request) {
if (inBrowser) {
var orgUrl = Url.parse(location.href);
var reqUrl = Url.parse(request.getUrl());
if (reqUrl.protocol !== orgUrl.protocol || reqUrl.host !== orgUrl.host) {
request.crossOrigin = true;
request.emulateHTTP = false;
if (!SUPPORTS_CORS) {
request.client = xdrClient;
}
}
}
}
/**
* Form data Interceptor.
*/
function form (request) {
if (isFormData(request.body)) {
request.headers["delete"]('Content-Type');
} else if (isObject(request.body) && request.emulateJSON) {
request.body = Url.params(request.body);
request.headers.set('Content-Type', 'application/x-www-form-urlencoded');
}
}
/**
* JSON Interceptor.
*/
function json (request) {
var type = request.headers.get('Content-Type') || '';
if (isObject(request.body) && type.indexOf('application/json') === 0) {
request.body = JSON.stringify(request.body);
}
return function (response) {
return response.bodyText ? when(response.text(), function (text) {
var type = response.headers.get('Content-Type') || '';
if (type.indexOf('application/json') === 0 || isJson(text)) {
try {
response.body = JSON.parse(text);
} catch (e) {
response.body = null;
}
} else {
response.body = text;
}
return response;
}) : response;
};
}
function isJson(str) {
var start = str.match(/^\s*(\[|\{)/);
var end = {
'[': /]\s*$/,
'{': /}\s*$/
};
return start && end[start[1]].test(str);
}
/**
* JSONP client (Browser).
*/
function jsonpClient (request) {
return new PromiseObj(function (resolve) {
var name = request.jsonp || 'callback',
callback = request.jsonpCallback || '_jsonp' + Math.random().toString(36).substr(2),
body = null,
handler,
script;
handler = function handler(_ref) {
var type = _ref.type;
var status = 0;
if (type === 'load' && body !== null) {
status = 200;
} else if (type === 'error') {
status = 500;
}
if (status && window[callback]) {
delete window[callback];
document.body.removeChild(script);
}
resolve(request.respondWith(body, {
status: status
}));
};
window[callback] = function (result) {
body = JSON.stringify(result);
};
request.abort = function () {
handler({
type: 'abort'
});
};
request.params[name] = callback;
if (request.timeout) {
setTimeout(request.abort, request.timeout);
}
script = document.createElement('script');
script.src = request.getUrl();
script.type = 'text/javascript';
script.async = true;
script.onload = handler;
script.onerror = handler;
document.body.appendChild(script);
});
}
/**
* JSONP Interceptor.
*/
function jsonp (request) {
if (request.method == 'JSONP') {
request.client = jsonpClient;
}
}
/**
* Before Interceptor.
*/
function before (request) {
if (isFunction(request.before)) {
request.before.call(this, request);
}
}
/**
* HTTP method override Interceptor.
*/
function method (request) {
if (request.emulateHTTP && /^(PUT|PATCH|DELETE)$/i.test(request.method)) {
request.headers.set('X-HTTP-Method-Override', request.method);
request.method = 'POST';
}
}
/**
* Header Interceptor.
*/
function header (request) {
var headers = assign({}, Http.headers.common, !request.crossOrigin ? Http.headers.custom : {}, Http.headers[toLower(request.method)]);
each(headers, function (value, name) {
if (!request.headers.has(name)) {
request.headers.set(name, value);
}
});
}
/**
* XMLHttp client (Browser).
*/
function xhrClient (request) {
return new PromiseObj(function (resolve) {
var xhr = new XMLHttpRequest(),
handler = function handler(event) {
var response = request.respondWith('response' in xhr ? xhr.response : xhr.responseText, {
status: xhr.status === 1223 ? 204 : xhr.status,
// IE9 status bug
statusText: xhr.status === 1223 ? 'No Content' : trim(xhr.statusText)
});
each(trim(xhr.getAllResponseHeaders()).split('\n'), function (row) {
response.headers.append(row.slice(0, row.indexOf(':')), row.slice(row.indexOf(':') + 1));
});
resolve(response);
};
request.abort = function () {
return xhr.abort();
};
xhr.open(request.method, request.getUrl(), true);
if (request.timeout) {
xhr.timeout = request.timeout;
}
if (request.responseType && 'responseType' in xhr) {
xhr.responseType = request.responseType;
}
if (request.withCredentials || request.credentials) {
xhr.withCredentials = true;
}
if (!request.crossOrigin) {
request.headers.set('X-Requested-With', 'XMLHttpRequest');
} // deprecated use downloadProgress
if (isFunction(request.progress) && request.method === 'GET') {
xhr.addEventListener('progress', request.progress);
}
if (isFunction(request.downloadProgress)) {
xhr.addEventListener('progress', request.downloadProgress);
} // deprecated use uploadProgress
if (isFunction(request.progress) && /^(POST|PUT)$/i.test(request.method)) {
xhr.upload.addEventListener('progress', request.progress);
}
if (isFunction(request.uploadProgress) && xhr.upload) {
xhr.upload.addEventListener('progress', request.uploadProgress);
}
request.headers.forEach(function (value, name) {
xhr.setRequestHeader(name, value);
});
xhr.onload = handler;
xhr.onabort = handler;
xhr.onerror = handler;
xhr.ontimeout = handler;
xhr.send(request.getBody());
});
}
/**
* Http client (Node).
*/
function nodeClient (request) {
var client = require('got');
return new PromiseObj(function (resolve) {
var url = request.getUrl();
var body = request.getBody();
var method = request.method;
var headers = {},
handler;
request.headers.forEach(function (value, name) {
headers[name] = value;
});
client(url, {
body: body,
method: method,
headers: headers
}).then(handler = function handler(resp) {
var response = request.respondWith(resp.body, {
status: resp.statusCode,
statusText: trim(resp.statusMessage)
});
each(resp.headers, function (value, name) {
response.headers.set(name, value);
});
resolve(response);
}, function (error$$1) {
return handler(error$$1.response);
});
});
}
/**
* Base client.
*/
function Client (context) {
var reqHandlers = [sendRequest],
resHandlers = [];
if (!isObject(context)) {
context = null;
}
function Client(request) {
while (reqHandlers.length) {
var handler = reqHandlers.pop();
if (isFunction(handler)) {
var _ret = function () {
var response = void 0,
next = void 0;
response = handler.call(context, request, function (val) {
return next = val;
}) || next;
if (isObject(response)) {
return {
v: new PromiseObj(function (resolve, reject) {
resHandlers.forEach(function (handler) {
response = when(response, function (response) {
return handler.call(context, response) || response;
}, reject);
});
when(response, resolve, reject);
}, context)
};
}
if (isFunction(response)) {
resHandlers.unshift(response);
}
}();
if (typeof _ret === "object") return _ret.v;
} else {
warn("Invalid interceptor of type " + typeof handler + ", must be a function");
}
}
}
Client.use = function (handler) {
reqHandlers.push(handler);
};
return Client;
}
function sendRequest(request) {
var client = request.client || (inBrowser ? xhrClient : nodeClient);
return client(request);
}
/**
* HTTP Headers.
*/
var Headers = /*#__PURE__*/function () {
function Headers(headers) {
var _this = this;
this.map = {};
each(headers, function (value, name) {
return _this.append(name, value);
});
}
var _proto = Headers.prototype;
_proto.has = function has(name) {
return getName(this.map, name) !== null;
};
_proto.get = function get(name) {
var list = this.map[getName(this.map, name)];
return list ? list.join() : null;
};
_proto.getAll = function getAll(name) {
return this.map[getName(this.map, name)] || [];
};
_proto.set = function set(name, value) {
this.map[normalizeName(getName(this.map, name) || name)] = [trim(value)];
};
_proto.append = function append(name, value) {
var list = this.map[getName(this.map, name)];
if (list) {
list.push(trim(value));
} else {
this.set(name, value);
}
};
_proto["delete"] = function _delete(name) {
delete this.map[getName(this.map, name)];
};
_proto.deleteAll = function deleteAll() {
this.map = {};
};
_proto.forEach = function forEach(callback, thisArg) {
var _this2 = this;
each(this.map, function (list, name) {
each(list, function (value) {
return callback.call(thisArg, value, name, _this2);
});
});
};
return Headers;
}();
function getName(map, name) {
return Object.keys(map).reduce(function (prev, curr) {
return toLower(name) === toLower(curr) ? curr : prev;
}, null);
}
function normalizeName(name) {
if (/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(name)) {
throw new TypeError('Invalid character in header field name');
}
return trim(name);
}
/**
* HTTP Response.
*/
var Response = /*#__PURE__*/function () {
function Response(body, _ref) {
var url = _ref.url,
headers = _ref.headers,
status = _ref.status,
statusText = _ref.statusText;
this.url = url;
this.ok = status >= 200 && status < 300;
this.status = status || 0;
this.statusText = statusText || '';
this.headers = new Headers(headers);
this.body = body;
if (isString(body)) {
this.bodyText = body;
} else if (isBlob(body)) {
this.bodyBlob = body;
if (isBlobText(body)) {
this.bodyText = blobText(body);
}
}
}
var _proto = Response.prototype;
_proto.blob = function blob() {
return when(this.bodyBlob);
};
_proto.text = function text() {
return when(this.bodyText);
};
_proto.json = function json() {
return when(this.text(), function (text) {
return JSON.parse(text);
});
};
return Response;
}();
Object.defineProperty(Response.prototype, 'data', {
get: function get() {
return this.body;
},
set: function set(body) {
this.body = body;
}
});
function blobText(body) {
return new PromiseObj(function (resolve) {
var reader = new FileReader();
reader.readAsText(body);
reader.onload = function () {
resolve(reader.result);
};
});
}
function isBlobText(body) {
return body.type.indexOf('text') === 0 || body.type.indexOf('json') !== -1;
}
/**
* HTTP Request.
*/
var Request = /*#__PURE__*/function () {
function Request(options$$1) {
this.body = null;
this.params = {};
assign(this, options$$1, {
method: toUpper(options$$1.method || 'GET')
});
if (!(this.headers instanceof Headers)) {
this.headers = new Headers(this.headers);
}
}
var _proto = Request.prototype;
_proto.getUrl = function getUrl() {
return Url(this);
};
_proto.getBody = function getBody() {
return this.body;
};
_proto.respondWith = function respondWith(body, options$$1) {
return new Response(body, assign(options$$1 || {}, {
url: this.getUrl()
}));
};
return Request;
}();
/**
* Service for sending network requests.
*/
var COMMON_HEADERS = {
'Accept': 'application/json, text/plain, */*'
};
var JSON_CONTENT_TYPE = {
'Content-Type': 'application/json;charset=utf-8'
};
function Http(options$$1) {
var self = this || {},
client = Client(self.$vm);
defaults(options$$1 || {}, self.$options, Http.options);
Http.interceptors.forEach(function (handler) {
if (isString(handler)) {
handler = Http.interceptor[handler];
}
if (isFunction(handler)) {
client.use(handler);
}
});
return client(new Request(options$$1)).then(function (response) {
return response.ok ? response : PromiseObj.reject(response);
}, function (response) {
if (response instanceof Error) {
error(response);
}
return PromiseObj.reject(response);
});
}
Http.options = {};
Http.headers = {
put: JSON_CONTENT_TYPE,
post: JSON_CONTENT_TYPE,
patch: JSON_CONTENT_TYPE,
"delete": JSON_CONTENT_TYPE,
common: COMMON_HEADERS,
custom: {}
};
Http.interceptor = {
before: before,
method: method,
jsonp: jsonp,
json: json,
form: form,
header: header,
cors: cors
};
Http.interceptors = ['before', 'method', 'jsonp', 'json', 'form', 'header', 'cors'];
['get', 'delete', 'head', 'jsonp'].forEach(function (method$$1) {
Http[method$$1] = function (url, options$$1) {
return this(assign(options$$1 || {}, {
url: url,
method: method$$1
}));
};
});
['post', 'put', 'patch'].forEach(function (method$$1) {
Http[method$$1] = function (url, body, options$$1) {
return this(assign(options$$1 || {}, {
url: url,
method: method$$1,
body: body
}));
};
});
/**
* Service for interacting with RESTful services.
*/
function Resource(url, params, actions, options$$1) {
var self = this || {},
resource = {};
actions = assign({}, Resource.actions, actions);
each(actions, function (action, name) {
action = merge({
url: url,
params: assign({}, params)
}, options$$1, action);
resource[name] = function () {
return (self.$http || Http)(opts(action, arguments));
};
});
return resource;
}
function opts(action, args) {
var options$$1 = assign({}, action),
params = {},
body;
switch (args.length) {
case 2:
params = args[0];
body = args[1];
break;
case 1:
if (/^(POST|PUT|PATCH)$/i.test(options$$1.method)) {
body = args[0];
} else {
params = args[0];
}
break;
case 0:
break;
default:
throw 'Expected up to 2 arguments [params, body], got ' + args.length + ' arguments';
}
options$$1.body = body;
options$$1.params = assign({}, options$$1.params, params);
return options$$1;
}
Resource.actions = {
get: {
method: 'GET'
},
save: {
method: 'POST'
},
query: {
method: 'GET'
},
update: {
method: 'PUT'
},
remove: {
method: 'DELETE'
},
"delete": {
method: 'DELETE'
}
};
/**
* Install plugin.
*/
function plugin(Vue) {
if (plugin.installed) {
return;
}
Util(Vue);
Vue.url = Url;
Vue.http = Http;
Vue.resource = Resource;
Vue.Promise = PromiseObj;
Object.defineProperties(Vue.prototype, {
$url: {
get: function get() {
return options(Vue.url, this, this.$options.url);
}
},
$http: {
get: function get() {
return options(Vue.http, this, this.$options.http);
}
},
$resource: {
get: function get() {
return Vue.resource.bind(this);
}
},
$promise: {
get: function get() {
var _this = this;
return function (executor) {
return new Vue.Promise(executor, _this);
};
}
}
});
}
if (typeof window !== 'undefined' && window.Vue && !window.Vue.resource) {
window.Vue.use(plugin);
}
module.exports = plugin;
|
console.log('argv[0]: '+process.argv[0]);
console.log('argv[1]: '+process.argv[1]);
|
'use strict';
var Crawler = require('../lib/crawler');
var expect = require('chai').expect;
var jsdom = require('jsdom');
var httpbinHost = 'localhost:8000';
describe('Errors', function() {
describe('timeout', function() {
var c = new Crawler({
timeout : 1500,
retryTimeout : 1000,
retries : 2,
jquery : false
});
it('should return a timeout error after ~5sec', function(done) {
// override default mocha test timeout of 2000ms
this.timeout(10000);
c.queue({
uri : 'http://'+httpbinHost+'/delay/15',
callback : function(error, response) //noinspection BadExpressionStatementJS,BadExpressionStatementJS
{
expect(error).not.to.be.null;
expect(error.code).to.equal("ETIMEDOUT");
//expect(response).to.be.undefined;
done();
}
});
});
it('should retry after a first timeout', function(done) {
// override default mocha test timeout of 2000ms
this.timeout(15000);
c.queue({
uri : 'http://'+httpbinHost+'/delay/1',
callback : function(error, response) {
expect(error).to.be.null;
expect(response.body).to.be.ok;
done();
}
});
});
});
describe('error status code', function() {
var c = new Crawler({
jQuery : false
});
it('should not return an error on status code 400 (Bad Request)', function(done) {
c.queue({
uri: 'http://' + httpbinHost + '/status/400',
callback: function(error, response, $){
expect(error).to.be.null;
expect(response.statusCode).to.equal(400);
done();
}
});
});
it('should not return an error on status code 401 (Unauthorized)', function(done) {
c.queue({
uri: 'http://' + httpbinHost + '/status/401',
callback: function(error, response, $){
expect(error).to.be.null;
expect(response.statusCode).to.equal(401);
done();
}
});
});
it('should not return an error on status code 403 (Forbidden)', function(done) {
c.queue({
uri: 'http://' + httpbinHost + '/status/403',
callback: function(error, response, $){
expect(error).to.be.null;
expect(response.statusCode).to.equal(403);
done();
}
});
});
it('should not return an error on a 404', function(done) {
c.queue({
uri : 'http://'+httpbinHost+'/status/404',
callback : function(error, response) {
expect(error).to.be.null;
expect(response.statusCode).to.equal(404);
done();
}
});
});
it('should not return an error on a 500', function(done) {
c.queue({
uri : 'http://'+httpbinHost+'/status/500',
callback : function(error, response) {
expect(error).to.be.null;
expect(response.statusCode).to.equal(500);
done();
}
});
});
it('should not failed on empty response', function(done) {
c.queue({
uri : 'http://'+httpbinHost+'/status/204',
callback : function(error) {
expect(error).to.be.null;
done();
}
});
});
it('should not failed on a malformed html if jquery is false', function(done) {
c.queue({
html : '<html><p>hello <div>dude</p></html>',
callback : function(error, response) {
expect(error).to.be.null;
expect(response).not.to.be.null;
done();
}
});
});
it('should not return an error on a malformed html if jQuery is jsdom', function(done) {
c.queue({
html : '<html><p>hello <div>dude</p></html>',
jQuery : jsdom,
callback : function(error, response) {
expect(error).to.be.null;
expect(response).not.to.be.undefined;
done();
}
});
});
});
});
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M21 3H3C2 3 1 4 1 5v14c0 1.1.9 2 2 2h18c1 0 2-1 2-2V5c0-1-1-2-2-2zM5 17l3.5-4.5 2.5 3.01L14.5 11l4.5 6H5z"
}), 'PhotoSizeSelectActual');
exports.default = _default; |
const PlotCard = require('../../plotcard.js');
class RiseOfTheKraken extends PlotCard {
setupCardAbilities() {
this.interrupt({
when: {
onUnopposedWin: event => event.challenge.winner === this.controller
},
handler: () => {
this.game.addMessage('{0} uses {1} to gain an additional power from winning an unopposed challenge', this.controller, this);
this.game.addPower(this.controller, 1);
}
});
}
}
RiseOfTheKraken.code = '02012';
module.exports = RiseOfTheKraken;
|
import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon( /*#__PURE__*/_jsx("path", {
d: "M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM8 17c-.55 0-1-.45-1-1v-5c0-.55.45-1 1-1s1 .45 1 1v5c0 .55-.45 1-1 1zm4 0c-.55 0-1-.45-1-1V8c0-.55.45-1 1-1s1 .45 1 1v8c0 .55-.45 1-1 1zm4 0c-.55 0-1-.45-1-1v-2c0-.55.45-1 1-1s1 .45 1 1v2c0 .55-.45 1-1 1z"
}), 'AssessmentRounded'); |
import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon([/*#__PURE__*/_jsx("path", {
d: "M12 4c4.41 0 8 3.59 8 8s-3.59 8-8 8-8-3.59-8-8 3.59-8 8-8m.06 9.34v2.14c-.92.02-1.84-.31-2.54-1.01-1.12-1.12-1.3-2.8-.59-4.13l-1.1-1.1c-1.28 1.94-1.07 4.59.64 6.29.97.98 2.25 1.47 3.53 1.47h.06v2l2.83-2.83-2.83-2.83zm3.48-4.88c-.99-.99-2.3-1.46-3.6-1.45V5L9.11 7.83l2.83 2.83V8.51H12c.9 0 1.79.34 2.48 1.02 1.12 1.12 1.3 2.8.59 4.13l1.1 1.1c1.28-1.94 1.07-4.59-.63-6.3z",
opacity: ".3"
}, "0"), /*#__PURE__*/_jsx("path", {
d: "M12 4c4.41 0 8 3.59 8 8s-3.59 8-8 8-8-3.59-8-8 3.59-8 8-8m0-2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm.06 11.34v2.14c-.92.02-1.84-.31-2.54-1.01-1.12-1.12-1.3-2.8-.59-4.13l-1.1-1.1c-1.28 1.94-1.07 4.59.64 6.29.97.98 2.25 1.47 3.53 1.47h.06v2l2.83-2.83-2.83-2.83zm3.48-4.88c-.99-.99-2.3-1.46-3.6-1.45V5L9.11 7.83l2.83 2.83V8.51H12c.9 0 1.79.34 2.48 1.02 1.12 1.12 1.3 2.8.59 4.13l1.1 1.1c1.28-1.94 1.07-4.59-.63-6.3z"
}, "1")], 'ChangeCircleTwoTone'); |
module.exports={A:{A:{"2":"K C G E B A WB"},B:{"2":"D u Y I M H"},C:{"1":"6 7","2":"0 1 2 3 UB z F J K C G E B A D u Y I M H N O P Q R S T U V W X w Z a b c d e f L h i j k l m n o p q r s t y SB RB","132":"v","578":"5 g"},D:{"1":"0 1 2 3 5 6 7 t y v g GB BB DB VB EB","2":"F J K C G E B A D u Y I M H N O P Q R S T U V W X w Z a b c d e f L h i j k l m n o p q r s"},E:{"1":"MB","2":"F J K C G E B FB AB HB IB JB KB LB","322":"A"},F:{"1":"L h i j k l m n o p q r s t","2":"8 9 E A D I M H N O P Q R S T U V W X w Z a b c d e f NB OB PB QB TB x"},G:{"2":"4 G AB CB XB YB ZB aB bB cB dB eB","322":"A"},H:{"2":"fB"},I:{"1":"v","2":"4 z F gB hB iB jB kB lB"},J:{"2":"C B"},K:{"1":"L","2":"8 9 B A D x"},L:{"1":"BB"},M:{"132":"g"},N:{"2":"B A"},O:{"2":"mB"},P:{"1":"J","2":"F"},Q:{"2":"nB"},R:{"2":"oB"}},B:5,C:"Resource Hints: preload"};
|
SVG.G = SVG.invent({
// Initialize node
create: 'g'
// Inherit from
, inherit: SVG.Container
// Add class methods
, extend: {
// Move over x-axis
x: function(x) {
return x == null ? this.transform('x') : this.transform({ x: x - this.x() }, true)
}
// Move over y-axis
, y: function(y) {
return y == null ? this.transform('y') : this.transform({ y: y - this.y() }, true)
}
// Move by center over x-axis
, cx: function(x) {
return x == null ? this.gbox().cx : this.x(x - this.gbox().width / 2)
}
// Move by center over y-axis
, cy: function(y) {
return y == null ? this.gbox().cy : this.y(y - this.gbox().height / 2)
}
, gbox: function() {
var bbox = this.bbox()
, trans = this.transform()
bbox.x += trans.x
bbox.x2 += trans.x
bbox.cx += trans.x
bbox.y += trans.y
bbox.y2 += trans.y
bbox.cy += trans.y
return bbox
}
}
// Add parent method
, construct: {
// Create a group element
group: function() {
return this.put(new SVG.G)
}
}
})
|
'use strict';
module.exports = function generate_format(it, $keyword) {
var out = ' ';
var $lvl = it.level;
var $dataLvl = it.dataLevel;
var $schema = it.schema[$keyword];
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
var $breakOnError = !it.opts.allErrors;
var $data = 'data' + ($dataLvl || '');
if (it.opts.format === false) {
if ($breakOnError) {
out += ' if (true) { ';
}
return out;
}
var $isData = it.opts.v5 && $schema && $schema.$data,
$schemaValue;
if ($isData) {
out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
$schemaValue = 'schema' + $lvl;
} else {
$schemaValue = $schema;
}
var $unknownFormats = it.opts.unknownFormats,
$allowUnknown = Array.isArray($unknownFormats);
if ($isData) {
var $format = 'format' + $lvl;
out += ' var ' + ($format) + ' = formats[' + ($schemaValue) + ']; var isObject' + ($lvl) + ' = typeof ' + ($format) + ' == \'object\' && !(' + ($format) + ' instanceof RegExp) && ' + ($format) + '.validate; if (isObject' + ($lvl) + ') { ';
if (it.async) {
out += ' var async' + ($lvl) + ' = ' + ($format) + '.async; ';
}
out += ' ' + ($format) + ' = ' + ($format) + '.validate; } if ( ';
if ($isData) {
out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || ';
}
out += ' (';
if ($unknownFormats === true || $allowUnknown) {
out += ' (' + ($schemaValue) + ' && !' + ($format) + ' ';
if ($allowUnknown) {
out += ' && self._opts.unknownFormats.indexOf(' + ($schemaValue) + ') == -1 ';
}
out += ') || ';
}
out += ' (' + ($format) + ' && !(typeof ' + ($format) + ' == \'function\' ? ';
if (it.async) {
out += ' (async' + ($lvl) + ' ? ' + (it.yieldAwait) + ' ' + ($format) + '(' + ($data) + ') : ' + ($format) + '(' + ($data) + ')) ';
} else {
out += ' ' + ($format) + '(' + ($data) + ') ';
}
out += ' : ' + ($format) + '.test(' + ($data) + '))))) {';
} else {
var $format = it.formats[$schema];
if (!$format) {
if ($unknownFormats === true || ($allowUnknown && $unknownFormats.indexOf($schema) == -1)) {
throw new Error('unknown format "' + $schema + '" is used in schema at path "' + it.errSchemaPath + '"');
} else {
if (!$allowUnknown) {
console.warn('unknown format "' + $schema + '" ignored in schema at path "' + it.errSchemaPath + '"');
if ($unknownFormats !== 'ignore') console.warn('In the next major version it will throw exception. See option unknownFormats for more information');
}
if ($breakOnError) {
out += ' if (true) { ';
}
return out;
}
}
var $isObject = typeof $format == 'object' && !($format instanceof RegExp) && $format.validate;
if ($isObject) {
var $async = $format.async === true;
$format = $format.validate;
}
if ($async) {
if (!it.async) throw new Error('async format in sync schema');
var $formatRef = 'formats' + it.util.getProperty($schema) + '.validate';
out += ' if (!(' + (it.yieldAwait) + ' ' + ($formatRef) + '(' + ($data) + '))) { ';
} else {
out += ' if (! ';
var $formatRef = 'formats' + it.util.getProperty($schema);
if ($isObject) $formatRef += '.validate';
if (typeof $format == 'function') {
out += ' ' + ($formatRef) + '(' + ($data) + ') ';
} else {
out += ' ' + ($formatRef) + '.test(' + ($data) + ') ';
}
out += ') { ';
}
}
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = ''; /* istanbul ignore else */
if (it.createErrors !== false) {
out += ' { keyword: \'' + ('format') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { format: ';
if ($isData) {
out += '' + ($schemaValue);
} else {
out += '' + (it.util.toQuotedString($schema));
}
out += ' } ';
if (it.opts.messages !== false) {
out += ' , message: \'should match format "';
if ($isData) {
out += '\' + ' + ($schemaValue) + ' + \'';
} else {
out += '' + (it.util.escapeQuotes($schema));
}
out += '"\' ';
}
if (it.opts.verbose) {
out += ' , schema: ';
if ($isData) {
out += 'validate.schema' + ($schemaPath);
} else {
out += '' + (it.util.toQuotedString($schema));
}
out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
}
out += ' } ';
} else {
out += ' {} ';
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {
out += ' validate.errors = [' + (__err) + ']; return false; ';
}
} else {
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
}
out += ' } ';
if ($breakOnError) {
out += ' else { ';
}
return out;
}
|
require(
[
'gui/Button'
],
function (Button) {
return;
var button = new Button({
main: $('#ui-button')
});
button.render();
}
); |
var GUID = (function () {
function _GUID() {
return UUIDcreatePart(4) +
UUIDcreatePart(2) +
UUIDcreatePart(2) +
UUIDcreatePart(2) +
UUIDcreatePart(6);
};
function UUIDcreatePart(length) {
var uuidpart = "";
for (var i = 0; i < length; i++) {
var uuidchar = parseInt((Math.random() * 256), 10).toString(16);
if (uuidchar.length == 1) {
uuidchar = "0" + uuidchar;
}
uuidpart += uuidchar;
}
return uuidpart;
}
return {
newGuid: _GUID
};
})();
var dataSource = (function () {
var tablesStorageKey = "60AE0285-40EE-4A2D-BA5F-F75D601593DD";
var globalData = [];
var tables = [
{
Id: 5,
Name: "Contact",
Schema: [
{
k: "name",
t: 1
},
{
k: "companyname",
t: 1
},
{
k: "position",
t: 1
}
],
Created: "2016-08-12T07:32:46.69"
},
{
Id: 6,
Name: "Profile",
Schema: [
{
k: "Name",
t: 1
},
{
k: "Age",
t: 2
},
{
k: "Gender",
t: 4
},
{
k: "Rating",
t: 3
},
{
k: "Created",
t: 5
}
],
Created: "2016-09-28T21:53:40.19"
}
];
function _loadData(){
globalData = JSON.parse(localStorage[tablesStorageKey] || "[]");
}
function _save()
{
localStorage[tablesStorageKey] = JSON.stringify(globalData);
}
function _getSchema(tableId) {
for (var t = 0; t < tables.length; t++)
if (tableId === tables[t].Id) return tables[t].Schema;
}
function _find(data) {
var skip = data.start;
var take = data.length;
return {
draw: data.draw,
recordsTotal: globalData.length,
recordsFiltered: globalData.length,
data: globalData.slice(skip, take + skip)
};
}
function _insert(data) {
var id = GUID.newGuid();
globalData.push([id, data.Name, data.Age, data.Gender, data.Rating, data.Created]);
_save()
return {
IsOk: true,
id: id
};
}
function _update(data) {
for (var t = 0; t < globalData.length; t++)
if (data._id === globalData[t][0]) {
globalData[t] = [data._id, data.Name, data.Age, data.Gender, data.Rating, data.Created];
_save()
return {
IsOk: true
};
}
return {
IsOk: false
};
}
function _delete(id) {
for (var t = 0; t < globalData.length; t++)
if (id === globalData[t][0]) {
globalData = globalData.filter(item => item !== globalData[t]);
_save();
return {
IsOk: true
};
}
return {
IsOk: false
};
}
_loadData();
return {
getSchema: _getSchema,
find: _find,
insert: _insert,
update: _update,
delete: _delete
};
})();
|
(function() {
'use strict';
angular
.module('app.core')
.constant('STATIC_URL', '/static/js/');
})();
|
$(document).ready(function(){
//Grabs url path
var url = window.location.pathname;
//Grabs current file name from URL
var url = url.substring(url.lastIndexOf('/')+1);
// now grab every link from the navigation
$('#navigation a').each(function(){
//Grab the current elements href tag value
var link = $(this).attr("href");
//Test if the url value and element value matches
if(url === link){
//Adds class to the current item
$(this).parent('li').addClass('active');
}
});
}); |
var fixDate = function(date) {
return date.Format('2006-01-02 15:04:05');
};
var entries = executeCommand('getEntries', {});
dbotCommands = [];
userCommands = [];
for (var i = 0; i < entries.length; i++) {
if (typeof entries[i].Contents == 'string' && entries[i].Contents.indexOf('!') === 0 && entries[i].Contents.indexOf('!listExecutedCommands') !== 0) {
if (entries[i].Metadata.User) {
if (args.source === 'All' || args.source === 'Manual') {
userCommands.push({
'Time': fixDate(entries[i].Metadata.Created),
'Entry ID': entries[i].ID,
'User': entries[i].Metadata.User,
'Command': entries[i].Contents
});
}
} else {
if (args.source === 'All' || args.source === 'Playbook') {
dbotCommands.push({
'Time': fixDate(entries[i].Metadata.Created),
'Entry ID': entries[i].ID,
'Playbook (Task)': entries[i].Metadata.EntryTask.PlaybookName + " (" + entries[i].Metadata.EntryTask.TaskName + ")",
'Command': entries[i].Contents
});
}
}
}
}
var md = '';
if (dbotCommands.length > 0) {
md += tableToMarkdown('DBot Executed Commands', dbotCommands, ['Time', 'Entry ID', 'Playbook (Task)', 'Command']) + '\n';
}
if (userCommands.length > 0) {
md += tableToMarkdown('User Executed Commands', userCommands, ['Time', 'Entry ID', 'User', 'Command']) + '\n';
}
if (md === '') {
md = 'No commands found\n';
}
return {ContentsFormat: formats.markdown, Type: entryTypes.note, Contents: md};
|
'use strict';
var canUseDOM = require('./canUseDOM');
var one = function() {
};
var on = function() {
};
var off = function() {
};
if (canUseDOM) {
var bind = window.addEventListener ? 'addEventListener' : 'attachEvent';
var unbind = window.removeEventListener ? 'removeEventListener' : 'detachEvent';
var prefix = bind !== 'addEventListener' ? 'on' : '';
one = function(node, eventNames, eventListener) {
var typeArray = eventNames.split(' ');
var recursiveFunction = function(e) {
e.target.removeEventListener(e.type, recursiveFunction);
return eventListener(e);
};
for (var i = typeArray.length - 1; i >= 0; i--) {
this.on(node, typeArray[i], recursiveFunction);
}
};
/**
* Bind `node` event `eventName` to `eventListener`.
*
* @param {Element} node
* @param {String} eventName
* @param {Function} eventListener
* @param {Boolean} capture
* @return {Obejct}
* @api public
*/
on = function(node, eventName, eventListener, capture) {
node[bind](prefix + eventName, eventListener, capture || false);
return {
off: function() {
node[unbind](prefix + eventName, eventListener, capture || false);
}
};
}
/**
* Unbind `node` event `eventName`'s callback `eventListener`.
*
* @param {Element} node
* @param {String} eventName
* @param {Function} eventListener
* @param {Boolean} capture
* @return {Function}
* @api public
*/
off = function(node, eventName, eventListener, capture) {
node[unbind](prefix + eventName, eventListener, capture || false);
return eventListener;
};
}
module.exports = {
one: one,
on: on,
off: off
};
|
'use strict';
describe('angular', function() {
var element;
afterEach(function(){
dealoc(element);
});
describe('case', function() {
it('should change case', function() {
expect(lowercase('ABC90')).toEqual('abc90');
expect(manualLowercase('ABC90')).toEqual('abc90');
expect(uppercase('abc90')).toEqual('ABC90');
expect(manualUppercase('abc90')).toEqual('ABC90');
});
});
describe("copy", function() {
it("should return same object", function () {
var obj = {};
var arr = [];
expect(copy({}, obj)).toBe(obj);
expect(copy([], arr)).toBe(arr);
});
it("should copy Date", function() {
var date = new Date(123);
expect(copy(date) instanceof Date).toBeTruthy();
expect(copy(date).getTime()).toEqual(123);
expect(copy(date) === date).toBeFalsy();
});
it("should deeply copy an array into an existing array", function() {
var src = [1, {name:"value"}];
var dst = [{key:"v"}];
expect(copy(src, dst)).toBe(dst);
expect(dst).toEqual([1, {name:"value"}]);
expect(dst[1]).toEqual({name:"value"});
expect(dst[1]).not.toBe(src[1]);
});
it("should deeply copy an array into a new array", function() {
var src = [1, {name:"value"}];
var dst = copy(src);
expect(src).toEqual([1, {name:"value"}]);
expect(dst).toEqual(src);
expect(dst).not.toBe(src);
expect(dst[1]).not.toBe(src[1]);
});
it('should copy empty array', function() {
var src = [];
var dst = [{key: "v"}];
expect(copy(src, dst)).toEqual([]);
expect(dst).toEqual([]);
});
it("should deeply copy an object into an existing object", function() {
var src = {a:{name:"value"}};
var dst = {b:{key:"v"}};
expect(copy(src, dst)).toBe(dst);
expect(dst).toEqual({a:{name:"value"}});
expect(dst.a).toEqual(src.a);
expect(dst.a).not.toBe(src.a);
});
it("should deeply copy an object into an existing object", function() {
var src = {a:{name:"value"}};
var dst = copy(src, dst);
expect(src).toEqual({a:{name:"value"}});
expect(dst).toEqual(src);
expect(dst).not.toBe(src);
expect(dst.a).toEqual(src.a);
expect(dst.a).not.toBe(src.a);
});
it("should copy primitives", function() {
expect(copy(null)).toEqual(null);
expect(copy('')).toBe('');
expect(copy('lala')).toBe('lala');
expect(copy(123)).toEqual(123);
expect(copy([{key:null}])).toEqual([{key:null}]);
});
it('should throw an exception if a Scope is being copied', inject(function($rootScope) {
expect(function() { copy($rootScope.$new()); }).
toThrow("[ng:cpws] Can't copy! Making copies of Window or Scope instances is not supported.");
}));
it('should throw an exception if a Window is being copied', function() {
expect(function() { copy(window); }).
toThrow("[ng:cpws] Can't copy! Making copies of Window or Scope instances is not supported.");
});
it('should throw an exception when source and destination are equivalent', function() {
var src, dst;
src = dst = {key: 'value'};
expect(function() { copy(src, dst); }).toThrow("[ng:cpi] Can't copy! Source and destination are identical.");
src = dst = [2, 4];
expect(function() { copy(src, dst); }).toThrow("[ng:cpi] Can't copy! Source and destination are identical.");
});
it('should not copy the private $$hashKey', function() {
var src,dst;
src = {};
hashKey(src);
dst = copy(src);
expect(hashKey(dst)).not.toEqual(hashKey(src));
});
it('should retain the previous $$hashKey', function() {
var src,dst,h;
src = {};
dst = {};
// force creation of a hashkey
h = hashKey(dst);
hashKey(src);
dst = copy(src,dst);
// make sure we don't copy the key
expect(hashKey(dst)).not.toEqual(hashKey(src));
// make sure we retain the old key
expect(hashKey(dst)).toEqual(h);
});
});
describe("extend", function() {
it('should not copy the private $$hashKey', function() {
var src,dst;
src = {};
dst = {};
hashKey(src);
dst = extend(dst,src);
expect(hashKey(dst)).not.toEqual(hashKey(src));
});
it('should retain the previous $$hashKey', function() {
var src,dst,h;
src = {};
dst = {};
h = hashKey(dst);
hashKey(src);
dst = extend(dst,src);
// make sure we don't copy the key
expect(hashKey(dst)).not.toEqual(hashKey(src));
// make sure we retain the old key
expect(hashKey(dst)).toEqual(h);
});
it('should work when extending with itself', function() {
var src,dst,h;
dst = src = {};
h = hashKey(dst);
dst = extend(dst,src);
// make sure we retain the old key
expect(hashKey(dst)).toEqual(h);
});
});
describe('shallow copy', function() {
it('should make a copy', function() {
var original = {key:{}};
var copy = shallowCopy(original);
expect(copy).toEqual(original);
expect(copy.key).toBe(original.key);
});
it('should not copy $$ properties nor prototype properties', function() {
var original = {$$some: true, $$: true};
var clone = {};
expect(shallowCopy(original, clone)).toBe(clone);
expect(clone.$$some).toBeUndefined();
expect(clone.$$).toBeUndefined();
});
});
describe('elementHTML', function() {
it('should dump element', function() {
expect(startingTag('<div attr="123">something<span></span></div>')).
toEqual('<div attr="123">');
});
});
describe('equals', function() {
it('should return true if same object', function() {
var o = {};
expect(equals(o, o)).toEqual(true);
expect(equals(o, {})).toEqual(true);
expect(equals(1, '1')).toEqual(false);
expect(equals(1, '2')).toEqual(false);
});
it('should recurse into object', function() {
expect(equals({}, {})).toEqual(true);
expect(equals({name:'misko'}, {name:'misko'})).toEqual(true);
expect(equals({name:'misko', age:1}, {name:'misko'})).toEqual(false);
expect(equals({name:'misko'}, {name:'misko', age:1})).toEqual(false);
expect(equals({name:'misko'}, {name:'adam'})).toEqual(false);
expect(equals(['misko'], ['misko'])).toEqual(true);
expect(equals(['misko'], ['adam'])).toEqual(false);
expect(equals(['misko'], ['misko', 'adam'])).toEqual(false);
});
it('should ignore undefined member variables during comparison', function() {
var obj1 = {name: 'misko'},
obj2 = {name: 'misko', undefinedvar: undefined};
expect(equals(obj1, obj2)).toBe(true);
expect(equals(obj2, obj1)).toBe(true);
});
it('should ignore $ member variables', function() {
expect(equals({name:'misko', $id:1}, {name:'misko', $id:2})).toEqual(true);
expect(equals({name:'misko'}, {name:'misko', $id:2})).toEqual(true);
expect(equals({name:'misko', $id:1}, {name:'misko'})).toEqual(true);
});
it('should ignore functions', function() {
expect(equals({func: function() {}}, {bar: function() {}})).toEqual(true);
});
it('should work well with nulls', function() {
expect(equals(null, '123')).toBe(false);
expect(equals('123', null)).toBe(false);
var obj = {foo:'bar'};
expect(equals(null, obj)).toBe(false);
expect(equals(obj, null)).toBe(false);
expect(equals(null, null)).toBe(true);
});
it('should work well with undefined', function() {
expect(equals(undefined, '123')).toBe(false);
expect(equals('123', undefined)).toBe(false);
var obj = {foo:'bar'};
expect(equals(undefined, obj)).toBe(false);
expect(equals(obj, undefined)).toBe(false);
expect(equals(undefined, undefined)).toBe(true);
});
it('should treat two NaNs as equal', function() {
expect(equals(NaN, NaN)).toBe(true);
});
it('should compare Scope instances only by identity', inject(function($rootScope) {
var scope1 = $rootScope.$new(),
scope2 = $rootScope.$new();
expect(equals(scope1, scope1)).toBe(true);
expect(equals(scope1, scope2)).toBe(false);
expect(equals($rootScope, scope1)).toBe(false);
expect(equals(undefined, scope1)).toBe(false);
}));
it('should compare Window instances only by identity', function() {
expect(equals(window, window)).toBe(true);
expect(equals(window, window.parent)).toBe(false);
expect(equals(window, undefined)).toBe(false);
});
it('should compare dates', function() {
expect(equals(new Date(0), new Date(0))).toBe(true);
expect(equals(new Date(0), new Date(1))).toBe(false);
expect(equals(new Date(0), 0)).toBe(false);
expect(equals(0, new Date(0))).toBe(false);
});
it('should correctly test for keys that are present on Object.prototype', function() {
// MS IE8 just doesn't work for this kind of thing, since "for ... in" doesn't return
// things like hasOwnProperty even if it is explicitly defined on the actual object!
if (msie<=8) return;
expect(equals({}, {hasOwnProperty: 1})).toBe(false);
expect(equals({}, {toString: null})).toBe(false);
});
});
describe('size', function() {
it('should return the number of items in an array', function() {
expect(size([])).toBe(0);
expect(size(['a', 'b', 'c'])).toBe(3);
});
it('should return the number of properties of an object', function() {
expect(size({})).toBe(0);
expect(size({a:1, b:'a', c:noop})).toBe(3);
});
it('should return the number of own properties of an object', function() {
var obj = inherit({protoProp: 'c', protoFn: noop}, {a:1, b:'a', c:noop});
expect(size(obj)).toBe(5);
expect(size(obj, true)).toBe(3);
});
it('should return the string length', function() {
expect(size('')).toBe(0);
expect(size('abc')).toBe(3);
});
it('should not rely on length property of an object to determine its size', function() {
expect(size({length:99})).toBe(1);
});
});
describe('parseKeyValue', function() {
it('should parse a string into key-value pairs', function() {
expect(parseKeyValue('')).toEqual({});
expect(parseKeyValue('simple=pair')).toEqual({simple: 'pair'});
expect(parseKeyValue('first=1&second=2')).toEqual({first: '1', second: '2'});
expect(parseKeyValue('escaped%20key=escaped%20value')).
toEqual({'escaped key': 'escaped value'});
expect(parseKeyValue('emptyKey=')).toEqual({emptyKey: ''});
expect(parseKeyValue('flag1&key=value&flag2')).
toEqual({flag1: true, key: 'value', flag2: true});
});
it('should ignore key values that are not valid URI components', function() {
expect(function() { parseKeyValue('%'); }).not.toThrow();
expect(parseKeyValue('%')).toEqual({});
expect(parseKeyValue('invalid=%')).toEqual({ invalid: undefined });
expect(parseKeyValue('invalid=%&valid=good')).toEqual({ invalid: undefined, valid: 'good' });
});
it('should parse a string into key-value pairs with duplicates grouped in an array', function() {
expect(parseKeyValue('')).toEqual({});
expect(parseKeyValue('duplicate=pair')).toEqual({duplicate: 'pair'});
expect(parseKeyValue('first=1&first=2')).toEqual({first: ['1','2']});
expect(parseKeyValue('escaped%20key=escaped%20value&&escaped%20key=escaped%20value2')).
toEqual({'escaped key': ['escaped value','escaped value2']});
expect(parseKeyValue('flag1&key=value&flag1')).
toEqual({flag1: [true,true], key: 'value'});
expect(parseKeyValue('flag1&flag1=value&flag1=value2&flag1')).
toEqual({flag1: [true,'value','value2',true]});
});
});
describe('toKeyValue', function() {
it('should serialize key-value pairs into string', function() {
expect(toKeyValue({})).toEqual('');
expect(toKeyValue({simple: 'pair'})).toEqual('simple=pair');
expect(toKeyValue({first: '1', second: '2'})).toEqual('first=1&second=2');
expect(toKeyValue({'escaped key': 'escaped value'})).
toEqual('escaped%20key=escaped%20value');
expect(toKeyValue({emptyKey: ''})).toEqual('emptyKey=');
});
it('should serialize true values into flags', function() {
expect(toKeyValue({flag1: true, key: 'value', flag2: true})).toEqual('flag1&key=value&flag2');
});
it('should serialize duplicates into duplicate param strings', function() {
expect(toKeyValue({key: [323,'value',true]})).toEqual('key=323&key=value&key');
expect(toKeyValue({key: [323,'value',true, 1234]})).
toEqual('key=323&key=value&key&key=1234');
});
});
describe('forEach', function() {
it('should iterate over *own* object properties', function() {
function MyObj() {
this.bar = 'barVal';
this.baz = 'bazVal';
}
MyObj.prototype.foo = 'fooVal';
var obj = new MyObj(),
log = [];
forEach(obj, function(value, key) { log.push(key + ':' + value)});
expect(log).toEqual(['bar:barVal', 'baz:bazVal']);
});
it('should handle JQLite and jQuery objects like arrays', function() {
var jqObject = jqLite("<p><span>s1</span><span>s2</span></p>").find("span"),
log = [];
forEach(jqObject, function(value, key) { log.push(key + ':' + value.innerHTML)});
expect(log).toEqual(['0:s1', '1:s2']);
});
it('should handle NodeList objects like arrays', function() {
var nodeList = jqLite("<p><span>a</span><span>b</span><span>c</span></p>")[0].childNodes,
log = [];
forEach(nodeList, function(value, key) { log.push(key + ':' + value.innerHTML)});
expect(log).toEqual(['0:a', '1:b', '2:c']);
});
it('should handle HTMLCollection objects like arrays', function() {
document.body.innerHTML = "<p>" +
"<a name='x'>a</a>" +
"<a name='y'>b</a>" +
"<a name='x'>c</a>" +
"</p>";
var htmlCollection = document.getElementsByName('x'),
log = [];
forEach(htmlCollection, function(value, key) { log.push(key + ':' + value.innerHTML)});
expect(log).toEqual(['0:a', '1:c']);
});
it('should handle arguments objects like arrays', function() {
var args,
log = [];
(function(){ args = arguments}('a', 'b', 'c'));
forEach(args, function(value, key) { log.push(key + ':' + value)});
expect(log).toEqual(['0:a', '1:b', '2:c']);
});
it('should handle objects with length property as objects', function() {
var obj = {
'foo' : 'bar',
'length': 2
},
log = [];
forEach(obj, function(value, key) { log.push(key + ':' + value)});
expect(log).toEqual(['foo:bar', 'length:2']);
});
it('should handle objects of custom types with length property as objects', function() {
function CustomType() {
this.length = 2;
this.foo = 'bar'
}
var obj = new CustomType(),
log = [];
forEach(obj, function(value, key) { log.push(key + ':' + value)});
expect(log).toEqual(['length:2', 'foo:bar']);
});
});
describe('sortedKeys', function() {
it('should collect keys from object', function() {
expect(sortedKeys({c:0, b:0, a:0})).toEqual(['a', 'b', 'c']);
});
});
describe('encodeUriSegment', function() {
it('should correctly encode uri segment and not encode chars defined as pchar set in rfc3986',
function() {
//don't encode alphanum
expect(encodeUriSegment('asdf1234asdf')).
toEqual('asdf1234asdf');
//don't encode unreserved'
expect(encodeUriSegment("-_.!~*'() -_.!~*'()")).
toEqual("-_.!~*'()%20-_.!~*'()");
//don't encode the rest of pchar'
expect(encodeUriSegment(':@&=+$, :@&=+$,')).
toEqual(':@&=+$,%20:@&=+$,');
//encode '/', ';' and ' ''
expect(encodeUriSegment('/; /;')).
toEqual('%2F%3B%20%2F%3B');
});
});
describe('encodeUriQuery', function() {
it('should correctly encode uri query and not encode chars defined as pchar set in rfc3986',
function() {
//don't encode alphanum
expect(encodeUriQuery('asdf1234asdf')).
toEqual('asdf1234asdf');
//don't encode unreserved
expect(encodeUriQuery("-_.!~*'() -_.!~*'()")).
toEqual("-_.!~*'()+-_.!~*'()");
//don't encode the rest of pchar
expect(encodeUriQuery(':@$, :@$,')).
toEqual(':@$,+:@$,');
//encode '&', ';', '=', '+', and '#'
expect(encodeUriQuery('&;=+# &;=+#')).
toEqual('%26%3B%3D%2B%23+%26%3B%3D%2B%23');
//encode ' ' as '+'
expect(encodeUriQuery(' ')).
toEqual('++');
//encode ' ' as '%20' when a flag is used
expect(encodeUriQuery(' ', true)).
toEqual('%20%20');
//do not encode `null` as '+' when flag is used
expect(encodeUriQuery('null', true)).
toEqual('null');
//do not encode `null` with no flag
expect(encodeUriQuery('null')).
toEqual('null');
});
});
describe('angularInit', function() {
var bootstrapSpy;
var element;
beforeEach(function() {
element = {
getElementById: function (id) {
return element.getElementById[id] || [];
},
querySelectorAll: function(arg) {
return element.querySelectorAll[arg] || [];
},
getAttribute: function(name) {
return element[name];
}
};
bootstrapSpy = jasmine.createSpy('bootstrapSpy');
});
it('should do nothing when not found', function() {
angularInit(element, bootstrapSpy);
expect(bootstrapSpy).not.toHaveBeenCalled();
});
it('should look for ngApp directive as attr', function() {
var appElement = jqLite('<div ng-app="ABC"></div>')[0];
element.querySelectorAll['[ng-app]'] = [appElement];
angularInit(element, bootstrapSpy);
expect(bootstrapSpy).toHaveBeenCalledOnceWith(appElement, ['ABC']);
});
it('should look for ngApp directive in id', function() {
var appElement = jqLite('<div id="ng-app" data-ng-app="ABC"></div>')[0];
jqLite(document.body).append(appElement);
angularInit(element, bootstrapSpy);
expect(bootstrapSpy).toHaveBeenCalledOnceWith(appElement, ['ABC']);
});
it('should look for ngApp directive in className', function() {
var appElement = jqLite('<div data-ng-app="ABC"></div>')[0];
element.querySelectorAll['.ng\\:app'] = [appElement];
angularInit(element, bootstrapSpy);
expect(bootstrapSpy).toHaveBeenCalledOnceWith(appElement, ['ABC']);
});
it('should look for ngApp directive using querySelectorAll', function() {
var appElement = jqLite('<div x-ng-app="ABC"></div>')[0];
element.querySelectorAll['[ng\\:app]'] = [ appElement ];
angularInit(element, bootstrapSpy);
expect(bootstrapSpy).toHaveBeenCalledOnceWith(appElement, ['ABC']);
});
it('should bootstrap using class name', function() {
var appElement = jqLite('<div class="ng-app: ABC;"></div>')[0];
angularInit(jqLite('<div></div>').append(appElement)[0], bootstrapSpy);
expect(bootstrapSpy).toHaveBeenCalledOnceWith(appElement, ['ABC']);
});
it('should bootstrap anonymously', function() {
var appElement = jqLite('<div x-ng-app></div>')[0];
element.querySelectorAll['[x-ng-app]'] = [ appElement ];
angularInit(element, bootstrapSpy);
expect(bootstrapSpy).toHaveBeenCalledOnceWith(appElement, []);
});
it('should bootstrap anonymously using class only', function() {
var appElement = jqLite('<div class="ng-app"></div>')[0];
angularInit(jqLite('<div></div>').append(appElement)[0], bootstrapSpy);
expect(bootstrapSpy).toHaveBeenCalledOnceWith(appElement, []);
});
it('should bootstrap if the annotation is on the root element', function() {
var appElement = jqLite('<div class="ng-app"></div>')[0];
angularInit(appElement, bootstrapSpy);
expect(bootstrapSpy).toHaveBeenCalledOnceWith(appElement, []);
});
it('should complain if app module cannot be found', function() {
var appElement = jqLite('<div ng-app="doesntexist"></div>')[0];
expect(function() {
angularInit(appElement, bootstrap);
}).toThrowMatching(
/\[\$injector:modulerr] Failed to instantiate module doesntexist due to:\n.*\[\$injector:nomod] Module 'doesntexist' is not available! You either misspelled the module name or forgot to load it\./
);
});
});
describe('angular service', function() {
it('should override services', function() {
module(function($provide){
$provide.value('fake', 'old');
$provide.value('fake', 'new');
});
inject(function(fake) {
expect(fake).toEqual('new');
});
});
it('should inject dependencies specified by $inject and ignore function argument name', function() {
expect(angular.injector([function($provide){
$provide.factory('svc1', function() { return 'svc1'; });
$provide.factory('svc2', ['svc1', function(s) { return 'svc2-' + s; }]);
}]).get('svc2')).toEqual('svc2-svc1');
});
});
describe('isDate', function() {
it('should return true for Date object', function() {
expect(isDate(new Date())).toBe(true);
});
it('should return false for non Date objects', function() {
expect(isDate([])).toBe(false);
expect(isDate('')).toBe(false);
expect(isDate(23)).toBe(false);
expect(isDate({})).toBe(false);
});
});
describe('compile', function() {
it('should link to existing node and create scope', inject(function($rootScope, $compile) {
var template = angular.element('<div>{{greeting = "hello world"}}</div>');
element = $compile(template)($rootScope);
$rootScope.$digest();
expect(template.text()).toEqual('hello world');
expect($rootScope.greeting).toEqual('hello world');
}));
it('should link to existing node and given scope', inject(function($rootScope, $compile) {
var template = angular.element('<div>{{greeting = "hello world"}}</div>');
element = $compile(template)($rootScope);
$rootScope.$digest();
expect(template.text()).toEqual('hello world');
}));
it('should link to new node and given scope', inject(function($rootScope, $compile) {
var template = jqLite('<div>{{greeting = "hello world"}}</div>');
var compile = $compile(template);
var templateClone = template.clone();
element = compile($rootScope, function(clone){
templateClone = clone;
});
$rootScope.$digest();
expect(template.text()).toEqual('{{greeting = "hello world"}}');
expect(element.text()).toEqual('hello world');
expect(element).toEqual(templateClone);
expect($rootScope.greeting).toEqual('hello world');
}));
it('should link to cloned node and create scope', inject(function($rootScope, $compile) {
var template = jqLite('<div>{{greeting = "hello world"}}</div>');
element = $compile(template)($rootScope, noop);
$rootScope.$digest();
expect(template.text()).toEqual('{{greeting = "hello world"}}');
expect(element.text()).toEqual('hello world');
expect($rootScope.greeting).toEqual('hello world');
}));
});
describe('nodeName_', function() {
it('should correctly detect node name with "namespace" when xmlns is defined', function() {
var div = jqLite('<div xmlns:ngtest="http://angularjs.org/">' +
'<ngtest:foo ngtest:attr="bar"></ngtest:foo>' +
'</div>')[0];
expect(nodeName_(div.childNodes[0])).toBe('NGTEST:FOO');
expect(div.childNodes[0].getAttribute('ngtest:attr')).toBe('bar');
});
if (!msie || msie >= 9) {
it('should correctly detect node name with "namespace" when xmlns is NOT defined', function() {
var div = jqLite('<div xmlns:ngtest="http://angularjs.org/">' +
'<ngtest:foo ngtest:attr="bar"></ng-test>' +
'</div>')[0];
expect(nodeName_(div.childNodes[0])).toBe('NGTEST:FOO');
expect(div.childNodes[0].getAttribute('ngtest:attr')).toBe('bar');
});
}
});
describe('nextUid()', function() {
it('should return new id per call', function() {
var seen = {};
var count = 100;
while(count--) {
var current = nextUid();
expect(current.match(/[\d\w]+/)).toBeTruthy();
expect(seen[current]).toBeFalsy();
seen[current] = true;
}
});
});
describe('version', function() {
it('version should have full/major/minor/dot/codeName properties', function() {
expect(version).toBeDefined();
expect(version.full).toBe('"NG_VERSION_FULL"');
expect(version.major).toBe("NG_VERSION_MAJOR");
expect(version.minor).toBe("NG_VERSION_MINOR");
expect(version.dot).toBe("NG_VERSION_DOT");
expect(version.codeName).toBe('"NG_VERSION_CODENAME"');
});
});
describe('bootstrap', function() {
it('should bootstrap app', function(){
var element = jqLite('<div>{{1+2}}</div>');
var injector = angular.bootstrap(element);
expect(injector).toBeDefined();
expect(element.injector()).toBe(injector);
dealoc(element);
});
it("should complain if app module can't be found", function() {
var element = jqLite('<div>{{1+2}}</div>');
expect(function() {
angular.bootstrap(element, ['doesntexist']);
}).toThrowMatching(
/\[\$injector:modulerr\] Failed to instantiate module doesntexist due to:\n.*\[\$injector:nomod\] Module 'doesntexist' is not available! You either misspelled the module name or forgot to load it\./);
expect(element.html()).toBe('{{1+2}}');
dealoc(element);
});
describe('deferred bootstrap', function() {
var originalName = window.name,
element;
beforeEach(function() {
window.name = '';
element = jqLite('<div>{{1+2}}</div>');
});
afterEach(function() {
dealoc(element);
window.name = originalName;
});
it('should wait for extra modules', function() {
window.name = 'NG_DEFER_BOOTSTRAP!';
angular.bootstrap(element);
expect(element.html()).toBe('{{1+2}}');
angular.resumeBootstrap();
expect(element.html()).toBe('3');
expect(window.name).toEqual('');
});
it('should load extra modules', function() {
element = jqLite('<div>{{1+2}}</div>');
window.name = 'NG_DEFER_BOOTSTRAP!';
var bootstrapping = jasmine.createSpy('bootstrapping');
angular.bootstrap(element, [bootstrapping]);
expect(bootstrapping).not.toHaveBeenCalled();
expect(element.injector()).toBeUndefined();
angular.module('addedModule', []).value('foo', 'bar');
angular.resumeBootstrap(['addedModule']);
expect(bootstrapping).toHaveBeenCalledOnce();
expect(element.injector().get('foo')).toEqual('bar');
});
it('should not defer bootstrap without window.name cue', function() {
angular.bootstrap(element, []);
angular.module('addedModule', []).value('foo', 'bar');
expect(function() {
element.injector().get('foo');
}).toThrow('[$injector:unpr] Unknown provider: fooProvider <- foo');
expect(element.injector().get('$http')).toBeDefined();
});
it('should restore the original window.name after bootstrap', function() {
window.name = 'NG_DEFER_BOOTSTRAP!my custom name';
angular.bootstrap(element);
expect(element.html()).toBe('{{1+2}}');
angular.resumeBootstrap();
expect(element.html()).toBe('3');
expect(window.name).toEqual('my custom name');
});
});
});
describe('startingElementHtml', function(){
it('should show starting element tag only', function(){
expect(startingTag('<ng-abc x="2A"><div>text</div></ng-abc>')).
toBe('<ng-abc x="2A">');
});
});
describe('startingTag', function() {
it('should allow passing in Nodes instead of Elements', function() {
var txtNode = document.createTextNode('some text');
expect(startingTag(txtNode)).toBe('some text');
});
});
describe('snake_case', function(){
it('should convert to snake_case', function() {
expect(snake_case('ABC')).toEqual('a_b_c');
expect(snake_case('alanBobCharles')).toEqual('alan_bob_charles');
});
});
describe('fromJson', function() {
it('should delegate to JSON.parse', function() {
var spy = spyOn(JSON, 'parse').andCallThrough();
expect(fromJson('{}')).toEqual({});
expect(spy).toHaveBeenCalled();
});
});
describe('toJson', function() {
it('should delegate to JSON.stringify', function() {
var spy = spyOn(JSON, 'stringify').andCallThrough();
expect(toJson({})).toEqual('{}');
expect(spy).toHaveBeenCalled();
});
it('should format objects pretty', function() {
expect(toJson({a: 1, b: 2}, true)).
toBeOneOf('{\n "a": 1,\n "b": 2\n}', '{\n "a":1,\n "b":2\n}');
expect(toJson({a: {b: 2}}, true)).
toBeOneOf('{\n "a": {\n "b": 2\n }\n}', '{\n "a":{\n "b":2\n }\n}');
});
it('should not serialize properties starting with $', function() {
expect(toJson({$few: 'v', $$some:'value'}, false)).toEqual('{}');
});
it('should not serialize $window object', function() {
expect(toJson(window)).toEqual('"$WINDOW"');
});
it('should not serialize $document object', function() {
expect(toJson(document)).toEqual('"$DOCUMENT"');
});
it('should not serialize scope instances', inject(function($rootScope) {
expect(toJson({key: $rootScope})).toEqual('{"key":"$SCOPE"}');
}));
});
});
|
/**
* Logger configuration
*
* Configure the log level for your app, as well as the transport
* (Underneath the covers, Sails uses Winston for logging, which
* allows for some pretty neat custom transports/adapters for log messages)
*
* For more information on the Sails logger, check out:
* http://sailsjs.org/#documentation
*/
module.exports = {
// Valid `level` configs:
// i.e. the minimum log level to capture with sails.log.*()
//
// 'error' : Display calls to `.error()`
// 'warn' : Display calls from `.error()` to `.warn()`
// 'debug' : Display calls from `.error()`, `.warn()` to `.debug()`
// 'info' : Display calls from `.error()`, `.warn()`, `.debug()` to `.info()`
// 'verbose': Display calls from `.error()`, `.warn()`, `.debug()`, `.info()` to `.verbose()`
//
log: {
level: 'info'
}
};
|
var partialsTemp = [
"login",
"profile"
];
exports.partialRender = function (req, res) {
var pageIndex = req.params[0];
if (partialsTemp.indexOf("" + pageIndex) > -1) {
res.render("partials/" + pageIndex, {});
} else {
res.render("common/404", {});
}
}; |
/*
* The MIT License
*
* Copyright 2015 Eduardo Weiland.
*
* 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.
*/
define(['knockout', 'grammar', 'productionrule', 'utils'], function(ko, Grammar, ProductionRule, utils) {
'use strict';
/**
* Encontra todos os símbolos não-terminais inalcançáveis dentro de uma gramática.
*
* @param {Grammar} grammar Gramática para ser verificada.
* @return {string[]} Lista de símbolos inalcançáveis.
*/
function findUnreachableSymbols(grammar) {
var unreachable = [],
nt = grammar.nonTerminalSymbols(),
s = grammar.productionStartSymbol();
for (var i = 0, l = nt.length; i < l; ++i) {
// Ignora símbolo de início de produção
if (nt[i] === s) {
continue;
}
var found = false;
for (var j = 0, k = nt.length; j < k && !found; ++j) {
if (i === j) {
// Ignora produções do próprio símbolo
continue;
}
var prods = grammar.getProductions(nt[j]);
for (var x = 0, y = prods.length; x < y; ++x) {
if (prods[x].indexOf(nt[i]) !== -1) {
found = true;
break;
}
}
}
if (!found) {
unreachable.push(nt[i]);
}
}
return unreachable;
}
function findSterileSymbols(grammar) {
var steriles = [],
rules = grammar.productionRules();
for (var i = 0, l = rules.length; i < l; ++i) {
var found = false,
left = rules[i].leftSide(),
right = rules[i].rightSide();
for (var j = 0, k = right.length; j < k && !found; ++j) {
if (right[j].indexOf(left) === -1) {
found = true;
break;
}
}
if (!found) {
steriles.push(left);
}
}
return steriles;
}
/**
* Substitui símbolos não terminais no começo de todas as produções pelas suas produções.
*
* @param {Grammar} grammar Gramática para ser modificada.
* @return {ProductionRule[]} Regras de produção modificadas.
*/
function replaceStartingSymbols(grammar) {
var rules = grammar.productionRules();
var nt = grammar.nonTerminalSymbols();
var s = grammar.productionStartSymbol();
for (var i = 0, l = rules.length; i < l; ++i) {
var left = rules[i].leftSide();
if (left === s) {
// Ignora produção inicial
continue;
}
var prods = rules[i].rightSide();
// Não usa cache do length porque o array é modificado internamente
for (var j = 0; j < prods.length; ++j) {
if ( (prods[j][0] === left) || (nt.indexOf(prods[j][0]) === -1) ) {
// Produção começa com o próprio símbolo não-terminal (recursivo) ou
// não começa com nenhum símbolo não-terminal, ignora as substituições
continue;
}
var otherProds = grammar.getProductions(prods[j][0]);
var rest = prods[j].substr(1);
for (var k = 0, m = otherProds.length; k < m; ++k) {
otherProds[k] = otherProds[k] + rest;
}
// Remove a produção que começa com não-terminal e adiciona as novas produções no lugar
prods.splice.apply(prods, [j--, 1].concat(otherProds));
}
}
return rules;
}
return {
/**
* Remove símbolos inúteis de uma gramática.
*
* @param {Grammar} grammar Gramática de entrada.
* @return {Grammar} Uma nova gramática sem os simbolos inúteis.
*/
removeUselessSymbols: function(grammar) {
var newGrammar = new Grammar(ko.toJS(grammar));
var sterile = findSterileSymbols(newGrammar),
unreachable = findUnreachableSymbols(newGrammar),
useless = utils.arrayUnion(sterile, unreachable),
nt = newGrammar.nonTerminalSymbols();
// Remove os símbolos inalcançáveis...
newGrammar.nonTerminalSymbols(utils.arrayRemove(nt, utils.arrayUnion(sterile, unreachable)));
newGrammar.removeSymbolRules(useless);
// .. e as produções em que eles aparecem
var rules = newGrammar.productionRules();
for (var i = 0, l = rules.length; i < l; ++i) {
var right = rules[i].rightSide();
for (var j = 0, m = useless.length; j < m; ++j) {
for (var k = 0; k < right.length; ++k) {
if (right[k].indexOf(useless[j]) !== -1) {
right.splice(k--, 1);
}
}
}
rules[i].rightSide(utils.arrayUnique(right));
}
newGrammar.productionRules(rules);
return newGrammar;
},
/**
* Remove produções vazias de uma gramática.
*
* @param {Grammar} grammar Gramática de entrada.
* @return {Grammar} Uma nova gramática sem as produções vazias.
*/
removeEmptyProductions: function(grammar) {
var newGrammar = new Grammar(ko.toJS(grammar));
var newStart;
var rules = newGrammar.productionRules();
for (var i = 0, l = rules.length; i < l; ++i) {
var left = rules[i].leftSide();
var right = rules[i].rightSide();
var emptyIndex = right.indexOf(ProductionRule.EPSILON);
if (emptyIndex === -1) {
// Essa regra não possui produção vazia, ignora e testa a próxima
continue;
}
if (left === newGrammar.productionStartSymbol()) {
// Início de produção pode gerar sentença vazia, então trata o caso especial
newStart = new ProductionRule(newGrammar, {
leftSide: left + "'",
rightSide: [left, ProductionRule.EPSILON]
});
}
// Encontra todas as outras regras que produzem esse símbolo e adiciona uma nova
// produção sem esse símbolo
for (var j = 0; j < l; ++j) {
var rightOther = rules[j].rightSide();
for (var k = 0, m = rightOther.length; k < m; ++k) {
if (rightOther[k].indexOf(left) !== -1) {
rightOther.push(rightOther[k].replace(new RegExp(left, 'g'), ''));
}
}
rules[j].rightSide(utils.arrayUnique(rightOther));
}
right.splice(emptyIndex, 1);
rules[i].rightSide(utils.arrayUnique(right));
}
if (newStart) {
rules.unshift(newStart);
newGrammar.productionStartSymbol(newStart.leftSide());
newGrammar.nonTerminalSymbols([newStart.leftSide()].concat(newGrammar.nonTerminalSymbols()));
}
newGrammar.productionRules(rules);
return newGrammar;
},
/**
* Fatora uma gramática.
*
* @param {Grammar} grammar Gramática de entrada.
* @return {Grammar} Uma nova gramática fatorada.
*/
factor: function(grammar) {
var newGrammar = new Grammar(ko.toJS(grammar));
var rules = replaceStartingSymbols(newGrammar);
var newRules = [];
for (var i = 0; i < rules.length; ++i) {
var left = rules[i].leftSide();
var right = rules[i].rightSide();
var newRight = [];
var firstSymbolGrouped = {};
// Percorre todos as produções verificando quais precisam ser fatoradas
for (var j = 0, l = right.length; j < l; ++j) {
if (right[j].length === 1) {
// Produções com apenas um símbolo são deixadas como estão
newRight.push(right[j]);
}
else {
// Agrupa todas as produções que começam com o mesmo símbolo terminal
var firstSymbol = right[j][0];
if (!firstSymbolGrouped[firstSymbol]) {
firstSymbolGrouped[firstSymbol] = [];
}
firstSymbolGrouped[firstSymbol].push(right[j].substr(1));
}
}
// Adiciona a produção na mesma ordem que estava antes, antes das novas produções serem adicionadas
newRules.push(rules[i]);
for (var j in firstSymbolGrouped) {
if (firstSymbolGrouped[j].length > 1) {
// Mais de uma produção começando com o mesmo símbolo terminal
var newSymbol = newGrammar.createNonTerminalSymbol(left);
newRight.push(j + newSymbol);
newRules.push(new ProductionRule(newGrammar, {
leftSide: newSymbol,
rightSide: firstSymbolGrouped[j]
}));
}
else {
// Senão, é apenas uma produção (índice 0), mantém ela no mesmo lugar
newRight.push(j + firstSymbolGrouped[j][0]);
}
}
// Atualiza as produções para o símbolo existente
rules[i].rightSide(utils.arrayUnique(newRight));
}
newGrammar.productionRules(newRules);
return newGrammar;
},
/**
* Remove recursão à esquerda de uma gramática.
*
* @param {Grammar} grammar Gramática de entrada.
* @return {Grammar} Uma nova gramática sem recursão à esquerda.
*/
removeLeftRecursion: function(grammar) {
var newGrammar = new Grammar(ko.toJS(grammar));
var rules = newGrammar.productionRules();
var newRules = [];
for (var i = 0, l = rules.length; i < l; ++i) {
var left = rules[i].leftSide();
var prods = rules[i].rightSide();
var recursives = [];
// Adiciona a produção na mesma ordem que estava antes, antes das nova produção ser adicionada
newRules.push(rules[i]);
// Não usa cache do length porque o array é modificado internamente
for (var j = 0; j < prods.length; ++j) {
if (prods[j][0] === left && prods[j].length > 1) {
// Encontrou produção recursiva, cria uma nova regra
var newSymbol = newGrammar.createNonTerminalSymbol(left);
recursives.push(newSymbol);
newRules.push(new ProductionRule(newGrammar, {
leftSide: newSymbol,
rightSide: [prods[j].substr(1) + newSymbol, ProductionRule.EPSILON]
}));
// Remove essa produção
prods.splice(j--, 1);
}
}
var newProds = [];
if (recursives.length === 0) {
newProds = prods.slice();
}
else {
for (var j = 0; j < prods.length; ++j) {
for (var k = 0; k < recursives.length; ++k) {
newProds.push(prods[j] + recursives[k]);
}
}
}
rules[i].rightSide(newProds);
}
newGrammar.productionRules(newRules);
return newGrammar;
}
};
});
|
/**
* Uploader implementation - with the Connection object in ExtJS 4
*
*/
Ext.define('MyApp.ux.panel.upload.uploader.ExtJsUploader', {
extend : 'MyApp.ux.panel.upload.uploader.AbstractXhrUploader',
requires : [ 'MyApp.ux.panel.upload.data.Connection' ],
config : {
/**
* @cfg {String} [method='PUT']
*
* The HTTP method to be used.
*/
method : 'PUT',
/**
* @cfg {Ext.data.Connection}
*
* If set, this connection object will be used when uploading files.
*/
connection : null
},
/**
* @property
* @private
*
* The connection object.
*/
conn : null,
/**
* @private
*
* Initializes and returns the connection object.
*
* @return {MyApp.ux.panel.upload.data.Connection}
*/
initConnection : function() {
var conn, url = this.url;
console.log('[ExtJsUploader initConnection params', this.params);
if (this.connection instanceof Ext.data.Connection) {
console.log('[ExtJsUploader] instanceof Connection');
conn = this.connection;
} else {
console.log('[ExtJsUploader] !! instanceof Connection');
if (this.params) {
url = Ext.urlAppend(url, Ext.urlEncode(this.params));
}
conn = Ext.create('MyApp.ux.panel.upload.data.Connection', {
disableCaching : true,
method : this.method,
url : url,
timeout : this.timeout,
defaultHeaders : {
'Content-Type' : this.contentType,
'X-Requested-With' : 'XMLHttpRequest'
}
});
}
return conn;
},
/**
* @protected
*/
initHeaders : function(item) {
console.log('[ExtJsUploader] initHeaders', item);
var headers = this.callParent(arguments);
headers['Content-Type'] = item.getType();
return headers;
},
/**
* Implements {@link MyApp.ux.panel.upload.uploader.AbstractUploader#uploadItem}
*
* @param {MyApp.ux.panel.upload.Item}
* item
*/
uploadItem : function(item) {
console.log('ExtJsUploader uploadItem', item);
var file = item.getFileApiObject();
if (!file) {
return;
}
item.setUploading();
// tony
this.params = {
folder : item.getRemoteFolder()
};
this.conn = this.initConnection();
/*
* Passing the File object directly as the "rawData" option. Specs: https://dvcs.w3.org/hg/xhr/raw-file/tip/Overview.html#the-send()-method
* http://dev.w3.org/2006/webapi/FileAPI/#blob
*/
console.log('ExtJsUploader conn', this.conn);
this.conn.request({
scope : this,
headers : this.initHeaders(item),
rawData : file,
timeout : MyApp.Const.JAVASCRIPT_MAX_NUMBER, // tony
success : Ext.Function.bind(this.onUploadSuccess, this, [ item ], true),
failure : Ext.Function.bind(this.onUploadFailure, this, [ item ], true),
progress : Ext.Function.bind(this.onUploadProgress, this, [ item ], true)
});
},
/**
* Implements {@link MyApp.ux.panel.upload.uploader.AbstractUploader#abortUpload}
*/
abortUpload : function() {
if (this.conn) {
/*
* If we don't suspend the events, the connection abortion will cause a failure event.
*/
this.suspendEvents();
console.log('abort conn', conn);
this.conn.abort();
this.resumeEvents();
}
}
});
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M9 10v4c0 .55.45 1 1 1s1-.45 1-1V4h2v10c0 .55.45 1 1 1s1-.45 1-1V4h1c.55 0 1-.45 1-1s-.45-1-1-1H9.17C7.08 2 5.22 3.53 5.02 5.61 4.79 7.99 6.66 10 9 10zm11.65 7.65-2.79-2.79c-.32-.32-.86-.1-.86.35V17H6c-.55 0-1 .45-1 1s.45 1 1 1h11v1.79c0 .45.54.67.85.35l2.79-2.79c.2-.19.2-.51.01-.7z"
}), 'FormatTextdirectionLToRRounded');
exports.default = _default; |
var jazz = require("../lib/jazz");
var fs = require("fs");
var data = fs.readFileSync(__dirname + "/foreach_object.jazz", "utf8");
var template = jazz.compile(data);
template.eval({"doc": {
"title": "First",
"content": "Some content"
}}, function(data) { console.log(data); });
|
/**********************************************************************
map_GoogleV2.js
$Comment: provides JavaScript for Google Api V2 calls
$Source :map_GoogleV2.js,v $
$InitialAuthor: guenter richter $
$InitialDate: 2011/01/03 $
$Author: guenter richter $
$Id:map_GoogleV2.js 1 2011-01-03 10:30:35Z Guenter Richter $
Copyright (c) Guenter Richter
$Log:map_GoogleV2.js,v $
**********************************************************************/
/**
* @fileoverview This is the interface to the Google maps API v2
*
* @author Guenter Richter [email protected]
* @version 0.9
*/
/* ...................................................................*
* global vars *
* ...................................................................*/
/* ...................................................................*
* Google directions *
* ...................................................................*/
function __directions_handleErrors(){
var result = $("#directions-result")[0];
if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
result.innerHTML = ("Indirizzo sconosciuto. Forse è troppo nuovo o sbagliato.\n Codice errore: " + gdir.getStatus().code);
else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
result.innerHTML = ("Richiesta non riuscita.\n Codice errore: " + gdir.getStatus().code);
else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
result.innerHTML = ("Inserire indirizzi! \n Codice errore: " + gdir.getStatus().code);
else if (gdir.getStatus().code == G_GEO_BAD_KEY)
result.innerHTML = ("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);
else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
result.innerHTML = ("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
else result.innerHTML = ("Errore sconosciuto!");
}
function _map_setDirections(map,fromAddress, toAddress, toHidden, locale) {
var result = $("#directions-result")[0];
result.innerHTML = "";
gdir.loadFromWaypoints([fromAddress,toHidden],
{ "locale": locale, "preserveViewport":true });
}
function _map_setDestinationWaypoint(marker){
if ( marker ){
var form = $("#directionsform")[0];
if ( form ){
form.to.value = marker.data.name;
if ( marker.getLatLng ){
form.toHidden.value = marker.getLatLng();
}
else if( marker.getVertex ){
form.toHidden.value = marker.getVertex(0);
}
}
}
}
/**
* Is called 'onload' to start creating the map
*/
function _map_loadMap(target){
var __map = null;
// if google maps API v2 is loaded
if ( GMap2 ){
// check if browser can handle Google Maps
if ( !GBrowserIsCompatible()) {
alert("sorry - your browser cannot handle Google Maps !");
return null;
}
__map = new GMap2(target);
if ( __map ){
// configure user map interface
__map.addControl(new GMapTypeControl());
// map.addControl(new GMenuMapTypeControl());
__map.addControl(new GLargeMapControl3D());
__map.addControl(new GScaleControl());
__map.addMapType(G_PHYSICAL_MAP);
__map.addMapType(G_SATELLITE_3D_MAP);
__map.enableDoubleClickZoom();
__map.enableScrollWheelZoom();
}
}
return __map;
}
/**
* Is called to set up directions query
*/
function _map_addDirections(map,target){
if (map){
gdir = new GDirections(map,target);
GEvent.addListener(gdir, "error", __directions_handleErrors);
}
}
/**
* Is called to set up traffic information layer
*/
function _map_addTrafficLayer(map,target){
/* tbd */
}
/**
* Is called to set event handler
*/
function _map_addEventListner(map,szEvent,callback,mapUp){
if (map){
GEvent.addListener(map, szEvent, GEvent.callback(map,callback,mapUp) );
}
}
/**
* Is called 'onunload' to clear objects
*/
function _map_unloadMap(map){
if (map){
GUnload();
}
}
// set map center and zoom
//
function _map_setMapExtension(map,bBox){
if (map){
var mapCenter = { lon: (bBox[0] + (bBox[1]-bBox[0])/2) , lat: (bBox[2] + (bBox[3]-bBox[2])/2) };
var mapZoom = map.getBoundsZoomLevel(new GLatLngBounds( new GLatLng(bBox[2],bBox[0]),
new GLatLng(bBox[3],bBox[1]) ) );
map.setCenter(new GLatLng(mapCenter.lat, mapCenter.lon), mapZoom);
}
}
// get map zoom
//
function _map_getZoom(map){
if (map){
return map.getZoom();
}
return 0;
}
// get map center
//
function _map_getCenter(map){
if (map){
return map.getCenter();
}
return null;
}
// set map zoom
//
function _map_setZoom(map,nZoom){
if (map){
map.setZoom(nZoom);
}
}
// set map center
//
function _map_setCenter(map,center){
if (map){
map.setCenter(center);
}
}
// set map center and zoom
//
function _map_setCenterAndZoom(map,center,nZoom){
if (map){
map.setCenter(center,nZoom);
}
}
// create custom tooltip
//
function _map_createMyTooltip(marker, text, padding){
var tooltip = new Tooltip(marker, text, padding);
marker.tooltip = tooltip;
map.addOverlay(tooltip);
}
function _map_createMyTooltipListener(element, tooltip){
GEvent.addDomListener(element,'mouseover',GEvent.callback(tooltip,
Tooltip.prototype.show));
GEvent.addDomListener(element,'mouseout',GEvent.callback(tooltip,
Tooltip.prototype.hide));
}
// -----------------------------
// EOF
// -----------------------------
|
import InputValidator from "../../common/js/InputValidator.js";
import ObjectUtilities from "../../common/js/ObjectUtilities.js";
import Action from "./Action.js";
import DefaultFilters from "./DefaultFilters.js";
import InitialState from "./InitialState.js";
var Reducer = {};
Reducer.root = function(state, action)
{
LOGGER.debug("root() type = " + action.type);
if (typeof state === 'undefined')
{
return new InitialState();
}
var newFilters, newFilteredTableRow;
switch (action.type)
{
case Action.REMOVE_FILTERS:
newFilteredTableRow = [];
newFilteredTableRow = newFilteredTableRow.concat(state.tableRows);
return Object.assign(
{}, state,
{
filteredTableRows: newFilteredTableRow,
});
case Action.SET_DEFAULT_FILTERS:
newFilters = DefaultFilters.create();
return Object.assign(
{}, state,
{
filters: newFilters,
});
case Action.SET_FILTERS:
LOGGER.debug("Reducer filters = ");
Object.getOwnPropertyNames(action.filters).forEach(function(propertyName)
{
LOGGER.debug(propertyName + ": " + action.filters[propertyName]);
});
newFilters = Object.assign(
{}, state.filters);
newFilters = ObjectUtilities.merge(newFilters, action.filters);
newFilteredTableRow = Reducer.filterTableRow(state.tableRows, newFilters);
Reducer.saveToLocalStorage(newFilters);
return Object.assign(
{}, state,
{
filters: newFilters,
filteredTableRows: newFilteredTableRow,
});
case Action.TOGGLE_FILTER_SHOWN:
return Object.assign(
{}, state,
{
isFilterShown: !state.isFilterShown,
});
default:
LOGGER.warn("Reducer.root: Unhandled action type: " + action.type);
return state;
}
};
Reducer.filterTableRow = function(tableRows, filters)
{
InputValidator.validateNotNull("tableRows", tableRows);
InputValidator.validateNotNull("filters", filters);
var answer = [];
tableRows.forEach(function(data)
{
if (Reducer.passes(data, filters))
{
answer.push(data);
}
});
return answer;
};
Reducer.passes = function(data, filters)
{
InputValidator.validateNotNull("data", data);
InputValidator.validateNotNull("filters", filters);
var answer = true;
var propertyNames = Object.getOwnPropertyNames(filters);
for (var i = 0; i < propertyNames.length; i++)
{
var propertyName = propertyNames[i];
var filter = filters[propertyName];
if (!filter.passes(data))
{
answer = false;
break;
}
}
return answer;
};
Reducer.saveToLocalStorage = function(filters)
{
InputValidator.validateNotNull("filters", filters);
var filterObjects = [];
Object.getOwnPropertyNames(filters).forEach(function(columnKey)
{
var filter = filters[columnKey];
filterObjects.push(filter.toObject());
});
localStorage.filters = JSON.stringify(filterObjects);
};
export default Reducer; |
ig.module(
'plusplus.config-user'
)
.defines(function() {
/**
* User configuration of Impact++.
* <span class="alert alert-info"><strong>Tip:</strong> it is recommended to modify this configuration file!</span>
* @example
* // in order to add your own custom configuration to Impact++
* // edit the file defining ig.CONFIG_USER, 'plusplus/config-user.js'
* // ig.CONFIG_USER is never modified by Impact++ (it is strictly for your use)
* // ig.CONFIG_USER is automatically merged over Impact++'s config
* @static
* @readonly
* @memberof ig
* @namespace ig.CONFIG_USER
* @author Collin Hover - collinhover.com
**/
ig.CONFIG_USER = {
// no need to do force entity extended checks, we won't mess it up
// because we know to have our entities extend ig.EntityExtended
FORCE_ENTITY_EXTENDED: false,
// auto sort
AUTO_SORT_LAYERS: true,
// fullscreen!
GAME_WIDTH_PCT: 1,
GAME_HEIGHT_PCT: 1,
// dynamic scaling based on dimensions in view (resolution independence)
GAME_WIDTH_VIEW: 352,
GAME_HEIGHT_VIEW: 208,
// clamped scaling is still dynamic, but within a range
// so we can't get too big or too small
SCALE_MIN: 1,
SCALE_MAX: 4,
// camera flexibility and smoothness
CAMERA: {
// keep the camera within the level
// (whenever possible)
//KEEP_INSIDE_LEVEL: true,
KEEP_CENTERED: false,
LERP: 0.025,
// trap helps with motion sickness
BOUNDS_TRAP_AS_PCT: true,
BOUNDS_TRAP_PCT_MINX: -0.2,
BOUNDS_TRAP_PCT_MINY: -0.3,
BOUNDS_TRAP_PCT_MAXX: 0.2,
BOUNDS_TRAP_PCT_MAXY: 0.3
},
// font and text settings
FONT: {
MAIN_NAME: "font_helloplusplus_white_16.png",
ALT_NAME: "font_helloplusplus_white_8.png",
CHAT_NAME: "font_helloplusplus_black_8.png",
// we can have the font be scaled relative to system
SCALE_OF_SYSTEM_SCALE: 0.5,
// and force a min / max
SCALE_MIN: 1,
SCALE_MAX: 2
},
// text bubble settings
TEXT_BUBBLE: {
// match the visual style
PIXEL_PERFECT: true
},
UI: {
// sometimes, we want to keep things at a static scale
// for example, UI is a possible target
SCALE: 3,
IGNORE_SYSTEM_SCALE: true
},
/*
// to try dynamic clamped UI scaling
// uncomment below and delete the UI settings above
UI: {
SCALE_MIN: 2,
SCALE_MAX: 4
}
*/
// UI should persist across all levels
UI_LAYER_CLEAR_ON_LOAD: false,
CHARACTER: {
// add some depth using offset
SIZE_OFFSET_X: 8,
SIZE_OFFSET_Y: 4
}
};
});
|
'use strict'
const path = require('path')
const hbs = require('express-hbs')
module.exports = function (app, express) {
hbs.registerHelper('asset', require('./helpers/asset'))
app.engine('hbs', hbs.express4({
partialsDir: path.resolve('app/client/views/partials'),
layoutsDir: path.resolve('app/client/views/layouts'),
beautify: app.locals.isProduction
}))
app.set('view engine', 'hbs')
app.set('views', path.resolve('app/client/views'))
app.use(express.static(path.resolve('app/public')))
return app
}
|
// Polyfills
if ( Number.EPSILON === undefined ) {
Number.EPSILON = Math.pow( 2, - 52 );
}
if ( Number.isInteger === undefined ) {
// Missing in IE
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger
Number.isInteger = function ( value ) {
return typeof value === 'number' && isFinite( value ) && Math.floor( value ) === value;
};
}
//
if ( Math.sign === undefined ) {
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
Math.sign = function ( x ) {
return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : + x;
};
}
if ( 'name' in Function.prototype === false ) {
// Missing in IE
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
Object.defineProperty( Function.prototype, 'name', {
get: function () {
return this.toString().match( /^\s*function\s*([^\(\s]*)/ )[ 1 ];
}
} );
}
if ( Object.assign === undefined ) {
// Missing in IE
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
Object.assign = function ( target ) {
'use strict';
if ( target === undefined || target === null ) {
throw new TypeError( 'Cannot convert undefined or null to object' );
}
const output = Object( target );
for ( let index = 1; index < arguments.length; index ++ ) {
const source = arguments[ index ];
if ( source !== undefined && source !== null ) {
for ( const nextKey in source ) {
if ( Object.prototype.hasOwnProperty.call( source, nextKey ) ) {
output[ nextKey ] = source[ nextKey ];
}
}
}
}
return output;
};
}
|
import supertest from 'supertest';
import { publicChannelName, privateChannelName } from './channel.js';
import { roleNameUsers, roleNameSubscriptions, roleScopeUsers, roleScopeSubscriptions, roleDescription } from './role.js';
import { username, email, adminUsername, adminPassword } from './user.js';
export const request = supertest('http://localhost:3000');
const prefix = '/api/v1/';
export function wait(cb, time) {
return () => setTimeout(cb, time);
}
export const apiUsername = `api${ username }`;
export const apiEmail = `api${ email }`;
export const apiPublicChannelName = `api${ publicChannelName }`;
export const apiPrivateChannelName = `api${ privateChannelName }`;
export const apiRoleNameUsers = `api${ roleNameUsers }`;
export const apiRoleNameSubscriptions = `api${ roleNameSubscriptions }`;
export const apiRoleScopeUsers = `${ roleScopeUsers }`;
export const apiRoleScopeSubscriptions = `${ roleScopeSubscriptions }`;
export const apiRoleDescription = `api${ roleDescription }`;
export const reservedWords = [
'admin',
'administrator',
'system',
'user',
];
export const targetUser = {};
export const channel = {};
export const group = {};
export const message = {};
export const directMessage = {};
export const integration = {};
export const credentials = {
'X-Auth-Token': undefined,
'X-User-Id': undefined,
};
export const login = {
user: adminUsername,
password: adminPassword,
};
export function api(path) {
return prefix + path;
}
export function methodCall(methodName) {
return api(`method.call/${ methodName }`);
}
export function log(res) {
console.log(res.req.path);
console.log({
body: res.body,
headers: res.headers,
});
}
export function getCredentials(done = function() {}) {
request.post(api('login'))
.send(login)
.expect('Content-Type', 'application/json')
.expect(200)
.expect((res) => {
credentials['X-Auth-Token'] = res.body.data.authToken;
credentials['X-User-Id'] = res.body.data.userId;
})
.end(done);
}
|
'use strict';
// https://github.com/betsol/gulp-require-tasks
// Require the module.
const gulpRequireTasks = require('gulp-require-tasks');
const gulp = require('gulp');
const env = require('../index');
// Call it when necessary.
gulpRequireTasks({
// Pass any options to it. Please see below.
path: env.inConfigs('gulp', 'tasks')// This is default
});
gulp.task('default', ['scripts:build', 'json-copy:build']);
|
/* @flow */
"use strict";
var _inherits = require("babel-runtime/helpers/inherits")["default"];
var _classCallCheck = require("babel-runtime/helpers/class-call-check")["default"];
var _getIterator = require("babel-runtime/core-js/get-iterator")["default"];
var _Object$assign = require("babel-runtime/core-js/object/assign")["default"];
var _interopRequireDefault = require("babel-runtime/helpers/interop-require-default")["default"];
var _interopRequireWildcard = require("babel-runtime/helpers/interop-require-wildcard")["default"];
exports.__esModule = true;
var _repeating = require("repeating");
var _repeating2 = _interopRequireDefault(_repeating);
var _buffer = require("./buffer");
var _buffer2 = _interopRequireDefault(_buffer);
var _node = require("./node");
var _node2 = _interopRequireDefault(_node);
var _babelTypes = require("babel-types");
var t = _interopRequireWildcard(_babelTypes);
var Printer = (function (_Buffer) {
_inherits(Printer, _Buffer);
function Printer() {
_classCallCheck(this, Printer);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_Buffer.call.apply(_Buffer, [this].concat(args));
this.insideAux = false;
this.printAuxAfterOnNextUserNode = false;
}
Printer.prototype.print = function print(node, parent) {
var opts = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
if (!node) return;
if (parent && parent._compact) {
node._compact = true;
}
var oldInAux = this.insideAux;
this.insideAux = !node.loc;
var oldConcise = this.format.concise;
if (node._compact) {
this.format.concise = true;
}
var printMethod = this[node.type];
if (!printMethod) {
throw new ReferenceError("unknown node of type " + JSON.stringify(node.type) + " with constructor " + JSON.stringify(node && node.constructor.name));
}
if (node.loc) this.printAuxAfterComment();
this.printAuxBeforeComment(oldInAux);
var needsParens = _node2["default"].needsParens(node, parent);
if (needsParens) this.push("(");
this.printLeadingComments(node, parent);
this.catchUp(node);
this._printNewline(true, node, parent, opts);
if (opts.before) opts.before();
this.map.mark(node, "start");
this._print(node, parent);
this.printTrailingComments(node, parent);
if (needsParens) this.push(")");
// end
this.map.mark(node, "end");
if (opts.after) opts.after();
this.format.concise = oldConcise;
this.insideAux = oldInAux;
this._printNewline(false, node, parent, opts);
};
Printer.prototype.printAuxBeforeComment = function printAuxBeforeComment(wasInAux) {
var comment = this.format.auxiliaryCommentBefore;
if (!wasInAux && this.insideAux) {
this.printAuxAfterOnNextUserNode = true;
if (comment) this.printComment({
type: "CommentBlock",
value: comment
});
}
};
Printer.prototype.printAuxAfterComment = function printAuxAfterComment() {
if (this.printAuxAfterOnNextUserNode) {
this.printAuxAfterOnNextUserNode = false;
var comment = this.format.auxiliaryCommentAfter;
if (comment) this.printComment({
type: "CommentBlock",
value: comment
});
}
};
Printer.prototype.getPossibleRaw = function getPossibleRaw(node) {
var extra = node.extra;
if (extra && extra.raw != null && extra.rawValue != null && node.value === extra.rawValue) {
return extra.raw;
}
};
Printer.prototype._print = function _print(node, parent) {
var extra = this.getPossibleRaw(node);
if (extra) {
this.push("");
this._push(extra);
} else {
var printMethod = this[node.type];
printMethod.call(this, node, parent);
}
};
Printer.prototype.printJoin = function printJoin(nodes /*: ?Array*/, parent /*: Object*/) {
// istanbul ignore next
var _this = this;
var opts = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
if (!nodes || !nodes.length) return;
var len = nodes.length;
var node = undefined,
i = undefined;
if (opts.indent) this.indent();
var printOpts = {
statement: opts.statement,
addNewlines: opts.addNewlines,
after: function after() {
if (opts.iterator) {
opts.iterator(node, i);
}
if (opts.separator && i < len - 1) {
_this.push(opts.separator);
}
}
};
for (i = 0; i < nodes.length; i++) {
node = nodes[i];
this.print(node, parent, printOpts);
}
if (opts.indent) this.dedent();
};
Printer.prototype.printAndIndentOnComments = function printAndIndentOnComments(node, parent) {
var indent = !!node.leadingComments;
if (indent) this.indent();
this.print(node, parent);
if (indent) this.dedent();
};
Printer.prototype.printBlock = function printBlock(parent) {
var node = parent.body;
if (t.isEmptyStatement(node)) {
this.semicolon();
} else {
this.push(" ");
this.print(node, parent);
}
};
Printer.prototype.generateComment = function generateComment(comment) {
var val = comment.value;
if (comment.type === "CommentLine") {
val = "//" + val;
} else {
val = "/*" + val + "*/";
}
return val;
};
Printer.prototype.printTrailingComments = function printTrailingComments(node, parent) {
this.printComments(this.getComments("trailingComments", node, parent));
};
Printer.prototype.printLeadingComments = function printLeadingComments(node, parent) {
this.printComments(this.getComments("leadingComments", node, parent));
};
Printer.prototype.printInnerComments = function printInnerComments(node) {
var indent = arguments.length <= 1 || arguments[1] === undefined ? true : arguments[1];
if (!node.innerComments) return;
if (indent) this.indent();
this.printComments(node.innerComments);
if (indent) this.dedent();
};
Printer.prototype.printSequence = function printSequence(nodes, parent) {
var opts = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
opts.statement = true;
return this.printJoin(nodes, parent, opts);
};
Printer.prototype.printList = function printList(items, parent) {
var opts = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
if (opts.separator == null) {
opts.separator = ",";
if (!this.format.compact) opts.separator += " ";
}
return this.printJoin(items, parent, opts);
};
Printer.prototype._printNewline = function _printNewline(leading, node, parent, opts) {
if (!opts.statement && !_node2["default"].isUserWhitespacable(node, parent)) {
return;
}
var lines = 0;
if (node.start != null && !node._ignoreUserWhitespace && this.tokens.length) {
// user node
if (leading) {
lines = this.whitespace.getNewlinesBefore(node);
} else {
lines = this.whitespace.getNewlinesAfter(node);
}
} else {
// generated node
if (!leading) lines++; // always include at least a single line after
if (opts.addNewlines) lines += opts.addNewlines(leading, node) || 0;
var needs = _node2["default"].needsWhitespaceAfter;
if (leading) needs = _node2["default"].needsWhitespaceBefore;
if (needs(node, parent)) lines++;
// generated nodes can't add starting file whitespace
if (!this.buf) lines = 0;
}
this.newline(lines);
};
Printer.prototype.getComments = function getComments(key, node) {
return node && node[key] || [];
};
Printer.prototype.shouldPrintComment = function shouldPrintComment(comment) {
if (this.format.shouldPrintComment) {
return this.format.shouldPrintComment(comment.value);
} else {
if (comment.value.indexOf("@license") >= 0 || comment.value.indexOf("@preserve") >= 0) {
return true;
} else {
return this.format.comments;
}
}
};
Printer.prototype.printComment = function printComment(comment) {
if (!this.shouldPrintComment(comment)) return;
if (comment.ignore) return;
comment.ignore = true;
if (comment.start != null) {
if (this.printedCommentStarts[comment.start]) return;
this.printedCommentStarts[comment.start] = true;
}
this.catchUp(comment);
// whitespace before
this.newline(this.whitespace.getNewlinesBefore(comment));
var column = this.position.column;
var val = this.generateComment(comment);
if (column && !this.isLast(["\n", " ", "[", "{"])) {
this._push(" ");
column++;
}
//
if (comment.type === "CommentBlock" && this.format.indent.adjustMultilineComment) {
var offset = comment.loc && comment.loc.start.column;
if (offset) {
var newlineRegex = new RegExp("\\n\\s{1," + offset + "}", "g");
val = val.replace(newlineRegex, "\n");
}
var indent = Math.max(this.indentSize(), column);
val = val.replace(/\n/g, "\n" + _repeating2["default"](" ", indent));
}
if (column === 0) {
val = this.getIndent() + val;
}
// force a newline for line comments when retainLines is set in case the next printed node
// doesn't catch up
if ((this.format.compact || this.format.retainLines) && comment.type === "CommentLine") {
val += "\n";
}
//
this._push(val);
// whitespace after
this.newline(this.whitespace.getNewlinesAfter(comment));
};
Printer.prototype.printComments = function printComments(comments /*:: ?: Array<Object>*/) {
if (!comments || !comments.length) return;
for (var _iterator = comments, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _getIterator(_iterator);;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var comment = _ref;
this.printComment(comment);
}
};
return Printer;
})(_buffer2["default"]);
exports["default"] = Printer;
var _arr = [require("./generators/template-literals"), require("./generators/expressions"), require("./generators/statements"), require("./generators/classes"), require("./generators/methods"), require("./generators/modules"), require("./generators/types"), require("./generators/flow"), require("./generators/base"), require("./generators/jsx")];
for (var _i2 = 0; _i2 < _arr.length; _i2++) {
var generator = _arr[_i2];
_Object$assign(Printer.prototype, generator);
}
module.exports = exports["default"]; |
/**
* Gulp tasks for wrapping Browserify modules.
*/
const browserify = require("browserify");
const gulp = require("gulp");
const sourcemaps = require("gulp-sourcemaps");
const uglify = require("gulp-uglify");
const path = require("path");
const through2 = require("through2");
const buffer = require("vinyl-buffer");
const source = require("vinyl-source-stream");
const asyncUtil = require("../../util/async-util");
const clientPackages = require("../../util/client-packages");
const display = require("../../util/display");
const uc = require("../../util/unite-config");
gulp.task("build-bundle-app", async () => {
const uniteConfig = await uc.getUniteConfig();
const buildConfiguration = uc.getBuildConfiguration(uniteConfig, false);
if (buildConfiguration.bundle) {
display.info("Running", "Browserify for App");
const bApp = browserify({
debug: buildConfiguration.sourcemaps,
entries: `./${path.join(uniteConfig.dirs.www.dist, "entryPoint.js")}`
});
const vendorPackages = await clientPackages.getBundleVendorPackages(uniteConfig);
let hasStyleLoader = false;
Object.keys(vendorPackages).forEach((key) => {
bApp.exclude(key);
const idx = key.indexOf("systemjs");
if (idx >= 0 && !hasStyleLoader) {
hasStyleLoader = key === "systemjs-plugin-css";
}
});
bApp.transform("envify", {
NODE_ENV: buildConfiguration.minify ? "production" : "development",
global: true
});
bApp.transform("browserify-css", {
autoInject: hasStyleLoader
});
bApp.transform("stringify", {
appliesTo: {
includeExtensions: uniteConfig.viewExtensions.map(ext => `.${ext}`)
}
});
bApp.transform("babelify", {
global: true,
presets: ["@babel/preset-env"]
});
return asyncUtil.stream(bApp.bundle().on("error", (err) => {
display.error(err);
})
.pipe(source("app-bundle.js"))
.pipe(buffer())
.pipe(buildConfiguration.minify ? uglify()
.on("error", (err) => {
display.error(err.toString());
}) : through2.obj())
.pipe(buildConfiguration.sourcemaps ? sourcemaps.init({
loadMaps: true
}) : through2.obj())
.pipe(buildConfiguration.sourcemaps ?
sourcemaps.mapSources((sourcePath) => sourcePath.replace(/dist\//, "./")) : through2.obj())
.pipe(buildConfiguration.sourcemaps ? sourcemaps.write({
includeContent: true
}) : through2.obj())
.pipe(gulp.dest(uniteConfig.dirs.www.dist)));
}
});
// Generated by UniteJS
|
// Commom Plugins
(function($) {
'use strict';
// Scroll to Top Button.
if (typeof theme.PluginScrollToTop !== 'undefined') {
theme.PluginScrollToTop.initialize();
}
// Tooltips
if ($.isFunction($.fn['tooltip'])) {
$('[data-tooltip]:not(.manual), [data-plugin-tooltip]:not(.manual)').tooltip();
}
// Popover
if ($.isFunction($.fn['popover'])) {
$(function() {
$('[data-plugin-popover]:not(.manual)').each(function() {
var $this = $(this),
opts;
var pluginOptions = $this.data('plugin-options');
if (pluginOptions)
opts = pluginOptions;
$this.popover(opts);
});
});
}
// Validations
if (typeof theme.PluginValidation !== 'undefined') {
theme.PluginValidation.initialize();
}
// Match Height
if ($.isFunction($.fn['matchHeight'])) {
$('.match-height').matchHeight();
// Featured Boxes
$('.featured-boxes .featured-box').matchHeight();
// Featured Box Full
$('.featured-box-full').matchHeight();
}
}).apply(this, [jQuery]);
// Animate
(function($) {
'use strict';
if ($.isFunction($.fn['themePluginAnimate'])) {
$(function() {
$('[data-plugin-animate], [data-appear-animation]').each(function() {
var $this = $(this),
opts;
var pluginOptions = $this.data('plugin-options');
if (pluginOptions)
opts = pluginOptions;
$this.themePluginAnimate(opts);
});
});
}
}).apply(this, [jQuery]);
// Carousel
(function($) {
'use strict';
if ($.isFunction($.fn['themePluginCarousel'])) {
$(function() {
$('[data-plugin-carousel]:not(.manual), .owl-carousel:not(.manual)').each(function() {
var $this = $(this),
opts;
var pluginOptions = $this.data('plugin-options');
if (pluginOptions)
opts = pluginOptions;
$this.themePluginCarousel(opts);
});
});
}
}).apply(this, [jQuery]);
// Chart.Circular
(function($) {
'use strict';
if ($.isFunction($.fn['themePluginChartCircular'])) {
$(function() {
$('[data-plugin-chart-circular]:not(.manual), .circular-bar-chart:not(.manual)').each(function() {
var $this = $(this),
opts;
var pluginOptions = $this.data('plugin-options');
if (pluginOptions)
opts = pluginOptions;
$this.themePluginChartCircular(opts);
});
});
}
}).apply(this, [jQuery]);
// Counter
(function($) {
'use strict';
if ($.isFunction($.fn['themePluginCounter'])) {
$(function() {
$('[data-plugin-counter]:not(.manual), .counters [data-to]').each(function() {
var $this = $(this),
opts;
var pluginOptions = $this.data('plugin-options');
if (pluginOptions)
opts = pluginOptions;
$this.themePluginCounter(opts);
});
});
}
}).apply(this, [jQuery]);
// Lazy Load
(function($) {
'use strict';
if ($.isFunction($.fn['themePluginLazyLoad'])) {
$(function() {
$('[data-plugin-lazyload]:not(.manual)').each(function() {
var $this = $(this),
opts;
var pluginOptions = $this.data('plugin-options');
if (pluginOptions)
opts = pluginOptions;
$this.themePluginLazyLoad(opts);
});
});
}
}).apply(this, [jQuery]);
// Lightbox
(function($) {
'use strict';
if ($.isFunction($.fn['themePluginLightbox'])) {
$(function() {
$('[data-plugin-lightbox]:not(.manual), .lightbox:not(.manual)').each(function() {
var $this = $(this),
opts;
var pluginOptions = $this.data('plugin-options');
if (pluginOptions)
opts = pluginOptions;
$this.themePluginLightbox(opts);
});
});
}
}).apply(this, [jQuery]);
// Masonry
(function($) {
'use strict';
if ($.isFunction($.fn['themePluginMasonry'])) {
$(function() {
$('[data-plugin-masonry]:not(.manual)').each(function() {
var $this = $(this),
opts;
var pluginOptions = $this.data('plugin-options');
if (pluginOptions)
opts = pluginOptions;
$this.themePluginMasonry(opts);
});
});
}
}).apply(this, [jQuery]);
// Match Height
(function($) {
'use strict';
if ($.isFunction($.fn['themePluginMatchHeight'])) {
$(function() {
$('[data-plugin-match-height]:not(.manual)').each(function() {
var $this = $(this),
opts;
var pluginOptions = $this.data('plugin-options');
if (pluginOptions)
opts = pluginOptions;
$this.themePluginMatchHeight(opts);
});
});
}
}).apply(this, [jQuery]);
// Parallax
(function($) {
'use strict';
if ($.isFunction($.fn['themePluginParallax'])) {
$(function() {
$('[data-plugin-parallax]:not(.manual)').each(function() {
var $this = $(this),
opts;
var pluginOptions = $this.data('plugin-options');
if (pluginOptions)
opts = pluginOptions;
$this.themePluginParallax(opts);
});
});
}
}).apply(this, [jQuery]);
// Progress Bar
(function($) {
'use strict';
if ($.isFunction($.fn['themePluginProgressBar'])) {
$(function() {
$('[data-plugin-progress-bar]:not(.manual), [data-appear-progress-animation]').each(function() {
var $this = $(this),
opts;
var pluginOptions = $this.data('plugin-options');
if (pluginOptions)
opts = pluginOptions;
$this.themePluginProgressBar(opts);
});
});
}
}).apply(this, [jQuery]);
// Revolution Slider
(function($) {
'use strict';
if ($.isFunction($.fn['themePluginRevolutionSlider'])) {
$(function() {
$('[data-plugin-revolution-slider]:not(.manual), .slider-container .slider:not(.manual)').each(function() {
var $this = $(this),
opts;
var pluginOptions = $this.data('plugin-options');
if (pluginOptions)
opts = pluginOptions;
$this.themePluginRevolutionSlider(opts);
});
});
}
}).apply(this, [jQuery]);
// Sort
(function($) {
'use strict';
if ($.isFunction($.fn['themePluginSort'])) {
$(function() {
$('[data-plugin-sort]:not(.manual), .sort-source:not(.manual)').each(function() {
var $this = $(this),
opts;
var pluginOptions = $this.data('plugin-options');
if (pluginOptions)
opts = pluginOptions;
$this.themePluginSort(opts);
});
});
}
}).apply(this, [jQuery]);
// Sticky
(function($) {
'use strict';
if ($.isFunction($.fn['themePluginSticky'])) {
$(function() {
$('[data-plugin-sticky]:not(.manual)').each(function() {
var $this = $(this),
opts;
var pluginOptions = $this.data('plugin-options');
if (pluginOptions)
opts = pluginOptions;
$this.themePluginSticky(opts);
});
});
}
}).apply(this, [jQuery]);
// Toggle
(function($) {
'use strict';
if ($.isFunction($.fn['themePluginToggle'])) {
$(function() {
$('[data-plugin-toggle]:not(.manual)').each(function() {
var $this = $(this),
opts;
var pluginOptions = $this.data('plugin-options');
if (pluginOptions)
opts = pluginOptions;
$this.themePluginToggle(opts);
});
});
}
}).apply(this, [jQuery]);
// Tweets
(function($) {
'use strict';
if ($.isFunction($.fn['themePluginTweets'])) {
$(function() {
$('[data-plugin-tweets]:not(.manual)').each(function() {
var $this = $(this),
opts;
var pluginOptions = $this.data('plugin-options');
if (pluginOptions)
opts = pluginOptions;
$this.themePluginTweets(opts);
});
});
}
}).apply(this, [jQuery]);
// Video Background
(function($) {
'use strict';
if ($.isFunction($.fn['themePluginVideoBackground'])) {
$(function() {
$('[data-plugin-video-background]:not(.manual)').each(function() {
var $this = $(this),
opts;
var pluginOptions = $this.data('plugin-options');
if (pluginOptions)
opts = pluginOptions;
$this.themePluginVideoBackground(opts);
});
});
}
}).apply(this, [jQuery]);
// Word Rotate
(function($) {
'use strict';
if ($.isFunction($.fn['themePluginWordRotate'])) {
$(function() {
$('[data-plugin-word-rotate]:not(.manual), .word-rotate:not(.manual)').each(function() {
var $this = $(this),
opts;
var pluginOptions = $this.data('plugin-options');
if (pluginOptions)
opts = pluginOptions;
$this.themePluginWordRotate(opts);
});
});
}
}).apply(this, [jQuery]);
// Commom Partials
(function($) {
'use strict';
// Sticky Header
if (typeof theme.StickyHeader !== 'undefined') {
theme.StickyHeader.initialize();
}
// Nav Menu
if (typeof theme.Nav !== 'undefined') {
theme.Nav.initialize();
}
// Search
if (typeof theme.Search !== 'undefined') {
theme.Search.initialize();
}
// Newsletter
if (typeof theme.Newsletter !== 'undefined') {
theme.Newsletter.initialize();
}
// Account
if (typeof theme.Account !== 'undefined') {
theme.Account.initialize();
}
}).apply(this, [jQuery]); |
'use strict';
const BitcrusherProps = {
bits: {
type: 'number',
bounds: [1, 16],
defaultValue: 4
},
normfreq: {
type: 'number',
bounds: [0, 1],
step: 0.1,
defaultValue: 0.1
},
bufferSize: {
type: 'number',
bounds: [256, 16384],
defaultValue: 4096
},
bypass: {
type: 'number',
bounds: [0, 1],
defaultValue: 0
}
};
export default BitcrusherProps;
|
define({
"_widgetLabel": "Tra cứu Địa lý",
"description": "Duyệt đến hoặc Kéo <a href='./widgets/GeoLookup/data/sample.csv' tooltip='Download an example sheet' target='_blank'> trang tính </a> tại đây để mô phỏng và thêm các dữ liệu bản đồ vào trang tính đó.",
"selectCSV": "Chọn một CSV",
"loadingCSV": "Đang tải CSV",
"savingCSV": "Xuất CSV",
"clearResults": "Xóa",
"downloadResults": "Tải xuống",
"plotOnly": "Chỉ các Điểm Vẽ bản đồ",
"plottingRows": "Hàng vẽ bản đồ",
"projectionChoice": "CSV trong",
"projectionLat": "Vĩ độ/Kinh độ",
"projectionMap": "Phép chiếu Bản đồ",
"messages": "Thông báo",
"error": {
"fetchingCSV": "Đã xảy ra lỗi khi truy xuất các mục từ kho lưu trữ CSV: ${0}",
"fileIssue": "Không xử lý được tệp.",
"notCSVFile": "Hiện chỉ hỗ trợ các tệp được ngăn cách bằng dấu phẩy (.csv).",
"invalidCoord": "Trường vị trí không hợp lệ. Vui lòng kiểm tra tệp .csv.",
"tooManyRecords": "Rất tiếc, hiện không được có quá ${0} bản ghi.",
"CSVNoRecords": "Tệp không chứa bất kỳ hồ sơ nào.",
"CSVEmptyFile": "Không có nội dung trong tệp."
},
"results": {
"csvLoaded": "Đã tải ${0} bản ghi từ tệp CSV",
"recordsPlotted": "Đã định vị ${0}/${1} bản ghi trên bản đồ",
"recordsEnriched": "Đã xử lý ${0}/${1}, đã bổ sung ${2} so với ${3}",
"recordsError": "${0} bản ghi có lỗi",
"recordsErrorList": "Hàng ${0} có sự cố",
"label": "Kết quả CSV"
}
}); |
var chai = require("chai")
var should = chai.should();
chai.use(require("chai-http"));
var request = chai.request(require("./server"))
var db = require("mongojs")("test")
describe("CRUD Handler", () => {
before(done => {
done()
})
beforeEach(done => {
db.dropDatabase(done);
})
after(done => {
db.dropDatabase(done)
})
it("should save a document", (done) => {
var data = {
name: "test"
}
request.post("/test")
.send(data)
.end((err, res) => {
should.not.exist(err)
res.should.have.status(201);
res.body.should.be.an("object")
res.body.should.have.keys(['error', 'data'])
res.body.error.should.not.be.ok;
res.body.data.name.should.be.eql("test")
res.body.data.should.have.property("_id");
done()
})
})
it("should list all documents", (done ) => {
var list = [
{name: 'test21'}, {name: 'test22'}
]
db.collection("test").insert(list, (err, result) => {
request.get("/test")
.end((err, res) => {
should.not.exist(err)
res.should.have.status(200)
res.body.should.be.an("object")
res.body.should.have.keys(['error', 'data'])
res.body.error.should.not.be.ok;
res.body.data.should.have.keys(['count', 'list'])
res.body.data.count.should.be.eql(2)
res.body.data.list.length.should.be.eql(2)
done()
})
})
})
it("should get a single document", done => {
var doc = {
name: 'test3'
}
db.collection('test').insert(doc, (err, result ) => {
request.get("/test/" + result._id)
.end((err, res) => {
should.not.exist(err)
res.should.have.status(200)
res.body.should.be.an("object")
res.body.should.have.keys(['error', 'data'])
res.body.error.should.not.be.ok;
res.body.data.should.have.keys(['_id', 'name'])
res.body.data.name.should.be.eql(doc.name);
done()
})
})
})
it("should update an existing document", done => {
var doc = {
name: 'test3'
}
db.collection('test').insert(doc, (err, result ) => {
result.name = "test3_updated";
request.put("/test/" + result._id)
.send(result)
.end((err, res) => {
should.not.exist(err)
res.should.have.status(202)
res.body.should.be.an("object")
res.body.should.have.keys(['error', 'data'])
res.body.error.should.not.be.ok;
db.collection('test').findOne({_id: db.ObjectId(result._id)}, (err, result1) => {
should.not.exist(err)
result1.name.should.be.eql(result.name);
done()
})
})
})
})
it("should remove a document", done => {
var doc = {
name: 'test3'
}
db.collection('test').insert(doc, (err, result ) => {
request.delete("/test/" + result._id)
.end((err, res) => {
should.not.exist(err)
res.should.have.status(202)
res.body.should.be.an("object")
res.body.should.have.keys(['error', 'data'])
res.body.error.should.not.be.ok;
db.collection('test').findOne({_id: db.ObjectId(result._id)}, (err, result1) => {
should.not.exist(err)
should.not.exist(result1);
done()
})
})
})
})
}) |
"use strict";
devdiv.directive('devDiv', [function () {
return {
restrict: 'E',
link: function (scope, iElement, iAttrs) {
iElement.addClass("dev-div");
iElement.addClass("row");
}
};
}])
devdiv.controller('NameCtrl', function ($scope, $watch) {
}); |
(function() {
'use strict';
/* Filters */
var md5 = function (s) {
if (!s) return '';
function L(k, d) {
return (k << d) | (k >>> (32 - d));
}
function K(G, k) {
var I, d, F, H, x;
F = (G & 2147483648);
H = (k & 2147483648);
I = (G & 1073741824);
d = (k & 1073741824);
x = (G & 1073741823) + (k & 1073741823);
if (I & d) {
return (x ^ 2147483648 ^ F ^ H);
}
if (I | d) {
if (x & 1073741824) {
return (x ^ 3221225472 ^ F ^ H);
} else {
return (x ^ 1073741824 ^ F ^ H);
}
} else {
return (x ^ F ^ H);
}
}
function r(d, F, k) {
return (d & F) | ((~d) & k);
}
function q(d, F, k) {
return (d & k) | (F & (~k));
}
function p(d, F, k) {
return (d ^ F ^ k);
}
function n(d, F, k) {
return (F ^ (d | (~k)));
}
function u(G, F, aa, Z, k, H, I) {
G = K(G, K(K(r(F, aa, Z), k), I));
return K(L(G, H), F);
}
function f(G, F, aa, Z, k, H, I) {
G = K(G, K(K(q(F, aa, Z), k), I));
return K(L(G, H), F);
}
function D(G, F, aa, Z, k, H, I) {
G = K(G, K(K(p(F, aa, Z), k), I));
return K(L(G, H), F);
}
function t(G, F, aa, Z, k, H, I) {
G = K(G, K(K(n(F, aa, Z), k), I));
return K(L(G, H), F);
}
function e(G) {
var Z;
var F = G.length;
var x = F + 8;
var k = (x - (x % 64)) / 64;
var I = (k + 1) * 16;
var aa = Array(I - 1);
var d = 0;
var H = 0;
while (H < F) {
Z = (H - (H % 4)) / 4;
d = (H % 4) * 8;
aa[Z] = (aa[Z] | (G.charCodeAt(H) << d));
H++;
}
Z = (H - (H % 4)) / 4;
d = (H % 4) * 8;
aa[Z] = aa[Z] | (128 << d);
aa[I - 2] = F << 3;
aa[I - 1] = F >>> 29;
return aa;
}
function B(x) {
var k = "",
F = "",
G, d;
for (d = 0; d <= 3; d++) {
G = (x >>> (d * 8)) & 255;
F = "0" + G.toString(16);
k = k + F.substr(F.length - 2, 2);
}
return k;
}
function J(k) {
k = k.replace(/rn/g, "n");
var d = "";
for (var F = 0; F < k.length; F++) {
var x = k.charCodeAt(F);
if (x < 128) {
d += String.fromCharCode(x);
} else {
if ((x > 127) && (x < 2048)) {
d += String.fromCharCode((x >> 6) | 192);
d += String.fromCharCode((x & 63) | 128);
} else {
d += String.fromCharCode((x >> 12) | 224);
d += String.fromCharCode(((x >> 6) & 63) | 128);
d += String.fromCharCode((x & 63) | 128);
}
}
}
return d;
}
var C = [];
var P, h, E, v, g, Y, X, W, V;
var S = 7,
Q = 12,
N = 17,
M = 22;
var A = 5,
z = 9,
y = 14,
w = 20;
var o = 4,
m = 11,
l = 16,
j = 23;
var U = 6,
T = 10,
R = 15,
O = 21;
s = J(s);
C = e(s);
Y = 1732584193;
X = 4023233417;
W = 2562383102;
V = 271733878;
for (P = 0; P < C.length; P += 16) {
h = Y;
E = X;
v = W;
g = V;
Y = u(Y, X, W, V, C[P + 0], S, 3614090360);
V = u(V, Y, X, W, C[P + 1], Q, 3905402710);
W = u(W, V, Y, X, C[P + 2], N, 606105819);
X = u(X, W, V, Y, C[P + 3], M, 3250441966);
Y = u(Y, X, W, V, C[P + 4], S, 4118548399);
V = u(V, Y, X, W, C[P + 5], Q, 1200080426);
W = u(W, V, Y, X, C[P + 6], N, 2821735955);
X = u(X, W, V, Y, C[P + 7], M, 4249261313);
Y = u(Y, X, W, V, C[P + 8], S, 1770035416);
V = u(V, Y, X, W, C[P + 9], Q, 2336552879);
W = u(W, V, Y, X, C[P + 10], N, 4294925233);
X = u(X, W, V, Y, C[P + 11], M, 2304563134);
Y = u(Y, X, W, V, C[P + 12], S, 1804603682);
V = u(V, Y, X, W, C[P + 13], Q, 4254626195);
W = u(W, V, Y, X, C[P + 14], N, 2792965006);
X = u(X, W, V, Y, C[P + 15], M, 1236535329);
Y = f(Y, X, W, V, C[P + 1], A, 4129170786);
V = f(V, Y, X, W, C[P + 6], z, 3225465664);
W = f(W, V, Y, X, C[P + 11], y, 643717713);
X = f(X, W, V, Y, C[P + 0], w, 3921069994);
Y = f(Y, X, W, V, C[P + 5], A, 3593408605);
V = f(V, Y, X, W, C[P + 10], z, 38016083);
W = f(W, V, Y, X, C[P + 15], y, 3634488961);
X = f(X, W, V, Y, C[P + 4], w, 3889429448);
Y = f(Y, X, W, V, C[P + 9], A, 568446438);
V = f(V, Y, X, W, C[P + 14], z, 3275163606);
W = f(W, V, Y, X, C[P + 3], y, 4107603335);
X = f(X, W, V, Y, C[P + 8], w, 1163531501);
Y = f(Y, X, W, V, C[P + 13], A, 2850285829);
V = f(V, Y, X, W, C[P + 2], z, 4243563512);
W = f(W, V, Y, X, C[P + 7], y, 1735328473);
X = f(X, W, V, Y, C[P + 12], w, 2368359562);
Y = D(Y, X, W, V, C[P + 5], o, 4294588738);
V = D(V, Y, X, W, C[P + 8], m, 2272392833);
W = D(W, V, Y, X, C[P + 11], l, 1839030562);
X = D(X, W, V, Y, C[P + 14], j, 4259657740);
Y = D(Y, X, W, V, C[P + 1], o, 2763975236);
V = D(V, Y, X, W, C[P + 4], m, 1272893353);
W = D(W, V, Y, X, C[P + 7], l, 4139469664);
X = D(X, W, V, Y, C[P + 10], j, 3200236656);
Y = D(Y, X, W, V, C[P + 13], o, 681279174);
V = D(V, Y, X, W, C[P + 0], m, 3936430074);
W = D(W, V, Y, X, C[P + 3], l, 3572445317);
X = D(X, W, V, Y, C[P + 6], j, 76029189);
Y = D(Y, X, W, V, C[P + 9], o, 3654602809);
V = D(V, Y, X, W, C[P + 12], m, 3873151461);
W = D(W, V, Y, X, C[P + 15], l, 530742520);
X = D(X, W, V, Y, C[P + 2], j, 3299628645);
Y = t(Y, X, W, V, C[P + 0], U, 4096336452);
V = t(V, Y, X, W, C[P + 7], T, 1126891415);
W = t(W, V, Y, X, C[P + 14], R, 2878612391);
X = t(X, W, V, Y, C[P + 5], O, 4237533241);
Y = t(Y, X, W, V, C[P + 12], U, 1700485571);
V = t(V, Y, X, W, C[P + 3], T, 2399980690);
W = t(W, V, Y, X, C[P + 10], R, 4293915773);
X = t(X, W, V, Y, C[P + 1], O, 2240044497);
Y = t(Y, X, W, V, C[P + 8], U, 1873313359);
V = t(V, Y, X, W, C[P + 15], T, 4264355552);
W = t(W, V, Y, X, C[P + 6], R, 2734768916);
X = t(X, W, V, Y, C[P + 13], O, 1309151649);
Y = t(Y, X, W, V, C[P + 4], U, 4149444226);
V = t(V, Y, X, W, C[P + 11], T, 3174756917);
W = t(W, V, Y, X, C[P + 2], R, 718787259);
X = t(X, W, V, Y, C[P + 9], O, 3951481745);
Y = K(Y, h);
X = K(X, E);
W = K(W, v);
V = K(V, g);
}
var i = B(Y) + B(X) + B(W) + B(V);
return i.toLowerCase();
};
angular.module('talis.filters.md5', []).
filter("md5", function(){
return md5;
});
}).call(this);
|
/*globals describe, before, beforeEach, afterEach, it */
/*jshint expr:true*/
var testUtils = require('../../utils'),
should = require('should'),
// Stuff we are testing
dbAPI = require('../../../server/api/db'),
ModelTag = require('../../../server/models/tag'),
ModelPost = require('../../../server/models/post');
describe('DB API', function () {
// Keep the DB clean
before(testUtils.teardown);
afterEach(testUtils.teardown);
beforeEach(testUtils.setup('users:roles', 'posts', 'perms:db', 'perms:init'));
should.exist(dbAPI);
it('delete all content (owner)', function (done) {
return dbAPI.deleteAllContent(testUtils.context.owner).then(function (result) {
should.exist(result.db);
result.db.should.be.instanceof(Array);
result.db.should.be.empty;
}).then(function () {
return ModelTag.Tag.findAll(testUtils.context.owner).then(function (results) {
should.exist(results);
results.length.should.equal(0);
});
}).then(function () {
return ModelPost.Post.findAll(testUtils.context.owner).then(function (results) {
should.exist(results);
results.length.should.equal(0);
done();
});
}).catch(done);
});
it('delete all content (admin)', function (done) {
return dbAPI.deleteAllContent(testUtils.context.admin).then(function (result) {
should.exist(result.db);
result.db.should.be.instanceof(Array);
result.db.should.be.empty;
}).then(function () {
return ModelTag.Tag.findAll(testUtils.context.admin).then(function (results) {
should.exist(results);
results.length.should.equal(0);
});
}).then(function () {
return ModelPost.Post.findAll(testUtils.context.admin).then(function (results) {
should.exist(results);
results.length.should.equal(0);
done();
});
}).catch(done);
});
it('delete all content is denied (editor & author)', function (done) {
return dbAPI.deleteAllContent(testUtils.context.editor).then(function () {
done(new Error('Delete all content is not denied for editor.'));
}, function (error) {
error.type.should.eql('NoPermissionError');
return dbAPI.deleteAllContent(testUtils.context.author);
}).then(function () {
done(new Error('Delete all content is not denied for author.'));
}, function (error) {
error.type.should.eql('NoPermissionError');
return dbAPI.deleteAllContent();
}).then(function () {
done(new Error('Delete all content is not denied without authentication.'));
}).catch(function (error) {
error.type.should.eql('NoPermissionError');
done();
}).catch(done);
});
it('export content is denied (editor & author)', function (done) {
return dbAPI.exportContent(testUtils.context.editor).then(function () {
done(new Error('Export content is not denied for editor.'));
}, function (error) {
error.type.should.eql('NoPermissionError');
return dbAPI.exportContent(testUtils.context.author);
}).then(function () {
done(new Error('Export content is not denied for author.'));
}, function (error) {
error.type.should.eql('NoPermissionError');
return dbAPI.exportContent();
}).then(function () {
done(new Error('Export content is not denied without authentication.'));
}).catch(function (error) {
error.type.should.eql('NoPermissionError');
done();
}).catch(done);
});
it('import content is denied (editor & author)', function (done) {
return dbAPI.importContent(testUtils.context.editor).then(function () {
done(new Error('Import content is not denied for editor.'));
}, function (error) {
error.type.should.eql('NoPermissionError');
return dbAPI.importContent(testUtils.context.author);
}).then(function () {
done(new Error('Import content is not denied for author.'));
}, function (error) {
error.type.should.eql('NoPermissionError');
return dbAPI.importContent();
}).then(function () {
done(new Error('Import content is not denied without authentication.'));
}).catch(function (error) {
error.type.should.eql('NoPermissionError');
done();
}).catch(done);
});
}); |
(function (subdivision) {
'use strict';
var count = 0;
var builders;
var defaultBuilder;
function buildInternal(type, addin, options, meta) {
var builder = subdivision.getBuilder(type);
if (builder.preBuildTarget) {
addin = buildInternal(builder.preBuildTarget, addin, options, meta);
}
return builder.build(addin, options, meta);
}
function buildInternalAsync(type, addin, options, meta) {
try {
var builder = subdivision.getBuilder(type);
var promise = Promise.resolve(addin);
if (builder.preBuildTarget) {
promise = buildInternalAsync(builder.preBuildTarget, addin, options, meta);
}
return promise.then(function (addin) {
return builder.build(addin, options, meta);
});
}
catch (ex) {
return Promise.reject(ex);
}
}
subdivision.Builder = function (options) {
var builder = subdivision.Addin.$internalConstructor('builder', count++, options);
if (!_.isFunction(builder.build)) {
throw new Error('Builder options must contain the "build" function ' + JSON.stringify(options));
}
builder.target = builder.target === undefined ? '' : builder.target;
return builder;
};
subdivision.systemPaths.builders = subdivision.registry.joinPath(subdivision.systemPaths.prefix, 'builders');
subdivision.defaultManifest.paths.push({
path: subdivision.systemPaths.builders,
addins: [
{
///Update docs if this changes
id: 'subdivision.defaultBuilder',
type: 'subdivision.builder',
target: null,
order: subdivision.registry.$defaultOrder,
build: function (addin) {
return _.cloneDeep(addin);
}
}
]
});
/**
* Adds a new builder created from the options to the list of known builders.
* If a builder that builds the given type already exists then
* the new builder is added based on the forced option. If force is truthy it is added anyway otherwise does nothing
* Returns true if a builder was added and false otherwise
*
*/
subdivision.addBuilder = function (options, force) {
var builder = new subdivision.Builder(options);
if (builder.target === null) {
if (!defaultBuilder || force) {
defaultBuilder = builder;
return true;
} else {
return false;
}
}
if (!builders.hasOwnProperty(builder.target) || force) {
builders[builder.target] = builder;
return true;
} else {
return false;
}
};
/**
* Gets a builder for the appropriate type, if no builder of the given type is found returns the default builder (builder with type === null)
* @param type
*/
subdivision.getBuilder = function (type) {
if (type === null && defaultBuilder) {
return defaultBuilder;
} else {
if (builders.hasOwnProperty(type)) {
return builders[type];
}
if (defaultBuilder) {
return defaultBuilder;
}
}
throw new Error('No builder of type "' + type + '" was defined and no default builder was registered');
};
/**
* Returns all the addins in the path after applying the appropriate builder on each
* @param path - The path to build
* @param options - Custom options to be passed to the addin builder
* @param searchCriteria - The search criteria for the underscore filter function
* @param skipSort - If truthy the topological sort is skipped
* @returns {Array} = The built addins
*/
subdivision.build = function (path, options, searchCriteria, skipSort) {
var addins = subdivision.getAddins(path, searchCriteria, skipSort);
if (addins.length === 0) {
return addins;
}
return _.map(addins, function (addin) {
return buildInternal(addin.type, addin, options, {
path: path
});
});
};
/**
* Returns all the addins in the path after applying the appropriate builder on each
* @param path - The path to build
* @param options - Custom options to be passed to the addin builder
* @param searchCriteria - The search criteria for the underscore filter function
* @param skipSort - If truthy the topological sort is skipped
* @returns {Array} = A promise that resolves with an array of the built addins
*/
subdivision.build.async = function (path, options, searchCriteria, skipSort) {
var addins = subdivision.getAddins(path, searchCriteria, skipSort);
if (addins.length === 0) {
return Promise.resolve(addins);
}
var promises = _.map(addins, function (addin) {
//TODO: Optimization that tries to guess the builder from previous builder
return buildInternalAsync(addin.type, addin, options, {
path: path
});
});
return Promise.all(promises);
};
/**
* Builds a single addin based on its type
* @param addin The addin to build
* @param options The options to pass to the builder
*/
subdivision.buildAddin = function (addin, options) {
return buildInternal(addin.type, addin, options, {
path: null
});
};
/**
* The async version of buildAddin
* @param addin The addin to build
* @param options The options to pass to the builder
* @returns A promise that when resolved returns the built addin
*/
subdivision.buildAddin.async = function (addin, options) {
return buildInternalAsync(addin.type, addin, options, {
path: null
});
};
/**
* Builds a tree out of the given path. Each addin will have child elements at path+addin.id added
* to its items property (default $items).
* @param path
* @param options - Custom options to be passed to the addin builder
*/
subdivision.buildTree = function (path, options) {
var addins = subdivision.getAddins(path);
if (addins.length === 0) {
return addins;
}
return _.map(addins, function (addin) {
//TODO: Optimization that tries to guess the builder from previous builder
var result = buildInternal(addin.type, addin, options, {
path: path
});
var itemsProperty = addin.itemsProperty || '$items';
result[itemsProperty] = subdivision.buildTree(subdivision.registry.joinPath(path, addin.id), options);
return result;
});
};
/**
* Regenerates all the builders from the system builders path
*/
subdivision.$generateBuilders = function () {
subdivision.$clearBuilders();
var addins = subdivision.getAddins(subdivision.systemPaths.builders, {target: null});
if (addins.length > 0) {
defaultBuilder = new subdivision.Builder(addins[0]);
}
addins = subdivision.getAddins(subdivision.systemPaths.builders);
_.forEach(addins, function (addin) {
subdivision.addBuilder(addin);
});
};
subdivision.$clearBuilders = function () {
builders = {};
defaultBuilder = null;
};
subdivision.$clearBuilders();
Object.defineProperty(subdivision, 'builders', {
enumerable: true,
configurable: false,
get: function () {
return _.clone(builders);
}
});
})(subdivision); |
/*!
* reveal.js
* http://lab.hakim.se/reveal-js
* MIT licensed
*
* Copyright (C) 2016 Hakim El Hattab, http://hakim.se
*/
(function( root, factory ) {
if( typeof define === 'function' && define.amd ) {
// AMD. Register as an anonymous module.
define( function() {
root.Reveal = factory();
return root.Reveal;
} );
} else if( typeof exports === 'object' ) {
// Node. Does not work with strict CommonJS.
module.exports = factory();
} else {
// Browser globals.
root.Reveal = factory();
}
}( this, function() {
'use strict';
var Reveal;
// The reveal.js version
var VERSION = '3.3.0';
var SLIDES_SELECTOR = '.slides section',
HORIZONTAL_SLIDES_SELECTOR = '.slides>section',
VERTICAL_SLIDES_SELECTOR = '.slides>section.present>section',
HOME_SLIDE_SELECTOR = '.slides>section:first-of-type',
UA = navigator.userAgent,
// Configuration defaults, can be overridden at initialization time
config = {
// The "normal" size of the presentation, aspect ratio will be preserved
// when the presentation is scaled to fit different resolutions
width: 960,
height: 700,
// Factor of the display size that should remain empty around the content
margin: 0.1,
// Bounds for smallest/largest possible scale to apply to content
minScale: 0.2,
maxScale: 1.5,
// Display controls in the bottom right corner
controls: true,
// Display a presentation progress bar
progress: true,
// Display the page number of the current slide
slideNumber: false,
// Push each slide change to the browser history
history: false,
// Enable keyboard shortcuts for navigation
keyboard: true,
// Optional function that blocks keyboard events when retuning false
keyboardCondition: null,
// Enable the slide overview mode
overview: true,
// Vertical centering of slides
center: true,
// Enables touch navigation on devices with touch input
touch: true,
// Loop the presentation
loop: false,
// Change the presentation direction to be RTL
rtl: false,
// Randomizes the order of slides each time the presentation loads
shuffle: false,
// Turns fragments on and off globally
fragments: true,
// Flags if the presentation is running in an embedded mode,
// i.e. contained within a limited portion of the screen
embedded: false,
// Flags if we should show a help overlay when the questionmark
// key is pressed
help: true,
// Flags if it should be possible to pause the presentation (blackout)
pause: true,
// Flags if speaker notes should be visible to all viewers
showNotes: false,
// Number of milliseconds between automatically proceeding to the
// next slide, disabled when set to 0, this value can be overwritten
// by using a data-autoslide attribute on your slides
autoSlide: 0,
// Stop auto-sliding after user input
autoSlideStoppable: true,
// Use this method for navigation when auto-sliding (defaults to navigateNext)
autoSlideMethod: null,
// Enable slide navigation via mouse wheel
mouseWheel: false,
// Apply a 3D roll to links on hover
rollingLinks: false,
// Hides the address bar on mobile devices
hideAddressBar: true,
// Opens links in an iframe preview overlay
previewLinks: false,
// Exposes the reveal.js API through window.postMessage
postMessage: true,
// Dispatches all reveal.js events to the parent window through postMessage
postMessageEvents: false,
// Focuses body when page changes visiblity to ensure keyboard shortcuts work
focusBodyOnPageVisibilityChange: true,
// Transition style
transition: 'fade', // none/fade/slide/convex/concave/zoom
// Transition speed
transitionSpeed: 'default', // default/fast/slow
// Transition style for full page slide backgrounds
backgroundTransition: 'fade', // none/fade/slide/convex/concave/zoom
// Parallax background image
parallaxBackgroundImage: '', // CSS syntax, e.g. "a.jpg"
// Parallax background size
parallaxBackgroundSize: '', // CSS syntax, e.g. "3000px 2000px"
// Amount of pixels to move the parallax background per slide step
parallaxBackgroundHorizontal: null,
parallaxBackgroundVertical: null,
// Number of slides away from the current that are visible
viewDistance: 3,
// Script dependencies to load
dependencies: []
},
// Flags if reveal.js is loaded (has dispatched the 'ready' event)
loaded = false,
// Flags if the overview mode is currently active
overview = false,
// Holds the dimensions of our overview slides, including margins
overviewSlideWidth = null,
overviewSlideHeight = null,
// The horizontal and vertical index of the currently active slide
indexh,
indexv,
// The previous and current slide HTML elements
previousSlide,
currentSlide,
previousBackground,
// Slides may hold a data-state attribute which we pick up and apply
// as a class to the body. This list contains the combined state of
// all current slides.
state = [],
// The current scale of the presentation (see width/height config)
scale = 1,
// CSS transform that is currently applied to the slides container,
// split into two groups
slidesTransform = { layout: '', overview: '' },
// Cached references to DOM elements
dom = {},
// Features supported by the browser, see #checkCapabilities()
features = {},
// Client is a mobile device, see #checkCapabilities()
isMobileDevice,
// Client is a desktop Chrome, see #checkCapabilities()
isChrome,
// Throttles mouse wheel navigation
lastMouseWheelStep = 0,
// Delays updates to the URL due to a Chrome thumbnailer bug
writeURLTimeout = 0,
// Flags if the interaction event listeners are bound
eventsAreBound = false,
// The current auto-slide duration
autoSlide = 0,
// Auto slide properties
autoSlidePlayer,
autoSlideTimeout = 0,
autoSlideStartTime = -1,
autoSlidePaused = false,
// Holds information about the currently ongoing touch input
touch = {
startX: 0,
startY: 0,
startSpan: 0,
startCount: 0,
captured: false,
threshold: 40
},
// Holds information about the keyboard shortcuts
keyboardShortcuts = {
'N , SPACE': 'Next slide',
'P': 'Previous slide',
'← , H': 'Navigate left',
'→ , L': 'Navigate right',
'↑ , K': 'Navigate up',
'↓ , J': 'Navigate down',
'Home': 'First slide',
'End': 'Last slide',
'B , .': 'Pause',
'F': 'Fullscreen',
'ESC, O': 'Slide overview'
};
/**
* Starts up the presentation if the client is capable.
*/
function initialize( options ) {
checkCapabilities();
if( !features.transforms2d && !features.transforms3d ) {
document.body.setAttribute( 'class', 'no-transforms' );
// Since JS won't be running any further, we load all lazy
// loading elements upfront
var images = toArray( document.getElementsByTagName( 'img' ) ),
iframes = toArray( document.getElementsByTagName( 'iframe' ) );
var lazyLoadable = images.concat( iframes );
for( var i = 0, len = lazyLoadable.length; i < len; i++ ) {
var element = lazyLoadable[i];
if( element.getAttribute( 'data-src' ) ) {
element.setAttribute( 'src', element.getAttribute( 'data-src' ) );
element.removeAttribute( 'data-src' );
}
}
// If the browser doesn't support core features we won't be
// using JavaScript to control the presentation
return;
}
// Cache references to key DOM elements
dom.wrapper = document.querySelector( '.reveal' );
dom.slides = document.querySelector( '.reveal .slides' );
// Force a layout when the whole page, incl fonts, has loaded
window.addEventListener( 'load', layout, false );
var query = Reveal.getQueryHash();
// Do not accept new dependencies via query config to avoid
// the potential of malicious script injection
if( typeof query['dependencies'] !== 'undefined' ) delete query['dependencies'];
// Copy options over to our config object
extend( config, options );
extend( config, query );
// Hide the address bar in mobile browsers
hideAddressBar();
// Loads the dependencies and continues to #start() once done
load();
}
/**
* Inspect the client to see what it's capable of, this
* should only happens once per runtime.
*/
function checkCapabilities() {
isMobileDevice = /(iphone|ipod|ipad|android)/gi.test( UA );
isChrome = /chrome/i.test( UA ) && !/edge/i.test( UA );
var testElement = document.createElement( 'div' );
features.transforms3d = 'WebkitPerspective' in testElement.style ||
'MozPerspective' in testElement.style ||
'msPerspective' in testElement.style ||
'OPerspective' in testElement.style ||
'perspective' in testElement.style;
features.transforms2d = 'WebkitTransform' in testElement.style ||
'MozTransform' in testElement.style ||
'msTransform' in testElement.style ||
'OTransform' in testElement.style ||
'transform' in testElement.style;
features.requestAnimationFrameMethod = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame;
features.requestAnimationFrame = typeof features.requestAnimationFrameMethod === 'function';
features.canvas = !!document.createElement( 'canvas' ).getContext;
// Transitions in the overview are disabled in desktop and
// Safari due to lag
features.overviewTransitions = !/Version\/[\d\.]+.*Safari/.test( UA );
// Flags if we should use zoom instead of transform to scale
// up slides. Zoom produces crisper results but has a lot of
// xbrowser quirks so we only use it in whitelsited browsers.
features.zoom = 'zoom' in testElement.style && !isMobileDevice &&
( isChrome || /Version\/[\d\.]+.*Safari/.test( UA ) );
}
/**
* Loads the dependencies of reveal.js. Dependencies are
* defined via the configuration option 'dependencies'
* and will be loaded prior to starting/binding reveal.js.
* Some dependencies may have an 'async' flag, if so they
* will load after reveal.js has been started up.
*/
function load() {
var scripts = [],
scriptsAsync = [],
scriptsToPreload = 0;
// Called once synchronous scripts finish loading
function proceed() {
if( scriptsAsync.length ) {
// Load asynchronous scripts
head.js.apply( null, scriptsAsync );
}
start();
}
function loadScript( s ) {
head.ready( s.src.match( /([\w\d_\-]*)\.?js$|[^\\\/]*$/i )[0], function() {
// Extension may contain callback functions
if( typeof s.callback === 'function' ) {
s.callback.apply( this );
}
if( --scriptsToPreload === 0 ) {
proceed();
}
});
}
for( var i = 0, len = config.dependencies.length; i < len; i++ ) {
var s = config.dependencies[i];
// Load if there's no condition or the condition is truthy
if( !s.condition || s.condition() ) {
if( s.async ) {
scriptsAsync.push( s.src );
}
else {
scripts.push( s.src );
}
loadScript( s );
}
}
if( scripts.length ) {
scriptsToPreload = scripts.length;
// Load synchronous scripts
head.js.apply( null, scripts );
}
else {
proceed();
}
}
/**
* Starts up reveal.js by binding input events and navigating
* to the current URL deeplink if there is one.
*/
function start() {
// Make sure we've got all the DOM elements we need
setupDOM();
// Listen to messages posted to this window
setupPostMessage();
// Prevent the slides from being scrolled out of view
setupScrollPrevention();
// Resets all vertical slides so that only the first is visible
resetVerticalSlides();
// Updates the presentation to match the current configuration values
configure();
// Read the initial hash
readURL();
// Update all backgrounds
updateBackground( true );
// Notify listeners that the presentation is ready but use a 1ms
// timeout to ensure it's not fired synchronously after #initialize()
setTimeout( function() {
// Enable transitions now that we're loaded
dom.slides.classList.remove( 'no-transition' );
loaded = true;
dispatchEvent( 'ready', {
'indexh': indexh,
'indexv': indexv,
'currentSlide': currentSlide
} );
}, 1 );
// Special setup and config is required when printing to PDF
if( isPrintingPDF() ) {
removeEventListeners();
// The document needs to have loaded for the PDF layout
// measurements to be accurate
if( document.readyState === 'complete' ) {
setupPDF();
}
else {
window.addEventListener( 'load', setupPDF );
}
}
}
/**
* Finds and stores references to DOM elements which are
* required by the presentation. If a required element is
* not found, it is created.
*/
function setupDOM() {
// Prevent transitions while we're loading
dom.slides.classList.add( 'no-transition' );
// Background element
dom.background = createSingletonNode( dom.wrapper, 'div', 'backgrounds', null );
// Progress bar
dom.progress = createSingletonNode( dom.wrapper, 'div', 'progress', '<span></span>' );
dom.progressbar = dom.progress.querySelector( 'span' );
// Arrow controls
createSingletonNode( dom.wrapper, 'aside', 'controls',
'<button class="navigate-left" aria-label="previous slide"></button>' +
'<button class="navigate-right" aria-label="next slide"></button>' +
'<button class="navigate-up" aria-label="above slide"></button>' +
'<button class="navigate-down" aria-label="below slide"></button>' );
// Slide number
dom.slideNumber = createSingletonNode( dom.wrapper, 'div', 'slide-number', '' );
// Element containing notes that are visible to the audience
dom.speakerNotes = createSingletonNode( dom.wrapper, 'div', 'speaker-notes', null );
dom.speakerNotes.setAttribute( 'data-prevent-swipe', '' );
// Overlay graphic which is displayed during the paused mode
createSingletonNode( dom.wrapper, 'div', 'pause-overlay', null );
// Cache references to elements
dom.controls = document.querySelector( '.reveal .controls' );
dom.theme = document.querySelector( '#theme' );
dom.wrapper.setAttribute( 'role', 'application' );
// There can be multiple instances of controls throughout the page
dom.controlsLeft = toArray( document.querySelectorAll( '.navigate-left' ) );
dom.controlsRight = toArray( document.querySelectorAll( '.navigate-right' ) );
dom.controlsUp = toArray( document.querySelectorAll( '.navigate-up' ) );
dom.controlsDown = toArray( document.querySelectorAll( '.navigate-down' ) );
dom.controlsPrev = toArray( document.querySelectorAll( '.navigate-prev' ) );
dom.controlsNext = toArray( document.querySelectorAll( '.navigate-next' ) );
dom.statusDiv = createStatusDiv();
}
/**
* Creates a hidden div with role aria-live to announce the
* current slide content. Hide the div off-screen to make it
* available only to Assistive Technologies.
*/
function createStatusDiv() {
var statusDiv = document.getElementById( 'aria-status-div' );
if( !statusDiv ) {
statusDiv = document.createElement( 'div' );
statusDiv.style.position = 'absolute';
statusDiv.style.height = '1px';
statusDiv.style.width = '1px';
statusDiv.style.overflow ='hidden';
statusDiv.style.clip = 'rect( 1px, 1px, 1px, 1px )';
statusDiv.setAttribute( 'id', 'aria-status-div' );
statusDiv.setAttribute( 'aria-live', 'polite' );
statusDiv.setAttribute( 'aria-atomic','true' );
dom.wrapper.appendChild( statusDiv );
}
return statusDiv;
}
/**
* Configures the presentation for printing to a static
* PDF.
*/
function setupPDF() {
var slideSize = getComputedSlideSize( window.innerWidth, window.innerHeight );
// Dimensions of the PDF pages
var pageWidth = Math.floor( slideSize.width * ( 1 + config.margin ) ),
pageHeight = Math.floor( slideSize.height * ( 1 + config.margin ) );
// Dimensions of slides within the pages
var slideWidth = slideSize.width,
slideHeight = slideSize.height;
// Let the browser know what page size we want to print
injectStyleSheet( '@page{size:'+ pageWidth +'px '+ pageHeight +'px; margin: 0;}' );
// Limit the size of certain elements to the dimensions of the slide
injectStyleSheet( '.reveal section>img, .reveal section>video, .reveal section>iframe{max-width: '+ slideWidth +'px; max-height:'+ slideHeight +'px}' );
document.body.classList.add( 'print-pdf' );
document.body.style.width = pageWidth + 'px';
document.body.style.height = pageHeight + 'px';
// Add each slide's index as attributes on itself, we need these
// indices to generate slide numbers below
toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ).forEach( function( hslide, h ) {
hslide.setAttribute( 'data-index-h', h );
if( hslide.classList.contains( 'stack' ) ) {
toArray( hslide.querySelectorAll( 'section' ) ).forEach( function( vslide, v ) {
vslide.setAttribute( 'data-index-h', h );
vslide.setAttribute( 'data-index-v', v );
} );
}
} );
// Slide and slide background layout
toArray( dom.wrapper.querySelectorAll( SLIDES_SELECTOR ) ).forEach( function( slide ) {
// Vertical stacks are not centred since their section
// children will be
if( slide.classList.contains( 'stack' ) === false ) {
// Center the slide inside of the page, giving the slide some margin
var left = ( pageWidth - slideWidth ) / 2,
top = ( pageHeight - slideHeight ) / 2;
var contentHeight = getAbsoluteHeight( slide );
var numberOfPages = Math.max( Math.ceil( contentHeight / pageHeight ), 1 );
// Center slides vertically
if( numberOfPages === 1 && config.center || slide.classList.contains( 'center' ) ) {
top = Math.max( ( pageHeight - contentHeight ) / 2, 0 );
}
// Position the slide inside of the page
slide.style.left = left + 'px';
slide.style.top = top + 'px';
slide.style.width = slideWidth + 'px';
// TODO Backgrounds need to be multiplied when the slide
// stretches over multiple pages
var background = slide.querySelector( '.slide-background' );
if( background ) {
background.style.width = pageWidth + 'px';
background.style.height = ( pageHeight * numberOfPages ) + 'px';
background.style.top = -top + 'px';
background.style.left = -left + 'px';
}
// Inject notes if `showNotes` is enabled
if( config.showNotes ) {
var notes = getSlideNotes( slide );
if( notes ) {
var notesSpacing = 8;
var notesElement = document.createElement( 'div' );
notesElement.classList.add( 'speaker-notes' );
notesElement.classList.add( 'speaker-notes-pdf' );
notesElement.innerHTML = notes;
notesElement.style.left = ( notesSpacing - left ) + 'px';
notesElement.style.bottom = ( notesSpacing - top ) + 'px';
notesElement.style.width = ( pageWidth - notesSpacing*2 ) + 'px';
slide.appendChild( notesElement );
}
}
// Inject slide numbers if `slideNumbers` are enabled
if( config.slideNumber ) {
var slideNumberH = parseInt( slide.getAttribute( 'data-index-h' ), 10 ) + 1,
slideNumberV = parseInt( slide.getAttribute( 'data-index-v' ), 10 ) + 1;
var numberElement = document.createElement( 'div' );
numberElement.classList.add( 'slide-number' );
numberElement.classList.add( 'slide-number-pdf' );
numberElement.innerHTML = formatSlideNumber( slideNumberH, '.', slideNumberV );
background.appendChild( numberElement );
}
}
} );
// Show all fragments
toArray( dom.wrapper.querySelectorAll( SLIDES_SELECTOR + ' .fragment' ) ).forEach( function( fragment ) {
fragment.classList.add( 'visible' );
} );
}
/**
* This is an unfortunate necessity. Some actions – such as
* an input field being focused in an iframe or using the
* keyboard to expand text selection beyond the bounds of
* a slide – can trigger our content to be pushed out of view.
* This scrolling can not be prevented by hiding overflow in
* CSS (we already do) so we have to resort to repeatedly
* checking if the slides have been offset :(
*/
function setupScrollPrevention() {
setInterval( function() {
if( dom.wrapper.scrollTop !== 0 || dom.wrapper.scrollLeft !== 0 ) {
dom.wrapper.scrollTop = 0;
dom.wrapper.scrollLeft = 0;
}
}, 1000 );
}
/**
* Creates an HTML element and returns a reference to it.
* If the element already exists the existing instance will
* be returned.
*/
function createSingletonNode( container, tagname, classname, innerHTML ) {
// Find all nodes matching the description
var nodes = container.querySelectorAll( '.' + classname );
// Check all matches to find one which is a direct child of
// the specified container
for( var i = 0; i < nodes.length; i++ ) {
var testNode = nodes[i];
if( testNode.parentNode === container ) {
return testNode;
}
}
// If no node was found, create it now
var node = document.createElement( tagname );
node.classList.add( classname );
if( typeof innerHTML === 'string' ) {
node.innerHTML = innerHTML;
}
container.appendChild( node );
return node;
}
/**
* Creates the slide background elements and appends them
* to the background container. One element is created per
* slide no matter if the given slide has visible background.
*/
function createBackgrounds() {
var printMode = isPrintingPDF();
// Clear prior backgrounds
dom.background.innerHTML = '';
dom.background.classList.add( 'no-transition' );
// Iterate over all horizontal slides
toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ).forEach( function( slideh ) {
var backgroundStack;
if( printMode ) {
backgroundStack = createBackground( slideh, slideh );
}
else {
backgroundStack = createBackground( slideh, dom.background );
}
// Iterate over all vertical slides
toArray( slideh.querySelectorAll( 'section' ) ).forEach( function( slidev ) {
if( printMode ) {
createBackground( slidev, slidev );
}
else {
createBackground( slidev, backgroundStack );
}
backgroundStack.classList.add( 'stack' );
} );
} );
// Add parallax background if specified
if( config.parallaxBackgroundImage ) {
dom.background.style.backgroundImage = 'url("' + config.parallaxBackgroundImage + '")';
dom.background.style.backgroundSize = config.parallaxBackgroundSize;
// Make sure the below properties are set on the element - these properties are
// needed for proper transitions to be set on the element via CSS. To remove
// annoying background slide-in effect when the presentation starts, apply
// these properties after short time delay
setTimeout( function() {
dom.wrapper.classList.add( 'has-parallax-background' );
}, 1 );
}
else {
dom.background.style.backgroundImage = '';
dom.wrapper.classList.remove( 'has-parallax-background' );
}
}
/**
* Creates a background for the given slide.
*
* @param {HTMLElement} slide
* @param {HTMLElement} container The element that the background
* should be appended to
*/
function createBackground( slide, container ) {
var data = {
background: slide.getAttribute( 'data-background' ),
backgroundSize: slide.getAttribute( 'data-background-size' ),
backgroundImage: slide.getAttribute( 'data-background-image' ),
backgroundVideo: slide.getAttribute( 'data-background-video' ),
backgroundIframe: slide.getAttribute( 'data-background-iframe' ),
backgroundColor: slide.getAttribute( 'data-background-color' ),
backgroundRepeat: slide.getAttribute( 'data-background-repeat' ),
backgroundPosition: slide.getAttribute( 'data-background-position' ),
backgroundTransition: slide.getAttribute( 'data-background-transition' )
};
var element = document.createElement( 'div' );
// Carry over custom classes from the slide to the background
element.className = 'slide-background ' + slide.className.replace( /present|past|future/, '' );
if( data.background ) {
// Auto-wrap image urls in url(...)
if( /^(http|file|\/\/)/gi.test( data.background ) || /\.(svg|png|jpg|jpeg|gif|bmp)$/gi.test( data.background ) ) {
slide.setAttribute( 'data-background-image', data.background );
}
else {
element.style.background = data.background;
}
}
// Create a hash for this combination of background settings.
// This is used to determine when two slide backgrounds are
// the same.
if( data.background || data.backgroundColor || data.backgroundImage || data.backgroundVideo || data.backgroundIframe ) {
element.setAttribute( 'data-background-hash', data.background +
data.backgroundSize +
data.backgroundImage +
data.backgroundVideo +
data.backgroundIframe +
data.backgroundColor +
data.backgroundRepeat +
data.backgroundPosition +
data.backgroundTransition );
}
// Additional and optional background properties
if( data.backgroundSize ) element.style.backgroundSize = data.backgroundSize;
if( data.backgroundColor ) element.style.backgroundColor = data.backgroundColor;
if( data.backgroundRepeat ) element.style.backgroundRepeat = data.backgroundRepeat;
if( data.backgroundPosition ) element.style.backgroundPosition = data.backgroundPosition;
if( data.backgroundTransition ) element.setAttribute( 'data-background-transition', data.backgroundTransition );
container.appendChild( element );
// If backgrounds are being recreated, clear old classes
slide.classList.remove( 'has-dark-background' );
slide.classList.remove( 'has-light-background' );
// If this slide has a background color, add a class that
// signals if it is light or dark. If the slide has no background
// color, no class will be set
var computedBackgroundColor = window.getComputedStyle( element ).backgroundColor;
if( computedBackgroundColor ) {
var rgb = colorToRgb( computedBackgroundColor );
// Ignore fully transparent backgrounds. Some browsers return
// rgba(0,0,0,0) when reading the computed background color of
// an element with no background
if( rgb && rgb.a !== 0 ) {
if( colorBrightness( computedBackgroundColor ) < 128 ) {
slide.classList.add( 'has-dark-background' );
}
else {
slide.classList.add( 'has-light-background' );
}
}
}
return element;
}
/**
* Registers a listener to postMessage events, this makes it
* possible to call all reveal.js API methods from another
* window. For example:
*
* revealWindow.postMessage( JSON.stringify({
* method: 'slide',
* args: [ 2 ]
* }), '*' );
*/
function setupPostMessage() {
if( config.postMessage ) {
window.addEventListener( 'message', function ( event ) {
var data = event.data;
// Make sure we're dealing with JSON
if( typeof data === 'string' && data.charAt( 0 ) === '{' && data.charAt( data.length - 1 ) === '}' ) {
data = JSON.parse( data );
// Check if the requested method can be found
if( data.method && typeof Reveal[data.method] === 'function' ) {
Reveal[data.method].apply( Reveal, data.args );
}
}
}, false );
}
}
/**
* Applies the configuration settings from the config
* object. May be called multiple times.
*/
function configure( options ) {
var numberOfSlides = dom.wrapper.querySelectorAll( SLIDES_SELECTOR ).length;
dom.wrapper.classList.remove( config.transition );
// New config options may be passed when this method
// is invoked through the API after initialization
if( typeof options === 'object' ) extend( config, options );
// Force linear transition based on browser capabilities
if( features.transforms3d === false ) config.transition = 'linear';
dom.wrapper.classList.add( config.transition );
dom.wrapper.setAttribute( 'data-transition-speed', config.transitionSpeed );
dom.wrapper.setAttribute( 'data-background-transition', config.backgroundTransition );
dom.controls.style.display = config.controls ? 'block' : 'none';
dom.progress.style.display = config.progress ? 'block' : 'none';
dom.slideNumber.style.display = config.slideNumber && !isPrintingPDF() ? 'block' : 'none';
if( config.shuffle ) {
shuffle();
}
if( config.rtl ) {
dom.wrapper.classList.add( 'rtl' );
}
else {
dom.wrapper.classList.remove( 'rtl' );
}
if( config.center ) {
dom.wrapper.classList.add( 'center' );
}
else {
dom.wrapper.classList.remove( 'center' );
}
// Exit the paused mode if it was configured off
if( config.pause === false ) {
resume();
}
if( config.showNotes ) {
dom.speakerNotes.classList.add( 'visible' );
}
else {
dom.speakerNotes.classList.remove( 'visible' );
}
if( config.mouseWheel ) {
document.addEventListener( 'DOMMouseScroll', onDocumentMouseScroll, false ); // FF
document.addEventListener( 'mousewheel', onDocumentMouseScroll, false );
}
else {
document.removeEventListener( 'DOMMouseScroll', onDocumentMouseScroll, false ); // FF
document.removeEventListener( 'mousewheel', onDocumentMouseScroll, false );
}
// Rolling 3D links
if( config.rollingLinks ) {
enableRollingLinks();
}
else {
disableRollingLinks();
}
// Iframe link previews
if( config.previewLinks ) {
enablePreviewLinks();
}
else {
disablePreviewLinks();
enablePreviewLinks( '[data-preview-link]' );
}
// Remove existing auto-slide controls
if( autoSlidePlayer ) {
autoSlidePlayer.destroy();
autoSlidePlayer = null;
}
// Generate auto-slide controls if needed
if( numberOfSlides > 1 && config.autoSlide && config.autoSlideStoppable && features.canvas && features.requestAnimationFrame ) {
autoSlidePlayer = new Playback( dom.wrapper, function() {
return Math.min( Math.max( ( Date.now() - autoSlideStartTime ) / autoSlide, 0 ), 1 );
} );
autoSlidePlayer.on( 'click', onAutoSlidePlayerClick );
autoSlidePaused = false;
}
// When fragments are turned off they should be visible
if( config.fragments === false ) {
toArray( dom.slides.querySelectorAll( '.fragment' ) ).forEach( function( element ) {
element.classList.add( 'visible' );
element.classList.remove( 'current-fragment' );
} );
}
sync();
}
/**
* Binds all event listeners.
*/
function addEventListeners() {
eventsAreBound = true;
window.addEventListener( 'hashchange', onWindowHashChange, false );
window.addEventListener( 'resize', onWindowResize, false );
if( config.touch ) {
dom.wrapper.addEventListener( 'touchstart', onTouchStart, false );
dom.wrapper.addEventListener( 'touchmove', onTouchMove, false );
dom.wrapper.addEventListener( 'touchend', onTouchEnd, false );
// Support pointer-style touch interaction as well
if( window.navigator.pointerEnabled ) {
// IE 11 uses un-prefixed version of pointer events
dom.wrapper.addEventListener( 'pointerdown', onPointerDown, false );
dom.wrapper.addEventListener( 'pointermove', onPointerMove, false );
dom.wrapper.addEventListener( 'pointerup', onPointerUp, false );
}
else if( window.navigator.msPointerEnabled ) {
// IE 10 uses prefixed version of pointer events
dom.wrapper.addEventListener( 'MSPointerDown', onPointerDown, false );
dom.wrapper.addEventListener( 'MSPointerMove', onPointerMove, false );
dom.wrapper.addEventListener( 'MSPointerUp', onPointerUp, false );
}
}
if( config.keyboard ) {
document.addEventListener( 'keydown', onDocumentKeyDown, false );
document.addEventListener( 'keypress', onDocumentKeyPress, false );
}
if( config.progress && dom.progress ) {
dom.progress.addEventListener( 'click', onProgressClicked, false );
}
if( config.focusBodyOnPageVisibilityChange ) {
var visibilityChange;
if( 'hidden' in document ) {
visibilityChange = 'visibilitychange';
}
else if( 'msHidden' in document ) {
visibilityChange = 'msvisibilitychange';
}
else if( 'webkitHidden' in document ) {
visibilityChange = 'webkitvisibilitychange';
}
if( visibilityChange ) {
document.addEventListener( visibilityChange, onPageVisibilityChange, false );
}
}
// Listen to both touch and click events, in case the device
// supports both
var pointerEvents = [ 'touchstart', 'click' ];
// Only support touch for Android, fixes double navigations in
// stock browser
if( UA.match( /android/gi ) ) {
pointerEvents = [ 'touchstart' ];
}
pointerEvents.forEach( function( eventName ) {
dom.controlsLeft.forEach( function( el ) { el.addEventListener( eventName, onNavigateLeftClicked, false ); } );
dom.controlsRight.forEach( function( el ) { el.addEventListener( eventName, onNavigateRightClicked, false ); } );
dom.controlsUp.forEach( function( el ) { el.addEventListener( eventName, onNavigateUpClicked, false ); } );
dom.controlsDown.forEach( function( el ) { el.addEventListener( eventName, onNavigateDownClicked, false ); } );
dom.controlsPrev.forEach( function( el ) { el.addEventListener( eventName, onNavigatePrevClicked, false ); } );
dom.controlsNext.forEach( function( el ) { el.addEventListener( eventName, onNavigateNextClicked, false ); } );
} );
}
/**
* Unbinds all event listeners.
*/
function removeEventListeners() {
eventsAreBound = false;
document.removeEventListener( 'keydown', onDocumentKeyDown, false );
document.removeEventListener( 'keypress', onDocumentKeyPress, false );
window.removeEventListener( 'hashchange', onWindowHashChange, false );
window.removeEventListener( 'resize', onWindowResize, false );
dom.wrapper.removeEventListener( 'touchstart', onTouchStart, false );
dom.wrapper.removeEventListener( 'touchmove', onTouchMove, false );
dom.wrapper.removeEventListener( 'touchend', onTouchEnd, false );
// IE11
if( window.navigator.pointerEnabled ) {
dom.wrapper.removeEventListener( 'pointerdown', onPointerDown, false );
dom.wrapper.removeEventListener( 'pointermove', onPointerMove, false );
dom.wrapper.removeEventListener( 'pointerup', onPointerUp, false );
}
// IE10
else if( window.navigator.msPointerEnabled ) {
dom.wrapper.removeEventListener( 'MSPointerDown', onPointerDown, false );
dom.wrapper.removeEventListener( 'MSPointerMove', onPointerMove, false );
dom.wrapper.removeEventListener( 'MSPointerUp', onPointerUp, false );
}
if ( config.progress && dom.progress ) {
dom.progress.removeEventListener( 'click', onProgressClicked, false );
}
[ 'touchstart', 'click' ].forEach( function( eventName ) {
dom.controlsLeft.forEach( function( el ) { el.removeEventListener( eventName, onNavigateLeftClicked, false ); } );
dom.controlsRight.forEach( function( el ) { el.removeEventListener( eventName, onNavigateRightClicked, false ); } );
dom.controlsUp.forEach( function( el ) { el.removeEventListener( eventName, onNavigateUpClicked, false ); } );
dom.controlsDown.forEach( function( el ) { el.removeEventListener( eventName, onNavigateDownClicked, false ); } );
dom.controlsPrev.forEach( function( el ) { el.removeEventListener( eventName, onNavigatePrevClicked, false ); } );
dom.controlsNext.forEach( function( el ) { el.removeEventListener( eventName, onNavigateNextClicked, false ); } );
} );
}
/**
* Extend object a with the properties of object b.
* If there's a conflict, object b takes precedence.
*/
function extend( a, b ) {
for( var i in b ) {
a[ i ] = b[ i ];
}
}
/**
* Converts the target object to an array.
*/
function toArray( o ) {
return Array.prototype.slice.call( o );
}
/**
* Utility for deserializing a value.
*/
function deserialize( value ) {
if( typeof value === 'string' ) {
if( value === 'null' ) return null;
else if( value === 'true' ) return true;
else if( value === 'false' ) return false;
else if( value.match( /^\d+$/ ) ) return parseFloat( value );
}
return value;
}
/**
* Measures the distance in pixels between point a
* and point b.
*
* @param {Object} a point with x/y properties
* @param {Object} b point with x/y properties
*/
function distanceBetween( a, b ) {
var dx = a.x - b.x,
dy = a.y - b.y;
return Math.sqrt( dx*dx + dy*dy );
}
/**
* Applies a CSS transform to the target element.
*/
function transformElement( element, transform ) {
element.style.WebkitTransform = transform;
element.style.MozTransform = transform;
element.style.msTransform = transform;
element.style.transform = transform;
}
/**
* Applies CSS transforms to the slides container. The container
* is transformed from two separate sources: layout and the overview
* mode.
*/
function transformSlides( transforms ) {
// Pick up new transforms from arguments
if( typeof transforms.layout === 'string' ) slidesTransform.layout = transforms.layout;
if( typeof transforms.overview === 'string' ) slidesTransform.overview = transforms.overview;
// Apply the transforms to the slides container
if( slidesTransform.layout ) {
transformElement( dom.slides, slidesTransform.layout + ' ' + slidesTransform.overview );
}
else {
transformElement( dom.slides, slidesTransform.overview );
}
}
/**
* Injects the given CSS styles into the DOM.
*/
function injectStyleSheet( value ) {
var tag = document.createElement( 'style' );
tag.type = 'text/css';
if( tag.styleSheet ) {
tag.styleSheet.cssText = value;
}
else {
tag.appendChild( document.createTextNode( value ) );
}
document.getElementsByTagName( 'head' )[0].appendChild( tag );
}
/**
* Converts various color input formats to an {r:0,g:0,b:0} object.
*
* @param {String} color The string representation of a color,
* the following formats are supported:
* - #000
* - #000000
* - rgb(0,0,0)
*/
function colorToRgb( color ) {
var hex3 = color.match( /^#([0-9a-f]{3})$/i );
if( hex3 && hex3[1] ) {
hex3 = hex3[1];
return {
r: parseInt( hex3.charAt( 0 ), 16 ) * 0x11,
g: parseInt( hex3.charAt( 1 ), 16 ) * 0x11,
b: parseInt( hex3.charAt( 2 ), 16 ) * 0x11
};
}
var hex6 = color.match( /^#([0-9a-f]{6})$/i );
if( hex6 && hex6[1] ) {
hex6 = hex6[1];
return {
r: parseInt( hex6.substr( 0, 2 ), 16 ),
g: parseInt( hex6.substr( 2, 2 ), 16 ),
b: parseInt( hex6.substr( 4, 2 ), 16 )
};
}
var rgb = color.match( /^rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/i );
if( rgb ) {
return {
r: parseInt( rgb[1], 10 ),
g: parseInt( rgb[2], 10 ),
b: parseInt( rgb[3], 10 )
};
}
var rgba = color.match( /^rgba\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\,\s*([\d]+|[\d]*.[\d]+)\s*\)$/i );
if( rgba ) {
return {
r: parseInt( rgba[1], 10 ),
g: parseInt( rgba[2], 10 ),
b: parseInt( rgba[3], 10 ),
a: parseFloat( rgba[4] )
};
}
return null;
}
/**
* Calculates brightness on a scale of 0-255.
*
* @param color See colorStringToRgb for supported formats.
*/
function colorBrightness( color ) {
if( typeof color === 'string' ) color = colorToRgb( color );
if( color ) {
return ( color.r * 299 + color.g * 587 + color.b * 114 ) / 1000;
}
return null;
}
/**
* Retrieves the height of the given element by looking
* at the position and height of its immediate children.
*/
function getAbsoluteHeight( element ) {
var height = 0;
if( element ) {
var absoluteChildren = 0;
toArray( element.childNodes ).forEach( function( child ) {
if( typeof child.offsetTop === 'number' && child.style ) {
// Count # of abs children
if( window.getComputedStyle( child ).position === 'absolute' ) {
absoluteChildren += 1;
}
height = Math.max( height, child.offsetTop + child.offsetHeight );
}
} );
// If there are no absolute children, use offsetHeight
if( absoluteChildren === 0 ) {
height = element.offsetHeight;
}
}
return height;
}
/**
* Returns the remaining height within the parent of the
* target element.
*
* remaining height = [ configured parent height ] - [ current parent height ]
*/
function getRemainingHeight( element, height ) {
height = height || 0;
if( element ) {
var newHeight, oldHeight = element.style.height;
// Change the .stretch element height to 0 in order find the height of all
// the other elements
element.style.height = '0px';
newHeight = height - element.parentNode.offsetHeight;
// Restore the old height, just in case
element.style.height = oldHeight + 'px';
return newHeight;
}
return height;
}
/**
* Checks if this instance is being used to print a PDF.
*/
function isPrintingPDF() {
return ( /print-pdf/gi ).test( window.location.search );
}
/**
* Hides the address bar if we're on a mobile device.
*/
function hideAddressBar() {
if( config.hideAddressBar && isMobileDevice ) {
// Events that should trigger the address bar to hide
window.addEventListener( 'load', removeAddressBar, false );
window.addEventListener( 'orientationchange', removeAddressBar, false );
}
}
/**
* Causes the address bar to hide on mobile devices,
* more vertical space ftw.
*/
function removeAddressBar() {
setTimeout( function() {
window.scrollTo( 0, 1 );
}, 10 );
}
/**
* Dispatches an event of the specified type from the
* reveal DOM element.
*/
function dispatchEvent( type, args ) {
var event = document.createEvent( 'HTMLEvents', 1, 2 );
event.initEvent( type, true, true );
extend( event, args );
dom.wrapper.dispatchEvent( event );
// If we're in an iframe, post each reveal.js event to the
// parent window. Used by the notes plugin
if( config.postMessageEvents && window.parent !== window.self ) {
window.parent.postMessage( JSON.stringify({ namespace: 'reveal', eventName: type, state: getState() }), '*' );
}
}
/**
* Wrap all links in 3D goodness.
*/
function enableRollingLinks() {
if( features.transforms3d && !( 'msPerspective' in document.body.style ) ) {
var anchors = dom.wrapper.querySelectorAll( SLIDES_SELECTOR + ' a' );
for( var i = 0, len = anchors.length; i < len; i++ ) {
var anchor = anchors[i];
if( anchor.textContent && !anchor.querySelector( '*' ) && ( !anchor.className || !anchor.classList.contains( anchor, 'roll' ) ) ) {
var span = document.createElement('span');
span.setAttribute('data-title', anchor.text);
span.innerHTML = anchor.innerHTML;
anchor.classList.add( 'roll' );
anchor.innerHTML = '';
anchor.appendChild(span);
}
}
}
}
/**
* Unwrap all 3D links.
*/
function disableRollingLinks() {
var anchors = dom.wrapper.querySelectorAll( SLIDES_SELECTOR + ' a.roll' );
for( var i = 0, len = anchors.length; i < len; i++ ) {
var anchor = anchors[i];
var span = anchor.querySelector( 'span' );
if( span ) {
anchor.classList.remove( 'roll' );
anchor.innerHTML = span.innerHTML;
}
}
}
/**
* Bind preview frame links.
*/
function enablePreviewLinks( selector ) {
var anchors = toArray( document.querySelectorAll( selector ? selector : 'a' ) );
anchors.forEach( function( element ) {
if( /^(http|www)/gi.test( element.getAttribute( 'href' ) ) ) {
element.addEventListener( 'click', onPreviewLinkClicked, false );
}
} );
}
/**
* Unbind preview frame links.
*/
function disablePreviewLinks() {
var anchors = toArray( document.querySelectorAll( 'a' ) );
anchors.forEach( function( element ) {
if( /^(http|www)/gi.test( element.getAttribute( 'href' ) ) ) {
element.removeEventListener( 'click', onPreviewLinkClicked, false );
}
} );
}
/**
* Opens a preview window for the target URL.
*/
function showPreview( url ) {
closeOverlay();
dom.overlay = document.createElement( 'div' );
dom.overlay.classList.add( 'overlay' );
dom.overlay.classList.add( 'overlay-preview' );
dom.wrapper.appendChild( dom.overlay );
dom.overlay.innerHTML = [
'<header>',
'<a class="close" href="#"><span class="icon"></span></a>',
'<a class="external" href="'+ url +'" target="_blank"><span class="icon"></span></a>',
'</header>',
'<div class="spinner"></div>',
'<div class="viewport">',
'<iframe src="'+ url +'"></iframe>',
'</div>'
].join('');
dom.overlay.querySelector( 'iframe' ).addEventListener( 'load', function( event ) {
dom.overlay.classList.add( 'loaded' );
}, false );
dom.overlay.querySelector( '.close' ).addEventListener( 'click', function( event ) {
closeOverlay();
event.preventDefault();
}, false );
dom.overlay.querySelector( '.external' ).addEventListener( 'click', function( event ) {
closeOverlay();
}, false );
setTimeout( function() {
dom.overlay.classList.add( 'visible' );
}, 1 );
}
/**
* Opens a overlay window with help material.
*/
function showHelp() {
if( config.help ) {
closeOverlay();
dom.overlay = document.createElement( 'div' );
dom.overlay.classList.add( 'overlay' );
dom.overlay.classList.add( 'overlay-help' );
dom.wrapper.appendChild( dom.overlay );
var html = '<p class="title">Keyboard Shortcuts</p><br/>';
html += '<table><th>KEY</th><th>ACTION</th>';
for( var key in keyboardShortcuts ) {
html += '<tr><td>' + key + '</td><td>' + keyboardShortcuts[ key ] + '</td></tr>';
}
html += '</table>';
dom.overlay.innerHTML = [
'<header>',
'<a class="close" href="#"><span class="icon"></span></a>',
'</header>',
'<div class="viewport">',
'<div class="viewport-inner">'+ html +'</div>',
'</div>'
].join('');
dom.overlay.querySelector( '.close' ).addEventListener( 'click', function( event ) {
closeOverlay();
event.preventDefault();
}, false );
setTimeout( function() {
dom.overlay.classList.add( 'visible' );
}, 1 );
}
}
/**
* Closes any currently open overlay.
*/
function closeOverlay() {
if( dom.overlay ) {
dom.overlay.parentNode.removeChild( dom.overlay );
dom.overlay = null;
}
}
/**
* Applies JavaScript-controlled layout rules to the
* presentation.
*/
function layout() {
if( dom.wrapper && !isPrintingPDF() ) {
var size = getComputedSlideSize();
var slidePadding = 20; // TODO Dig this out of DOM
// Layout the contents of the slides
layoutSlideContents( config.width, config.height, slidePadding );
dom.slides.style.width = size.width + 'px';
dom.slides.style.height = size.height + 'px';
// Determine scale of content to fit within available space
scale = Math.min( size.presentationWidth / size.width, size.presentationHeight / size.height );
// Respect max/min scale settings
scale = Math.max( scale, config.minScale );
scale = Math.min( scale, config.maxScale );
// Don't apply any scaling styles if scale is 1
if( scale === 1 ) {
dom.slides.style.zoom = '';
dom.slides.style.left = '';
dom.slides.style.top = '';
dom.slides.style.bottom = '';
dom.slides.style.right = '';
transformSlides( { layout: '' } );
}
else {
// Prefer zoom for scaling up so that content remains crisp.
// Don't use zoom to scale down since that can lead to shifts
// in text layout/line breaks.
if( scale > 1 && features.zoom ) {
dom.slides.style.zoom = scale;
dom.slides.style.left = '';
dom.slides.style.top = '';
dom.slides.style.bottom = '';
dom.slides.style.right = '';
transformSlides( { layout: '' } );
}
// Apply scale transform as a fallback
else {
dom.slides.style.zoom = '';
dom.slides.style.left = '50%';
dom.slides.style.top = '50%';
dom.slides.style.bottom = 'auto';
dom.slides.style.right = 'auto';
transformSlides( { layout: 'translate(-50%, -50%) scale('+ scale +')' } );
}
}
// Select all slides, vertical and horizontal
var slides = toArray( dom.wrapper.querySelectorAll( SLIDES_SELECTOR ) );
for( var i = 0, len = slides.length; i < len; i++ ) {
var slide = slides[ i ];
// Don't bother updating invisible slides
if( slide.style.display === 'none' ) {
continue;
}
if( config.center || slide.classList.contains( 'center' ) ) {
// Vertical stacks are not centred since their section
// children will be
if( slide.classList.contains( 'stack' ) ) {
slide.style.top = 0;
}
else {
slide.style.top = Math.max( ( ( size.height - getAbsoluteHeight( slide ) ) / 2 ) - slidePadding, 0 ) + 'px';
}
}
else {
slide.style.top = '';
}
}
updateProgress();
updateParallax();
}
}
/**
* Applies layout logic to the contents of all slides in
* the presentation.
*/
function layoutSlideContents( width, height, padding ) {
// Handle sizing of elements with the 'stretch' class
toArray( dom.slides.querySelectorAll( 'section > .stretch' ) ).forEach( function( element ) {
// Determine how much vertical space we can use
var remainingHeight = getRemainingHeight( element, height );
// Consider the aspect ratio of media elements
if( /(img|video)/gi.test( element.nodeName ) ) {
var nw = element.naturalWidth || element.videoWidth,
nh = element.naturalHeight || element.videoHeight;
var es = Math.min( width / nw, remainingHeight / nh );
element.style.width = ( nw * es ) + 'px';
element.style.height = ( nh * es ) + 'px';
}
else {
element.style.width = width + 'px';
element.style.height = remainingHeight + 'px';
}
} );
}
/**
* Calculates the computed pixel size of our slides. These
* values are based on the width and height configuration
* options.
*/
function getComputedSlideSize( presentationWidth, presentationHeight ) {
var size = {
// Slide size
width: config.width,
height: config.height,
// Presentation size
presentationWidth: presentationWidth || dom.wrapper.offsetWidth,
presentationHeight: presentationHeight || dom.wrapper.offsetHeight
};
// Reduce available space by margin
size.presentationWidth -= ( size.presentationWidth * config.margin );
size.presentationHeight -= ( size.presentationHeight * config.margin );
// Slide width may be a percentage of available width
if( typeof size.width === 'string' && /%$/.test( size.width ) ) {
size.width = parseInt( size.width, 10 ) / 100 * size.presentationWidth;
}
// Slide height may be a percentage of available height
if( typeof size.height === 'string' && /%$/.test( size.height ) ) {
size.height = parseInt( size.height, 10 ) / 100 * size.presentationHeight;
}
return size;
}
/**
* Stores the vertical index of a stack so that the same
* vertical slide can be selected when navigating to and
* from the stack.
*
* @param {HTMLElement} stack The vertical stack element
* @param {int} v Index to memorize
*/
function setPreviousVerticalIndex( stack, v ) {
if( typeof stack === 'object' && typeof stack.setAttribute === 'function' ) {
stack.setAttribute( 'data-previous-indexv', v || 0 );
}
}
/**
* Retrieves the vertical index which was stored using
* #setPreviousVerticalIndex() or 0 if no previous index
* exists.
*
* @param {HTMLElement} stack The vertical stack element
*/
function getPreviousVerticalIndex( stack ) {
if( typeof stack === 'object' && typeof stack.setAttribute === 'function' && stack.classList.contains( 'stack' ) ) {
// Prefer manually defined start-indexv
var attributeName = stack.hasAttribute( 'data-start-indexv' ) ? 'data-start-indexv' : 'data-previous-indexv';
return parseInt( stack.getAttribute( attributeName ) || 0, 10 );
}
return 0;
}
/**
* Displays the overview of slides (quick nav) by scaling
* down and arranging all slide elements.
*/
function activateOverview() {
// Only proceed if enabled in config
if( config.overview && !isOverview() ) {
overview = true;
dom.wrapper.classList.add( 'overview' );
dom.wrapper.classList.remove( 'overview-deactivating' );
if( features.overviewTransitions ) {
setTimeout( function() {
dom.wrapper.classList.add( 'overview-animated' );
}, 1 );
}
// Don't auto-slide while in overview mode
cancelAutoSlide();
// Move the backgrounds element into the slide container to
// that the same scaling is applied
dom.slides.appendChild( dom.background );
// Clicking on an overview slide navigates to it
toArray( dom.wrapper.querySelectorAll( SLIDES_SELECTOR ) ).forEach( function( slide ) {
if( !slide.classList.contains( 'stack' ) ) {
slide.addEventListener( 'click', onOverviewSlideClicked, true );
}
} );
// Calculate slide sizes
var margin = 70;
var slideSize = getComputedSlideSize();
overviewSlideWidth = slideSize.width + margin;
overviewSlideHeight = slideSize.height + margin;
// Reverse in RTL mode
if( config.rtl ) {
overviewSlideWidth = -overviewSlideWidth;
}
updateSlidesVisibility();
layoutOverview();
updateOverview();
layout();
// Notify observers of the overview showing
dispatchEvent( 'overviewshown', {
'indexh': indexh,
'indexv': indexv,
'currentSlide': currentSlide
} );
}
}
/**
* Uses CSS transforms to position all slides in a grid for
* display inside of the overview mode.
*/
function layoutOverview() {
// Layout slides
toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ).forEach( function( hslide, h ) {
hslide.setAttribute( 'data-index-h', h );
transformElement( hslide, 'translate3d(' + ( h * overviewSlideWidth ) + 'px, 0, 0)' );
if( hslide.classList.contains( 'stack' ) ) {
toArray( hslide.querySelectorAll( 'section' ) ).forEach( function( vslide, v ) {
vslide.setAttribute( 'data-index-h', h );
vslide.setAttribute( 'data-index-v', v );
transformElement( vslide, 'translate3d(0, ' + ( v * overviewSlideHeight ) + 'px, 0)' );
} );
}
} );
// Layout slide backgrounds
toArray( dom.background.childNodes ).forEach( function( hbackground, h ) {
transformElement( hbackground, 'translate3d(' + ( h * overviewSlideWidth ) + 'px, 0, 0)' );
toArray( hbackground.querySelectorAll( '.slide-background' ) ).forEach( function( vbackground, v ) {
transformElement( vbackground, 'translate3d(0, ' + ( v * overviewSlideHeight ) + 'px, 0)' );
} );
} );
}
/**
* Moves the overview viewport to the current slides.
* Called each time the current slide changes.
*/
function updateOverview() {
transformSlides( {
overview: [
'translateX('+ ( -indexh * overviewSlideWidth ) +'px)',
'translateY('+ ( -indexv * overviewSlideHeight ) +'px)',
'translateZ('+ ( window.innerWidth < 400 ? -1000 : -2500 ) +'px)'
].join( ' ' )
} );
}
/**
* Exits the slide overview and enters the currently
* active slide.
*/
function deactivateOverview() {
// Only proceed if enabled in config
if( config.overview ) {
overview = false;
dom.wrapper.classList.remove( 'overview' );
dom.wrapper.classList.remove( 'overview-animated' );
// Temporarily add a class so that transitions can do different things
// depending on whether they are exiting/entering overview, or just
// moving from slide to slide
dom.wrapper.classList.add( 'overview-deactivating' );
setTimeout( function () {
dom.wrapper.classList.remove( 'overview-deactivating' );
}, 1 );
// Move the background element back out
dom.wrapper.appendChild( dom.background );
// Clean up changes made to slides
toArray( dom.wrapper.querySelectorAll( SLIDES_SELECTOR ) ).forEach( function( slide ) {
transformElement( slide, '' );
slide.removeEventListener( 'click', onOverviewSlideClicked, true );
} );
// Clean up changes made to backgrounds
toArray( dom.background.querySelectorAll( '.slide-background' ) ).forEach( function( background ) {
transformElement( background, '' );
} );
transformSlides( { overview: '' } );
slide( indexh, indexv );
layout();
cueAutoSlide();
// Notify observers of the overview hiding
dispatchEvent( 'overviewhidden', {
'indexh': indexh,
'indexv': indexv,
'currentSlide': currentSlide
} );
}
}
/**
* Toggles the slide overview mode on and off.
*
* @param {Boolean} override Optional flag which overrides the
* toggle logic and forcibly sets the desired state. True means
* overview is open, false means it's closed.
*/
function toggleOverview( override ) {
if( typeof override === 'boolean' ) {
override ? activateOverview() : deactivateOverview();
}
else {
isOverview() ? deactivateOverview() : activateOverview();
}
}
/**
* Checks if the overview is currently active.
*
* @return {Boolean} true if the overview is active,
* false otherwise
*/
function isOverview() {
return overview;
}
/**
* Checks if the current or specified slide is vertical
* (nested within another slide).
*
* @param {HTMLElement} slide [optional] The slide to check
* orientation of
*/
function isVerticalSlide( slide ) {
// Prefer slide argument, otherwise use current slide
slide = slide ? slide : currentSlide;
return slide && slide.parentNode && !!slide.parentNode.nodeName.match( /section/i );
}
/**
* Handling the fullscreen functionality via the fullscreen API
*
* @see http://fullscreen.spec.whatwg.org/
* @see https://developer.mozilla.org/en-US/docs/DOM/Using_fullscreen_mode
*/
function enterFullscreen() {
var element = document.body;
// Check which implementation is available
var requestMethod = element.requestFullScreen ||
element.webkitRequestFullscreen ||
element.webkitRequestFullScreen ||
element.mozRequestFullScreen ||
element.msRequestFullscreen;
if( requestMethod ) {
requestMethod.apply( element );
}
}
/**
* Enters the paused mode which fades everything on screen to
* black.
*/
function pause() {
if( config.pause ) {
var wasPaused = dom.wrapper.classList.contains( 'paused' );
cancelAutoSlide();
dom.wrapper.classList.add( 'paused' );
if( wasPaused === false ) {
dispatchEvent( 'paused' );
}
}
}
/**
* Exits from the paused mode.
*/
function resume() {
var wasPaused = dom.wrapper.classList.contains( 'paused' );
dom.wrapper.classList.remove( 'paused' );
cueAutoSlide();
if( wasPaused ) {
dispatchEvent( 'resumed' );
}
}
/**
* Toggles the paused mode on and off.
*/
function togglePause( override ) {
if( typeof override === 'boolean' ) {
override ? pause() : resume();
}
else {
isPaused() ? resume() : pause();
}
}
/**
* Checks if we are currently in the paused mode.
*/
function isPaused() {
return dom.wrapper.classList.contains( 'paused' );
}
/**
* Toggles the auto slide mode on and off.
*
* @param {Boolean} override Optional flag which sets the desired state.
* True means autoplay starts, false means it stops.
*/
function toggleAutoSlide( override ) {
if( typeof override === 'boolean' ) {
override ? resumeAutoSlide() : pauseAutoSlide();
}
else {
autoSlidePaused ? resumeAutoSlide() : pauseAutoSlide();
}
}
/**
* Checks if the auto slide mode is currently on.
*/
function isAutoSliding() {
return !!( autoSlide && !autoSlidePaused );
}
/**
* Steps from the current point in the presentation to the
* slide which matches the specified horizontal and vertical
* indices.
*
* @param {int} h Horizontal index of the target slide
* @param {int} v Vertical index of the target slide
* @param {int} f Optional index of a fragment within the
* target slide to activate
* @param {int} o Optional origin for use in multimaster environments
*/
function slide( h, v, f, o ) {
// Remember where we were at before
previousSlide = currentSlide;
// Query all horizontal slides in the deck
var horizontalSlides = dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR );
// If no vertical index is specified and the upcoming slide is a
// stack, resume at its previous vertical index
if( v === undefined && !isOverview() ) {
v = getPreviousVerticalIndex( horizontalSlides[ h ] );
}
// If we were on a vertical stack, remember what vertical index
// it was on so we can resume at the same position when returning
if( previousSlide && previousSlide.parentNode && previousSlide.parentNode.classList.contains( 'stack' ) ) {
setPreviousVerticalIndex( previousSlide.parentNode, indexv );
}
// Remember the state before this slide
var stateBefore = state.concat();
// Reset the state array
state.length = 0;
var indexhBefore = indexh || 0,
indexvBefore = indexv || 0;
// Activate and transition to the new slide
indexh = updateSlides( HORIZONTAL_SLIDES_SELECTOR, h === undefined ? indexh : h );
indexv = updateSlides( VERTICAL_SLIDES_SELECTOR, v === undefined ? indexv : v );
// Update the visibility of slides now that the indices have changed
updateSlidesVisibility();
layout();
// Apply the new state
stateLoop: for( var i = 0, len = state.length; i < len; i++ ) {
// Check if this state existed on the previous slide. If it
// did, we will avoid adding it repeatedly
for( var j = 0; j < stateBefore.length; j++ ) {
if( stateBefore[j] === state[i] ) {
stateBefore.splice( j, 1 );
continue stateLoop;
}
}
document.documentElement.classList.add( state[i] );
// Dispatch custom event matching the state's name
dispatchEvent( state[i] );
}
// Clean up the remains of the previous state
while( stateBefore.length ) {
document.documentElement.classList.remove( stateBefore.pop() );
}
// Update the overview if it's currently active
if( isOverview() ) {
updateOverview();
}
// Find the current horizontal slide and any possible vertical slides
// within it
var currentHorizontalSlide = horizontalSlides[ indexh ],
currentVerticalSlides = currentHorizontalSlide.querySelectorAll( 'section' );
// Store references to the previous and current slides
currentSlide = currentVerticalSlides[ indexv ] || currentHorizontalSlide;
// Show fragment, if specified
if( typeof f !== 'undefined' ) {
navigateFragment( f );
}
// Dispatch an event if the slide changed
var slideChanged = ( indexh !== indexhBefore || indexv !== indexvBefore );
if( slideChanged ) {
dispatchEvent( 'slidechanged', {
'indexh': indexh,
'indexv': indexv,
'previousSlide': previousSlide,
'currentSlide': currentSlide,
'origin': o
} );
}
else {
// Ensure that the previous slide is never the same as the current
previousSlide = null;
}
// Solves an edge case where the previous slide maintains the
// 'present' class when navigating between adjacent vertical
// stacks
if( previousSlide ) {
previousSlide.classList.remove( 'present' );
previousSlide.setAttribute( 'aria-hidden', 'true' );
// Reset all slides upon navigate to home
// Issue: #285
if ( dom.wrapper.querySelector( HOME_SLIDE_SELECTOR ).classList.contains( 'present' ) ) {
// Launch async task
setTimeout( function () {
var slides = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR + '.stack') ), i;
for( i in slides ) {
if( slides[i] ) {
// Reset stack
setPreviousVerticalIndex( slides[i], 0 );
}
}
}, 0 );
}
}
// Handle embedded content
if( slideChanged || !previousSlide ) {
stopEmbeddedContent( previousSlide );
startEmbeddedContent( currentSlide );
}
// Announce the current slide contents, for screen readers
dom.statusDiv.textContent = currentSlide.textContent;
updateControls();
updateProgress();
updateBackground();
updateParallax();
updateSlideNumber();
updateNotes();
// Update the URL hash
writeURL();
cueAutoSlide();
}
/**
* Syncs the presentation with the current DOM. Useful
* when new slides or control elements are added or when
* the configuration has changed.
*/
function sync() {
// Subscribe to input
removeEventListeners();
addEventListeners();
// Force a layout to make sure the current config is accounted for
layout();
// Reflect the current autoSlide value
autoSlide = config.autoSlide;
// Start auto-sliding if it's enabled
cueAutoSlide();
// Re-create the slide backgrounds
createBackgrounds();
// Write the current hash to the URL
writeURL();
sortAllFragments();
updateControls();
updateProgress();
updateBackground( true );
updateSlideNumber();
updateSlidesVisibility();
updateNotes();
formatEmbeddedContent();
startEmbeddedContent( currentSlide );
if( isOverview() ) {
layoutOverview();
}
}
/**
* Resets all vertical slides so that only the first
* is visible.
*/
function resetVerticalSlides() {
var horizontalSlides = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) );
horizontalSlides.forEach( function( horizontalSlide ) {
var verticalSlides = toArray( horizontalSlide.querySelectorAll( 'section' ) );
verticalSlides.forEach( function( verticalSlide, y ) {
if( y > 0 ) {
verticalSlide.classList.remove( 'present' );
verticalSlide.classList.remove( 'past' );
verticalSlide.classList.add( 'future' );
verticalSlide.setAttribute( 'aria-hidden', 'true' );
}
} );
} );
}
/**
* Sorts and formats all of fragments in the
* presentation.
*/
function sortAllFragments() {
var horizontalSlides = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) );
horizontalSlides.forEach( function( horizontalSlide ) {
var verticalSlides = toArray( horizontalSlide.querySelectorAll( 'section' ) );
verticalSlides.forEach( function( verticalSlide, y ) {
sortFragments( verticalSlide.querySelectorAll( '.fragment' ) );
} );
if( verticalSlides.length === 0 ) sortFragments( horizontalSlide.querySelectorAll( '.fragment' ) );
} );
}
/**
* Randomly shuffles all slides in the deck.
*/
function shuffle() {
var slides = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) );
slides.forEach( function( slide ) {
// Insert this slide next to another random slide. This may
// cause the slide to insert before itself but that's fine.
dom.slides.insertBefore( slide, slides[ Math.floor( Math.random() * slides.length ) ] );
} );
}
/**
* Updates one dimension of slides by showing the slide
* with the specified index.
*
* @param {String} selector A CSS selector that will fetch
* the group of slides we are working with
* @param {Number} index The index of the slide that should be
* shown
*
* @return {Number} The index of the slide that is now shown,
* might differ from the passed in index if it was out of
* bounds.
*/
function updateSlides( selector, index ) {
// Select all slides and convert the NodeList result to
// an array
var slides = toArray( dom.wrapper.querySelectorAll( selector ) ),
slidesLength = slides.length;
var printMode = isPrintingPDF();
if( slidesLength ) {
// Should the index loop?
if( config.loop ) {
index %= slidesLength;
if( index < 0 ) {
index = slidesLength + index;
}
}
// Enforce max and minimum index bounds
index = Math.max( Math.min( index, slidesLength - 1 ), 0 );
for( var i = 0; i < slidesLength; i++ ) {
var element = slides[i];
var reverse = config.rtl && !isVerticalSlide( element );
element.classList.remove( 'past' );
element.classList.remove( 'present' );
element.classList.remove( 'future' );
// http://www.w3.org/html/wg/drafts/html/master/editing.html#the-hidden-attribute
element.setAttribute( 'hidden', '' );
element.setAttribute( 'aria-hidden', 'true' );
// If this element contains vertical slides
if( element.querySelector( 'section' ) ) {
element.classList.add( 'stack' );
}
// If we're printing static slides, all slides are "present"
if( printMode ) {
element.classList.add( 'present' );
continue;
}
if( i < index ) {
// Any element previous to index is given the 'past' class
element.classList.add( reverse ? 'future' : 'past' );
if( config.fragments ) {
var pastFragments = toArray( element.querySelectorAll( '.fragment' ) );
// Show all fragments on prior slides
while( pastFragments.length ) {
var pastFragment = pastFragments.pop();
pastFragment.classList.add( 'visible' );
pastFragment.classList.remove( 'current-fragment' );
}
}
}
else if( i > index ) {
// Any element subsequent to index is given the 'future' class
element.classList.add( reverse ? 'past' : 'future' );
if( config.fragments ) {
var futureFragments = toArray( element.querySelectorAll( '.fragment.visible' ) );
// No fragments in future slides should be visible ahead of time
while( futureFragments.length ) {
var futureFragment = futureFragments.pop();
futureFragment.classList.remove( 'visible' );
futureFragment.classList.remove( 'current-fragment' );
}
}
}
}
// Mark the current slide as present
slides[index].classList.add( 'present' );
slides[index].removeAttribute( 'hidden' );
slides[index].removeAttribute( 'aria-hidden' );
// If this slide has a state associated with it, add it
// onto the current state of the deck
var slideState = slides[index].getAttribute( 'data-state' );
if( slideState ) {
state = state.concat( slideState.split( ' ' ) );
}
}
else {
// Since there are no slides we can't be anywhere beyond the
// zeroth index
index = 0;
}
return index;
}
/**
* Optimization method; hide all slides that are far away
* from the present slide.
*/
function updateSlidesVisibility() {
// Select all slides and convert the NodeList result to
// an array
var horizontalSlides = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ),
horizontalSlidesLength = horizontalSlides.length,
distanceX,
distanceY;
if( horizontalSlidesLength && typeof indexh !== 'undefined' ) {
// The number of steps away from the present slide that will
// be visible
var viewDistance = isOverview() ? 10 : config.viewDistance;
// Limit view distance on weaker devices
if( isMobileDevice ) {
viewDistance = isOverview() ? 6 : 2;
}
// All slides need to be visible when exporting to PDF
if( isPrintingPDF() ) {
viewDistance = Number.MAX_VALUE;
}
for( var x = 0; x < horizontalSlidesLength; x++ ) {
var horizontalSlide = horizontalSlides[x];
var verticalSlides = toArray( horizontalSlide.querySelectorAll( 'section' ) ),
verticalSlidesLength = verticalSlides.length;
// Determine how far away this slide is from the present
distanceX = Math.abs( ( indexh || 0 ) - x ) || 0;
// If the presentation is looped, distance should measure
// 1 between the first and last slides
if( config.loop ) {
distanceX = Math.abs( ( ( indexh || 0 ) - x ) % ( horizontalSlidesLength - viewDistance ) ) || 0;
}
// Show the horizontal slide if it's within the view distance
if( distanceX < viewDistance ) {
showSlide( horizontalSlide );
}
else {
hideSlide( horizontalSlide );
}
if( verticalSlidesLength ) {
var oy = getPreviousVerticalIndex( horizontalSlide );
for( var y = 0; y < verticalSlidesLength; y++ ) {
var verticalSlide = verticalSlides[y];
distanceY = x === ( indexh || 0 ) ? Math.abs( ( indexv || 0 ) - y ) : Math.abs( y - oy );
if( distanceX + distanceY < viewDistance ) {
showSlide( verticalSlide );
}
else {
hideSlide( verticalSlide );
}
}
}
}
}
}
/**
* Pick up notes from the current slide and display tham
* to the viewer.
*
* @see `showNotes` config value
*/
function updateNotes() {
if( config.showNotes && dom.speakerNotes && currentSlide && !isPrintingPDF() ) {
dom.speakerNotes.innerHTML = getSlideNotes() || '';
}
}
/**
* Updates the progress bar to reflect the current slide.
*/
function updateProgress() {
// Update progress if enabled
if( config.progress && dom.progressbar ) {
dom.progressbar.style.width = getProgress() * dom.wrapper.offsetWidth + 'px';
}
}
/**
* Updates the slide number div to reflect the current slide.
*
* The following slide number formats are available:
* "h.v": horizontal . vertical slide number (default)
* "h/v": horizontal / vertical slide number
* "c": flattened slide number
* "c/t": flattened slide number / total slides
*/
function updateSlideNumber() {
// Update slide number if enabled
if( config.slideNumber && dom.slideNumber ) {
var value = [];
var format = 'h.v';
// Check if a custom number format is available
if( typeof config.slideNumber === 'string' ) {
format = config.slideNumber;
}
switch( format ) {
case 'c':
value.push( getSlidePastCount() + 1 );
break;
case 'c/t':
value.push( getSlidePastCount() + 1, '/', getTotalSlides() );
break;
case 'h/v':
value.push( indexh + 1 );
if( isVerticalSlide() ) value.push( '/', indexv + 1 );
break;
default:
value.push( indexh + 1 );
if( isVerticalSlide() ) value.push( '.', indexv + 1 );
}
dom.slideNumber.innerHTML = formatSlideNumber( value[0], value[1], value[2] );
}
}
/**
* Applies HTML formatting to a slide number before it's
* written to the DOM.
*/
function formatSlideNumber( a, delimiter, b ) {
if( typeof b === 'number' && !isNaN( b ) ) {
return '<span class="slide-number-a">'+ a +'</span>' +
'<span class="slide-number-delimiter">'+ delimiter +'</span>' +
'<span class="slide-number-b">'+ b +'</span>';
}
else {
return '<span class="slide-number-a">'+ a +'</span>';
}
}
/**
* Updates the state of all control/navigation arrows.
*/
function updateControls() {
var routes = availableRoutes();
var fragments = availableFragments();
// Remove the 'enabled' class from all directions
dom.controlsLeft.concat( dom.controlsRight )
.concat( dom.controlsUp )
.concat( dom.controlsDown )
.concat( dom.controlsPrev )
.concat( dom.controlsNext ).forEach( function( node ) {
node.classList.remove( 'enabled' );
node.classList.remove( 'fragmented' );
} );
// Add the 'enabled' class to the available routes
if( routes.left ) dom.controlsLeft.forEach( function( el ) { el.classList.add( 'enabled' ); } );
if( routes.right ) dom.controlsRight.forEach( function( el ) { el.classList.add( 'enabled' ); } );
if( routes.up ) dom.controlsUp.forEach( function( el ) { el.classList.add( 'enabled' ); } );
if( routes.down ) dom.controlsDown.forEach( function( el ) { el.classList.add( 'enabled' ); } );
// Prev/next buttons
if( routes.left || routes.up ) dom.controlsPrev.forEach( function( el ) { el.classList.add( 'enabled' ); } );
if( routes.right || routes.down ) dom.controlsNext.forEach( function( el ) { el.classList.add( 'enabled' ); } );
// Highlight fragment directions
if( currentSlide ) {
// Always apply fragment decorator to prev/next buttons
if( fragments.prev ) dom.controlsPrev.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } );
if( fragments.next ) dom.controlsNext.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } );
// Apply fragment decorators to directional buttons based on
// what slide axis they are in
if( isVerticalSlide( currentSlide ) ) {
if( fragments.prev ) dom.controlsUp.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } );
if( fragments.next ) dom.controlsDown.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } );
}
else {
if( fragments.prev ) dom.controlsLeft.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } );
if( fragments.next ) dom.controlsRight.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } );
}
}
}
/**
* Updates the background elements to reflect the current
* slide.
*
* @param {Boolean} includeAll If true, the backgrounds of
* all vertical slides (not just the present) will be updated.
*/
function updateBackground( includeAll ) {
var currentBackground = null;
// Reverse past/future classes when in RTL mode
var horizontalPast = config.rtl ? 'future' : 'past',
horizontalFuture = config.rtl ? 'past' : 'future';
// Update the classes of all backgrounds to match the
// states of their slides (past/present/future)
toArray( dom.background.childNodes ).forEach( function( backgroundh, h ) {
backgroundh.classList.remove( 'past' );
backgroundh.classList.remove( 'present' );
backgroundh.classList.remove( 'future' );
if( h < indexh ) {
backgroundh.classList.add( horizontalPast );
}
else if ( h > indexh ) {
backgroundh.classList.add( horizontalFuture );
}
else {
backgroundh.classList.add( 'present' );
// Store a reference to the current background element
currentBackground = backgroundh;
}
if( includeAll || h === indexh ) {
toArray( backgroundh.querySelectorAll( '.slide-background' ) ).forEach( function( backgroundv, v ) {
backgroundv.classList.remove( 'past' );
backgroundv.classList.remove( 'present' );
backgroundv.classList.remove( 'future' );
if( v < indexv ) {
backgroundv.classList.add( 'past' );
}
else if ( v > indexv ) {
backgroundv.classList.add( 'future' );
}
else {
backgroundv.classList.add( 'present' );
// Only if this is the present horizontal and vertical slide
if( h === indexh ) currentBackground = backgroundv;
}
} );
}
} );
// Stop any currently playing video background
if( previousBackground ) {
var previousVideo = previousBackground.querySelector( 'video' );
if( previousVideo ) previousVideo.pause();
}
if( currentBackground ) {
// Start video playback
var currentVideo = currentBackground.querySelector( 'video' );
if( currentVideo ) {
var startVideo = function() {
currentVideo.currentTime = 0;
currentVideo.play();
currentVideo.removeEventListener( 'loadeddata', startVideo );
};
if( currentVideo.readyState > 1 ) {
startVideo();
}
else {
currentVideo.addEventListener( 'loadeddata', startVideo );
}
}
var backgroundImageURL = currentBackground.style.backgroundImage || '';
// Restart GIFs (doesn't work in Firefox)
if( /\.gif/i.test( backgroundImageURL ) ) {
currentBackground.style.backgroundImage = '';
window.getComputedStyle( currentBackground ).opacity;
currentBackground.style.backgroundImage = backgroundImageURL;
}
// Don't transition between identical backgrounds. This
// prevents unwanted flicker.
var previousBackgroundHash = previousBackground ? previousBackground.getAttribute( 'data-background-hash' ) : null;
var currentBackgroundHash = currentBackground.getAttribute( 'data-background-hash' );
if( currentBackgroundHash && currentBackgroundHash === previousBackgroundHash && currentBackground !== previousBackground ) {
dom.background.classList.add( 'no-transition' );
}
previousBackground = currentBackground;
}
// If there's a background brightness flag for this slide,
// bubble it to the .reveal container
if( currentSlide ) {
[ 'has-light-background', 'has-dark-background' ].forEach( function( classToBubble ) {
if( currentSlide.classList.contains( classToBubble ) ) {
dom.wrapper.classList.add( classToBubble );
}
else {
dom.wrapper.classList.remove( classToBubble );
}
} );
}
// Allow the first background to apply without transition
setTimeout( function() {
dom.background.classList.remove( 'no-transition' );
}, 1 );
}
/**
* Updates the position of the parallax background based
* on the current slide index.
*/
function updateParallax() {
if( config.parallaxBackgroundImage ) {
var horizontalSlides = dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ),
verticalSlides = dom.wrapper.querySelectorAll( VERTICAL_SLIDES_SELECTOR );
var backgroundSize = dom.background.style.backgroundSize.split( ' ' ),
backgroundWidth, backgroundHeight;
if( backgroundSize.length === 1 ) {
backgroundWidth = backgroundHeight = parseInt( backgroundSize[0], 10 );
}
else {
backgroundWidth = parseInt( backgroundSize[0], 10 );
backgroundHeight = parseInt( backgroundSize[1], 10 );
}
var slideWidth = dom.background.offsetWidth,
horizontalSlideCount = horizontalSlides.length,
horizontalOffsetMultiplier,
horizontalOffset;
if( typeof config.parallaxBackgroundHorizontal === 'number' ) {
horizontalOffsetMultiplier = config.parallaxBackgroundHorizontal;
}
else {
horizontalOffsetMultiplier = horizontalSlideCount > 1 ? ( backgroundWidth - slideWidth ) / ( horizontalSlideCount-1 ) : 0;
}
horizontalOffset = horizontalOffsetMultiplier * indexh * -1;
var slideHeight = dom.background.offsetHeight,
verticalSlideCount = verticalSlides.length,
verticalOffsetMultiplier,
verticalOffset;
if( typeof config.parallaxBackgroundVertical === 'number' ) {
verticalOffsetMultiplier = config.parallaxBackgroundVertical;
}
else {
verticalOffsetMultiplier = ( backgroundHeight - slideHeight ) / ( verticalSlideCount-1 );
}
verticalOffset = verticalSlideCount > 0 ? verticalOffsetMultiplier * indexv * 1 : 0;
dom.background.style.backgroundPosition = horizontalOffset + 'px ' + -verticalOffset + 'px';
}
}
/**
* Called when the given slide is within the configured view
* distance. Shows the slide element and loads any content
* that is set to load lazily (data-src).
*/
function showSlide( slide ) {
// Show the slide element
slide.style.display = 'block';
// Media elements with data-src attributes
toArray( slide.querySelectorAll( 'img[data-src], video[data-src], audio[data-src]' ) ).forEach( function( element ) {
element.setAttribute( 'src', element.getAttribute( 'data-src' ) );
element.removeAttribute( 'data-src' );
} );
// Media elements with <source> children
toArray( slide.querySelectorAll( 'video, audio' ) ).forEach( function( media ) {
var sources = 0;
toArray( media.querySelectorAll( 'source[data-src]' ) ).forEach( function( source ) {
source.setAttribute( 'src', source.getAttribute( 'data-src' ) );
source.removeAttribute( 'data-src' );
sources += 1;
} );
// If we rewrote sources for this video/audio element, we need
// to manually tell it to load from its new origin
if( sources > 0 ) {
media.load();
}
} );
// Show the corresponding background element
var indices = getIndices( slide );
var background = getSlideBackground( indices.h, indices.v );
if( background ) {
background.style.display = 'block';
// If the background contains media, load it
if( background.hasAttribute( 'data-loaded' ) === false ) {
background.setAttribute( 'data-loaded', 'true' );
var backgroundImage = slide.getAttribute( 'data-background-image' ),
backgroundVideo = slide.getAttribute( 'data-background-video' ),
backgroundVideoLoop = slide.hasAttribute( 'data-background-video-loop' ),
backgroundVideoMuted = slide.hasAttribute( 'data-background-video-muted' ),
backgroundIframe = slide.getAttribute( 'data-background-iframe' );
// Images
if( backgroundImage ) {
background.style.backgroundImage = 'url('+ backgroundImage +')';
}
// Videos
else if ( backgroundVideo && !isSpeakerNotes() ) {
var video = document.createElement( 'video' );
if( backgroundVideoLoop ) {
video.setAttribute( 'loop', '' );
}
if( backgroundVideoMuted ) {
video.muted = true;
}
// Support comma separated lists of video sources
backgroundVideo.split( ',' ).forEach( function( source ) {
video.innerHTML += '<source src="'+ source +'">';
} );
background.appendChild( video );
}
// Iframes
else if( backgroundIframe ) {
var iframe = document.createElement( 'iframe' );
iframe.setAttribute( 'src', backgroundIframe );
iframe.style.width = '100%';
iframe.style.height = '100%';
iframe.style.maxHeight = '100%';
iframe.style.maxWidth = '100%';
background.appendChild( iframe );
}
}
}
}
/**
* Called when the given slide is moved outside of the
* configured view distance.
*/
function hideSlide( slide ) {
// Hide the slide element
slide.style.display = 'none';
// Hide the corresponding background element
var indices = getIndices( slide );
var background = getSlideBackground( indices.h, indices.v );
if( background ) {
background.style.display = 'none';
}
}
/**
* Determine what available routes there are for navigation.
*
* @return {Object} containing four booleans: left/right/up/down
*/
function availableRoutes() {
var horizontalSlides = dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ),
verticalSlides = dom.wrapper.querySelectorAll( VERTICAL_SLIDES_SELECTOR );
var routes = {
left: indexh > 0 || config.loop,
right: indexh < horizontalSlides.length - 1 || config.loop,
up: indexv > 0,
down: indexv < verticalSlides.length - 1
};
// reverse horizontal controls for rtl
if( config.rtl ) {
var left = routes.left;
routes.left = routes.right;
routes.right = left;
}
return routes;
}
/**
* Returns an object describing the available fragment
* directions.
*
* @return {Object} two boolean properties: prev/next
*/
function availableFragments() {
if( currentSlide && config.fragments ) {
var fragments = currentSlide.querySelectorAll( '.fragment' );
var hiddenFragments = currentSlide.querySelectorAll( '.fragment:not(.visible)' );
return {
prev: fragments.length - hiddenFragments.length > 0,
next: !!hiddenFragments.length
};
}
else {
return { prev: false, next: false };
}
}
/**
* Enforces origin-specific format rules for embedded media.
*/
function formatEmbeddedContent() {
var _appendParamToIframeSource = function( sourceAttribute, sourceURL, param ) {
toArray( dom.slides.querySelectorAll( 'iframe['+ sourceAttribute +'*="'+ sourceURL +'"]' ) ).forEach( function( el ) {
var src = el.getAttribute( sourceAttribute );
if( src && src.indexOf( param ) === -1 ) {
el.setAttribute( sourceAttribute, src + ( !/\?/.test( src ) ? '?' : '&' ) + param );
}
});
};
// YouTube frames must include "?enablejsapi=1"
_appendParamToIframeSource( 'src', 'youtube.com/embed/', 'enablejsapi=1' );
_appendParamToIframeSource( 'data-src', 'youtube.com/embed/', 'enablejsapi=1' );
// Vimeo frames must include "?api=1"
_appendParamToIframeSource( 'src', 'player.vimeo.com/', 'api=1' );
_appendParamToIframeSource( 'data-src', 'player.vimeo.com/', 'api=1' );
}
/**
* Start playback of any embedded content inside of
* the targeted slide.
*/
function startEmbeddedContent( slide ) {
if( slide && !isSpeakerNotes() ) {
// Restart GIFs
toArray( slide.querySelectorAll( 'img[src$=".gif"]' ) ).forEach( function( el ) {
// Setting the same unchanged source like this was confirmed
// to work in Chrome, FF & Safari
el.setAttribute( 'src', el.getAttribute( 'src' ) );
} );
// HTML5 media elements
toArray( slide.querySelectorAll( 'video, audio' ) ).forEach( function( el ) {
if( el.hasAttribute( 'data-autoplay' ) && typeof el.play === 'function' ) {
el.play();
}
} );
// Normal iframes
toArray( slide.querySelectorAll( 'iframe[src]' ) ).forEach( function( el ) {
startEmbeddedIframe( { target: el } );
} );
// Lazy loading iframes
toArray( slide.querySelectorAll( 'iframe[data-src]' ) ).forEach( function( el ) {
if( el.getAttribute( 'src' ) !== el.getAttribute( 'data-src' ) ) {
el.removeEventListener( 'load', startEmbeddedIframe ); // remove first to avoid dupes
el.addEventListener( 'load', startEmbeddedIframe );
el.setAttribute( 'src', el.getAttribute( 'data-src' ) );
}
} );
}
}
/**
* "Starts" the content of an embedded iframe using the
* postmessage API.
*/
function startEmbeddedIframe( event ) {
var iframe = event.target;
// YouTube postMessage API
if( /youtube\.com\/embed\//.test( iframe.getAttribute( 'src' ) ) && iframe.hasAttribute( 'data-autoplay' ) ) {
iframe.contentWindow.postMessage( '{"event":"command","func":"playVideo","args":""}', '*' );
}
// Vimeo postMessage API
else if( /player\.vimeo\.com\//.test( iframe.getAttribute( 'src' ) ) && iframe.hasAttribute( 'data-autoplay' ) ) {
iframe.contentWindow.postMessage( '{"method":"play"}', '*' );
}
// Generic postMessage API
else {
iframe.contentWindow.postMessage( 'slide:start', '*' );
}
}
/**
* Stop playback of any embedded content inside of
* the targeted slide.
*/
function stopEmbeddedContent( slide ) {
if( slide && slide.parentNode ) {
// HTML5 media elements
toArray( slide.querySelectorAll( 'video, audio' ) ).forEach( function( el ) {
if( !el.hasAttribute( 'data-ignore' ) && typeof el.pause === 'function' ) {
el.pause();
}
} );
// Generic postMessage API for non-lazy loaded iframes
toArray( slide.querySelectorAll( 'iframe' ) ).forEach( function( el ) {
el.contentWindow.postMessage( 'slide:stop', '*' );
el.removeEventListener( 'load', startEmbeddedIframe );
});
// YouTube postMessage API
toArray( slide.querySelectorAll( 'iframe[src*="youtube.com/embed/"]' ) ).forEach( function( el ) {
if( !el.hasAttribute( 'data-ignore' ) && typeof el.contentWindow.postMessage === 'function' ) {
el.contentWindow.postMessage( '{"event":"command","func":"pauseVideo","args":""}', '*' );
}
});
// Vimeo postMessage API
toArray( slide.querySelectorAll( 'iframe[src*="player.vimeo.com/"]' ) ).forEach( function( el ) {
if( !el.hasAttribute( 'data-ignore' ) && typeof el.contentWindow.postMessage === 'function' ) {
el.contentWindow.postMessage( '{"method":"pause"}', '*' );
}
});
// Lazy loading iframes
toArray( slide.querySelectorAll( 'iframe[data-src]' ) ).forEach( function( el ) {
// Only removing the src doesn't actually unload the frame
// in all browsers (Firefox) so we set it to blank first
el.setAttribute( 'src', 'about:blank' );
el.removeAttribute( 'src' );
} );
}
}
/**
* Returns the number of past slides. This can be used as a global
* flattened index for slides.
*/
function getSlidePastCount() {
var horizontalSlides = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) );
// The number of past slides
var pastCount = 0;
// Step through all slides and count the past ones
mainLoop: for( var i = 0; i < horizontalSlides.length; i++ ) {
var horizontalSlide = horizontalSlides[i];
var verticalSlides = toArray( horizontalSlide.querySelectorAll( 'section' ) );
for( var j = 0; j < verticalSlides.length; j++ ) {
// Stop as soon as we arrive at the present
if( verticalSlides[j].classList.contains( 'present' ) ) {
break mainLoop;
}
pastCount++;
}
// Stop as soon as we arrive at the present
if( horizontalSlide.classList.contains( 'present' ) ) {
break;
}
// Don't count the wrapping section for vertical slides
if( horizontalSlide.classList.contains( 'stack' ) === false ) {
pastCount++;
}
}
return pastCount;
}
/**
* Returns a value ranging from 0-1 that represents
* how far into the presentation we have navigated.
*/
function getProgress() {
// The number of past and total slides
var totalCount = getTotalSlides();
var pastCount = getSlidePastCount();
if( currentSlide ) {
var allFragments = currentSlide.querySelectorAll( '.fragment' );
// If there are fragments in the current slide those should be
// accounted for in the progress.
if( allFragments.length > 0 ) {
var visibleFragments = currentSlide.querySelectorAll( '.fragment.visible' );
// This value represents how big a portion of the slide progress
// that is made up by its fragments (0-1)
var fragmentWeight = 0.9;
// Add fragment progress to the past slide count
pastCount += ( visibleFragments.length / allFragments.length ) * fragmentWeight;
}
}
return pastCount / ( totalCount - 1 );
}
/**
* Checks if this presentation is running inside of the
* speaker notes window.
*/
function isSpeakerNotes() {
return !!window.location.search.match( /receiver/gi );
}
/**
* Reads the current URL (hash) and navigates accordingly.
*/
function readURL() {
var hash = window.location.hash;
// Attempt to parse the hash as either an index or name
var bits = hash.slice( 2 ).split( '/' ),
name = hash.replace( /#|\//gi, '' );
// If the first bit is invalid and there is a name we can
// assume that this is a named link
if( isNaN( parseInt( bits[0], 10 ) ) && name.length ) {
var element;
// Ensure the named link is a valid HTML ID attribute
if( /^[a-zA-Z][\w:.-]*$/.test( name ) ) {
// Find the slide with the specified ID
element = document.getElementById( name );
}
if( element ) {
// Find the position of the named slide and navigate to it
var indices = Reveal.getIndices( element );
slide( indices.h, indices.v );
}
// If the slide doesn't exist, navigate to the current slide
else {
slide( indexh || 0, indexv || 0 );
}
}
else {
// Read the index components of the hash
var h = parseInt( bits[0], 10 ) || 0,
v = parseInt( bits[1], 10 ) || 0;
if( h !== indexh || v !== indexv ) {
slide( h, v );
}
}
}
/**
* Updates the page URL (hash) to reflect the current
* state.
*
* @param {Number} delay The time in ms to wait before
* writing the hash
*/
function writeURL( delay ) {
if( config.history ) {
// Make sure there's never more than one timeout running
clearTimeout( writeURLTimeout );
// If a delay is specified, timeout this call
if( typeof delay === 'number' ) {
writeURLTimeout = setTimeout( writeURL, delay );
}
else if( currentSlide ) {
var url = '/';
// Attempt to create a named link based on the slide's ID
var id = currentSlide.getAttribute( 'id' );
if( id ) {
id = id.replace( /[^a-zA-Z0-9\-\_\:\.]/g, '' );
}
// If the current slide has an ID, use that as a named link
if( typeof id === 'string' && id.length ) {
url = '/' + id;
}
// Otherwise use the /h/v index
else {
if( indexh > 0 || indexv > 0 ) url += indexh;
if( indexv > 0 ) url += '/' + indexv;
}
window.location.hash = url;
}
}
}
/**
* Retrieves the h/v location of the current, or specified,
* slide.
*
* @param {HTMLElement} slide If specified, the returned
* index will be for this slide rather than the currently
* active one
*
* @return {Object} { h: <int>, v: <int>, f: <int> }
*/
function getIndices( slide ) {
// By default, return the current indices
var h = indexh,
v = indexv,
f;
// If a slide is specified, return the indices of that slide
if( slide ) {
var isVertical = isVerticalSlide( slide );
var slideh = isVertical ? slide.parentNode : slide;
// Select all horizontal slides
var horizontalSlides = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) );
// Now that we know which the horizontal slide is, get its index
h = Math.max( horizontalSlides.indexOf( slideh ), 0 );
// Assume we're not vertical
v = undefined;
// If this is a vertical slide, grab the vertical index
if( isVertical ) {
v = Math.max( toArray( slide.parentNode.querySelectorAll( 'section' ) ).indexOf( slide ), 0 );
}
}
if( !slide && currentSlide ) {
var hasFragments = currentSlide.querySelectorAll( '.fragment' ).length > 0;
if( hasFragments ) {
var currentFragment = currentSlide.querySelector( '.current-fragment' );
if( currentFragment && currentFragment.hasAttribute( 'data-fragment-index' ) ) {
f = parseInt( currentFragment.getAttribute( 'data-fragment-index' ), 10 );
}
else {
f = currentSlide.querySelectorAll( '.fragment.visible' ).length - 1;
}
}
}
return { h: h, v: v, f: f };
}
/**
* Retrieves the total number of slides in this presentation.
*/
function getTotalSlides() {
return dom.wrapper.querySelectorAll( SLIDES_SELECTOR + ':not(.stack)' ).length;
}
/**
* Returns the slide element matching the specified index.
*/
function getSlide( x, y ) {
var horizontalSlide = dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR )[ x ];
var verticalSlides = horizontalSlide && horizontalSlide.querySelectorAll( 'section' );
if( verticalSlides && verticalSlides.length && typeof y === 'number' ) {
return verticalSlides ? verticalSlides[ y ] : undefined;
}
return horizontalSlide;
}
/**
* Returns the background element for the given slide.
* All slides, even the ones with no background properties
* defined, have a background element so as long as the
* index is valid an element will be returned.
*/
function getSlideBackground( x, y ) {
// When printing to PDF the slide backgrounds are nested
// inside of the slides
if( isPrintingPDF() ) {
var slide = getSlide( x, y );
if( slide ) {
var background = slide.querySelector( '.slide-background' );
if( background && background.parentNode === slide ) {
return background;
}
}
return undefined;
}
var horizontalBackground = dom.wrapper.querySelectorAll( '.backgrounds>.slide-background' )[ x ];
var verticalBackgrounds = horizontalBackground && horizontalBackground.querySelectorAll( '.slide-background' );
if( verticalBackgrounds && verticalBackgrounds.length && typeof y === 'number' ) {
return verticalBackgrounds ? verticalBackgrounds[ y ] : undefined;
}
return horizontalBackground;
}
/**
* Retrieves the speaker notes from a slide. Notes can be
* defined in two ways:
* 1. As a data-notes attribute on the slide <section>
* 2. As an <aside class="notes"> inside of the slide
*/
function getSlideNotes( slide ) {
// Default to the current slide
slide = slide || currentSlide;
// Notes can be specified via the data-notes attribute...
if( slide.hasAttribute( 'data-notes' ) ) {
return slide.getAttribute( 'data-notes' );
}
// ... or using an <aside class="notes"> element
var notesElement = slide.querySelector( 'aside.notes' );
if( notesElement ) {
return notesElement.innerHTML;
}
return null;
}
/**
* Retrieves the current state of the presentation as
* an object. This state can then be restored at any
* time.
*/
function getState() {
var indices = getIndices();
return {
indexh: indices.h,
indexv: indices.v,
indexf: indices.f,
paused: isPaused(),
overview: isOverview()
};
}
/**
* Restores the presentation to the given state.
*
* @param {Object} state As generated by getState()
*/
function setState( state ) {
if( typeof state === 'object' ) {
slide( deserialize( state.indexh ), deserialize( state.indexv ), deserialize( state.indexf ) );
var pausedFlag = deserialize( state.paused ),
overviewFlag = deserialize( state.overview );
if( typeof pausedFlag === 'boolean' && pausedFlag !== isPaused() ) {
togglePause( pausedFlag );
}
if( typeof overviewFlag === 'boolean' && overviewFlag !== isOverview() ) {
toggleOverview( overviewFlag );
}
}
}
/**
* Return a sorted fragments list, ordered by an increasing
* "data-fragment-index" attribute.
*
* Fragments will be revealed in the order that they are returned by
* this function, so you can use the index attributes to control the
* order of fragment appearance.
*
* To maintain a sensible default fragment order, fragments are presumed
* to be passed in document order. This function adds a "fragment-index"
* attribute to each node if such an attribute is not already present,
* and sets that attribute to an integer value which is the position of
* the fragment within the fragments list.
*/
function sortFragments( fragments ) {
fragments = toArray( fragments );
var ordered = [],
unordered = [],
sorted = [];
// Group ordered and unordered elements
fragments.forEach( function( fragment, i ) {
if( fragment.hasAttribute( 'data-fragment-index' ) ) {
var index = parseInt( fragment.getAttribute( 'data-fragment-index' ), 10 );
if( !ordered[index] ) {
ordered[index] = [];
}
ordered[index].push( fragment );
}
else {
unordered.push( [ fragment ] );
}
} );
// Append fragments without explicit indices in their
// DOM order
ordered = ordered.concat( unordered );
// Manually count the index up per group to ensure there
// are no gaps
var index = 0;
// Push all fragments in their sorted order to an array,
// this flattens the groups
ordered.forEach( function( group ) {
group.forEach( function( fragment ) {
sorted.push( fragment );
fragment.setAttribute( 'data-fragment-index', index );
} );
index ++;
} );
return sorted;
}
/**
* Navigate to the specified slide fragment.
*
* @param {Number} index The index of the fragment that
* should be shown, -1 means all are invisible
* @param {Number} offset Integer offset to apply to the
* fragment index
*
* @return {Boolean} true if a change was made in any
* fragments visibility as part of this call
*/
function navigateFragment( index, offset ) {
if( currentSlide && config.fragments ) {
var fragments = sortFragments( currentSlide.querySelectorAll( '.fragment' ) );
if( fragments.length ) {
// If no index is specified, find the current
if( typeof index !== 'number' ) {
var lastVisibleFragment = sortFragments( currentSlide.querySelectorAll( '.fragment.visible' ) ).pop();
if( lastVisibleFragment ) {
index = parseInt( lastVisibleFragment.getAttribute( 'data-fragment-index' ) || 0, 10 );
}
else {
index = -1;
}
}
// If an offset is specified, apply it to the index
if( typeof offset === 'number' ) {
index += offset;
}
var fragmentsShown = [],
fragmentsHidden = [];
toArray( fragments ).forEach( function( element, i ) {
if( element.hasAttribute( 'data-fragment-index' ) ) {
i = parseInt( element.getAttribute( 'data-fragment-index' ), 10 );
}
// Visible fragments
if( i <= index ) {
if( !element.classList.contains( 'visible' ) ) fragmentsShown.push( element );
element.classList.add( 'visible' );
element.classList.remove( 'current-fragment' );
// Announce the fragments one by one to the Screen Reader
dom.statusDiv.textContent = element.textContent;
if( i === index ) {
element.classList.add( 'current-fragment' );
}
}
// Hidden fragments
else {
if( element.classList.contains( 'visible' ) ) fragmentsHidden.push( element );
element.classList.remove( 'visible' );
element.classList.remove( 'current-fragment' );
}
} );
if( fragmentsHidden.length ) {
dispatchEvent( 'fragmenthidden', { fragment: fragmentsHidden[0], fragments: fragmentsHidden } );
}
if( fragmentsShown.length ) {
dispatchEvent( 'fragmentshown', { fragment: fragmentsShown[0], fragments: fragmentsShown } );
}
updateControls();
updateProgress();
return !!( fragmentsShown.length || fragmentsHidden.length );
}
}
return false;
}
/**
* Navigate to the next slide fragment.
*
* @return {Boolean} true if there was a next fragment,
* false otherwise
*/
function nextFragment() {
return navigateFragment( null, 1 );
}
/**
* Navigate to the previous slide fragment.
*
* @return {Boolean} true if there was a previous fragment,
* false otherwise
*/
function previousFragment() {
return navigateFragment( null, -1 );
}
/**
* Cues a new automated slide if enabled in the config.
*/
function cueAutoSlide() {
cancelAutoSlide();
if( currentSlide ) {
var currentFragment = currentSlide.querySelector( '.current-fragment' );
var fragmentAutoSlide = currentFragment ? currentFragment.getAttribute( 'data-autoslide' ) : null;
var parentAutoSlide = currentSlide.parentNode ? currentSlide.parentNode.getAttribute( 'data-autoslide' ) : null;
var slideAutoSlide = currentSlide.getAttribute( 'data-autoslide' );
// Pick value in the following priority order:
// 1. Current fragment's data-autoslide
// 2. Current slide's data-autoslide
// 3. Parent slide's data-autoslide
// 4. Global autoSlide setting
if( fragmentAutoSlide ) {
autoSlide = parseInt( fragmentAutoSlide, 10 );
}
else if( slideAutoSlide ) {
autoSlide = parseInt( slideAutoSlide, 10 );
}
else if( parentAutoSlide ) {
autoSlide = parseInt( parentAutoSlide, 10 );
}
else {
autoSlide = config.autoSlide;
}
// If there are media elements with data-autoplay,
// automatically set the autoSlide duration to the
// length of that media. Not applicable if the slide
// is divided up into fragments.
if( currentSlide.querySelectorAll( '.fragment' ).length === 0 ) {
toArray( currentSlide.querySelectorAll( 'video, audio' ) ).forEach( function( el ) {
if( el.hasAttribute( 'data-autoplay' ) ) {
if( autoSlide && el.duration * 1000 > autoSlide ) {
autoSlide = ( el.duration * 1000 ) + 1000;
}
}
} );
}
// Cue the next auto-slide if:
// - There is an autoSlide value
// - Auto-sliding isn't paused by the user
// - The presentation isn't paused
// - The overview isn't active
// - The presentation isn't over
if( autoSlide && !autoSlidePaused && !isPaused() && !isOverview() && ( !Reveal.isLastSlide() || availableFragments().next || config.loop === true ) ) {
autoSlideTimeout = setTimeout( function() {
typeof config.autoSlideMethod === 'function' ? config.autoSlideMethod() : navigateNext();
cueAutoSlide();
}, autoSlide );
autoSlideStartTime = Date.now();
}
if( autoSlidePlayer ) {
autoSlidePlayer.setPlaying( autoSlideTimeout !== -1 );
}
}
}
/**
* Cancels any ongoing request to auto-slide.
*/
function cancelAutoSlide() {
clearTimeout( autoSlideTimeout );
autoSlideTimeout = -1;
}
function pauseAutoSlide() {
if( autoSlide && !autoSlidePaused ) {
autoSlidePaused = true;
dispatchEvent( 'autoslidepaused' );
clearTimeout( autoSlideTimeout );
if( autoSlidePlayer ) {
autoSlidePlayer.setPlaying( false );
}
}
}
function resumeAutoSlide() {
if( autoSlide && autoSlidePaused ) {
autoSlidePaused = false;
dispatchEvent( 'autoslideresumed' );
cueAutoSlide();
}
}
function navigateLeft() {
// Reverse for RTL
if( config.rtl ) {
if( ( isOverview() || nextFragment() === false ) && availableRoutes().left ) {
slide( indexh + 1 );
}
}
// Normal navigation
else if( ( isOverview() || previousFragment() === false ) && availableRoutes().left ) {
slide( indexh - 1 );
}
}
function navigateRight() {
// Reverse for RTL
if( config.rtl ) {
if( ( isOverview() || previousFragment() === false ) && availableRoutes().right ) {
slide( indexh - 1 );
}
}
// Normal navigation
else if( ( isOverview() || nextFragment() === false ) && availableRoutes().right ) {
slide( indexh + 1 );
}
}
function navigateUp() {
// Prioritize hiding fragments
if( ( isOverview() || previousFragment() === false ) && availableRoutes().up ) {
slide( indexh, indexv - 1 );
}
}
function navigateDown() {
// Prioritize revealing fragments
if( ( isOverview() || nextFragment() === false ) && availableRoutes().down ) {
slide( indexh, indexv + 1 );
}
}
/**
* Navigates backwards, prioritized in the following order:
* 1) Previous fragment
* 2) Previous vertical slide
* 3) Previous horizontal slide
*/
function navigatePrev() {
// Prioritize revealing fragments
if( previousFragment() === false ) {
if( availableRoutes().up ) {
navigateUp();
}
else {
// Fetch the previous horizontal slide, if there is one
var previousSlide;
if( config.rtl ) {
previousSlide = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR + '.future' ) ).pop();
}
else {
previousSlide = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR + '.past' ) ).pop();
}
if( previousSlide ) {
var v = ( previousSlide.querySelectorAll( 'section' ).length - 1 ) || undefined;
var h = indexh - 1;
slide( h, v );
}
}
}
}
/**
* The reverse of #navigatePrev().
*/
function navigateNext() {
// Prioritize revealing fragments
if( nextFragment() === false ) {
if( availableRoutes().down ) {
navigateDown();
}
else if( config.rtl ) {
navigateLeft();
}
else {
navigateRight();
}
}
}
/**
* Checks if the target element prevents the triggering of
* swipe navigation.
*/
function isSwipePrevented( target ) {
while( target && typeof target.hasAttribute === 'function' ) {
if( target.hasAttribute( 'data-prevent-swipe' ) ) return true;
target = target.parentNode;
}
return false;
}
// --------------------------------------------------------------------//
// ----------------------------- EVENTS -------------------------------//
// --------------------------------------------------------------------//
/**
* Called by all event handlers that are based on user
* input.
*/
function onUserInput( event ) {
if( config.autoSlideStoppable ) {
pauseAutoSlide();
}
}
/**
* Handler for the document level 'keypress' event.
*/
function onDocumentKeyPress( event ) {
// Check if the pressed key is question mark
if( event.shiftKey && event.charCode === 63 ) {
if( dom.overlay ) {
closeOverlay();
}
else {
showHelp( true );
}
}
}
/**
* Handler for the document level 'keydown' event.
*/
function onDocumentKeyDown( event ) {
// If there's a condition specified and it returns false,
// ignore this event
if( typeof config.keyboardCondition === 'function' && config.keyboardCondition() === false ) {
return true;
}
// Remember if auto-sliding was paused so we can toggle it
var autoSlideWasPaused = autoSlidePaused;
onUserInput( event );
// Check if there's a focused element that could be using
// the keyboard
var activeElementIsCE = document.activeElement && document.activeElement.contentEditable !== 'inherit';
var activeElementIsInput = document.activeElement && document.activeElement.tagName && /input|textarea/i.test( document.activeElement.tagName );
// Disregard the event if there's a focused element or a
// keyboard modifier key is present
if( activeElementIsCE || activeElementIsInput || (event.shiftKey && event.keyCode !== 32) || event.altKey || event.ctrlKey || event.metaKey ) return;
// While paused only allow resume keyboard events; 'b', '.''
var resumeKeyCodes = [66,190,191];
var key;
// Custom key bindings for togglePause should be able to resume
if( typeof config.keyboard === 'object' ) {
for( key in config.keyboard ) {
if( config.keyboard[key] === 'togglePause' ) {
resumeKeyCodes.push( parseInt( key, 10 ) );
}
}
}
if( isPaused() && resumeKeyCodes.indexOf( event.keyCode ) === -1 ) {
return false;
}
var triggered = false;
// 1. User defined key bindings
if( typeof config.keyboard === 'object' ) {
for( key in config.keyboard ) {
// Check if this binding matches the pressed key
if( parseInt( key, 10 ) === event.keyCode ) {
var value = config.keyboard[ key ];
// Callback function
if( typeof value === 'function' ) {
value.apply( null, [ event ] );
}
// String shortcuts to reveal.js API
else if( typeof value === 'string' && typeof Reveal[ value ] === 'function' ) {
Reveal[ value ].call();
}
triggered = true;
}
}
}
// 2. System defined key bindings
if( triggered === false ) {
// Assume true and try to prove false
triggered = true;
switch( event.keyCode ) {
// p, page up
case 80: case 33: navigatePrev(); break;
// n, page down
case 78: case 34: navigateNext(); break;
// h, left
case 72: case 37: navigateLeft(); break;
// l, right
case 76: case 39: navigateRight(); break;
// k, up
case 75: case 38: navigateUp(); break;
// j, down
case 74: case 40: navigateDown(); break;
// home
case 36: slide( 0 ); break;
// end
case 35: slide( Number.MAX_VALUE ); break;
// space
case 32: isOverview() ? deactivateOverview() : event.shiftKey ? navigatePrev() : navigateNext(); break;
// return
case 13: isOverview() ? deactivateOverview() : triggered = false; break;
// two-spot, semicolon, b, period, Logitech presenter tools "black screen" button
case 58: case 59: case 66: case 190: case 191: togglePause(); break;
// f
case 70: enterFullscreen(); break;
// a
case 65: if ( config.autoSlideStoppable ) toggleAutoSlide( autoSlideWasPaused ); break;
default:
triggered = false;
}
}
// If the input resulted in a triggered action we should prevent
// the browsers default behavior
if( triggered ) {
event.preventDefault && event.preventDefault();
}
// ESC or O key
else if ( ( event.keyCode === 27 || event.keyCode === 79 ) && features.transforms3d ) {
if( dom.overlay ) {
closeOverlay();
}
else {
toggleOverview();
}
event.preventDefault && event.preventDefault();
}
// If auto-sliding is enabled we need to cue up
// another timeout
cueAutoSlide();
}
/**
* Handler for the 'touchstart' event, enables support for
* swipe and pinch gestures.
*/
function onTouchStart( event ) {
if( isSwipePrevented( event.target ) ) return true;
touch.startX = event.touches[0].clientX;
touch.startY = event.touches[0].clientY;
touch.startCount = event.touches.length;
// If there's two touches we need to memorize the distance
// between those two points to detect pinching
if( event.touches.length === 2 && config.overview ) {
touch.startSpan = distanceBetween( {
x: event.touches[1].clientX,
y: event.touches[1].clientY
}, {
x: touch.startX,
y: touch.startY
} );
}
}
/**
* Handler for the 'touchmove' event.
*/
function onTouchMove( event ) {
if( isSwipePrevented( event.target ) ) return true;
// Each touch should only trigger one action
if( !touch.captured ) {
onUserInput( event );
var currentX = event.touches[0].clientX;
var currentY = event.touches[0].clientY;
// If the touch started with two points and still has
// two active touches; test for the pinch gesture
if( event.touches.length === 2 && touch.startCount === 2 && config.overview ) {
// The current distance in pixels between the two touch points
var currentSpan = distanceBetween( {
x: event.touches[1].clientX,
y: event.touches[1].clientY
}, {
x: touch.startX,
y: touch.startY
} );
// If the span is larger than the desire amount we've got
// ourselves a pinch
if( Math.abs( touch.startSpan - currentSpan ) > touch.threshold ) {
touch.captured = true;
if( currentSpan < touch.startSpan ) {
activateOverview();
}
else {
deactivateOverview();
}
}
event.preventDefault();
}
// There was only one touch point, look for a swipe
else if( event.touches.length === 1 && touch.startCount !== 2 ) {
var deltaX = currentX - touch.startX,
deltaY = currentY - touch.startY;
if( deltaX > touch.threshold && Math.abs( deltaX ) > Math.abs( deltaY ) ) {
touch.captured = true;
navigateLeft();
}
else if( deltaX < -touch.threshold && Math.abs( deltaX ) > Math.abs( deltaY ) ) {
touch.captured = true;
navigateRight();
}
else if( deltaY > touch.threshold ) {
touch.captured = true;
navigateUp();
}
else if( deltaY < -touch.threshold ) {
touch.captured = true;
navigateDown();
}
// If we're embedded, only block touch events if they have
// triggered an action
if( config.embedded ) {
if( touch.captured || isVerticalSlide( currentSlide ) ) {
event.preventDefault();
}
}
// Not embedded? Block them all to avoid needless tossing
// around of the viewport in iOS
else {
event.preventDefault();
}
}
}
// There's a bug with swiping on some Android devices unless
// the default action is always prevented
else if( UA.match( /android/gi ) ) {
event.preventDefault();
}
}
/**
* Handler for the 'touchend' event.
*/
function onTouchEnd( event ) {
touch.captured = false;
}
/**
* Convert pointer down to touch start.
*/
function onPointerDown( event ) {
if( event.pointerType === event.MSPOINTER_TYPE_TOUCH || event.pointerType === "touch" ) {
event.touches = [{ clientX: event.clientX, clientY: event.clientY }];
onTouchStart( event );
}
}
/**
* Convert pointer move to touch move.
*/
function onPointerMove( event ) {
if( event.pointerType === event.MSPOINTER_TYPE_TOUCH || event.pointerType === "touch" ) {
event.touches = [{ clientX: event.clientX, clientY: event.clientY }];
onTouchMove( event );
}
}
/**
* Convert pointer up to touch end.
*/
function onPointerUp( event ) {
if( event.pointerType === event.MSPOINTER_TYPE_TOUCH || event.pointerType === "touch" ) {
event.touches = [{ clientX: event.clientX, clientY: event.clientY }];
onTouchEnd( event );
}
}
/**
* Handles mouse wheel scrolling, throttled to avoid skipping
* multiple slides.
*/
function onDocumentMouseScroll( event ) {
if( Date.now() - lastMouseWheelStep > 600 ) {
lastMouseWheelStep = Date.now();
var delta = event.detail || -event.wheelDelta;
if( delta > 0 ) {
navigateNext();
}
else {
navigatePrev();
}
}
}
/**
* Clicking on the progress bar results in a navigation to the
* closest approximate horizontal slide using this equation:
*
* ( clickX / presentationWidth ) * numberOfSlides
*/
function onProgressClicked( event ) {
onUserInput( event );
event.preventDefault();
var slidesTotal = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ).length;
var slideIndex = Math.floor( ( event.clientX / dom.wrapper.offsetWidth ) * slidesTotal );
if( config.rtl ) {
slideIndex = slidesTotal - slideIndex;
}
slide( slideIndex );
}
/**
* Event handler for navigation control buttons.
*/
function onNavigateLeftClicked( event ) { event.preventDefault(); onUserInput(); navigateLeft(); }
function onNavigateRightClicked( event ) { event.preventDefault(); onUserInput(); navigateRight(); }
function onNavigateUpClicked( event ) { event.preventDefault(); onUserInput(); navigateUp(); }
function onNavigateDownClicked( event ) { event.preventDefault(); onUserInput(); navigateDown(); }
function onNavigatePrevClicked( event ) { event.preventDefault(); onUserInput(); navigatePrev(); }
function onNavigateNextClicked( event ) { event.preventDefault(); onUserInput(); navigateNext(); }
/**
* Handler for the window level 'hashchange' event.
*/
function onWindowHashChange( event ) {
readURL();
}
/**
* Handler for the window level 'resize' event.
*/
function onWindowResize( event ) {
layout();
}
/**
* Handle for the window level 'visibilitychange' event.
*/
function onPageVisibilityChange( event ) {
var isHidden = document.webkitHidden ||
document.msHidden ||
document.hidden;
// If, after clicking a link or similar and we're coming back,
// focus the document.body to ensure we can use keyboard shortcuts
if( isHidden === false && document.activeElement !== document.body ) {
// Not all elements support .blur() - SVGs among them.
if( typeof document.activeElement.blur === 'function' ) {
document.activeElement.blur();
}
document.body.focus();
}
}
/**
* Invoked when a slide is and we're in the overview.
*/
function onOverviewSlideClicked( event ) {
// TODO There's a bug here where the event listeners are not
// removed after deactivating the overview.
if( eventsAreBound && isOverview() ) {
event.preventDefault();
var element = event.target;
while( element && !element.nodeName.match( /section/gi ) ) {
element = element.parentNode;
}
if( element && !element.classList.contains( 'disabled' ) ) {
deactivateOverview();
if( element.nodeName.match( /section/gi ) ) {
var h = parseInt( element.getAttribute( 'data-index-h' ), 10 ),
v = parseInt( element.getAttribute( 'data-index-v' ), 10 );
slide( h, v );
}
}
}
}
/**
* Handles clicks on links that are set to preview in the
* iframe overlay.
*/
function onPreviewLinkClicked( event ) {
if( event.currentTarget && event.currentTarget.hasAttribute( 'href' ) ) {
var url = event.currentTarget.getAttribute( 'href' );
if( url ) {
showPreview( url );
event.preventDefault();
}
}
}
/**
* Handles click on the auto-sliding controls element.
*/
function onAutoSlidePlayerClick( event ) {
// Replay
if( Reveal.isLastSlide() && config.loop === false ) {
slide( 0, 0 );
resumeAutoSlide();
}
// Resume
else if( autoSlidePaused ) {
resumeAutoSlide();
}
// Pause
else {
pauseAutoSlide();
}
}
// --------------------------------------------------------------------//
// ------------------------ PLAYBACK COMPONENT ------------------------//
// --------------------------------------------------------------------//
/**
* Constructor for the playback component, which displays
* play/pause/progress controls.
*
* @param {HTMLElement} container The component will append
* itself to this
* @param {Function} progressCheck A method which will be
* called frequently to get the current progress on a range
* of 0-1
*/
function Playback( container, progressCheck ) {
// Cosmetics
this.diameter = 100;
this.diameter2 = this.diameter/2;
this.thickness = 6;
// Flags if we are currently playing
this.playing = false;
// Current progress on a 0-1 range
this.progress = 0;
// Used to loop the animation smoothly
this.progressOffset = 1;
this.container = container;
this.progressCheck = progressCheck;
this.canvas = document.createElement( 'canvas' );
this.canvas.className = 'playback';
this.canvas.width = this.diameter;
this.canvas.height = this.diameter;
this.canvas.style.width = this.diameter2 + 'px';
this.canvas.style.height = this.diameter2 + 'px';
this.context = this.canvas.getContext( '2d' );
this.container.appendChild( this.canvas );
this.render();
}
Playback.prototype.setPlaying = function( value ) {
var wasPlaying = this.playing;
this.playing = value;
// Start repainting if we weren't already
if( !wasPlaying && this.playing ) {
this.animate();
}
else {
this.render();
}
};
Playback.prototype.animate = function() {
var progressBefore = this.progress;
this.progress = this.progressCheck();
// When we loop, offset the progress so that it eases
// smoothly rather than immediately resetting
if( progressBefore > 0.8 && this.progress < 0.2 ) {
this.progressOffset = this.progress;
}
this.render();
if( this.playing ) {
features.requestAnimationFrameMethod.call( window, this.animate.bind( this ) );
}
};
/**
* Renders the current progress and playback state.
*/
Playback.prototype.render = function() {
var progress = this.playing ? this.progress : 0,
radius = ( this.diameter2 ) - this.thickness,
x = this.diameter2,
y = this.diameter2,
iconSize = 28;
// Ease towards 1
this.progressOffset += ( 1 - this.progressOffset ) * 0.1;
var endAngle = ( - Math.PI / 2 ) + ( progress * ( Math.PI * 2 ) );
var startAngle = ( - Math.PI / 2 ) + ( this.progressOffset * ( Math.PI * 2 ) );
this.context.save();
this.context.clearRect( 0, 0, this.diameter, this.diameter );
// Solid background color
this.context.beginPath();
this.context.arc( x, y, radius + 4, 0, Math.PI * 2, false );
this.context.fillStyle = 'rgba( 0, 0, 0, 0.4 )';
this.context.fill();
// Draw progress track
this.context.beginPath();
this.context.arc( x, y, radius, 0, Math.PI * 2, false );
this.context.lineWidth = this.thickness;
this.context.strokeStyle = '#666';
this.context.stroke();
if( this.playing ) {
// Draw progress on top of track
this.context.beginPath();
this.context.arc( x, y, radius, startAngle, endAngle, false );
this.context.lineWidth = this.thickness;
this.context.strokeStyle = '#fff';
this.context.stroke();
}
this.context.translate( x - ( iconSize / 2 ), y - ( iconSize / 2 ) );
// Draw play/pause icons
if( this.playing ) {
this.context.fillStyle = '#fff';
this.context.fillRect( 0, 0, iconSize / 2 - 4, iconSize );
this.context.fillRect( iconSize / 2 + 4, 0, iconSize / 2 - 4, iconSize );
}
else {
this.context.beginPath();
this.context.translate( 4, 0 );
this.context.moveTo( 0, 0 );
this.context.lineTo( iconSize - 4, iconSize / 2 );
this.context.lineTo( 0, iconSize );
this.context.fillStyle = '#fff';
this.context.fill();
}
this.context.restore();
};
Playback.prototype.on = function( type, listener ) {
this.canvas.addEventListener( type, listener, false );
};
Playback.prototype.off = function( type, listener ) {
this.canvas.removeEventListener( type, listener, false );
};
Playback.prototype.destroy = function() {
this.playing = false;
if( this.canvas.parentNode ) {
this.container.removeChild( this.canvas );
}
};
// --------------------------------------------------------------------//
// ------------------------------- API --------------------------------//
// --------------------------------------------------------------------//
Reveal = {
VERSION: VERSION,
initialize: initialize,
configure: configure,
sync: sync,
// Navigation methods
slide: slide,
left: navigateLeft,
right: navigateRight,
up: navigateUp,
down: navigateDown,
prev: navigatePrev,
next: navigateNext,
// Fragment methods
navigateFragment: navigateFragment,
prevFragment: previousFragment,
nextFragment: nextFragment,
// Deprecated aliases
navigateTo: slide,
navigateLeft: navigateLeft,
navigateRight: navigateRight,
navigateUp: navigateUp,
navigateDown: navigateDown,
navigatePrev: navigatePrev,
navigateNext: navigateNext,
// Forces an update in slide layout
layout: layout,
// Randomizes the order of slides
shuffle: shuffle,
// Returns an object with the available routes as booleans (left/right/top/bottom)
availableRoutes: availableRoutes,
// Returns an object with the available fragments as booleans (prev/next)
availableFragments: availableFragments,
// Toggles the overview mode on/off
toggleOverview: toggleOverview,
// Toggles the "black screen" mode on/off
togglePause: togglePause,
// Toggles the auto slide mode on/off
toggleAutoSlide: toggleAutoSlide,
// State checks
isOverview: isOverview,
isPaused: isPaused,
isAutoSliding: isAutoSliding,
// Adds or removes all internal event listeners (such as keyboard)
addEventListeners: addEventListeners,
removeEventListeners: removeEventListeners,
// Facility for persisting and restoring the presentation state
getState: getState,
setState: setState,
// Presentation progress on range of 0-1
getProgress: getProgress,
// Returns the indices of the current, or specified, slide
getIndices: getIndices,
getTotalSlides: getTotalSlides,
// Returns the slide element at the specified index
getSlide: getSlide,
// Returns the slide background element at the specified index
getSlideBackground: getSlideBackground,
// Returns the speaker notes string for a slide, or null
getSlideNotes: getSlideNotes,
// Returns the previous slide element, may be null
getPreviousSlide: function() {
return previousSlide;
},
// Returns the current slide element
getCurrentSlide: function() {
return currentSlide;
},
// Returns the current scale of the presentation content
getScale: function() {
return scale;
},
// Returns the current configuration object
getConfig: function() {
return config;
},
// Helper method, retrieves query string as a key/value hash
getQueryHash: function() {
var query = {};
location.search.replace( /[A-Z0-9]+?=([\w\.%-]*)/gi, function(a) {
query[ a.split( '=' ).shift() ] = a.split( '=' ).pop();
} );
// Basic deserialization
for( var i in query ) {
var value = query[ i ];
query[ i ] = deserialize( unescape( value ) );
}
return query;
},
// Returns true if we're currently on the first slide
isFirstSlide: function() {
return ( indexh === 0 && indexv === 0 );
},
// Returns true if we're currently on the last slide
isLastSlide: function() {
if( currentSlide ) {
// Does this slide has next a sibling?
if( currentSlide.nextElementSibling ) return false;
// If it's vertical, does its parent have a next sibling?
if( isVerticalSlide( currentSlide ) && currentSlide.parentNode.nextElementSibling ) return false;
return true;
}
return false;
},
// Checks if reveal.js has been loaded and is ready for use
isReady: function() {
return loaded;
},
// Forward event binding to the reveal DOM element
addEventListener: function( type, listener, useCapture ) {
if( 'addEventListener' in window ) {
( dom.wrapper || document.querySelector( '.reveal' ) ).addEventListener( type, listener, useCapture );
}
},
removeEventListener: function( type, listener, useCapture ) {
if( 'addEventListener' in window ) {
( dom.wrapper || document.querySelector( '.reveal' ) ).removeEventListener( type, listener, useCapture );
}
},
// Programatically triggers a keyboard event
triggerKey: function( keyCode ) {
onDocumentKeyDown( { keyCode: keyCode } );
},
// Registers a new shortcut to include in the help overlay
registerKeyboardShortcut: function( key, value ) {
keyboardShortcuts[key] = value;
}
};
return Reveal;
}));
|
var Example = Example || {};
Example.staticFriction = function() {
var Engine = Matter.Engine,
Render = Matter.Render,
Runner = Matter.Runner,
Body = Matter.Body,
Composites = Matter.Composites,
Events = Matter.Events,
MouseConstraint = Matter.MouseConstraint,
Mouse = Matter.Mouse,
World = Matter.World,
Bodies = Matter.Bodies;
// create engine
var engine = Engine.create(),
world = engine.world;
// create renderer
var render = Render.create({
element: document.body,
engine: engine,
options: {
width: Math.min(document.documentElement.clientWidth, 800),
height: Math.min(document.documentElement.clientHeight, 600),
showVelocity: true
}
});
Render.run(render);
// create runner
var runner = Runner.create();
Runner.run(runner, engine);
// add bodies
var body = Bodies.rectangle(400, 500, 200, 60, { isStatic: true, chamfer: 10 }),
size = 50,
counter = -1;
var stack = Composites.stack(350, 470 - 6 * size, 1, 6, 0, 0, function(x, y) {
return Bodies.rectangle(x, y, size * 2, size, {
slop: 0.5,
friction: 1,
frictionStatic: Infinity
});
});
World.add(world, [
body,
stack,
// walls
Bodies.rectangle(400, 0, 800, 50, { isStatic: true }),
Bodies.rectangle(400, 600, 800, 50, { isStatic: true }),
Bodies.rectangle(800, 300, 50, 600, { isStatic: true }),
Bodies.rectangle(0, 300, 50, 600, { isStatic: true })
]);
Events.on(engine, 'beforeUpdate', function(event) {
counter += 0.014;
if (counter < 0) {
return;
}
var px = 400 + 100 * Math.sin(counter);
// body is static so must manually update velocity for friction to work
Body.setVelocity(body, { x: px - body.position.x, y: 0 });
Body.setPosition(body, { x: px, y: body.position.y });
});
// add mouse control
var mouse = Mouse.create(render.canvas),
mouseConstraint = MouseConstraint.create(engine, {
mouse: mouse,
constraint: {
stiffness: 0.2,
render: {
visible: false
}
}
});
World.add(world, mouseConstraint);
// keep the mouse in sync with rendering
render.mouse = mouse;
// fit the render viewport to the scene
Render.lookAt(render, {
min: { x: 0, y: 0 },
max: { x: 800, y: 600 }
});
// context for MatterTools.Demo
return {
engine: engine,
runner: runner,
render: render,
canvas: render.canvas,
stop: function() {
Matter.Render.stop(render);
Matter.Runner.stop(runner);
}
};
}; |
var searchData=
[
['vertical_5fline',['vertical_line',['../class_abstract_board.html#a78c4d43cc32d9dc74d73156497db6d3f',1,'AbstractBoard']]]
];
|
/**
* Created by huangyao on 14-10-1.
*/
var _ = require('lodash');
var color =require('colors');
var fs =require('fs');
var config = require('../config.js');
var path = require('path');
var mongoose = require("mongoose");
var lcommon = require('lush').common;
console.log(config.db);
mongoose.connect(config.db,function (err) {
if(err){
throw new Error('db connect error!\n'+err);
}
console.log('db connect success!'.yellow);
});
// console.log('point');
// var models = {
//
// init : function (callback) {
// fs.readdir(path+'/module',function (err,files) {
// if(err){
// throw err;
// }
// // console.log(files);
// return callback(files.filter(function (item) {
// return !(item === "index.js" || item === "." || item === "..");
// }));
// });
// },
// };
//
//
// models.init(function (files) {
// // console.log(files);
// for (var item in files) {
// //reuire all modules
// // console.log(lcommon.literat(files[item]).slice(0,-3));
// console.log(files[item]);
// item = files[item].split('.')[0];
// require('./'+ item);
// var m = lcommon.literat(item);
// console.log('loading and use ',m,' model');
// exports[m] = mongoose.model(m);
//
// // _.extend(models,file.exports);
// // console.log(file);
// }
// });
//
var models = fs.readdirSync(path.resolve('.','module'));
models.forEach(function(item,index){
if(item !== '.' && item !== '..' && item !== 'index.js'){
// console.log(item.indexOf('.js'));
//ends with .js
if(item.indexOf('.js') == (item.length-3)){
item = item.split('.')[0];
require('./'+ item);
var m = lcommon.literat(item);
console.log('loading and use ',m,' model');
exports[m] = mongoose.model(m);
}
}
});
|
version https://git-lfs.github.com/spec/v1
oid sha256:054dbc79bbfc64911008a1e140813a8705dfc5cff35cbffd8bf7bc1f74c446b6
size 5257
|
define(["widgetjs/widgetjs", "lodash", "jquery", "prettify", "code", "bootstrap"], function(widgetjs, lodash, jQuery, prettify, code) {
var examples = {};
examples.modals = code({
group: "Modals",
label: "Modals",
links: ["http://getbootstrap.com/javascript/#modals"],
example : function(html) {
// Modal
html.div({"class": "clearfix bs-example-modal"},
html.div({ klass: "modal"},
html.div({ klass: "modal-dialog"},
html.div({ klass: "modal-content"},
html.div({ klass: "modal-header"},
html.button({ type: "button", klass: "close", "data-dismiss": "modal", "aria-hidden": "true"},
"×"
),
html.h4({ klass: "modal-title"},
"Modal title"
)
),
html.div({ klass: "modal-body"},
html.p(
"One fine body…"
)
),
html.div({ klass: "modal-footer"},
html.button({ type: "button", klass: "btn btn-default", "data-dismiss": "modal"},
"Close"
),
html.button({ type: "button", klass: "btn btn-primary"},
"Save changes"
)
)
)
)
)
);
}
});
examples.modalsDemo = code({
group: "Modals",
label: "Live Demo",
links: ["http://getbootstrap.com/javascript/#modals"],
example : function(html) {
// Modal
html.div({ id: "myModal", klass: "modal fade"},
html.div({ klass: "modal-dialog"},
html.div({ klass: "modal-content"},
html.div({ klass: "modal-header"},
html.button({ type: "button", klass: "close", "data-dismiss": "modal", "aria-hidden": "true"},
"×"
),
html.h4({ klass: "modal-title"},
"Modal title"
)
),
html.div({ klass: "modal-body"},
html.p(
"One fine body…"
)
),
html.div({ klass: "modal-footer"},
html.button({ type: "button", klass: "btn btn-default", "data-dismiss": "modal"},
"Close"
),
html.button({ type: "button", klass: "btn btn-primary"},
"Save changes"
)
)
)
)
);
html.button({ klass: "btn btn-primary btn-lg", "data-toggle": "modal", "data-target": "#myModal"}, "Show modal");
}
});
examples.toolTips = code({
group: "Tooltips",
label: "Live Demo",
links: ["http://getbootstrap.com/javascript/#tooltips"],
example : function(html) {
// TOOLTIPS
html.div({ klass: "tooltip-demo"},
html.div({ klass: "bs-example-tooltips"},
html.button({ type: "button", klass: "btn btn-default", "data-toggle": "tooltip", "data-placement": "left", title: "", "data-original-title": "Tooltip on left"},
"Tooltip on left"
),
html.button({ type: "button", klass: "btn btn-default", "data-toggle": "tooltip", "data-placement": "top", title: "", "data-original-title": "Tooltip on top"},
"Tooltip on top"
),
html.button({ type: "button", klass: "btn btn-default", "data-toggle": "tooltip", "data-placement": "bottom", title: "", "data-original-title": "Tooltip on bottom"},
"Tooltip on bottom"
),
html.button({ type: "button", klass: "btn btn-default", "data-toggle": "tooltip", "data-placement": "right", title: "", "data-original-title": "Tooltip on right"},
"Tooltip on right"
)
)
);
jQuery(".bs-example-tooltips").tooltip();
}
});
examples.popovers = code({
group: "Popovers",
label: "Popovers",
links: ["http://getbootstrap.com/javascript/#popovers"],
example : function(html) {
// Popovers
html.div({ klass: "bs-example-popovers"},
html.button({ type: "button", klass: "btn btn-default", "data-container": "body", "data-toggle": "popover", "data-placement": "left", "data-content": "Vivamus sagittis lacus vel augue laoreet rutrum faucibus.", "data-original-title": "", title: ""},
"Left"
),
html.button({ type: "button", klass: "btn btn-default", "data-container": "body", "data-toggle": "popover", "data-placement": "top", "data-content": "Vivamus sagittis lacus vel augue laoreet rutrum faucibus.", "data-original-title": "", title: ""},
"Top"
),
html.button({ type: "button", klass: "btn btn-default", "data-container": "body", "data-toggle": "popover", "data-placement": "bottom", "data-content": "Vivamus sagittis lacus vel augue laoreet rutrum faucibus.", "data-original-title": "", title: ""},
"Bottom"
),
html.button({ type: "button", klass: "btn btn-default", "data-container": "body", "data-toggle": "popover", "data-placement": "right", "data-content": "Vivamus sagittis lacus vel augue laoreet rutrum faucibus.", "data-original-title": "", title: ""},
"Right"
)
);
jQuery(".bs-example-popovers button").popover();
}
});
examples.buttonsCheckbox = code({
group: "Buttons",
label: "Checkbox",
links: ["http://getbootstrap.com/javascript/#buttons"],
example : function(html) {
html.div({ style: "padding-bottom: 24px;"},
html.div({ klass: "btn-group", "data-toggle": "buttons"},
html.label({ klass: "btn btn-primary"},
html.input({ type: "checkbox"}),
"Option 1"
),
html.label({ klass: "btn btn-primary"},
html.input({ type: "checkbox"}),
"Option 2"
),
html.label({ klass: "btn btn-primary"},
html.input({ type: "checkbox"}),
"Option 3"
)
)
);
}
});
examples.buttonsRadio= code({
group: "Buttons",
label: "Radio",
links: ["http://getbootstrap.com/javascript/#buttons"],
example : function(html) {
html.div({ style: "padding-bottom: 24px;"},
html.div({ klass: "btn-group", "data-toggle": "buttons"},
html.label({ klass: "btn btn-primary"},
html.input({ type: "radio"}),
"Option 1"
),
html.label({ klass: "btn btn-primary"},
html.input({ type: "radio"}),
"Option 2"
),
html.label({ klass: "btn btn-primary"},
html.input({ type: "radio"}),
"Option 3"
)
)
);
}
});
examples.collapse = code({
group: "Collapse",
label: "Collapse",
links: ["http://getbootstrap.com/javascript/#collapse"],
example : function(html) {
html.div({ klass: "panel-group", id: "accordion"},
html.div({ klass: "panel panel-default"},
html.div({ klass: "panel-heading"},
html.h4({ klass: "panel-title"},
html.a({ "data-toggle": "collapse", "data-parent": "#accordion", href: "#collapseOne"},
"Heading #1"
)
)
),
html.div({ id: "collapseOne", klass: "panel-collapse collapse in"},
html.div({ klass: "panel-body"},
"Content"
)
)
),
html.div({ klass: "panel panel-default"},
html.div({ klass: "panel-heading"},
html.h4({ klass: "panel-title"},
html.a({ "data-toggle": "collapse", "data-parent": "#accordion", href: "#collapseTwo"},
"Heading #2"
)
)
),
html.div({ id: "collapseTwo", klass: "panel-collapse collapse"},
html.div({ klass: "panel-body"},
"Content"
)
)
),
html.div({ klass: "panel panel-default"},
html.div({ klass: "panel-heading"},
html.h4({ klass: "panel-title"},
html.a({ "data-toggle": "collapse", "data-parent": "#accordion", href: "#collapseThree"},
"Heading #2"
)
)
),
html.div({ id: "collapseThree", klass: "panel-collapse collapse"},
html.div({ klass: "panel-body"},
"Content"
)
)
)
);
}
});
return examples;
}); |
module.exports = require('./lib/dustjs-browserify'); |
version https://git-lfs.github.com/spec/v1
oid sha256:94e212e6fc0c837cd9fff7fca8feff0187a0a22a97c7bd4c6d8f05c5cc358519
size 3077
|
import React from 'react'
import Icon from 'react-icon-base'
const IoTshirtOutline = props => (
<Icon viewBox="0 0 40 40" {...props}>
<g><path d="m11.4 6.7l-8.1 2.4 0.8 2.5 3.1-0.3 3-0.4-0.2 3-1.1 19.9h17.2l-1.1-19.9-0.2-3 3 0.4 3.1 0.3 0.8-2.5-8.1-2.4c-0.5 0.6-1 1.1-1.6 1.5-1.2 0.8-2.7 1.2-4.5 1.2-2.7-0.1-4.6-0.9-6.1-2.7z m11.1-2.9l12.5 3.7-2.5 6.9-5-0.6 1.3 22.5h-22.5l1.2-22.5-5 0.6-2.5-6.9 12.5-3.7c1.1 2.1 2.4 3 5 3.1 2.6 0 3.9-1 5-3.1z"/></g>
</Icon>
)
export default IoTshirtOutline
|
declare module "react-apollo" {
declare function graphql(query: Object, options: Object): Function;
}
|
/*
* deferred.js
*
* Copyright 2011, HeavyLifters Network Ltd. All rights reserved.
*/
;(function() {
var DeferredAPI = {
deferred: deferred,
all: all,
Deferred: Deferred,
DeferredList: DeferredList,
wrapResult: wrapResult,
wrapFailure: wrapFailure,
Failure: Failure
}
// CommonJS module support
if (typeof module !== 'undefined') {
var DeferredURLRequest = require('./DeferredURLRequest')
for (var k in DeferredURLRequest) {
DeferredAPI[k] = DeferredURLRequest[k]
}
module.exports = DeferredAPI
}
// Browser API
else if (typeof window !== 'undefined') {
window.deferred = DeferredAPI
}
// Fake out console if necessary
if (typeof console === 'undefined') {
var global = function() { return this || (1,eval)('this') }
;(function() {
var noop = function(){}
global().console = { log: noop, warn: noop, error: noop, dir: noop }
}())
}
function wrapResult(result) {
return new Deferred().resolve(result)
}
function wrapFailure(error) {
return new Deferred().reject(error)
}
function Failure(v) { this.value = v }
// Crockford style constructor
function deferred(t) { return new Deferred(t) }
function Deferred(canceller) {
this.called = false
this.running = false
this.result = null
this.pauseCount = 0
this.callbacks = []
this.verbose = false
this._canceller = canceller
// If this Deferred is cancelled and the creator of this Deferred
// didn't cancel it, then they may not know about the cancellation and
// try to resolve or reject it as well. This flag causes the
// "already called" error that resolve() or reject() normally throws
// to be suppressed once.
this._suppressAlreadyCalled = false
}
if (typeof Object.defineProperty === 'function') {
var _consumeThrownExceptions = true
Object.defineProperty(Deferred, 'consumeThrownExceptions', {
enumerable: false,
set: function(v) { _consumeThrownExceptions = v },
get: function() { return _consumeThrownExceptions }
})
} else {
Deferred.consumeThrownExceptions = true
}
Deferred.prototype.cancel = function() {
if (!this.called) {
if (typeof this._canceller === 'function') {
this._canceller(this)
} else {
this._suppressAlreadyCalled = true
}
if (!this.called) {
this.reject('cancelled')
}
} else if (this.result instanceof Deferred) {
this.result.cancel()
}
}
Deferred.prototype.then = function(callback, errback) {
this.callbacks.push({callback: callback, errback: errback})
if (this.called) _run(this)
return this
}
Deferred.prototype.fail = function(errback) {
this.callbacks.push({callback: null, errback: errback})
if (this.called) _run(this)
return this
}
Deferred.prototype.both = function(callback) {
return this.then(callback, callback)
}
Deferred.prototype.resolve = function(result) {
_startRun(this, result)
return this
}
Deferred.prototype.reject = function(err) {
if (!(err instanceof Failure)) {
err = new Failure(err)
}
_startRun(this, err)
return this
}
Deferred.prototype.pause = function() {
this.pauseCount += 1
if (this.extra) {
console.log('Deferred.pause ' + this.pauseCount + ': ' + this.extra)
}
return this
}
Deferred.prototype.unpause = function() {
this.pauseCount -= 1
if (this.extra) {
console.log('Deferred.unpause ' + this.pauseCount + ': ' + this.extra)
}
if (this.pauseCount <= 0 && this.called) {
_run(this)
}
return this
}
// For debugging
Deferred.prototype.inspect = function(extra, cb) {
this.extra = extra
var self = this
return this.then(function(r) {
console.log('Deferred.inspect resolved: ' + self.extra)
console.dir(r)
return r
}, function(e) {
console.log('Deferred.inspect rejected: ' + self.extra)
console.dir(e)
return e
})
}
/// A couple of sugary methods
Deferred.prototype.thenReturn = function(result) {
return this.then(function(_) { return result })
}
Deferred.prototype.thenCall = function(f) {
return this.then(function(result) {
f(result)
return result
})
}
Deferred.prototype.failReturn = function(result) {
return this.fail(function(_) { return result })
}
Deferred.prototype.failCall = function(f) {
return this.fail(function(result) {
f(result)
return result
})
}
function _continue(d, newResult) {
d.result = newResult
d.unpause()
return d.result
}
function _nest(outer) {
outer.result.both(function(newResult) {
return _continue(outer, newResult)
})
}
function _startRun(d, result) {
if (d.called) {
if (d._suppressAlreadyCalled) {
d._suppressAlreadyCalled = false
return
}
throw new Error("Already resolved Deferred: " + d)
}
d.called = true
d.result = result
if (d.result instanceof Deferred) {
d.pause()
_nest(d)
return
}
_run(d)
}
function _run(d) {
if (d.running) return
var link, status, fn
if (d.pauseCount > 0) return
while (d.callbacks.length > 0) {
link = d.callbacks.shift()
status = (d.result instanceof Failure) ? 'errback' : 'callback'
fn = link[status]
if (typeof fn !== 'function') continue
try {
d.running = true
d.result = fn(d.result)
d.running = false
if (d.result instanceof Deferred) {
d.pause()
_nest(d)
return
}
} catch (e) {
if (Deferred.consumeThrownExceptions) {
d.running = false
var f = new Failure(e)
f.source = f.source || status
d.result = f
if (d.verbose) {
console.warn('uncaught error in deferred ' + status + ': ' + e.message)
console.warn('Stack: ' + e.stack)
}
} else {
throw e
}
}
}
}
/// DeferredList / all
function all(ds, opts) { return new DeferredList(ds, opts) }
function DeferredList(ds, opts) {
opts = opts || {}
Deferred.call(this)
this._deferreds = ds
this._finished = 0
this._length = ds.length
this._results = []
this._fireOnFirstResult = opts.fireOnFirstResult
this._fireOnFirstError = opts.fireOnFirstError
this._consumeErrors = opts.consumeErrors
this._cancelDeferredsWhenCancelled = opts.cancelDeferredsWhenCancelled
if (this._length === 0 && !this._fireOnFirstResult) {
this.resolve(this._results)
}
for (var i = 0, n = this._length; i < n; ++i) {
ds[i].both(deferredListCallback(this, i))
}
}
if (typeof Object.create === 'function') {
DeferredList.prototype = Object.create(Deferred.prototype, {
constructor: { value: DeferredList, enumerable: false }
})
} else {
DeferredList.prototype = new Deferred()
DeferredList.prototype.constructor = DeferredList
}
DeferredList.prototype.cancelDeferredsWhenCancelled = function() {
this._cancelDeferredsWhenCancelled = true
}
var _deferredCancel = Deferred.prototype.cancel
DeferredList.prototype.cancel = function() {
_deferredCancel.call(this)
if (this._cancelDeferredsWhenCancelled) {
for (var i = 0; i < this._length; ++i) {
this._deferreds[i].cancel()
}
}
}
function deferredListCallback(d, i) {
return function(result) {
var isErr = result instanceof Failure
, myResult = (isErr && d._consumeErrors) ? null : result
// Support nesting
if (result instanceof Deferred) {
result.both(deferredListCallback(d, i))
return
}
d._results[i] = myResult
d._finished += 1
if (!d.called) {
if (d._fireOnFirstResult && !isErr) {
d.resolve(result)
} else if (d._fireOnFirstError && isErr) {
d.reject(result)
} else if (d._finished === d._length) {
d.resolve(d._results)
}
}
return myResult
}
}
}()) |
'use strict';
var request = require('request');
var querystring = require('querystring');
var FirebaseError = require('./error');
var RSVP = require('rsvp');
var _ = require('lodash');
var logger = require('./logger');
var utils = require('./utils');
var responseToError = require('./responseToError');
var refreshToken;
var commandScopes;
var scopes = require('./scopes');
var CLI_VERSION = require('../package.json').version;
var _request = function(options) {
logger.debug('>>> HTTP REQUEST',
options.method,
options.url,
options.body || options.form || ''
);
return new RSVP.Promise(function(resolve, reject) {
var req = request(options, function(err, response, body) {
if (err) {
return reject(new FirebaseError('Server Error. ' + err.message, {
original: err,
exit: 2
}));
}
logger.debug('<<< HTTP RESPONSE', response.statusCode, response.headers);
if (response.statusCode >= 400) {
logger.debug('<<< HTTP RESPONSE BODY', response.body);
if (!options.resolveOnHTTPError) {
return reject(responseToError(response, body, options));
}
}
return resolve({
status: response.statusCode,
response: response,
body: body
});
});
if (_.size(options.files) > 0) {
var form = req.form();
_.forEach(options.files, function(details, param) {
form.append(param, details.stream, {
knownLength: details.knownLength,
filename: details.filename,
contentType: details.contentType
});
});
}
});
};
var _appendQueryData = function(path, data) {
if (data && _.size(data) > 0) {
path += _.includes(path, '?') ? '&' : '?';
path += querystring.stringify(data);
}
return path;
};
var api = {
// "In this context, the client secret is obviously not treated as a secret"
// https://developers.google.com/identity/protocols/OAuth2InstalledApp
billingOrigin: utils.envOverride('FIREBASE_BILLING_URL', 'https://cloudbilling.googleapis.com'),
clientId: utils.envOverride('FIREBASE_CLIENT_ID', '563584335869-fgrhgmd47bqnekij5i8b5pr03ho849e6.apps.googleusercontent.com'),
clientSecret: utils.envOverride('FIREBASE_CLIENT_SECRET', 'j9iVZfS8kkCEFUPaAeJV0sAi'),
cloudloggingOrigin: utils.envOverride('FIREBASE_CLOUDLOGGING_URL', 'https://logging.googleapis.com'),
adminOrigin: utils.envOverride('FIREBASE_ADMIN_URL', 'https://admin.firebase.com'),
apikeysOrigin: utils.envOverride('FIREBASE_APIKEYS_URL', 'https://apikeys.googleapis.com'),
appengineOrigin: utils.envOverride('FIREBASE_APPENGINE_URL', 'https://appengine.googleapis.com'),
authOrigin: utils.envOverride('FIREBASE_AUTH_URL', 'https://accounts.google.com'),
consoleOrigin: utils.envOverride('FIREBASE_CONSOLE_URL', 'https://console.firebase.google.com'),
deployOrigin: utils.envOverride('FIREBASE_DEPLOY_URL', utils.envOverride('FIREBASE_UPLOAD_URL', 'https://deploy.firebase.com')),
functionsOrigin: utils.envOverride('FIREBASE_FUNCTIONS_URL', 'https://cloudfunctions.googleapis.com'),
googleOrigin: utils.envOverride('FIREBASE_TOKEN_URL', utils.envOverride('FIREBASE_GOOGLE_URL', 'https://www.googleapis.com')),
hostingOrigin: utils.envOverride('FIREBASE_HOSTING_URL', 'https://firebaseapp.com'),
realtimeOrigin: utils.envOverride('FIREBASE_REALTIME_URL', 'https://firebaseio.com'),
rulesOrigin: utils.envOverride('FIREBASE_RULES_URL', 'https://firebaserules.googleapis.com'),
runtimeconfigOrigin: utils.envOverride('FIREBASE_RUNTIMECONFIG_URL', 'https://runtimeconfig.googleapis.com'),
setToken: function(token) {
refreshToken = token;
},
setScopes: function(s) {
commandScopes = _.uniq(_.flatten([
scopes.EMAIL,
scopes.OPENID,
scopes.CLOUD_PROJECTS_READONLY,
scopes.FIREBASE_PLATFORM
].concat(s || [])));
logger.debug('> command requires scopes:', JSON.stringify(commandScopes));
},
getAccessToken: function() {
return require('./auth').getAccessToken(refreshToken, commandScopes);
},
addRequestHeaders: function(reqOptions) {
// Runtime fetch of Auth singleton to prevent circular module dependencies
_.set(reqOptions, ['headers', 'User-Agent'], 'FirebaseCLI/' + CLI_VERSION);
var auth = require('../lib/auth');
return auth.getAccessToken(refreshToken, commandScopes).then(function(result) {
_.set(reqOptions, 'headers.authorization', 'Bearer ' + result.access_token);
return reqOptions;
});
},
request: function(method, resource, options) {
options = _.extend({
data: {},
origin: api.adminOrigin, // default to hitting the admin backend
resolveOnHTTPError: false, // by default, status codes >= 400 leads to reject
json: true
}, options);
var validMethods = ['GET', 'PUT', 'POST', 'DELETE', 'PATCH'];
if (validMethods.indexOf(method) < 0) {
method = 'GET';
}
var reqOptions = {
method: method
};
if (options.query) {
resource = _appendQueryData(resource, options.query);
}
if (method === 'GET') {
resource = _appendQueryData(resource, options.data);
} else {
if (_.size(options.data) > 0) {
reqOptions.body = options.data;
} else if (_.size(options.form) > 0) {
reqOptions.form = options.form;
}
}
reqOptions.url = options.origin + resource;
reqOptions.files = options.files;
reqOptions.resolveOnHTTPError = options.resolveOnHTTPError;
reqOptions.json = options.json;
if (options.auth === true) {
return api.addRequestHeaders(reqOptions).then(function(reqOptionsWithToken) {
return _request(reqOptionsWithToken);
});
}
return _request(reqOptions);
},
getProject: function(projectId) {
return api.request('GET', '/v1/projects/' + encodeURIComponent(projectId), {
auth: true
}).then(function(res) {
if (res.body && !res.body.error) {
return res.body;
}
return RSVP.reject(new FirebaseError('Server Error: Unexpected Response. Please try again', {
context: res,
exit: 2
}));
});
},
getProjects: function() {
return api.request('GET', '/v1/projects', {
auth: true
}).then(function(res) {
if (res.body && res.body.projects) {
return res.body.projects;
}
return RSVP.reject(new FirebaseError('Server Error: Unexpected Response. Please try again', {
context: res,
exit: 2
}));
});
}
};
module.exports = api;
|
/**!
* urllib - test/fixtures/server.js
*
* Copyright(c) 2011 - 2014 fengmk2 and other contributors.
* MIT Licensed
*
* Authors:
* fengmk2 <[email protected]> (http://fengmk2.github.com)
*/
"use strict";
/**
* Module dependencies.
*/
var should = require('should');
var http = require('http');
var querystring = require('querystring');
var fs = require('fs');
var zlib = require('zlib');
var iconv = require('iconv-lite');
var server = http.createServer(function (req, res) {
// req.headers['user-agent'].should.match(/^node\-urllib\/\d+\.\d+\.\d+ node\//);
var chunks = [];
var size = 0;
req.on('data', function (buf) {
chunks.push(buf);
size += buf.length;
});
req.on('end', function () {
if (req.url === '/timeout') {
return setTimeout(function () {
res.end('timeout 500ms');
}, 500);
} else if (req.url === '/response_timeout') {
res.write('foo');
return setTimeout(function () {
res.end('timeout 700ms');
}, 700);
} else if (req.url === '/error') {
return res.destroy();
} else if (req.url === '/socket.destroy') {
res.write('foo haha\n');
setTimeout(function () {
res.write('foo haha 2');
setTimeout(function () {
res.destroy();
}, 300);
}, 200);
return;
} else if (req.url === '/socket.end') {
res.write('foo haha\n');
setTimeout(function () {
res.write('foo haha 2');
setTimeout(function () {
// res.end();
res.socket.end();
// res.socket.end('foosdfsdf');
}, 300);
}, 200);
return;
} else if (req.url === '/socket.end.error') {
res.write('foo haha\n');
setTimeout(function () {
res.write('foo haha 2');
setTimeout(function () {
res.socket.end('balabala');
}, 300);
}, 200);
return;
} else if (req.url === '/302') {
res.statusCode = 302;
res.setHeader('Location', '/204');
return res.end('Redirect to /204');
} else if (req.url === '/301') {
res.statusCode = 301;
res.setHeader('Location', '/204');
return res.end('I am 301 body');
} else if (req.url === '/303') {
res.statusCode = 303;
res.setHeader('Location', '/204');
return res.end('Redirect to /204');
} else if (req.url === '/307') {
res.statusCode = 307;
res.setHeader('Location', '/204');
return res.end('I am 307 body');
} else if (req.url === '/redirect_no_location') {
res.statusCode = 302;
return res.end('I am 302 body');
} else if (req.url === '/204') {
res.statusCode = 204;
return res.end();
} else if (req.url === '/loop_redirect') {
res.statusCode = 302;
res.setHeader('Location', '/loop_redirect');
return res.end('Redirect to /loop_redirect');
} else if (req.url === '/post') {
res.setHeader('X-Request-Content-Type', req.headers['content-type'] || '');
res.writeHeader(200);
return res.end(Buffer.concat(chunks));
} else if (req.url.indexOf('/get') === 0) {
res.writeHeader(200);
return res.end(req.url);
} else if (req.url === '/wrongjson') {
res.writeHeader(200);
return res.end(new Buffer('{"foo":""'));
} else if (req.url === '/wrongjson-gbk') {
res.setHeader('content-type', 'application/json; charset=gbk');
res.writeHeader(200);
return res.end(fs.readFileSync(__filename));
} else if (req.url === '/writestream') {
var s = fs.createReadStream(__filename);
return s.pipe(res);
} else if (req.url === '/auth') {
var auth = new Buffer(req.headers.authorization.split(' ')[1], 'base64').toString().split(':');
res.writeHeader(200);
return res.end(JSON.stringify({user: auth[0], password: auth[1]}));
} else if (req.url === '/stream') {
res.writeHeader(200, {
'Content-Length': String(size)
});
for (var i = 0; i < chunks.length; i++) {
res.write(chunks[i]);
}
res.end();
return;
} else if (req.url.indexOf('/json_mirror') === 0) {
res.setHeader('Content-Type', req.headers['content-type'] || 'application/json');
if (req.method === 'GET') {
res.end(JSON.stringify({
url: req.url,
data: Buffer.concat(chunks).toString(),
}));
} else {
res.end(JSON.stringify(JSON.parse(Buffer.concat(chunks))));
}
return;
} else if (req.url.indexOf('/no-gzip') === 0) {
fs.createReadStream(__filename).pipe(res);
return;
} else if (req.url.indexOf('/gzip') === 0) {
res.setHeader('Content-Encoding', 'gzip');
fs.createReadStream(__filename).pipe(zlib.createGzip()).pipe(res);
return;
} else if (req.url === '/ua') {
res.end(JSON.stringify(req.headers));
return;
} else if (req.url === '/gbk/json') {
res.setHeader('Content-Type', 'application/json;charset=gbk');
var content = iconv.encode(JSON.stringify({hello: '你好'}), 'gbk');
return res.end(content);
} else if (req.url === '/gbk/text') {
res.setHeader('Content-Type', 'text/plain;charset=gbk');
var content = iconv.encode('你好', 'gbk');
return res.end(content);
} else if (req.url === '/errorcharset') {
res.setHeader('Content-Type', 'text/plain;charset=notfound');
return res.end('你好');
}
var url = req.url.split('?');
var get = querystring.parse(url[1]);
var ret;
if (chunks.length > 0) {
ret = Buffer.concat(chunks).toString();
} else {
ret = '<html><head><meta http-equiv="Content-Type" content="text/html;charset=##{charset}##">...</html>';
}
chunks = [];
res.writeHead(get.code ? get.code : 200, {
'Content-Type': 'text/html',
});
res.end(ret.replace('##{charset}##', get.charset ? get.charset : ''));
});
});
module.exports = server;
|
/**
* @license Highcharts JS v8.2.2 (2020-10-22)
* @module highcharts/modules/funnel3d
* @requires highcharts
* @requires highcharts/highcharts-3d
* @requires highcharts/modules/cylinder
*
* Highcharts funnel module
*
* (c) 2010-2019 Kacper Madej
*
* License: www.highcharts.com/license
*/
'use strict';
import '../../Series/Funnel3DSeries.js';
|
function* f() {
var x;
try {
x = yield 1;
} catch (ex) {
yield ex;
}
return 2;
}
var g = f();
expect(g.next()).toEqual({value: 1, done: false});
expect(g.next()).toEqual({value: 2, done: true});
g = f();
expect(g.next()).toEqual({value: 1, done: false});
expect(g.throw(3)).toEqual({value: 3, done: false});
expect(g.next()).toEqual({value: 2, done: true});
|
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'use strict';
const models = require('./index');
/**
* Properties of an artifact source.
*
* @extends models['Resource']
*/
class ArtifactSource extends models['Resource'] {
/**
* Create a ArtifactSource.
* @member {string} [displayName] The artifact source's display name.
* @member {string} [uri] The artifact source's URI.
* @member {string} [sourceType] The artifact source's type. Possible values
* include: 'VsoGit', 'GitHub'
* @member {string} [folderPath] The folder containing artifacts.
* @member {string} [armTemplateFolderPath] The folder containing Azure
* Resource Manager templates.
* @member {string} [branchRef] The artifact source's branch reference.
* @member {string} [securityToken] The security token to authenticate to the
* artifact source.
* @member {string} [status] Indicates if the artifact source is enabled
* (values: Enabled, Disabled). Possible values include: 'Enabled',
* 'Disabled'
* @member {date} [createdDate] The artifact source's creation date.
* @member {string} [provisioningState] The provisioning status of the
* resource.
* @member {string} [uniqueIdentifier] The unique immutable identifier of a
* resource (Guid).
*/
constructor() {
super();
}
/**
* Defines the metadata of ArtifactSource
*
* @returns {object} metadata of ArtifactSource
*
*/
mapper() {
return {
required: false,
serializedName: 'ArtifactSource',
type: {
name: 'Composite',
className: 'ArtifactSource',
modelProperties: {
id: {
required: false,
readOnly: true,
serializedName: 'id',
type: {
name: 'String'
}
},
name: {
required: false,
readOnly: true,
serializedName: 'name',
type: {
name: 'String'
}
},
type: {
required: false,
readOnly: true,
serializedName: 'type',
type: {
name: 'String'
}
},
location: {
required: false,
serializedName: 'location',
type: {
name: 'String'
}
},
tags: {
required: false,
serializedName: 'tags',
type: {
name: 'Dictionary',
value: {
required: false,
serializedName: 'StringElementType',
type: {
name: 'String'
}
}
}
},
displayName: {
required: false,
serializedName: 'properties.displayName',
type: {
name: 'String'
}
},
uri: {
required: false,
serializedName: 'properties.uri',
type: {
name: 'String'
}
},
sourceType: {
required: false,
serializedName: 'properties.sourceType',
type: {
name: 'String'
}
},
folderPath: {
required: false,
serializedName: 'properties.folderPath',
type: {
name: 'String'
}
},
armTemplateFolderPath: {
required: false,
serializedName: 'properties.armTemplateFolderPath',
type: {
name: 'String'
}
},
branchRef: {
required: false,
serializedName: 'properties.branchRef',
type: {
name: 'String'
}
},
securityToken: {
required: false,
serializedName: 'properties.securityToken',
type: {
name: 'String'
}
},
status: {
required: false,
serializedName: 'properties.status',
type: {
name: 'String'
}
},
createdDate: {
required: false,
readOnly: true,
serializedName: 'properties.createdDate',
type: {
name: 'DateTime'
}
},
provisioningState: {
required: false,
serializedName: 'properties.provisioningState',
type: {
name: 'String'
}
},
uniqueIdentifier: {
required: false,
serializedName: 'properties.uniqueIdentifier',
type: {
name: 'String'
}
}
}
}
};
}
}
module.exports = ArtifactSource;
|
/**
* Bootstrap
* (sails.config.bootstrap)
*
* An asynchronous bootstrap function that runs before your Sails app gets lifted.
* This gives you an opportunity to set up your data model, run jobs, or perform some special logic.
*
* For more information on bootstrapping your app, check out:
* http://sailsjs.org/#!/documentation/reference/sails.config/sails.config.bootstrap.html
*/
module.exports.bootstrap = function(cb) {
// It's very important to trigger this callback method when you are finished
// with the bootstrap! (otherwise your server will never lift, since it's waiting on the bootstrap)
sails.services.passport.loadStrategies();
// CRON JOBS FOR INFLUENCERS, HASHTAGS, MENTIONS
// Runs every 15 minutes
const TIMEZONE = 'America/Los_Angeles';
var CronJob = require('cron').CronJob;
var cronJobs = Object.keys(sails.config.cron);
cronJobs.forEach(function(key) {
var value = sails.config.cron[key];
new CronJob(key, value, null, true, TIMEZONE);
})
sails.config.twitterstream();
// new CronJob('00 * * * * *', function() {
// console.log(new Date(), 'You will see this message every minute.');
// }, null, true, TIMEZONE);
cb();
};
|
const latestIncome = require('./latestIncome')
const latestSpending = require('./latestSpending')
function aggFinances(search) {
return {
latestIncome: () => latestIncome(search),
latestSpending: () => latestSpending(search),
}
}
module.exports = aggFinances
|
define(function(require, exports, module) {
var Notify = require('common/bootstrap-notify');
var FileChooser = require('../widget/file/file-chooser3');
exports.run = function() {
var $form = $("#course-material-form");
var materialChooser = new FileChooser({
element: '#material-file-chooser'
});
materialChooser.on('change', function(item) {
$form.find('[name="fileId"]').val(item.id);
});
$form.on('click', '.delete-btn', function(){
var $btn = $(this);
if (!confirm(Translator.trans('真的要删除该资料吗?'))) {
return ;
}
$.post($btn.data('url'), function(){
$btn.parents('.list-group-item').remove();
Notify.success(Translator.trans('资料已删除'));
});
});
$form.on('submit', function(){
if ($form.find('[name="fileId"]').val().length == 0) {
Notify.danger(Translator.trans('请先上传文件或添加资料网络链接!'));
return false;
}
$.post($form.attr('action'), $form.serialize(), function(html){
Notify.success(Translator.trans('资料添加成功!'));
$("#material-list").append(html).show();
$form.find('.text-warning').hide();
$form.find('[name="fileId"]').val('');
$form.find('[name="link"]').val('');
$form.find('[name="description"]').val('');
materialChooser.open();
}).fail(function(){
Notify.success(Translator.trans('资料添加失败,请重试!'));
});
return false;
});
$('.modal').on('hidden.bs.modal', function(){
window.location.reload();
});
};
}); |
module.exports={A:{A:{"2":"H D G E A B FB"},B:{"1":"p z J L N I","2":"C"},C:{"1":"0 2 3 5 6 8 9 P Q R S T U V W X Y Z a c d e f g h i j k l m n o M q r s t u v w x y CB AB","2":"4 aB F K H D G E A B C p z J L N I O YB SB"},D:{"1":"0 2 3 5 6 8 9 z J L N I O P Q R S T U V W X Y Z a c d e f g h i j k l m n o M q r s t u v w x y CB AB MB cB GB b HB IB JB KB","2":"F K H D G E A B C p"},E:{"1":"1 B C RB TB","2":"F K H D G E A LB DB NB OB PB QB"},F:{"1":"2 J L N I O P Q R S T U V W X Y Z a c d e f g h i j k l m n o M q r s t u v w x y","2":"1 E B C UB VB WB XB BB ZB EB"},G:{"2":"7 G C DB bB dB eB fB gB hB iB jB kB lB mB"},H:{"2":"nB"},I:{"1":"b sB tB","2":"4 7 F oB pB qB rB"},J:{"1":"A","2":"D"},K:{"1":"M","2":"1 A B C BB EB"},L:{"1":"b"},M:{"1":"0"},N:{"2":"A B"},O:{"1":"uB"},P:{"1":"F K vB wB"},Q:{"1":"xB"},R:{"1":"yB"}},B:1,C:"Download attribute"};
|
'use strict';
const EventEmitter = require('events');
const uuid = require('node-uuid');
const ItemType = require('./ItemType');
const { Inventory, InventoryFullError } = require('./Inventory');
const Logger = require('./Logger');
const Player = require('./Player');
/**
* @property {Area} area Area the item belongs to (warning: this is not the area is currently in but the
* area it belongs to on a fresh load)
* @property {object} properties Essentially a blob of whatever attrs the item designer wanted to add
* @property {array|string} behaviors Single or list of behaviors this object uses
* @property {string} description Long description seen when looking at it
* @property {number} id vnum
* @property {boolean} isEquipped Whether or not item is currently equipped
* @property {Map} inventory Current items this item contains
* @property {string} name Name shown in inventory and when equipped
* @property {Room} room Room the item is currently in
* @property {string} roomDesc Description shown when item is seen in a room
* @property {string} script A custom script for this item
* @property {ItemType|string} type
* @property {string} uuid UUID differentiating all instances of this item
*/
class Item extends EventEmitter {
constructor (area, item) {
super();
const validate = ['keywords', 'name', 'id'];
for (const prop of validate) {
if (!(prop in item)) {
throw new ReferenceError(`Item in area [${area.name}] missing required property [${prop}]`);
}
}
this.area = area;
this.properties = item.properties || {};
this.behaviors = item.behaviors || {};
this.defaultItems = item.items || [];
this.description = item.description || 'Nothing special.';
this.entityReference = item.entityReference; // EntityFactory key
this.id = item.id;
this.maxItems = item.maxItems || Infinity;
this.inventory = item.inventory ? new Inventory(item.inventory) : null;
if (this.inventory) {
this.inventory.setMax(this.maxItems);
}
this.isEquipped = item.isEquipped || false;
this.keywords = item.keywords;
this.level = item.level || 1;
this.itemLevel = item.itemLevel || this.level;
this.name = item.name;
this.quality = item.quality || 'common';
this.room = item.room || null;
this.roomDesc = item.roomDesc || '';
this.script = item.script || null;
this.slot = item.slot || null;
this.type = typeof item.type === 'string' ? ItemType[item.type] : (item.type || ItemType.OBJECT);
this.uuid = item.uuid || uuid.v4();
}
hasKeyword(keyword) {
return this.keywords.indexOf(keyword) !== -1;
}
/**
* @param {string} name
* @return {boolean}
*/
hasBehavior(name) {
if (!(this.behaviors instanceof Map)) {
throw new Error("Item has not been hydrated. Cannot access behaviors.");
}
return this.behaviors.has(name);
}
/**
* @param {string} name
* @return {*}
*/
getBehavior(name) {
if (!(this.behaviors instanceof Map)) {
throw new Error("Item has not been hydrated. Cannot access behaviors.");
}
return this.behaviors.get(name);
}
addItem(item) {
this._setupInventory();
this.inventory.addItem(item);
item.belongsTo = this;
}
removeItem(item) {
this.inventory.removeItem(item);
// if we removed the last item unset the inventory
// This ensures that when it's reloaded it won't try to set
// its default inventory. Instead it will persist the fact
// that all the items were removed from it
if (!this.inventory.size) {
this.inventory = null;
}
item.belongsTo = null;
}
isInventoryFull() {
this._setupInventory();
return this.inventory.isFull;
}
_setupInventory() {
if (!this.inventory) {
this.inventory = new Inventory({
items: [],
max: this.maxItems
});
}
}
get qualityColors() {
return ({
poor: ['bold', 'black'],
common: ['bold', 'white'],
uncommon: ['bold', 'green'],
rare: ['bold', 'blue'],
epic: ['bold', 'magenta'],
legendary: ['bold', 'red'],
artifact: ['yellow'],
})[this.quality];
}
/**
* Friendly display colorized by quality
*/
get display() {
return this.qualityColorize(`[${this.name}]`);
}
/**
* Colorize the given string according to this item's quality
* @param {string} string
* @return string
*/
qualityColorize(string) {
const colors = this.qualityColors;
const open = '<' + colors.join('><') + '>';
const close = '</' + colors.reverse().join('></') + '>';
return open + string + close;
}
/**
* For finding the player who has the item in their possession.
* @return {Player|null} owner
*/
findOwner() {
let found = null;
let owner = this.belongsTo;
while (owner) {
if (owner instanceof Player) {
found = owner;
break;
}
owner = owner.belongsTo;
}
return found;
}
hydrate(state, serialized = {}) {
if (typeof this.area === 'string') {
this.area = state.AreaManager.getArea(this.area);
}
// if the item was saved with a custom inventory hydrate it
if (this.inventory) {
this.inventory.hydrate(state);
} else {
// otherwise load its default inv
this.defaultItems.forEach(defaultItemId => {
Logger.verbose(`\tDIST: Adding item [${defaultItemId}] to item [${this.name}]`);
const newItem = state.ItemFactory.create(this.area, defaultItemId);
newItem.hydrate(state);
state.ItemManager.add(newItem);
this.addItem(newItem);
});
}
// perform deep copy if behaviors is set to prevent sharing of the object between
// item instances
const behaviors = JSON.parse(JSON.stringify(serialized.behaviors || this.behaviors));
this.behaviors = new Map(Object.entries(behaviors));
for (let [behaviorName, config] of this.behaviors) {
let behavior = state.ItemBehaviorManager.get(behaviorName);
if (!behavior) {
return;
}
// behavior may be a boolean in which case it will be `behaviorName: true`
config = config === true ? {} : config;
behavior.attach(this, config);
}
}
serialize() {
let behaviors = {};
for (const [key, val] of this.behaviors) {
behaviors[key] = val;
}
return {
entityReference: this.entityReference,
inventory: this.inventory && this.inventory.serialize(),
// behaviors are serialized in case their config was modified during gameplay
// and that state needs to persist (charges of a scroll remaining, etc)
behaviors,
};
}
}
module.exports = Item;
|
var JobsList = React.createClass({displayName: "JobsList",
render: function() {
return (
React.createElement(JobItem, {title: "Trabalho Python", desc: "Descricao aqui"})
);
}
});
var JobItem = React.createClass({displayName: "JobItem",
render: function() {
React.createElement("div", {className: "panel panel-default"},
React.createElement("div", {className: "panel-heading"}, this.params.job.title),
React.createElement("div", {className: "panel-body"},
this.params.job.desc
)
)
}
}) |
/*
* @package jsDAV
* @subpackage CardDAV
* @copyright Copyright(c) 2013 Mike de Boer. <info AT mikedeboer DOT nl>
* @author Mike de Boer <info AT mikedeboer DOT nl>
* @license http://github.com/mikedeboer/jsDAV/blob/master/LICENSE MIT License
*/
"use strict";
var jsDAV_Plugin = require("./../DAV/plugin");
var jsDAV_Property_Href = require("./../DAV/property/href");
var jsDAV_Property_HrefList = require("./../DAV/property/hrefList");
var jsDAV_Property_iHref = require("./../DAV/interfaces/iHref");
var jsCardDAV_iAddressBook = require("./interfaces/iAddressBook");
var jsCardDAV_iCard = require("./interfaces/iCard");
var jsCardDAV_iDirectory = require("./interfaces/iDirectory");
var jsCardDAV_UserAddressBooks = require("./userAddressBooks");
var jsCardDAV_AddressBookQueryParser = require("./addressBookQueryParser");
var jsDAVACL_iPrincipal = require("./../DAVACL/interfaces/iPrincipal");
var jsVObject_Reader = require("./../VObject/reader");
var AsyncEventEmitter = require("./../shared/asyncEvents").EventEmitter;
var Exc = require("./../shared/exceptions");
var Util = require("./../shared/util");
var Xml = require("./../shared/xml");
var Async = require("asyncjs");
/**
* CardDAV plugin
*
* The CardDAV plugin adds CardDAV functionality to the WebDAV server
*/
var jsCardDAV_Plugin = module.exports = jsDAV_Plugin.extend({
/**
* Plugin name
*
* @var String
*/
name: "carddav",
/**
* Url to the addressbooks
*/
ADDRESSBOOK_ROOT: "addressbooks",
/**
* xml namespace for CardDAV elements
*/
NS_CARDDAV: "urn:ietf:params:xml:ns:carddav",
/**
* Add urls to this property to have them automatically exposed as
* 'directories' to the user.
*
* @var array
*/
directories: null,
/**
* Handler class
*
* @var jsDAV_Handler
*/
handler: null,
/**
* Initializes the plugin
*
* @param DAV\Server server
* @return void
*/
initialize: function(handler) {
this.directories = [];
// Events
handler.addEventListener("beforeGetProperties", this.beforeGetProperties.bind(this));
handler.addEventListener("afterGetProperties", this.afterGetProperties.bind(this));
handler.addEventListener("updateProperties", this.updateProperties.bind(this));
handler.addEventListener("report", this.report.bind(this));
handler.addEventListener("onHTMLActionsPanel", this.htmlActionsPanel.bind(this), AsyncEventEmitter.PRIO_HIGH);
handler.addEventListener("onBrowserPostAction", this.browserPostAction.bind(this), AsyncEventEmitter.PRIO_HIGH);
handler.addEventListener("beforeWriteContent", this.beforeWriteContent.bind(this));
handler.addEventListener("beforeCreateFile", this.beforeCreateFile.bind(this));
// Namespaces
Xml.xmlNamespaces[this.NS_CARDDAV] = "card";
// Mapping Interfaces to {DAV:}resourcetype values
handler.resourceTypeMapping["{" + this.NS_CARDDAV + "}addressbook"] = jsCardDAV_iAddressBook;
handler.resourceTypeMapping["{" + this.NS_CARDDAV + "}directory"] = jsCardDAV_iDirectory;
// Adding properties that may never be changed
handler.protectedProperties.push(
"{" + this.NS_CARDDAV + "}supported-address-data",
"{" + this.NS_CARDDAV + "}max-resource-size",
"{" + this.NS_CARDDAV + "}addressbook-home-set",
"{" + this.NS_CARDDAV + "}supported-collation-set"
);
handler.protectedProperties = Util.makeUnique(handler.protectedProperties);
handler.propertyMap["{http://calendarserver.org/ns/}me-card"] = jsDAV_Property_Href;
this.handler = handler;
},
/**
* Returns a list of supported features.
*
* This is used in the DAV: header in the OPTIONS and PROPFIND requests.
*
* @return array
*/
getFeatures: function() {
return ["addressbook"];
},
/**
* Returns a list of reports this plugin supports.
*
* This will be used in the {DAV:}supported-report-set property.
* Note that you still need to subscribe to the 'report' event to actually
* implement them
*
* @param {String} uri
* @return array
*/
getSupportedReportSet: function(uri, callback) {
var self = this;
this.handler.getNodeForPath(uri, function(err, node) {
if (err)
return callback(err);
if (node.hasFeature(jsCardDAV_iAddressBook) || node.hasFeature(jsCardDAV_iCard)) {
return callback(null, [
"{" + self.NS_CARDDAV + "}addressbook-multiget",
"{" + self.NS_CARDDAV + "}addressbook-query"
]);
}
return callback(null, []);
});
},
/**
* Adds all CardDAV-specific properties
*
* @param {String} path
* @param DAV\INode node
* @param {Array} requestedProperties
* @param {Array} returnedProperties
* @return void
*/
beforeGetProperties: function(e, path, node, requestedProperties, returnedProperties) {
var self = this;
if (node.hasFeature(jsDAVACL_iPrincipal)) {
// calendar-home-set property
var addHome = "{" + this.NS_CARDDAV + "}addressbook-home-set";
if (requestedProperties[addHome]) {
var principalId = node.getName();
var addressbookHomePath = this.ADDRESSBOOK_ROOT + "/" + principalId + "/";
delete requestedProperties[addHome];
returnedProperties["200"][addHome] = jsDAV_Property_Href.new(addressbookHomePath);
}
var directories = "{" + this.NS_CARDDAV + "}directory-gateway";
if (this.directories && requestedProperties[directories]) {
delete requestedProperties[directories];
returnedProperties["200"][directories] = jsDAV_Property_HrefList.new(this.directories);
}
}
if (node.hasFeature(jsCardDAV_iCard)) {
// The address-data property is not supposed to be a 'real'
// property, but in large chunks of the spec it does act as such.
// Therefore we simply expose it as a property.
var addressDataProp = "{" + this.NS_CARDDAV + "}address-data";
if (requestedProperties[addressDataProp]) {
delete requestedProperties[addressDataProp];
node.get(function(err, val) {
if (err)
return e.next(err);
returnedProperties["200"][addressDataProp] = val.toString("utf8");
afterICard();
});
}
else
afterICard();
}
else
afterICard();
function afterICard() {
if (node.hasFeature(jsCardDAV_UserAddressBooks)) {
var meCardProp = "{http://calendarserver.org/ns/}me-card";
if (requestedProperties[meCardProp]) {
self.handler.getProperties(node.getOwner(), ["{http://ajax.org/2005/aml}vcard-url"], function(err, props) {
if (err)
return e.next(err);
if (props["{http://ajax.org/2005/aml}vcard-url"]) {
returnedProperties["200"][meCardProp] = jsDAV_Property_Href.new(
props["{http://ajax.org/2005/aml}vcard-url"]
);
delete requestedProperties[meCardProp];
}
e.next();
});
}
else
e.next();
}
else
e.next();
}
},
/**
* This event is triggered when a PROPPATCH method is executed
*
* @param {Array} mutations
* @param {Array} result
* @param DAV\INode node
* @return bool
*/
updateProperties: function(e, mutations, result, node) {
if (!node.hasFeature(jsCardDAV_UserAddressBooks))
return e.next();
var meCard = "{http://calendarserver.org/ns/}me-card";
// The only property we care about
if (!mutations[meCard])
return e.next();
var value = mutations[meCard];
delete mutations[meCard];
if (value.hasFeature(jsDAV_Property_iHref)) {
value = this.handler.calculateUri(value.getHref());
}
else if (!value) {
result["400"][meCard] = null;
return e.stop();
}
this.server.updateProperties(node.getOwner(), {"{http://ajax.org/2005/aml}vcard-url": value}, function(err, innerResult) {
if (err)
return e.next(err);
var closureResult = false;
var props;
for (var status in innerResult) {
props = innerResult[status];
if (props["{http://ajax.org/2005/aml}vcard-url"]) {
result[status][meCard] = null;
status = parseInt(status);
closureResult = (status >= 200 && status < 300);
}
}
if (!closureResult)
return e.stop();
e.next();
});
},
/**
* This functions handles REPORT requests specific to CardDAV
*
* @param {String} reportName
* @param DOMNode dom
* @return bool
*/
report: function(e, reportName, dom) {
switch(reportName) {
case "{" + this.NS_CARDDAV + "}addressbook-multiget" :
this.addressbookMultiGetReport(e, dom);
break;
case "{" + this.NS_CARDDAV + "}addressbook-query" :
this.addressBookQueryReport(e, dom);
break;
default :
return e.next();
}
},
/**
* This function handles the addressbook-multiget REPORT.
*
* This report is used by the client to fetch the content of a series
* of urls. Effectively avoiding a lot of redundant requests.
*
* @param DOMNode dom
* @return void
*/
addressbookMultiGetReport: function(e, dom) {
var properties = Object.keys(Xml.parseProperties(dom));
var hrefElems = dom.getElementsByTagNameNS("urn:DAV", "href");
var propertyList = {};
var self = this;
Async.list(hrefElems)
.each(function(elem, next) {
var uri = self.handler.calculateUri(elem.firstChild.nodeValue);
//propertyList[uri]
self.handler.getPropertiesForPath(uri, properties, 0, function(err, props) {
if (err)
return next(err);
Util.extend(propertyList, props);
next();
});
})
.end(function(err) {
if (err)
return e.next(err);
var prefer = self.handler.getHTTPPrefer();
e.stop();
self.handler.httpResponse.writeHead(207, {
"content-type": "application/xml; charset=utf-8",
"vary": "Brief,Prefer"
});
self.handler.httpResponse.end(self.handler.generateMultiStatus(propertyList, prefer["return-minimal"]));
});
},
/**
* This method is triggered before a file gets updated with new content.
*
* This plugin uses this method to ensure that Card nodes receive valid
* vcard data.
*
* @param {String} path
* @param jsDAV_iFile node
* @param resource data
* @return void
*/
beforeWriteContent: function(e, path, node) {
if (!node.hasFeature(jsCardDAV_iCard))
return e.next();
var self = this;
this.handler.getRequestBody("utf8", null, false, function(err, data) {
if (err)
return e.next(err);
try {
self.validateVCard(data);
}
catch (ex) {
return e.next(ex);
}
e.next();
});
},
/**
* This method is triggered before a new file is created.
*
* This plugin uses this method to ensure that Card nodes receive valid
* vcard data.
*
* @param {String} path
* @param resource data
* @param jsDAV_iCollection parentNode
* @return void
*/
beforeCreateFile: function(e, path, data, enc, parentNode) {
if (!parentNode.hasFeature(jsCardDAV_iAddressBook))
return e.next();
try {
this.validateVCard(data);
}
catch (ex) {
return e.next(ex);
}
e.next();
},
/**
* Checks if the submitted iCalendar data is in fact, valid.
*
* An exception is thrown if it's not.
*
* @param resource|string data
* @return void
*/
validateVCard: function(data) {
// If it's a stream, we convert it to a string first.
if (Buffer.isBuffer(data))
data = data.toString("utf8");
var vobj;
try {
vobj = jsVObject_Reader.read(data);
}
catch (ex) {
throw new Exc.UnsupportedMediaType("This resource only supports valid vcard data. Parse error: " + ex.message);
}
if (vobj.name != "VCARD")
throw new Exc.UnsupportedMediaType("This collection can only support vcard objects.");
if (!vobj.UID)
throw new Exc.BadRequest("Every vcard must have a UID.");
},
/**
* This function handles the addressbook-query REPORT
*
* This report is used by the client to filter an addressbook based on a
* complex query.
*
* @param DOMNode dom
* @return void
*/
addressbookQueryReport: function(e, dom) {
var query = jsCardDAV_AddressBookQueryParser.new(dom);
try {
query.parse();
}
catch(ex) {
return e.next(ex);
}
var depth = this.handler.getHTTPDepth(0);
if (depth === 0) {
this.handler.getNodeForPath(this.handler.getRequestUri(), function(err, node) {
if (err)
return e.next(err);
afterCandidates([node]);
})
}
else {
this.handler.server.tree.getChildren(this.handler.getRequestUri(), function(err, children) {
if (err)
return e.next(err);
afterCandidates(children);
});
}
var self = this;
function afterCandidates(candidateNodes) {
var validNodes = [];
Async.list(candidateNodes)
.each(function(node, next) {
if (!node.hasFeature(jsCardDAV_iCard))
return next();
node.get(function(err, blob) {
if (err)
return next(err);
if (!self.validateFilters(blob.toString("utf8"), query.filters, query.test))
return next();
validNodes.push(node);
if (query.limit && query.limit <= validNodes.length) {
// We hit the maximum number of items, we can stop now.
return next(Async.STOP);
}
next();
});
})
.end(function(err) {
if (err)
return e.next(err);
var result = {};
Async.list(validNodes)
.each(function(validNode, next) {
var href = self.handler.getRequestUri();
if (depth !== 0)
href = href + "/" + validNode.getName();
self.handler.getPropertiesForPath(href, query.requestedProperties, 0, function(err, props) {
if (err)
return next(err);
Util.extend(result, props);
next();
});
})
.end(function(err) {
if (err)
return e.next(err);
e.stop();
var prefer = self.handler.getHTTPPRefer();
self.handler.httpResponse.writeHead(207, {
"content-type": "application/xml; charset=utf-8",
"vary": "Brief,Prefer"
});
self.handler.httpResponse.end(self.handler.generateMultiStatus(result, prefer["return-minimal"]));
});
});
}
},
/**
* Validates if a vcard makes it throught a list of filters.
*
* @param {String} vcardData
* @param {Array} filters
* @param {String} test anyof or allof (which means OR or AND)
* @return bool
*/
validateFilters: function(vcardData, filters, test) {
var vcard;
try {
vcard = jsVObject_Reader.read(vcardData);
}
catch (ex) {
return false;
}
if (!filters)
return true;
var filter, isDefined, success, vProperties, results, texts;
for (var i = 0, l = filters.length; i < l; ++i) {
filter = filters[i];
isDefined = vcard.get(filter.name);
if (filter["is-not-defined"]) {
if (isDefined)
success = false;
else
success = true;
}
else if ((!filter["param-filters"] && !filter["text-matches"]) || !isDefined) {
// We only need to check for existence
success = isDefined;
}
else {
vProperties = vcard.select(filter.name);
results = [];
if (filter["param-filters"])
results.push(this.validateParamFilters(vProperties, filter["param-filters"], filter.test));
if (filter["text-matches"]) {
texts = vProperties.map(function(vProperty) {
return vProperty.value;
});
results.push(this.validateTextMatches(texts, filter["text-matches"], filter.test));
}
if (results.length === 1) {
success = results[0];
}
else {
if (filter.test == "anyof")
success = results[0] || results[1];
else
success = results[0] && results[1];
}
} // else
// There are two conditions where we can already determine whether
// or not this filter succeeds.
if (test == "anyof" && success)
return true;
if (test == "allof" && !success)
return false;
} // foreach
// If we got all the way here, it means we haven't been able to
// determine early if the test failed or not.
//
// This implies for 'anyof' that the test failed, and for 'allof' that
// we succeeded. Sounds weird, but makes sense.
return test === "allof";
},
/**
* Validates if a param-filter can be applied to a specific property.
*
* @todo currently we're only validating the first parameter of the passed
* property. Any subsequence parameters with the same name are
* ignored.
* @param {Array} vProperties
* @param {Array} filters
* @param {String} test
* @return bool
*/
validateParamFilters: function(vProperties, filters, test) {
var filter, isDefined, success, j, l2, vProperty;
for (var i = 0, l = filters.length; i < l; ++i) {
filter = filters[i];
isDefined = false;
for (j = 0, l2 = vProperties.length; j < l2; ++j) {
vProperty = vProperties[j];
isDefined = !!vProperty.get(filter.name);
if (isDefined)
break;
}
if (filter["is-not-defined"]) {
success = !isDefined;
// If there's no text-match, we can just check for existence
}
else if (!filter["text-match"] || !isDefined) {
success = isDefined;
}
else {
success = false;
for (j = 0, l2 = vProperties.length; j < l2; ++j) {
vProperty = vProperties[j];
// If we got all the way here, we'll need to validate the
// text-match filter.
success = Util.textMatch(vProperty.get(filter.name).value, filter["text-match"].value, filter["text-match"]["match-type"]);
if (success)
break;
}
if (filter["text-match"]["negate-condition"])
success = !success;
} // else
// There are two conditions where we can already determine whether
// or not this filter succeeds.
if (test == "anyof" && success)
return true;
if (test == "allof" && !success)
return false;
}
// If we got all the way here, it means we haven't been able to
// determine early if the test failed or not.
//
// This implies for 'anyof' that the test failed, and for 'allof' that
// we succeeded. Sounds weird, but makes sense.
return test == "allof";
},
/**
* Validates if a text-filter can be applied to a specific property.
*
* @param {Array} texts
* @param {Array} filters
* @param {String} test
* @return bool
*/
validateTextMatches: function(texts, filters, test) {
var success, filter, j, l2, haystack;
for (var i = 0, l = filters.length; i < l; ++i) {
filter = filters[i];
success = false;
for (j = 0, l2 = texts.length; j < l2; ++j) {
haystack = texts[j];
success = Util.textMatch(haystack, filter.value, filter["match-type"]);
// Breaking on the first match
if (success)
break;
}
if (filter["negate-condition"])
success = !success;
if (success && test == "anyof")
return true;
if (!success && test == "allof")
return false;
}
// If we got all the way here, it means we haven't been able to
// determine early if the test failed or not.
//
// This implies for 'anyof' that the test failed, and for 'allof' that
// we succeeded. Sounds weird, but makes sense.
return test == "allof";
},
/**
* This event is triggered after webdav-properties have been retrieved.
*
* @return bool
*/
afterGetProperties: function(e, uri, properties) {
// If the request was made using the SOGO connector, we must rewrite
// the content-type property. By default jsDAV will send back
// text/x-vcard; charset=utf-8, but for SOGO we must strip that last
// part.
if (!properties["200"]["{DAV:}getcontenttype"])
return e.next();
if (this.handler.httpRequest.headers["user-agent"].indexOf("Thunderbird") === -1)
return e.next();
if (properties["200"]["{DAV:}getcontenttype"].indexOf("text/x-vcard") === 0)
properties["200"]["{DAV:}getcontenttype"] = "text/x-vcard";
e.next();
},
/**
* This method is used to generate HTML output for the
* Sabre\DAV\Browser\Plugin. This allows us to generate an interface users
* can use to create new calendars.
*
* @param DAV\INode node
* @param {String} output
* @return bool
*/
htmlActionsPanel: function(e, node, output) {
if (!node.hasFeature(jsCardDAV_UserAddressBooks))
return e.next();
output.html = '<tr><td colspan="2"><form method="post" action="">' +
'<h3>Create new address book</h3>' +
'<input type="hidden" name="jsdavAction" value="mkaddressbook" />' +
'<label>Name (uri):</label> <input type="text" name="name" /><br />' +
'<label>Display name:</label> <input type="text" name="{DAV:}displayname" /><br />' +
'<input type="submit" value="create" />' +
'</form>' +
'</td></tr>';
e.stop();
},
/**
* This method allows us to intercept the 'mkcalendar' sabreAction. This
* action enables the user to create new calendars from the browser plugin.
*
* @param {String} uri
* @param {String} action
* @param {Array} postVars
* @return bool
*/
browserPostAction: function(e, uri, action, postVars) {
if (action != "mkaddressbook")
return e.next();
var resourceType = ["{DAV:}collection", "{urn:ietf:params:xml:ns:carddav}addressbook"];
var properties = {};
if (postVars["{DAV:}displayname"])
properties["{DAV:}displayname"] = postVars["{DAV:}displayname"];
this.handler.createCollection(uri + "/" + postVars.name, resourceType, properties, function(err) {
if (err)
return e.next(err);
e.stop();
});
}
});
|
'@fixture click';
'@page http://example.com';
'@test'['Take a screenshot'] = {
'1.Click on non-existing element': function () {
act.screenshot();
},
};
'@test'['Screenshot on test code error'] = {
'1.Click on non-existing element': function () {
throw new Error('STOP');
},
};
|
game.LoadProfile = me.ScreenObject.extend({
/**
* action to perform on state change
*/
onResetEvent: function() {
me.game.world.addChild(new me.Sprite(0, 0, me.loader.getImage('load-screen')), -10);
//puts load screen in when game starts
document.getElementById("input").style.visibility = "visible";
document.getElementById("load").style.visibility = "visible";
me.input.unbindKey(me.input.KEY.B);
me.input.unbindKey(me.input.KEY.I);
me.input.unbindKey(me.input.KEY.O);
me.input.unbindKey(me.input.KEY.P);
me.input.unbindKey(me.input.KEY.SPACE);
//unbinds keys
var exp1cost = ((game.data.exp1 + 1) * 10);
var exp2cost = ((game.data.exp2 + 1) * 10);
var exp3cost = ((game.data.exp3 + 1) * 10);
var exp4cost = ((game.data.exp4 + 1) * 10);
me.game.world.addChild(new (me.Renderable.extend({
init: function() {
this._super(me.Renderable, 'init', [10, 10, 300, 50]);
this.font = new me.Font("Arial", 26, "white");
},
draw: function(renderer) {
this.font.draw(renderer.getContext(), "Enter Username & Password", this.pos.x, this.pos.y);
}
})));
},
/**
* action to perform when leaving this screen (state change)
*/
onDestroyEvent: function() {
document.getElementById("input").style.visibility = "hidden";
document.getElementById("load").style.visibility = "hidden";
}
}); |
/*
---
MooTools: the javascript framework
web build:
- http://mootools.net/core/8423c12ffd6a6bfcde9ea22554aec795
packager build:
- packager build Core/Core Core/Array Core/String Core/Number Core/Function Core/Object Core/Event Core/Browser Core/Class Core/Class.Extras Core/Slick.Parser Core/Slick.Finder Core/Element Core/Element.Style Core/Element.Event Core/Element.Delegation Core/Element.Dimensions Core/Fx Core/Fx.CSS Core/Fx.Tween Core/Fx.Morph Core/Fx.Transitions Core/Request Core/Request.HTML Core/Request.JSON Core/Cookie Core/JSON Core/DOMReady
...
*/
/*
---
name: Core
description: The heart of MooTools.
license: MIT-style license.
copyright: Copyright (c) 2006-2012 [Valerio Proietti](http://mad4milk.net/).
authors: The MooTools production team (http://mootools.net/developers/)
inspiration:
- Class implementation inspired by [Base.js](http://dean.edwards.name/weblog/2006/03/base/) Copyright (c) 2006 Dean Edwards, [GNU Lesser General Public License](http://opensource.org/licenses/lgpl-license.php)
- Some functionality inspired by [Prototype.js](http://prototypejs.org) Copyright (c) 2005-2007 Sam Stephenson, [MIT License](http://opensource.org/licenses/mit-license.php)
provides: [Core, MooTools, Type, typeOf, instanceOf, Native]
...
*/
(function(){
this.MooTools = {
version: '1.4.5',
build: 'ab8ea8824dc3b24b6666867a2c4ed58ebb762cf0'
};
// typeOf, instanceOf
var typeOf = this.typeOf = function(item){
if (item == null) return 'null';
if (item.$family != null) return item.$family();
if (item.nodeName){
if (item.nodeType == 1) return 'element';
if (item.nodeType == 3) return (/\S/).test(item.nodeValue) ? 'textnode' : 'whitespace';
} else if (typeof item.length == 'number'){
if (item.callee) return 'arguments';
if ('item' in item) return 'collection';
}
return typeof item;
};
var instanceOf = this.instanceOf = function(item, object){
if (item == null) return false;
var constructor = item.$constructor || item.constructor;
while (constructor){
if (constructor === object) return true;
constructor = constructor.parent;
}
/*<ltIE8>*/
if (!item.hasOwnProperty) return false;
/*</ltIE8>*/
return item instanceof object;
};
// Function overloading
var Function = this.Function;
var enumerables = true;
for (var i in {toString: 1}) enumerables = null;
if (enumerables) enumerables = ['hasOwnProperty', 'valueOf', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'constructor'];
Function.prototype.overloadSetter = function(usePlural){
var self = this;
return function(a, b){
if (a == null) return this;
if (usePlural || typeof a != 'string'){
for (var k in a) self.call(this, k, a[k]);
if (enumerables) for (var i = enumerables.length; i--;){
k = enumerables[i];
if (a.hasOwnProperty(k)) self.call(this, k, a[k]);
}
} else {
self.call(this, a, b);
}
return this;
};
};
Function.prototype.overloadGetter = function(usePlural){
var self = this;
return function(a){
var args, result;
if (typeof a != 'string') args = a;
else if (arguments.length > 1) args = arguments;
else if (usePlural) args = [a];
if (args){
result = {};
for (var i = 0; i < args.length; i++) result[args[i]] = self.call(this, args[i]);
} else {
result = self.call(this, a);
}
return result;
};
};
Function.prototype.extend = function(key, value){
this[key] = value;
}.overloadSetter();
Function.prototype.implement = function(key, value){
this.prototype[key] = value;
}.overloadSetter();
// From
var slice = Array.prototype.slice;
Function.from = function(item){
return (typeOf(item) == 'function') ? item : function(){
return item;
};
};
Array.from = function(item){
if (item == null) return [];
return (Type.isEnumerable(item) && typeof item != 'string') ? (typeOf(item) == 'array') ? item : slice.call(item) : [item];
};
Number.from = function(item){
var number = parseFloat(item);
return isFinite(number) ? number : null;
};
String.from = function(item){
return item + '';
};
// hide, protect
Function.implement({
hide: function(){
this.$hidden = true;
return this;
},
protect: function(){
this.$protected = true;
return this;
}
});
// Type
var Type = this.Type = function(name, object){
if (name){
var lower = name.toLowerCase();
var typeCheck = function(item){
return (typeOf(item) == lower);
};
Type['is' + name] = typeCheck;
if (object != null){
object.prototype.$family = (function(){
return lower;
}).hide();
}
}
if (object == null) return null;
object.extend(this);
object.$constructor = Type;
object.prototype.$constructor = object;
return object;
};
var toString = Object.prototype.toString;
Type.isEnumerable = function(item){
return (item != null && typeof item.length == 'number' && toString.call(item) != '[object Function]' );
};
var hooks = {};
var hooksOf = function(object){
var type = typeOf(object.prototype);
return hooks[type] || (hooks[type] = []);
};
var implement = function(name, method){
if (method && method.$hidden) return;
var hooks = hooksOf(this);
for (var i = 0; i < hooks.length; i++){
var hook = hooks[i];
if (typeOf(hook) == 'type') implement.call(hook, name, method);
else hook.call(this, name, method);
}
var previous = this.prototype[name];
if (previous == null || !previous.$protected) this.prototype[name] = method;
if (this[name] == null && typeOf(method) == 'function') extend.call(this, name, function(item){
return method.apply(item, slice.call(arguments, 1));
});
};
var extend = function(name, method){
if (method && method.$hidden) return;
var previous = this[name];
if (previous == null || !previous.$protected) this[name] = method;
};
Type.implement({
implement: implement.overloadSetter(),
extend: extend.overloadSetter(),
alias: function(name, existing){
implement.call(this, name, this.prototype[existing]);
}.overloadSetter(),
mirror: function(hook){
hooksOf(this).push(hook);
return this;
}
});
new Type('Type', Type);
// Default Types
var force = function(name, object, methods){
var isType = (object != Object),
prototype = object.prototype;
if (isType) object = new Type(name, object);
for (var i = 0, l = methods.length; i < l; i++){
var key = methods[i],
generic = object[key],
proto = prototype[key];
if (generic) generic.protect();
if (isType && proto) object.implement(key, proto.protect());
}
if (isType){
var methodsEnumerable = prototype.propertyIsEnumerable(methods[0]);
object.forEachMethod = function(fn){
if (!methodsEnumerable) for (var i = 0, l = methods.length; i < l; i++){
fn.call(prototype, prototype[methods[i]], methods[i]);
}
for (var key in prototype) fn.call(prototype, prototype[key], key)
};
}
return force;
};
force('String', String, [
'charAt', 'charCodeAt', 'concat', 'indexOf', 'lastIndexOf', 'match', 'quote', 'replace', 'search',
'slice', 'split', 'substr', 'substring', 'trim', 'toLowerCase', 'toUpperCase'
])('Array', Array, [
'pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift', 'concat', 'join', 'slice',
'indexOf', 'lastIndexOf', 'filter', 'forEach', 'every', 'map', 'some', 'reduce', 'reduceRight'
])('Number', Number, [
'toExponential', 'toFixed', 'toLocaleString', 'toPrecision'
])('Function', Function, [
'apply', 'call', 'bind'
])('RegExp', RegExp, [
'exec', 'test'
])('Object', Object, [
'create', 'defineProperty', 'defineProperties', 'keys',
'getPrototypeOf', 'getOwnPropertyDescriptor', 'getOwnPropertyNames',
'preventExtensions', 'isExtensible', 'seal', 'isSealed', 'freeze', 'isFrozen'
])('Date', Date, ['now']);
Object.extend = extend.overloadSetter();
Date.extend('now', function(){
return +(new Date);
});
new Type('Boolean', Boolean);
// fixes NaN returning as Number
Number.prototype.$family = function(){
return isFinite(this) ? 'number' : 'null';
}.hide();
// Number.random
Number.extend('random', function(min, max){
return Math.floor(Math.random() * (max - min + 1) + min);
});
// forEach, each
var hasOwnProperty = Object.prototype.hasOwnProperty;
Object.extend('forEach', function(object, fn, bind){
for (var key in object){
if (hasOwnProperty.call(object, key)) fn.call(bind, object[key], key, object);
}
});
Object.each = Object.forEach;
Array.implement({
forEach: function(fn, bind){
for (var i = 0, l = this.length; i < l; i++){
if (i in this) fn.call(bind, this[i], i, this);
}
},
each: function(fn, bind){
Array.forEach(this, fn, bind);
return this;
}
});
// Array & Object cloning, Object merging and appending
var cloneOf = function(item){
switch (typeOf(item)){
case 'array': return item.clone();
case 'object': return Object.clone(item);
default: return item;
}
};
Array.implement('clone', function(){
var i = this.length, clone = new Array(i);
while (i--) clone[i] = cloneOf(this[i]);
return clone;
});
var mergeOne = function(source, key, current){
switch (typeOf(current)){
case 'object':
if (typeOf(source[key]) == 'object') Object.merge(source[key], current);
else source[key] = Object.clone(current);
break;
case 'array': source[key] = current.clone(); break;
default: source[key] = current;
}
return source;
};
Object.extend({
merge: function(source, k, v){
if (typeOf(k) == 'string') return mergeOne(source, k, v);
for (var i = 1, l = arguments.length; i < l; i++){
var object = arguments[i];
for (var key in object) mergeOne(source, key, object[key]);
}
return source;
},
clone: function(object){
var clone = {};
for (var key in object) clone[key] = cloneOf(object[key]);
return clone;
},
append: function(original){
for (var i = 1, l = arguments.length; i < l; i++){
var extended = arguments[i] || {};
for (var key in extended) original[key] = extended[key];
}
return original;
}
});
// Object-less types
['Object', 'WhiteSpace', 'TextNode', 'Collection', 'Arguments'].each(function(name){
new Type(name);
});
// Unique ID
var UID = Date.now();
String.extend('uniqueID', function(){
return (UID++).toString(36);
});
})();
/*
---
name: Array
description: Contains Array Prototypes like each, contains, and erase.
license: MIT-style license.
requires: Type
provides: Array
...
*/
Array.implement({
/*<!ES5>*/
every: function(fn, bind){
for (var i = 0, l = this.length >>> 0; i < l; i++){
if ((i in this) && !fn.call(bind, this[i], i, this)) return false;
}
return true;
},
filter: function(fn, bind){
var results = [];
for (var value, i = 0, l = this.length >>> 0; i < l; i++) if (i in this){
value = this[i];
if (fn.call(bind, value, i, this)) results.push(value);
}
return results;
},
indexOf: function(item, from){
var length = this.length >>> 0;
for (var i = (from < 0) ? Math.max(0, length + from) : from || 0; i < length; i++){
if (this[i] === item) return i;
}
return -1;
},
map: function(fn, bind){
var length = this.length >>> 0, results = Array(length);
for (var i = 0; i < length; i++){
if (i in this) results[i] = fn.call(bind, this[i], i, this);
}
return results;
},
some: function(fn, bind){
for (var i = 0, l = this.length >>> 0; i < l; i++){
if ((i in this) && fn.call(bind, this[i], i, this)) return true;
}
return false;
},
/*</!ES5>*/
clean: function(){
return this.filter(function(item){
return item != null;
});
},
invoke: function(methodName){
var args = Array.slice(arguments, 1);
return this.map(function(item){
return item[methodName].apply(item, args);
});
},
associate: function(keys){
var obj = {}, length = Math.min(this.length, keys.length);
for (var i = 0; i < length; i++) obj[keys[i]] = this[i];
return obj;
},
link: function(object){
var result = {};
for (var i = 0, l = this.length; i < l; i++){
for (var key in object){
if (object[key](this[i])){
result[key] = this[i];
delete object[key];
break;
}
}
}
return result;
},
contains: function(item, from){
return this.indexOf(item, from) != -1;
},
append: function(array){
this.push.apply(this, array);
return this;
},
getLast: function(){
return (this.length) ? this[this.length - 1] : null;
},
getRandom: function(){
return (this.length) ? this[Number.random(0, this.length - 1)] : null;
},
include: function(item){
if (!this.contains(item)) this.push(item);
return this;
},
combine: function(array){
for (var i = 0, l = array.length; i < l; i++) this.include(array[i]);
return this;
},
erase: function(item){
for (var i = this.length; i--;){
if (this[i] === item) this.splice(i, 1);
}
return this;
},
empty: function(){
this.length = 0;
return this;
},
flatten: function(){
var array = [];
for (var i = 0, l = this.length; i < l; i++){
var type = typeOf(this[i]);
if (type == 'null') continue;
array = array.concat((type == 'array' || type == 'collection' || type == 'arguments' || instanceOf(this[i], Array)) ? Array.flatten(this[i]) : this[i]);
}
return array;
},
pick: function(){
for (var i = 0, l = this.length; i < l; i++){
if (this[i] != null) return this[i];
}
return null;
},
hexToRgb: function(array){
if (this.length != 3) return null;
var rgb = this.map(function(value){
if (value.length == 1) value += value;
return value.toInt(16);
});
return (array) ? rgb : 'rgb(' + rgb + ')';
},
rgbToHex: function(array){
if (this.length < 3) return null;
if (this.length == 4 && this[3] == 0 && !array) return 'transparent';
var hex = [];
for (var i = 0; i < 3; i++){
var bit = (this[i] - 0).toString(16);
hex.push((bit.length == 1) ? '0' + bit : bit);
}
return (array) ? hex : '#' + hex.join('');
}
});
/*
---
name: String
description: Contains String Prototypes like camelCase, capitalize, test, and toInt.
license: MIT-style license.
requires: Type
provides: String
...
*/
String.implement({
test: function(regex, params){
return ((typeOf(regex) == 'regexp') ? regex : new RegExp('' + regex, params)).test(this);
},
contains: function(string, separator){
return (separator) ? (separator + this + separator).indexOf(separator + string + separator) > -1 : String(this).indexOf(string) > -1;
},
trim: function(){
return String(this).replace(/^\s+|\s+$/g, '');
},
clean: function(){
return String(this).replace(/\s+/g, ' ').trim();
},
camelCase: function(){
return String(this).replace(/-\D/g, function(match){
return match.charAt(1).toUpperCase();
});
},
hyphenate: function(){
return String(this).replace(/[A-Z]/g, function(match){
return ('-' + match.charAt(0).toLowerCase());
});
},
capitalize: function(){
return String(this).replace(/\b[a-z]/g, function(match){
return match.toUpperCase();
});
},
escapeRegExp: function(){
return String(this).replace(/([-.*+?^${}()|[\]\/\\])/g, '\\$1');
},
toInt: function(base){
return parseInt(this, base || 10);
},
toFloat: function(){
return parseFloat(this);
},
hexToRgb: function(array){
var hex = String(this).match(/^#?(\w{1,2})(\w{1,2})(\w{1,2})$/);
return (hex) ? hex.slice(1).hexToRgb(array) : null;
},
rgbToHex: function(array){
var rgb = String(this).match(/\d{1,3}/g);
return (rgb) ? rgb.rgbToHex(array) : null;
},
substitute: function(object, regexp){
return String(this).replace(regexp || (/\\?\{([^{}]+)\}/g), function(match, name){
if (match.charAt(0) == '\\') return match.slice(1);
return (object[name] != null) ? object[name] : '';
});
}
});
/*
---
name: Number
description: Contains Number Prototypes like limit, round, times, and ceil.
license: MIT-style license.
requires: Type
provides: Number
...
*/
Number.implement({
limit: function(min, max){
return Math.min(max, Math.max(min, this));
},
round: function(precision){
precision = Math.pow(10, precision || 0).toFixed(precision < 0 ? -precision : 0);
return Math.round(this * precision) / precision;
},
times: function(fn, bind){
for (var i = 0; i < this; i++) fn.call(bind, i, this);
},
toFloat: function(){
return parseFloat(this);
},
toInt: function(base){
return parseInt(this, base || 10);
}
});
Number.alias('each', 'times');
(function(math){
var methods = {};
math.each(function(name){
if (!Number[name]) methods[name] = function(){
return Math[name].apply(null, [this].concat(Array.from(arguments)));
};
});
Number.implement(methods);
})(['abs', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'exp', 'floor', 'log', 'max', 'min', 'pow', 'sin', 'sqrt', 'tan']);
/*
---
name: Function
description: Contains Function Prototypes like create, bind, pass, and delay.
license: MIT-style license.
requires: Type
provides: Function
...
*/
Function.extend({
attempt: function(){
for (var i = 0, l = arguments.length; i < l; i++){
try {
return arguments[i]();
} catch (e){}
}
return null;
}
});
Function.implement({
attempt: function(args, bind){
try {
return this.apply(bind, Array.from(args));
} catch (e){}
return null;
},
/*<!ES5-bind>*/
bind: function(that){
var self = this,
args = arguments.length > 1 ? Array.slice(arguments, 1) : null,
F = function(){};
var bound = function(){
var context = that, length = arguments.length;
if (this instanceof bound){
F.prototype = self.prototype;
context = new F;
}
var result = (!args && !length)
? self.call(context)
: self.apply(context, args && length ? args.concat(Array.slice(arguments)) : args || arguments);
return context == that ? result : context;
};
return bound;
},
/*</!ES5-bind>*/
pass: function(args, bind){
var self = this;
if (args != null) args = Array.from(args);
return function(){
return self.apply(bind, args || arguments);
};
},
delay: function(delay, bind, args){
return setTimeout(this.pass((args == null ? [] : args), bind), delay);
},
periodical: function(periodical, bind, args){
return setInterval(this.pass((args == null ? [] : args), bind), periodical);
}
});
/*
---
name: Object
description: Object generic methods
license: MIT-style license.
requires: Type
provides: [Object, Hash]
...
*/
(function(){
var hasOwnProperty = Object.prototype.hasOwnProperty;
Object.extend({
subset: function(object, keys){
var results = {};
for (var i = 0, l = keys.length; i < l; i++){
var k = keys[i];
if (k in object) results[k] = object[k];
}
return results;
},
map: function(object, fn, bind){
var results = {};
for (var key in object){
if (hasOwnProperty.call(object, key)) results[key] = fn.call(bind, object[key], key, object);
}
return results;
},
filter: function(object, fn, bind){
var results = {};
for (var key in object){
var value = object[key];
if (hasOwnProperty.call(object, key) && fn.call(bind, value, key, object)) results[key] = value;
}
return results;
},
every: function(object, fn, bind){
for (var key in object){
if (hasOwnProperty.call(object, key) && !fn.call(bind, object[key], key)) return false;
}
return true;
},
some: function(object, fn, bind){
for (var key in object){
if (hasOwnProperty.call(object, key) && fn.call(bind, object[key], key)) return true;
}
return false;
},
keys: function(object){
var keys = [];
for (var key in object){
if (hasOwnProperty.call(object, key)) keys.push(key);
}
return keys;
},
values: function(object){
var values = [];
for (var key in object){
if (hasOwnProperty.call(object, key)) values.push(object[key]);
}
return values;
},
getLength: function(object){
return Object.keys(object).length;
},
keyOf: function(object, value){
for (var key in object){
if (hasOwnProperty.call(object, key) && object[key] === value) return key;
}
return null;
},
contains: function(object, value){
return Object.keyOf(object, value) != null;
},
toQueryString: function(object, base){
var queryString = [];
Object.each(object, function(value, key){
if (base) key = base + '[' + key + ']';
var result;
switch (typeOf(value)){
case 'object': result = Object.toQueryString(value, key); break;
case 'array':
var qs = {};
value.each(function(val, i){
qs[i] = val;
});
result = Object.toQueryString(qs, key);
break;
default: result = key + '=' + encodeURIComponent(value);
}
if (value != null) queryString.push(result);
});
return queryString.join('&');
}
});
})();
/*
---
name: Browser
description: The Browser Object. Contains Browser initialization, Window and Document, and the Browser Hash.
license: MIT-style license.
requires: [Array, Function, Number, String]
provides: [Browser, Window, Document]
...
*/
(function(){
var document = this.document;
var window = document.window = this;
var ua = navigator.userAgent.toLowerCase(),
platform = navigator.platform.toLowerCase(),
UA = ua.match(/(opera|ie|firefox|chrome|version)[\s\/:]([\w\d\.]+)?.*?(safari|version[\s\/:]([\w\d\.]+)|$)/) || [null, 'unknown', 0],
mode = UA[1] == 'ie' && document.documentMode;
var Browser = this.Browser = {
extend: Function.prototype.extend,
name: (UA[1] == 'version') ? UA[3] : UA[1],
version: mode || parseFloat((UA[1] == 'opera' && UA[4]) ? UA[4] : UA[2]),
Platform: {
name: ua.match(/ip(?:ad|od|hone)/) ? 'ios' : (ua.match(/(?:webos|android)/) || platform.match(/mac|win|linux/) || ['other'])[0]
},
Features: {
xpath: !!(document.evaluate),
air: !!(window.runtime),
query: !!(document.querySelector),
json: !!(window.JSON)
},
Plugins: {}
};
Browser[Browser.name] = true;
Browser[Browser.name + parseInt(Browser.version, 10)] = true;
Browser.Platform[Browser.Platform.name] = true;
// Request
Browser.Request = (function(){
var XMLHTTP = function(){
return new XMLHttpRequest();
};
var MSXML2 = function(){
return new ActiveXObject('MSXML2.XMLHTTP');
};
var MSXML = function(){
return new ActiveXObject('Microsoft.XMLHTTP');
};
return Function.attempt(function(){
XMLHTTP();
return XMLHTTP;
}, function(){
MSXML2();
return MSXML2;
}, function(){
MSXML();
return MSXML;
});
})();
Browser.Features.xhr = !!(Browser.Request);
// Flash detection
var version = (Function.attempt(function(){
return navigator.plugins['Shockwave Flash'].description;
}, function(){
return new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version');
}) || '0 r0').match(/\d+/g);
Browser.Plugins.Flash = {
version: Number(version[0] || '0.' + version[1]) || 0,
build: Number(version[2]) || 0
};
// String scripts
Browser.exec = function(text){
if (!text) return text;
if (window.execScript){
window.execScript(text);
} else {
var script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.text = text;
document.head.appendChild(script);
document.head.removeChild(script);
}
return text;
};
String.implement('stripScripts', function(exec){
var scripts = '';
var text = this.replace(/<script[^>]*>([\s\S]*?)<\/script>/gi, function(all, code){
scripts += code + '\n';
return '';
});
if (exec === true) Browser.exec(scripts);
else if (typeOf(exec) == 'function') exec(scripts, text);
return text;
});
// Window, Document
Browser.extend({
Document: this.Document,
Window: this.Window,
Element: this.Element,
Event: this.Event
});
this.Window = this.$constructor = new Type('Window', function(){});
this.$family = Function.from('window').hide();
Window.mirror(function(name, method){
window[name] = method;
});
this.Document = document.$constructor = new Type('Document', function(){});
document.$family = Function.from('document').hide();
Document.mirror(function(name, method){
document[name] = method;
});
document.html = document.documentElement;
if (!document.head) document.head = document.getElementsByTagName('head')[0];
if (document.execCommand) try {
document.execCommand("BackgroundImageCache", false, true);
} catch (e){}
/*<ltIE9>*/
if (this.attachEvent && !this.addEventListener){
var unloadEvent = function(){
this.detachEvent('onunload', unloadEvent);
document.head = document.html = document.window = null;
};
this.attachEvent('onunload', unloadEvent);
}
// IE fails on collections and <select>.options (refers to <select>)
var arrayFrom = Array.from;
try {
arrayFrom(document.html.childNodes);
} catch(e){
Array.from = function(item){
if (typeof item != 'string' && Type.isEnumerable(item) && typeOf(item) != 'array'){
var i = item.length, array = new Array(i);
while (i--) array[i] = item[i];
return array;
}
return arrayFrom(item);
};
var prototype = Array.prototype,
slice = prototype.slice;
['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift', 'concat', 'join', 'slice'].each(function(name){
var method = prototype[name];
Array[name] = function(item){
return method.apply(Array.from(item), slice.call(arguments, 1));
};
});
}
/*</ltIE9>*/
})();
/*
---
name: Event
description: Contains the Event Type, to make the event object cross-browser.
license: MIT-style license.
requires: [Window, Document, Array, Function, String, Object]
provides: Event
...
*/
(function() {
var _keys = {};
var DOMEvent = this.DOMEvent = new Type('DOMEvent', function(event, win){
if (!win) win = window;
event = event || win.event;
if (event.$extended) return event;
this.event = event;
this.$extended = true;
this.shift = event.shiftKey;
this.control = event.ctrlKey;
this.alt = event.altKey;
this.meta = event.metaKey;
var type = this.type = event.type;
var target = event.target || event.srcElement;
while (target && target.nodeType == 3) target = target.parentNode;
this.target = document.id(target);
if (type.indexOf('key') == 0){
var code = this.code = (event.which || event.keyCode);
this.key = _keys[code];
if (type == 'keydown'){
if (code > 111 && code < 124) this.key = 'f' + (code - 111);
else if (code > 95 && code < 106) this.key = code - 96;
}
if (this.key == null) this.key = String.fromCharCode(code).toLowerCase();
} else if (type == 'click' || type == 'dblclick' || type == 'contextmenu' || type == 'DOMMouseScroll' || type.indexOf('mouse') == 0){
var doc = win.document;
doc = (!doc.compatMode || doc.compatMode == 'CSS1Compat') ? doc.html : doc.body;
this.page = {
x: (event.pageX != null) ? event.pageX : event.clientX + doc.scrollLeft,
y: (event.pageY != null) ? event.pageY : event.clientY + doc.scrollTop
};
this.client = {
x: (event.pageX != null) ? event.pageX - win.pageXOffset : event.clientX,
y: (event.pageY != null) ? event.pageY - win.pageYOffset : event.clientY
};
if (type == 'DOMMouseScroll' || type == 'mousewheel')
this.wheel = (event.wheelDelta) ? event.wheelDelta / 120 : -(event.detail || 0) / 3;
this.rightClick = (event.which == 3 || event.button == 2);
if (type == 'mouseover' || type == 'mouseout'){
var related = event.relatedTarget || event[(type == 'mouseover' ? 'from' : 'to') + 'Element'];
while (related && related.nodeType == 3) related = related.parentNode;
this.relatedTarget = document.id(related);
}
} else if (type.indexOf('touch') == 0 || type.indexOf('gesture') == 0){
this.rotation = event.rotation;
this.scale = event.scale;
this.targetTouches = event.targetTouches;
this.changedTouches = event.changedTouches;
var touches = this.touches = event.touches;
if (touches && touches[0]){
var touch = touches[0];
this.page = {x: touch.pageX, y: touch.pageY};
this.client = {x: touch.clientX, y: touch.clientY};
}
}
if (!this.client) this.client = {};
if (!this.page) this.page = {};
});
DOMEvent.implement({
stop: function(){
return this.preventDefault().stopPropagation();
},
stopPropagation: function(){
if (this.event.stopPropagation) this.event.stopPropagation();
else this.event.cancelBubble = true;
return this;
},
preventDefault: function(){
if (this.event.preventDefault) this.event.preventDefault();
else this.event.returnValue = false;
return this;
}
});
DOMEvent.defineKey = function(code, key){
_keys[code] = key;
return this;
};
DOMEvent.defineKeys = DOMEvent.defineKey.overloadSetter(true);
DOMEvent.defineKeys({
'38': 'up', '40': 'down', '37': 'left', '39': 'right',
'27': 'esc', '32': 'space', '8': 'backspace', '9': 'tab',
'46': 'delete', '13': 'enter'
});
})();
/*
---
name: Class
description: Contains the Class Function for easily creating, extending, and implementing reusable Classes.
license: MIT-style license.
requires: [Array, String, Function, Number]
provides: Class
...
*/
(function(){
var Class = this.Class = new Type('Class', function(params){
if (instanceOf(params, Function)) params = {initialize: params};
var newClass = function(){
reset(this);
if (newClass.$prototyping) return this;
this.$caller = null;
var value = (this.initialize) ? this.initialize.apply(this, arguments) : this;
this.$caller = this.caller = null;
return value;
}.extend(this).implement(params);
newClass.$constructor = Class;
newClass.prototype.$constructor = newClass;
newClass.prototype.parent = parent;
return newClass;
});
var parent = function(){
if (!this.$caller) throw new Error('The method "parent" cannot be called.');
var name = this.$caller.$name,
parent = this.$caller.$owner.parent,
previous = (parent) ? parent.prototype[name] : null;
if (!previous) throw new Error('The method "' + name + '" has no parent.');
return previous.apply(this, arguments);
};
var reset = function(object){
for (var key in object){
var value = object[key];
switch (typeOf(value)){
case 'object':
var F = function(){};
F.prototype = value;
object[key] = reset(new F);
break;
case 'array': object[key] = value.clone(); break;
}
}
return object;
};
var wrap = function(self, key, method){
if (method.$origin) method = method.$origin;
var wrapper = function(){
if (method.$protected && this.$caller == null) throw new Error('The method "' + key + '" cannot be called.');
var caller = this.caller, current = this.$caller;
this.caller = current; this.$caller = wrapper;
var result = method.apply(this, arguments);
this.$caller = current; this.caller = caller;
return result;
}.extend({$owner: self, $origin: method, $name: key});
return wrapper;
};
var implement = function(key, value, retain){
if (Class.Mutators.hasOwnProperty(key)){
value = Class.Mutators[key].call(this, value);
if (value == null) return this;
}
if (typeOf(value) == 'function'){
if (value.$hidden) return this;
this.prototype[key] = (retain) ? value : wrap(this, key, value);
} else {
Object.merge(this.prototype, key, value);
}
return this;
};
var getInstance = function(klass){
klass.$prototyping = true;
var proto = new klass;
delete klass.$prototyping;
return proto;
};
Class.implement('implement', implement.overloadSetter());
Class.Mutators = {
Extends: function(parent){
this.parent = parent;
this.prototype = getInstance(parent);
},
Implements: function(items){
Array.from(items).each(function(item){
var instance = new item;
for (var key in instance) implement.call(this, key, instance[key], true);
}, this);
}
};
})();
/*
---
name: Class.Extras
description: Contains Utility Classes that can be implemented into your own Classes to ease the execution of many common tasks.
license: MIT-style license.
requires: Class
provides: [Class.Extras, Chain, Events, Options]
...
*/
(function(){
this.Chain = new Class({
$chain: [],
chain: function(){
this.$chain.append(Array.flatten(arguments));
return this;
},
callChain: function(){
return (this.$chain.length) ? this.$chain.shift().apply(this, arguments) : false;
},
clearChain: function(){
this.$chain.empty();
return this;
}
});
var removeOn = function(string){
return string.replace(/^on([A-Z])/, function(full, first){
return first.toLowerCase();
});
};
this.Events = new Class({
$events: {},
addEvent: function(type, fn, internal){
type = removeOn(type);
this.$events[type] = (this.$events[type] || []).include(fn);
if (internal) fn.internal = true;
return this;
},
addEvents: function(events){
for (var type in events) this.addEvent(type, events[type]);
return this;
},
fireEvent: function(type, args, delay){
type = removeOn(type);
var events = this.$events[type];
if (!events) return this;
args = Array.from(args);
events.each(function(fn){
if (delay) fn.delay(delay, this, args);
else fn.apply(this, args);
}, this);
return this;
},
removeEvent: function(type, fn){
type = removeOn(type);
var events = this.$events[type];
if (events && !fn.internal){
var index = events.indexOf(fn);
if (index != -1) delete events[index];
}
return this;
},
removeEvents: function(events){
var type;
if (typeOf(events) == 'object'){
for (type in events) this.removeEvent(type, events[type]);
return this;
}
if (events) events = removeOn(events);
for (type in this.$events){
if (events && events != type) continue;
var fns = this.$events[type];
for (var i = fns.length; i--;) if (i in fns){
this.removeEvent(type, fns[i]);
}
}
return this;
}
});
this.Options = new Class({
setOptions: function(){
var options = this.options = Object.merge.apply(null, [{}, this.options].append(arguments));
if (this.addEvent) for (var option in options){
if (typeOf(options[option]) != 'function' || !(/^on[A-Z]/).test(option)) continue;
this.addEvent(option, options[option]);
delete options[option];
}
return this;
}
});
})();
/*
---
name: Slick.Parser
description: Standalone CSS3 Selector parser
provides: Slick.Parser
...
*/
;(function(){
var parsed,
separatorIndex,
combinatorIndex,
reversed,
cache = {},
reverseCache = {},
reUnescape = /\\/g;
var parse = function(expression, isReversed){
if (expression == null) return null;
if (expression.Slick === true) return expression;
expression = ('' + expression).replace(/^\s+|\s+$/g, '');
reversed = !!isReversed;
var currentCache = (reversed) ? reverseCache : cache;
if (currentCache[expression]) return currentCache[expression];
parsed = {
Slick: true,
expressions: [],
raw: expression,
reverse: function(){
return parse(this.raw, true);
}
};
separatorIndex = -1;
while (expression != (expression = expression.replace(regexp, parser)));
parsed.length = parsed.expressions.length;
return currentCache[parsed.raw] = (reversed) ? reverse(parsed) : parsed;
};
var reverseCombinator = function(combinator){
if (combinator === '!') return ' ';
else if (combinator === ' ') return '!';
else if ((/^!/).test(combinator)) return combinator.replace(/^!/, '');
else return '!' + combinator;
};
var reverse = function(expression){
var expressions = expression.expressions;
for (var i = 0; i < expressions.length; i++){
var exp = expressions[i];
var last = {parts: [], tag: '*', combinator: reverseCombinator(exp[0].combinator)};
for (var j = 0; j < exp.length; j++){
var cexp = exp[j];
if (!cexp.reverseCombinator) cexp.reverseCombinator = ' ';
cexp.combinator = cexp.reverseCombinator;
delete cexp.reverseCombinator;
}
exp.reverse().push(last);
}
return expression;
};
var escapeRegExp = function(string){// Credit: XRegExp 0.6.1 (c) 2007-2008 Steven Levithan <http://stevenlevithan.com/regex/xregexp/> MIT License
return string.replace(/[-[\]{}()*+?.\\^$|,#\s]/g, function(match){
return '\\' + match;
});
};
var regexp = new RegExp(
/*
#!/usr/bin/env ruby
puts "\t\t" + DATA.read.gsub(/\(\?x\)|\s+#.*$|\s+|\\$|\\n/,'')
__END__
"(?x)^(?:\
\\s* ( , ) \\s* # Separator \n\
| \\s* ( <combinator>+ ) \\s* # Combinator \n\
| ( \\s+ ) # CombinatorChildren \n\
| ( <unicode>+ | \\* ) # Tag \n\
| \\# ( <unicode>+ ) # ID \n\
| \\. ( <unicode>+ ) # ClassName \n\
| # Attribute \n\
\\[ \
\\s* (<unicode1>+) (?: \
\\s* ([*^$!~|]?=) (?: \
\\s* (?:\
([\"']?)(.*?)\\9 \
)\
) \
)? \\s* \
\\](?!\\]) \n\
| :+ ( <unicode>+ )(?:\
\\( (?:\
(?:([\"'])([^\\12]*)\\12)|((?:\\([^)]+\\)|[^()]*)+)\
) \\)\
)?\
)"
*/
"^(?:\\s*(,)\\s*|\\s*(<combinator>+)\\s*|(\\s+)|(<unicode>+|\\*)|\\#(<unicode>+)|\\.(<unicode>+)|\\[\\s*(<unicode1>+)(?:\\s*([*^$!~|]?=)(?:\\s*(?:([\"']?)(.*?)\\9)))?\\s*\\](?!\\])|(:+)(<unicode>+)(?:\\((?:(?:([\"'])([^\\13]*)\\13)|((?:\\([^)]+\\)|[^()]*)+))\\))?)"
.replace(/<combinator>/, '[' + escapeRegExp(">+~`!@$%^&={}\\;</") + ']')
.replace(/<unicode>/g, '(?:[\\w\\u00a1-\\uFFFF-]|\\\\[^\\s0-9a-f])')
.replace(/<unicode1>/g, '(?:[:\\w\\u00a1-\\uFFFF-]|\\\\[^\\s0-9a-f])')
);
function parser(
rawMatch,
separator,
combinator,
combinatorChildren,
tagName,
id,
className,
attributeKey,
attributeOperator,
attributeQuote,
attributeValue,
pseudoMarker,
pseudoClass,
pseudoQuote,
pseudoClassQuotedValue,
pseudoClassValue
){
if (separator || separatorIndex === -1){
parsed.expressions[++separatorIndex] = [];
combinatorIndex = -1;
if (separator) return '';
}
if (combinator || combinatorChildren || combinatorIndex === -1){
combinator = combinator || ' ';
var currentSeparator = parsed.expressions[separatorIndex];
if (reversed && currentSeparator[combinatorIndex])
currentSeparator[combinatorIndex].reverseCombinator = reverseCombinator(combinator);
currentSeparator[++combinatorIndex] = {combinator: combinator, tag: '*'};
}
var currentParsed = parsed.expressions[separatorIndex][combinatorIndex];
if (tagName){
currentParsed.tag = tagName.replace(reUnescape, '');
} else if (id){
currentParsed.id = id.replace(reUnescape, '');
} else if (className){
className = className.replace(reUnescape, '');
if (!currentParsed.classList) currentParsed.classList = [];
if (!currentParsed.classes) currentParsed.classes = [];
currentParsed.classList.push(className);
currentParsed.classes.push({
value: className,
regexp: new RegExp('(^|\\s)' + escapeRegExp(className) + '(\\s|$)')
});
} else if (pseudoClass){
pseudoClassValue = pseudoClassValue || pseudoClassQuotedValue;
pseudoClassValue = pseudoClassValue ? pseudoClassValue.replace(reUnescape, '') : null;
if (!currentParsed.pseudos) currentParsed.pseudos = [];
currentParsed.pseudos.push({
key: pseudoClass.replace(reUnescape, ''),
value: pseudoClassValue,
type: pseudoMarker.length == 1 ? 'class' : 'element'
});
} else if (attributeKey){
attributeKey = attributeKey.replace(reUnescape, '');
attributeValue = (attributeValue || '').replace(reUnescape, '');
var test, regexp;
switch (attributeOperator){
case '^=' : regexp = new RegExp( '^'+ escapeRegExp(attributeValue) ); break;
case '$=' : regexp = new RegExp( escapeRegExp(attributeValue) +'$' ); break;
case '~=' : regexp = new RegExp( '(^|\\s)'+ escapeRegExp(attributeValue) +'(\\s|$)' ); break;
case '|=' : regexp = new RegExp( '^'+ escapeRegExp(attributeValue) +'(-|$)' ); break;
case '=' : test = function(value){
return attributeValue == value;
}; break;
case '*=' : test = function(value){
return value && value.indexOf(attributeValue) > -1;
}; break;
case '!=' : test = function(value){
return attributeValue != value;
}; break;
default : test = function(value){
return !!value;
};
}
if (attributeValue == '' && (/^[*$^]=$/).test(attributeOperator)) test = function(){
return false;
};
if (!test) test = function(value){
return value && regexp.test(value);
};
if (!currentParsed.attributes) currentParsed.attributes = [];
currentParsed.attributes.push({
key: attributeKey,
operator: attributeOperator,
value: attributeValue,
test: test
});
}
return '';
};
// Slick NS
var Slick = (this.Slick || {});
Slick.parse = function(expression){
return parse(expression);
};
Slick.escapeRegExp = escapeRegExp;
if (!this.Slick) this.Slick = Slick;
}).apply(/*<CommonJS>*/(typeof exports != 'undefined') ? exports : /*</CommonJS>*/this);
/*
---
name: Slick.Finder
description: The new, superfast css selector engine.
provides: Slick.Finder
requires: Slick.Parser
...
*/
;(function(){
var local = {},
featuresCache = {},
toString = Object.prototype.toString;
// Feature / Bug detection
local.isNativeCode = function(fn){
return (/\{\s*\[native code\]\s*\}/).test('' + fn);
};
local.isXML = function(document){
return (!!document.xmlVersion) || (!!document.xml) || (toString.call(document) == '[object XMLDocument]') ||
(document.nodeType == 9 && document.documentElement.nodeName != 'HTML');
};
local.setDocument = function(document){
// convert elements / window arguments to document. if document cannot be extrapolated, the function returns.
var nodeType = document.nodeType;
if (nodeType == 9); // document
else if (nodeType) document = document.ownerDocument; // node
else if (document.navigator) document = document.document; // window
else return;
// check if it's the old document
if (this.document === document) return;
this.document = document;
// check if we have done feature detection on this document before
var root = document.documentElement,
rootUid = this.getUIDXML(root),
features = featuresCache[rootUid],
feature;
if (features){
for (feature in features){
this[feature] = features[feature];
}
return;
}
features = featuresCache[rootUid] = {};
features.root = root;
features.isXMLDocument = this.isXML(document);
features.brokenStarGEBTN
= features.starSelectsClosedQSA
= features.idGetsName
= features.brokenMixedCaseQSA
= features.brokenGEBCN
= features.brokenCheckedQSA
= features.brokenEmptyAttributeQSA
= features.isHTMLDocument
= features.nativeMatchesSelector
= false;
var starSelectsClosed, starSelectsComments,
brokenSecondClassNameGEBCN, cachedGetElementsByClassName,
brokenFormAttributeGetter;
var selected, id = 'slick_uniqueid';
var testNode = document.createElement('div');
var testRoot = document.body || document.getElementsByTagName('body')[0] || root;
testRoot.appendChild(testNode);
// on non-HTML documents innerHTML and getElementsById doesnt work properly
try {
testNode.innerHTML = '<a id="'+id+'"></a>';
features.isHTMLDocument = !!document.getElementById(id);
} catch(e){};
if (features.isHTMLDocument){
testNode.style.display = 'none';
// IE returns comment nodes for getElementsByTagName('*') for some documents
testNode.appendChild(document.createComment(''));
starSelectsComments = (testNode.getElementsByTagName('*').length > 1);
// IE returns closed nodes (EG:"</foo>") for getElementsByTagName('*') for some documents
try {
testNode.innerHTML = 'foo</foo>';
selected = testNode.getElementsByTagName('*');
starSelectsClosed = (selected && !!selected.length && selected[0].nodeName.charAt(0) == '/');
} catch(e){};
features.brokenStarGEBTN = starSelectsComments || starSelectsClosed;
// IE returns elements with the name instead of just id for getElementsById for some documents
try {
testNode.innerHTML = '<a name="'+ id +'"></a><b id="'+ id +'"></b>';
features.idGetsName = document.getElementById(id) === testNode.firstChild;
} catch(e){};
if (testNode.getElementsByClassName){
// Safari 3.2 getElementsByClassName caches results
try {
testNode.innerHTML = '<a class="f"></a><a class="b"></a>';
testNode.getElementsByClassName('b').length;
testNode.firstChild.className = 'b';
cachedGetElementsByClassName = (testNode.getElementsByClassName('b').length != 2);
} catch(e){};
// Opera 9.6 getElementsByClassName doesnt detects the class if its not the first one
try {
testNode.innerHTML = '<a class="a"></a><a class="f b a"></a>';
brokenSecondClassNameGEBCN = (testNode.getElementsByClassName('a').length != 2);
} catch(e){};
features.brokenGEBCN = cachedGetElementsByClassName || brokenSecondClassNameGEBCN;
}
if (testNode.querySelectorAll){
// IE 8 returns closed nodes (EG:"</foo>") for querySelectorAll('*') for some documents
try {
testNode.innerHTML = 'foo</foo>';
selected = testNode.querySelectorAll('*');
features.starSelectsClosedQSA = (selected && !!selected.length && selected[0].nodeName.charAt(0) == '/');
} catch(e){};
// Safari 3.2 querySelectorAll doesnt work with mixedcase on quirksmode
try {
testNode.innerHTML = '<a class="MiX"></a>';
features.brokenMixedCaseQSA = !testNode.querySelectorAll('.MiX').length;
} catch(e){};
// Webkit and Opera dont return selected options on querySelectorAll
try {
testNode.innerHTML = '<select><option selected="selected">a</option></select>';
features.brokenCheckedQSA = (testNode.querySelectorAll(':checked').length == 0);
} catch(e){};
// IE returns incorrect results for attr[*^$]="" selectors on querySelectorAll
try {
testNode.innerHTML = '<a class=""></a>';
features.brokenEmptyAttributeQSA = (testNode.querySelectorAll('[class*=""]').length != 0);
} catch(e){};
}
// IE6-7, if a form has an input of id x, form.getAttribute(x) returns a reference to the input
try {
testNode.innerHTML = '<form action="s"><input id="action"/></form>';
brokenFormAttributeGetter = (testNode.firstChild.getAttribute('action') != 's');
} catch(e){};
// native matchesSelector function
features.nativeMatchesSelector = root.matchesSelector || /*root.msMatchesSelector ||*/ root.mozMatchesSelector || root.webkitMatchesSelector;
if (features.nativeMatchesSelector) try {
// if matchesSelector trows errors on incorrect sintaxes we can use it
features.nativeMatchesSelector.call(root, ':slick');
features.nativeMatchesSelector = null;
} catch(e){};
}
try {
root.slick_expando = 1;
delete root.slick_expando;
features.getUID = this.getUIDHTML;
} catch(e) {
features.getUID = this.getUIDXML;
}
testRoot.removeChild(testNode);
testNode = selected = testRoot = null;
// getAttribute
features.getAttribute = (features.isHTMLDocument && brokenFormAttributeGetter) ? function(node, name){
var method = this.attributeGetters[name];
if (method) return method.call(node);
var attributeNode = node.getAttributeNode(name);
return (attributeNode) ? attributeNode.nodeValue : null;
} : function(node, name){
var method = this.attributeGetters[name];
return (method) ? method.call(node) : node.getAttribute(name);
};
// hasAttribute
features.hasAttribute = (root && this.isNativeCode(root.hasAttribute)) ? function(node, attribute) {
return node.hasAttribute(attribute);
} : function(node, attribute) {
node = node.getAttributeNode(attribute);
return !!(node && (node.specified || node.nodeValue));
};
// contains
// FIXME: Add specs: local.contains should be different for xml and html documents?
var nativeRootContains = root && this.isNativeCode(root.contains),
nativeDocumentContains = document && this.isNativeCode(document.contains);
features.contains = (nativeRootContains && nativeDocumentContains) ? function(context, node){
return context.contains(node);
} : (nativeRootContains && !nativeDocumentContains) ? function(context, node){
// IE8 does not have .contains on document.
return context === node || ((context === document) ? document.documentElement : context).contains(node);
} : (root && root.compareDocumentPosition) ? function(context, node){
return context === node || !!(context.compareDocumentPosition(node) & 16);
} : function(context, node){
if (node) do {
if (node === context) return true;
} while ((node = node.parentNode));
return false;
};
// document order sorting
// credits to Sizzle (http://sizzlejs.com/)
features.documentSorter = (root.compareDocumentPosition) ? function(a, b){
if (!a.compareDocumentPosition || !b.compareDocumentPosition) return 0;
return a.compareDocumentPosition(b) & 4 ? -1 : a === b ? 0 : 1;
} : ('sourceIndex' in root) ? function(a, b){
if (!a.sourceIndex || !b.sourceIndex) return 0;
return a.sourceIndex - b.sourceIndex;
} : (document.createRange) ? function(a, b){
if (!a.ownerDocument || !b.ownerDocument) return 0;
var aRange = a.ownerDocument.createRange(), bRange = b.ownerDocument.createRange();
aRange.setStart(a, 0);
aRange.setEnd(a, 0);
bRange.setStart(b, 0);
bRange.setEnd(b, 0);
return aRange.compareBoundaryPoints(Range.START_TO_END, bRange);
} : null ;
root = null;
for (feature in features){
this[feature] = features[feature];
}
};
// Main Method
var reSimpleSelector = /^([#.]?)((?:[\w-]+|\*))$/,
reEmptyAttribute = /\[.+[*$^]=(?:""|'')?\]/,
qsaFailExpCache = {};
local.search = function(context, expression, append, first){
var found = this.found = (first) ? null : (append || []);
if (!context) return found;
else if (context.navigator) context = context.document; // Convert the node from a window to a document
else if (!context.nodeType) return found;
// setup
var parsed, i,
uniques = this.uniques = {},
hasOthers = !!(append && append.length),
contextIsDocument = (context.nodeType == 9);
if (this.document !== (contextIsDocument ? context : context.ownerDocument)) this.setDocument(context);
// avoid duplicating items already in the append array
if (hasOthers) for (i = found.length; i--;) uniques[this.getUID(found[i])] = true;
// expression checks
if (typeof expression == 'string'){ // expression is a string
/*<simple-selectors-override>*/
var simpleSelector = expression.match(reSimpleSelector);
simpleSelectors: if (simpleSelector) {
var symbol = simpleSelector[1],
name = simpleSelector[2],
node, nodes;
if (!symbol){
if (name == '*' && this.brokenStarGEBTN) break simpleSelectors;
nodes = context.getElementsByTagName(name);
if (first) return nodes[0] || null;
for (i = 0; node = nodes[i++];){
if (!(hasOthers && uniques[this.getUID(node)])) found.push(node);
}
} else if (symbol == '#'){
if (!this.isHTMLDocument || !contextIsDocument) break simpleSelectors;
node = context.getElementById(name);
if (!node) return found;
if (this.idGetsName && node.getAttributeNode('id').nodeValue != name) break simpleSelectors;
if (first) return node || null;
if (!(hasOthers && uniques[this.getUID(node)])) found.push(node);
} else if (symbol == '.'){
if (!this.isHTMLDocument || ((!context.getElementsByClassName || this.brokenGEBCN) && context.querySelectorAll)) break simpleSelectors;
if (context.getElementsByClassName && !this.brokenGEBCN){
nodes = context.getElementsByClassName(name);
if (first) return nodes[0] || null;
for (i = 0; node = nodes[i++];){
if (!(hasOthers && uniques[this.getUID(node)])) found.push(node);
}
} else {
var matchClass = new RegExp('(^|\\s)'+ Slick.escapeRegExp(name) +'(\\s|$)');
nodes = context.getElementsByTagName('*');
for (i = 0; node = nodes[i++];){
className = node.className;
if (!(className && matchClass.test(className))) continue;
if (first) return node;
if (!(hasOthers && uniques[this.getUID(node)])) found.push(node);
}
}
}
if (hasOthers) this.sort(found);
return (first) ? null : found;
}
/*</simple-selectors-override>*/
/*<query-selector-override>*/
querySelector: if (context.querySelectorAll) {
if (!this.isHTMLDocument
|| qsaFailExpCache[expression]
//TODO: only skip when expression is actually mixed case
|| this.brokenMixedCaseQSA
|| (this.brokenCheckedQSA && expression.indexOf(':checked') > -1)
|| (this.brokenEmptyAttributeQSA && reEmptyAttribute.test(expression))
|| (!contextIsDocument //Abort when !contextIsDocument and...
// there are multiple expressions in the selector
// since we currently only fix non-document rooted QSA for single expression selectors
&& expression.indexOf(',') > -1
)
|| Slick.disableQSA
) break querySelector;
var _expression = expression, _context = context;
if (!contextIsDocument){
// non-document rooted QSA
// credits to Andrew Dupont
var currentId = _context.getAttribute('id'), slickid = 'slickid__';
_context.setAttribute('id', slickid);
_expression = '#' + slickid + ' ' + _expression;
context = _context.parentNode;
}
try {
if (first) return context.querySelector(_expression) || null;
else nodes = context.querySelectorAll(_expression);
} catch(e) {
qsaFailExpCache[expression] = 1;
break querySelector;
} finally {
if (!contextIsDocument){
if (currentId) _context.setAttribute('id', currentId);
else _context.removeAttribute('id');
context = _context;
}
}
if (this.starSelectsClosedQSA) for (i = 0; node = nodes[i++];){
if (node.nodeName > '@' && !(hasOthers && uniques[this.getUID(node)])) found.push(node);
} else for (i = 0; node = nodes[i++];){
if (!(hasOthers && uniques[this.getUID(node)])) found.push(node);
}
if (hasOthers) this.sort(found);
return found;
}
/*</query-selector-override>*/
parsed = this.Slick.parse(expression);
if (!parsed.length) return found;
} else if (expression == null){ // there is no expression
return found;
} else if (expression.Slick){ // expression is a parsed Slick object
parsed = expression;
} else if (this.contains(context.documentElement || context, expression)){ // expression is a node
(found) ? found.push(expression) : found = expression;
return found;
} else { // other junk
return found;
}
/*<pseudo-selectors>*//*<nth-pseudo-selectors>*/
// cache elements for the nth selectors
this.posNTH = {};
this.posNTHLast = {};
this.posNTHType = {};
this.posNTHTypeLast = {};
/*</nth-pseudo-selectors>*//*</pseudo-selectors>*/
// if append is null and there is only a single selector with one expression use pushArray, else use pushUID
this.push = (!hasOthers && (first || (parsed.length == 1 && parsed.expressions[0].length == 1))) ? this.pushArray : this.pushUID;
if (found == null) found = [];
// default engine
var j, m, n;
var combinator, tag, id, classList, classes, attributes, pseudos;
var currentItems, currentExpression, currentBit, lastBit, expressions = parsed.expressions;
search: for (i = 0; (currentExpression = expressions[i]); i++) for (j = 0; (currentBit = currentExpression[j]); j++){
combinator = 'combinator:' + currentBit.combinator;
if (!this[combinator]) continue search;
tag = (this.isXMLDocument) ? currentBit.tag : currentBit.tag.toUpperCase();
id = currentBit.id;
classList = currentBit.classList;
classes = currentBit.classes;
attributes = currentBit.attributes;
pseudos = currentBit.pseudos;
lastBit = (j === (currentExpression.length - 1));
this.bitUniques = {};
if (lastBit){
this.uniques = uniques;
this.found = found;
} else {
this.uniques = {};
this.found = [];
}
if (j === 0){
this[combinator](context, tag, id, classes, attributes, pseudos, classList);
if (first && lastBit && found.length) break search;
} else {
if (first && lastBit) for (m = 0, n = currentItems.length; m < n; m++){
this[combinator](currentItems[m], tag, id, classes, attributes, pseudos, classList);
if (found.length) break search;
} else for (m = 0, n = currentItems.length; m < n; m++) this[combinator](currentItems[m], tag, id, classes, attributes, pseudos, classList);
}
currentItems = this.found;
}
// should sort if there are nodes in append and if you pass multiple expressions.
if (hasOthers || (parsed.expressions.length > 1)) this.sort(found);
return (first) ? (found[0] || null) : found;
};
// Utils
local.uidx = 1;
local.uidk = 'slick-uniqueid';
local.getUIDXML = function(node){
var uid = node.getAttribute(this.uidk);
if (!uid){
uid = this.uidx++;
node.setAttribute(this.uidk, uid);
}
return uid;
};
local.getUIDHTML = function(node){
return node.uniqueNumber || (node.uniqueNumber = this.uidx++);
};
// sort based on the setDocument documentSorter method.
local.sort = function(results){
if (!this.documentSorter) return results;
results.sort(this.documentSorter);
return results;
};
/*<pseudo-selectors>*//*<nth-pseudo-selectors>*/
local.cacheNTH = {};
local.matchNTH = /^([+-]?\d*)?([a-z]+)?([+-]\d+)?$/;
local.parseNTHArgument = function(argument){
var parsed = argument.match(this.matchNTH);
if (!parsed) return false;
var special = parsed[2] || false;
var a = parsed[1] || 1;
if (a == '-') a = -1;
var b = +parsed[3] || 0;
parsed =
(special == 'n') ? {a: a, b: b} :
(special == 'odd') ? {a: 2, b: 1} :
(special == 'even') ? {a: 2, b: 0} : {a: 0, b: a};
return (this.cacheNTH[argument] = parsed);
};
local.createNTHPseudo = function(child, sibling, positions, ofType){
return function(node, argument){
var uid = this.getUID(node);
if (!this[positions][uid]){
var parent = node.parentNode;
if (!parent) return false;
var el = parent[child], count = 1;
if (ofType){
var nodeName = node.nodeName;
do {
if (el.nodeName != nodeName) continue;
this[positions][this.getUID(el)] = count++;
} while ((el = el[sibling]));
} else {
do {
if (el.nodeType != 1) continue;
this[positions][this.getUID(el)] = count++;
} while ((el = el[sibling]));
}
}
argument = argument || 'n';
var parsed = this.cacheNTH[argument] || this.parseNTHArgument(argument);
if (!parsed) return false;
var a = parsed.a, b = parsed.b, pos = this[positions][uid];
if (a == 0) return b == pos;
if (a > 0){
if (pos < b) return false;
} else {
if (b < pos) return false;
}
return ((pos - b) % a) == 0;
};
};
/*</nth-pseudo-selectors>*//*</pseudo-selectors>*/
local.pushArray = function(node, tag, id, classes, attributes, pseudos){
if (this.matchSelector(node, tag, id, classes, attributes, pseudos)) this.found.push(node);
};
local.pushUID = function(node, tag, id, classes, attributes, pseudos){
var uid = this.getUID(node);
if (!this.uniques[uid] && this.matchSelector(node, tag, id, classes, attributes, pseudos)){
this.uniques[uid] = true;
this.found.push(node);
}
};
local.matchNode = function(node, selector){
if (this.isHTMLDocument && this.nativeMatchesSelector){
try {
return this.nativeMatchesSelector.call(node, selector.replace(/\[([^=]+)=\s*([^'"\]]+?)\s*\]/g, '[$1="$2"]'));
} catch(matchError) {}
}
var parsed = this.Slick.parse(selector);
if (!parsed) return true;
// simple (single) selectors
var expressions = parsed.expressions, simpleExpCounter = 0, i;
for (i = 0; (currentExpression = expressions[i]); i++){
if (currentExpression.length == 1){
var exp = currentExpression[0];
if (this.matchSelector(node, (this.isXMLDocument) ? exp.tag : exp.tag.toUpperCase(), exp.id, exp.classes, exp.attributes, exp.pseudos)) return true;
simpleExpCounter++;
}
}
if (simpleExpCounter == parsed.length) return false;
var nodes = this.search(this.document, parsed), item;
for (i = 0; item = nodes[i++];){
if (item === node) return true;
}
return false;
};
local.matchPseudo = function(node, name, argument){
var pseudoName = 'pseudo:' + name;
if (this[pseudoName]) return this[pseudoName](node, argument);
var attribute = this.getAttribute(node, name);
return (argument) ? argument == attribute : !!attribute;
};
local.matchSelector = function(node, tag, id, classes, attributes, pseudos){
if (tag){
var nodeName = (this.isXMLDocument) ? node.nodeName : node.nodeName.toUpperCase();
if (tag == '*'){
if (nodeName < '@') return false; // Fix for comment nodes and closed nodes
} else {
if (nodeName != tag) return false;
}
}
if (id && node.getAttribute('id') != id) return false;
var i, part, cls;
if (classes) for (i = classes.length; i--;){
cls = this.getAttribute(node, 'class');
if (!(cls && classes[i].regexp.test(cls))) return false;
}
if (attributes) for (i = attributes.length; i--;){
part = attributes[i];
if (part.operator ? !part.test(this.getAttribute(node, part.key)) : !this.hasAttribute(node, part.key)) return false;
}
if (pseudos) for (i = pseudos.length; i--;){
part = pseudos[i];
if (!this.matchPseudo(node, part.key, part.value)) return false;
}
return true;
};
var combinators = {
' ': function(node, tag, id, classes, attributes, pseudos, classList){ // all child nodes, any level
var i, item, children;
if (this.isHTMLDocument){
getById: if (id){
item = this.document.getElementById(id);
if ((!item && node.all) || (this.idGetsName && item && item.getAttributeNode('id').nodeValue != id)){
// all[id] returns all the elements with that name or id inside node
// if theres just one it will return the element, else it will be a collection
children = node.all[id];
if (!children) return;
if (!children[0]) children = [children];
for (i = 0; item = children[i++];){
var idNode = item.getAttributeNode('id');
if (idNode && idNode.nodeValue == id){
this.push(item, tag, null, classes, attributes, pseudos);
break;
}
}
return;
}
if (!item){
// if the context is in the dom we return, else we will try GEBTN, breaking the getById label
if (this.contains(this.root, node)) return;
else break getById;
} else if (this.document !== node && !this.contains(node, item)) return;
this.push(item, tag, null, classes, attributes, pseudos);
return;
}
getByClass: if (classes && node.getElementsByClassName && !this.brokenGEBCN){
children = node.getElementsByClassName(classList.join(' '));
if (!(children && children.length)) break getByClass;
for (i = 0; item = children[i++];) this.push(item, tag, id, null, attributes, pseudos);
return;
}
}
getByTag: {
children = node.getElementsByTagName(tag);
if (!(children && children.length)) break getByTag;
if (!this.brokenStarGEBTN) tag = null;
for (i = 0; item = children[i++];) this.push(item, tag, id, classes, attributes, pseudos);
}
},
'>': function(node, tag, id, classes, attributes, pseudos){ // direct children
if ((node = node.firstChild)) do {
if (node.nodeType == 1) this.push(node, tag, id, classes, attributes, pseudos);
} while ((node = node.nextSibling));
},
'+': function(node, tag, id, classes, attributes, pseudos){ // next sibling
while ((node = node.nextSibling)) if (node.nodeType == 1){
this.push(node, tag, id, classes, attributes, pseudos);
break;
}
},
'^': function(node, tag, id, classes, attributes, pseudos){ // first child
node = node.firstChild;
if (node){
if (node.nodeType == 1) this.push(node, tag, id, classes, attributes, pseudos);
else this['combinator:+'](node, tag, id, classes, attributes, pseudos);
}
},
'~': function(node, tag, id, classes, attributes, pseudos){ // next siblings
while ((node = node.nextSibling)){
if (node.nodeType != 1) continue;
var uid = this.getUID(node);
if (this.bitUniques[uid]) break;
this.bitUniques[uid] = true;
this.push(node, tag, id, classes, attributes, pseudos);
}
},
'++': function(node, tag, id, classes, attributes, pseudos){ // next sibling and previous sibling
this['combinator:+'](node, tag, id, classes, attributes, pseudos);
this['combinator:!+'](node, tag, id, classes, attributes, pseudos);
},
'~~': function(node, tag, id, classes, attributes, pseudos){ // next siblings and previous siblings
this['combinator:~'](node, tag, id, classes, attributes, pseudos);
this['combinator:!~'](node, tag, id, classes, attributes, pseudos);
},
'!': function(node, tag, id, classes, attributes, pseudos){ // all parent nodes up to document
while ((node = node.parentNode)) if (node !== this.document) this.push(node, tag, id, classes, attributes, pseudos);
},
'!>': function(node, tag, id, classes, attributes, pseudos){ // direct parent (one level)
node = node.parentNode;
if (node !== this.document) this.push(node, tag, id, classes, attributes, pseudos);
},
'!+': function(node, tag, id, classes, attributes, pseudos){ // previous sibling
while ((node = node.previousSibling)) if (node.nodeType == 1){
this.push(node, tag, id, classes, attributes, pseudos);
break;
}
},
'!^': function(node, tag, id, classes, attributes, pseudos){ // last child
node = node.lastChild;
if (node){
if (node.nodeType == 1) this.push(node, tag, id, classes, attributes, pseudos);
else this['combinator:!+'](node, tag, id, classes, attributes, pseudos);
}
},
'!~': function(node, tag, id, classes, attributes, pseudos){ // previous siblings
while ((node = node.previousSibling)){
if (node.nodeType != 1) continue;
var uid = this.getUID(node);
if (this.bitUniques[uid]) break;
this.bitUniques[uid] = true;
this.push(node, tag, id, classes, attributes, pseudos);
}
}
};
for (var c in combinators) local['combinator:' + c] = combinators[c];
var pseudos = {
/*<pseudo-selectors>*/
'empty': function(node){
var child = node.firstChild;
return !(child && child.nodeType == 1) && !(node.innerText || node.textContent || '').length;
},
'not': function(node, expression){
return !this.matchNode(node, expression);
},
'contains': function(node, text){
return (node.innerText || node.textContent || '').indexOf(text) > -1;
},
'first-child': function(node){
while ((node = node.previousSibling)) if (node.nodeType == 1) return false;
return true;
},
'last-child': function(node){
while ((node = node.nextSibling)) if (node.nodeType == 1) return false;
return true;
},
'only-child': function(node){
var prev = node;
while ((prev = prev.previousSibling)) if (prev.nodeType == 1) return false;
var next = node;
while ((next = next.nextSibling)) if (next.nodeType == 1) return false;
return true;
},
/*<nth-pseudo-selectors>*/
'nth-child': local.createNTHPseudo('firstChild', 'nextSibling', 'posNTH'),
'nth-last-child': local.createNTHPseudo('lastChild', 'previousSibling', 'posNTHLast'),
'nth-of-type': local.createNTHPseudo('firstChild', 'nextSibling', 'posNTHType', true),
'nth-last-of-type': local.createNTHPseudo('lastChild', 'previousSibling', 'posNTHTypeLast', true),
'index': function(node, index){
return this['pseudo:nth-child'](node, '' + (index + 1));
},
'even': function(node){
return this['pseudo:nth-child'](node, '2n');
},
'odd': function(node){
return this['pseudo:nth-child'](node, '2n+1');
},
/*</nth-pseudo-selectors>*/
/*<of-type-pseudo-selectors>*/
'first-of-type': function(node){
var nodeName = node.nodeName;
while ((node = node.previousSibling)) if (node.nodeName == nodeName) return false;
return true;
},
'last-of-type': function(node){
var nodeName = node.nodeName;
while ((node = node.nextSibling)) if (node.nodeName == nodeName) return false;
return true;
},
'only-of-type': function(node){
var prev = node, nodeName = node.nodeName;
while ((prev = prev.previousSibling)) if (prev.nodeName == nodeName) return false;
var next = node;
while ((next = next.nextSibling)) if (next.nodeName == nodeName) return false;
return true;
},
/*</of-type-pseudo-selectors>*/
// custom pseudos
'enabled': function(node){
return !node.disabled;
},
'disabled': function(node){
return node.disabled;
},
'checked': function(node){
return node.checked || node.selected;
},
'focus': function(node){
return this.isHTMLDocument && this.document.activeElement === node && (node.href || node.type || this.hasAttribute(node, 'tabindex'));
},
'root': function(node){
return (node === this.root);
},
'selected': function(node){
return node.selected;
}
/*</pseudo-selectors>*/
};
for (var p in pseudos) local['pseudo:' + p] = pseudos[p];
// attributes methods
var attributeGetters = local.attributeGetters = {
'for': function(){
return ('htmlFor' in this) ? this.htmlFor : this.getAttribute('for');
},
'href': function(){
return ('href' in this) ? this.getAttribute('href', 2) : this.getAttribute('href');
},
'style': function(){
return (this.style) ? this.style.cssText : this.getAttribute('style');
},
'tabindex': function(){
var attributeNode = this.getAttributeNode('tabindex');
return (attributeNode && attributeNode.specified) ? attributeNode.nodeValue : null;
},
'type': function(){
return this.getAttribute('type');
},
'maxlength': function(){
var attributeNode = this.getAttributeNode('maxLength');
return (attributeNode && attributeNode.specified) ? attributeNode.nodeValue : null;
}
};
attributeGetters.MAXLENGTH = attributeGetters.maxLength = attributeGetters.maxlength;
// Slick
var Slick = local.Slick = (this.Slick || {});
Slick.version = '1.1.7';
// Slick finder
Slick.search = function(context, expression, append){
return local.search(context, expression, append);
};
Slick.find = function(context, expression){
return local.search(context, expression, null, true);
};
// Slick containment checker
Slick.contains = function(container, node){
local.setDocument(container);
return local.contains(container, node);
};
// Slick attribute getter
Slick.getAttribute = function(node, name){
local.setDocument(node);
return local.getAttribute(node, name);
};
Slick.hasAttribute = function(node, name){
local.setDocument(node);
return local.hasAttribute(node, name);
};
// Slick matcher
Slick.match = function(node, selector){
if (!(node && selector)) return false;
if (!selector || selector === node) return true;
local.setDocument(node);
return local.matchNode(node, selector);
};
// Slick attribute accessor
Slick.defineAttributeGetter = function(name, fn){
local.attributeGetters[name] = fn;
return this;
};
Slick.lookupAttributeGetter = function(name){
return local.attributeGetters[name];
};
// Slick pseudo accessor
Slick.definePseudo = function(name, fn){
local['pseudo:' + name] = function(node, argument){
return fn.call(node, argument);
};
return this;
};
Slick.lookupPseudo = function(name){
var pseudo = local['pseudo:' + name];
if (pseudo) return function(argument){
return pseudo.call(this, argument);
};
return null;
};
// Slick overrides accessor
Slick.override = function(regexp, fn){
local.override(regexp, fn);
return this;
};
Slick.isXML = local.isXML;
Slick.uidOf = function(node){
return local.getUIDHTML(node);
};
if (!this.Slick) this.Slick = Slick;
}).apply(/*<CommonJS>*/(typeof exports != 'undefined') ? exports : /*</CommonJS>*/this);
/*
---
name: Element
description: One of the most important items in MooTools. Contains the dollar function, the dollars function, and an handful of cross-browser, time-saver methods to let you easily work with HTML Elements.
license: MIT-style license.
requires: [Window, Document, Array, String, Function, Object, Number, Slick.Parser, Slick.Finder]
provides: [Element, Elements, $, $$, Iframe, Selectors]
...
*/
var Element = function(tag, props){
var konstructor = Element.Constructors[tag];
if (konstructor) return konstructor(props);
if (typeof tag != 'string') return document.id(tag).set(props);
if (!props) props = {};
if (!(/^[\w-]+$/).test(tag)){
var parsed = Slick.parse(tag).expressions[0][0];
tag = (parsed.tag == '*') ? 'div' : parsed.tag;
if (parsed.id && props.id == null) props.id = parsed.id;
var attributes = parsed.attributes;
if (attributes) for (var attr, i = 0, l = attributes.length; i < l; i++){
attr = attributes[i];
if (props[attr.key] != null) continue;
if (attr.value != null && attr.operator == '=') props[attr.key] = attr.value;
else if (!attr.value && !attr.operator) props[attr.key] = true;
}
if (parsed.classList && props['class'] == null) props['class'] = parsed.classList.join(' ');
}
return document.newElement(tag, props);
};
if (Browser.Element){
Element.prototype = Browser.Element.prototype;
// IE8 and IE9 require the wrapping.
Element.prototype._fireEvent = (function(fireEvent){
return function(type, event){
return fireEvent.call(this, type, event);
};
})(Element.prototype.fireEvent);
}
new Type('Element', Element).mirror(function(name){
if (Array.prototype[name]) return;
var obj = {};
obj[name] = function(){
var results = [], args = arguments, elements = true;
for (var i = 0, l = this.length; i < l; i++){
var element = this[i], result = results[i] = element[name].apply(element, args);
elements = (elements && typeOf(result) == 'element');
}
return (elements) ? new Elements(results) : results;
};
Elements.implement(obj);
});
if (!Browser.Element){
Element.parent = Object;
Element.Prototype = {
'$constructor': Element,
'$family': Function.from('element').hide()
};
Element.mirror(function(name, method){
Element.Prototype[name] = method;
});
}
Element.Constructors = {};
var IFrame = new Type('IFrame', function(){
var params = Array.link(arguments, {
properties: Type.isObject,
iframe: function(obj){
return (obj != null);
}
});
var props = params.properties || {}, iframe;
if (params.iframe) iframe = document.id(params.iframe);
var onload = props.onload || function(){};
delete props.onload;
props.id = props.name = [props.id, props.name, iframe ? (iframe.id || iframe.name) : 'IFrame_' + String.uniqueID()].pick();
iframe = new Element(iframe || 'iframe', props);
var onLoad = function(){
onload.call(iframe.contentWindow);
};
if (window.frames[props.id]) onLoad();
else iframe.addListener('load', onLoad);
return iframe;
});
var Elements = this.Elements = function(nodes){
if (nodes && nodes.length){
var uniques = {}, node;
for (var i = 0; node = nodes[i++];){
var uid = Slick.uidOf(node);
if (!uniques[uid]){
uniques[uid] = true;
this.push(node);
}
}
}
};
Elements.prototype = {length: 0};
Elements.parent = Array;
new Type('Elements', Elements).implement({
filter: function(filter, bind){
if (!filter) return this;
return new Elements(Array.filter(this, (typeOf(filter) == 'string') ? function(item){
return item.match(filter);
} : filter, bind));
}.protect(),
push: function(){
var length = this.length;
for (var i = 0, l = arguments.length; i < l; i++){
var item = document.id(arguments[i]);
if (item) this[length++] = item;
}
return (this.length = length);
}.protect(),
unshift: function(){
var items = [];
for (var i = 0, l = arguments.length; i < l; i++){
var item = document.id(arguments[i]);
if (item) items.push(item);
}
return Array.prototype.unshift.apply(this, items);
}.protect(),
concat: function(){
var newElements = new Elements(this);
for (var i = 0, l = arguments.length; i < l; i++){
var item = arguments[i];
if (Type.isEnumerable(item)) newElements.append(item);
else newElements.push(item);
}
return newElements;
}.protect(),
append: function(collection){
for (var i = 0, l = collection.length; i < l; i++) this.push(collection[i]);
return this;
}.protect(),
empty: function(){
while (this.length) delete this[--this.length];
return this;
}.protect()
});
(function(){
// FF, IE
var splice = Array.prototype.splice, object = {'0': 0, '1': 1, length: 2};
splice.call(object, 1, 1);
if (object[1] == 1) Elements.implement('splice', function(){
var length = this.length;
var result = splice.apply(this, arguments);
while (length >= this.length) delete this[length--];
return result;
}.protect());
Array.forEachMethod(function(method, name){
Elements.implement(name, method);
});
Array.mirror(Elements);
/*<ltIE8>*/
var createElementAcceptsHTML;
try {
createElementAcceptsHTML = (document.createElement('<input name=x>').name == 'x');
} catch (e){}
var escapeQuotes = function(html){
return ('' + html).replace(/&/g, '&').replace(/"/g, '"');
};
/*</ltIE8>*/
Document.implement({
newElement: function(tag, props){
if (props && props.checked != null) props.defaultChecked = props.checked;
/*<ltIE8>*/// Fix for readonly name and type properties in IE < 8
if (createElementAcceptsHTML && props){
tag = '<' + tag;
if (props.name) tag += ' name="' + escapeQuotes(props.name) + '"';
if (props.type) tag += ' type="' + escapeQuotes(props.type) + '"';
tag += '>';
delete props.name;
delete props.type;
}
/*</ltIE8>*/
return this.id(this.createElement(tag)).set(props);
}
});
})();
(function(){
Slick.uidOf(window);
Slick.uidOf(document);
Document.implement({
newTextNode: function(text){
return this.createTextNode(text);
},
getDocument: function(){
return this;
},
getWindow: function(){
return this.window;
},
id: (function(){
var types = {
string: function(id, nocash, doc){
id = Slick.find(doc, '#' + id.replace(/(\W)/g, '\\$1'));
return (id) ? types.element(id, nocash) : null;
},
element: function(el, nocash){
Slick.uidOf(el);
if (!nocash && !el.$family && !(/^(?:object|embed)$/i).test(el.tagName)){
var fireEvent = el.fireEvent;
// wrapping needed in IE7, or else crash
el._fireEvent = function(type, event){
return fireEvent(type, event);
};
Object.append(el, Element.Prototype);
}
return el;
},
object: function(obj, nocash, doc){
if (obj.toElement) return types.element(obj.toElement(doc), nocash);
return null;
}
};
types.textnode = types.whitespace = types.window = types.document = function(zero){
return zero;
};
return function(el, nocash, doc){
if (el && el.$family && el.uniqueNumber) return el;
var type = typeOf(el);
return (types[type]) ? types[type](el, nocash, doc || document) : null;
};
})()
});
if (window.$ == null) Window.implement('$', function(el, nc){
return document.id(el, nc, this.document);
});
Window.implement({
getDocument: function(){
return this.document;
},
getWindow: function(){
return this;
}
});
[Document, Element].invoke('implement', {
getElements: function(expression){
return Slick.search(this, expression, new Elements);
},
getElement: function(expression){
return document.id(Slick.find(this, expression));
}
});
var contains = {contains: function(element){
return Slick.contains(this, element);
}};
if (!document.contains) Document.implement(contains);
if (!document.createElement('div').contains) Element.implement(contains);
// tree walking
var injectCombinator = function(expression, combinator){
if (!expression) return combinator;
expression = Object.clone(Slick.parse(expression));
var expressions = expression.expressions;
for (var i = expressions.length; i--;)
expressions[i][0].combinator = combinator;
return expression;
};
Object.forEach({
getNext: '~',
getPrevious: '!~',
getParent: '!'
}, function(combinator, method){
Element.implement(method, function(expression){
return this.getElement(injectCombinator(expression, combinator));
});
});
Object.forEach({
getAllNext: '~',
getAllPrevious: '!~',
getSiblings: '~~',
getChildren: '>',
getParents: '!'
}, function(combinator, method){
Element.implement(method, function(expression){
return this.getElements(injectCombinator(expression, combinator));
});
});
Element.implement({
getFirst: function(expression){
return document.id(Slick.search(this, injectCombinator(expression, '>'))[0]);
},
getLast: function(expression){
return document.id(Slick.search(this, injectCombinator(expression, '>')).getLast());
},
getWindow: function(){
return this.ownerDocument.window;
},
getDocument: function(){
return this.ownerDocument;
},
getElementById: function(id){
return document.id(Slick.find(this, '#' + ('' + id).replace(/(\W)/g, '\\$1')));
},
match: function(expression){
return !expression || Slick.match(this, expression);
}
});
if (window.$$ == null) Window.implement('$$', function(selector){
if (arguments.length == 1){
if (typeof selector == 'string') return Slick.search(this.document, selector, new Elements);
else if (Type.isEnumerable(selector)) return new Elements(selector);
}
return new Elements(arguments);
});
// Inserters
var inserters = {
before: function(context, element){
var parent = element.parentNode;
if (parent) parent.insertBefore(context, element);
},
after: function(context, element){
var parent = element.parentNode;
if (parent) parent.insertBefore(context, element.nextSibling);
},
bottom: function(context, element){
element.appendChild(context);
},
top: function(context, element){
element.insertBefore(context, element.firstChild);
}
};
inserters.inside = inserters.bottom;
// getProperty / setProperty
var propertyGetters = {}, propertySetters = {};
// properties
var properties = {};
Array.forEach([
'type', 'value', 'defaultValue', 'accessKey', 'cellPadding', 'cellSpacing', 'colSpan',
'frameBorder', 'rowSpan', 'tabIndex', 'useMap'
], function(property){
properties[property.toLowerCase()] = property;
});
properties.html = 'innerHTML';
properties.text = (document.createElement('div').textContent == null) ? 'innerText': 'textContent';
Object.forEach(properties, function(real, key){
propertySetters[key] = function(node, value){
node[real] = value;
};
propertyGetters[key] = function(node){
return node[real];
};
});
// Booleans
var bools = [
'compact', 'nowrap', 'ismap', 'declare', 'noshade', 'checked',
'disabled', 'readOnly', 'multiple', 'selected', 'noresize',
'defer', 'defaultChecked', 'autofocus', 'controls', 'autoplay',
'loop'
];
var booleans = {};
Array.forEach(bools, function(bool){
var lower = bool.toLowerCase();
booleans[lower] = bool;
propertySetters[lower] = function(node, value){
node[bool] = !!value;
};
propertyGetters[lower] = function(node){
return !!node[bool];
};
});
// Special cases
Object.append(propertySetters, {
'class': function(node, value){
('className' in node) ? node.className = (value || '') : node.setAttribute('class', value);
},
'for': function(node, value){
('htmlFor' in node) ? node.htmlFor = value : node.setAttribute('for', value);
},
'style': function(node, value){
(node.style) ? node.style.cssText = value : node.setAttribute('style', value);
},
'value': function(node, value){
node.value = (value != null) ? value : '';
}
});
propertyGetters['class'] = function(node){
return ('className' in node) ? node.className || null : node.getAttribute('class');
};
/* <webkit> */
var el = document.createElement('button');
// IE sets type as readonly and throws
try { el.type = 'button'; } catch(e){}
if (el.type != 'button') propertySetters.type = function(node, value){
node.setAttribute('type', value);
};
el = null;
/* </webkit> */
/*<IE>*/
var input = document.createElement('input');
input.value = 't';
input.type = 'submit';
if (input.value != 't') propertySetters.type = function(node, type){
var value = node.value;
node.type = type;
node.value = value;
};
input = null;
/*</IE>*/
/* getProperty, setProperty */
/* <ltIE9> */
var pollutesGetAttribute = (function(div){
div.random = 'attribute';
return (div.getAttribute('random') == 'attribute');
})(document.createElement('div'));
/* <ltIE9> */
Element.implement({
setProperty: function(name, value){
var setter = propertySetters[name.toLowerCase()];
if (setter){
setter(this, value);
} else {
/* <ltIE9> */
if (pollutesGetAttribute) var attributeWhiteList = this.retrieve('$attributeWhiteList', {});
/* </ltIE9> */
if (value == null){
this.removeAttribute(name);
/* <ltIE9> */
if (pollutesGetAttribute) delete attributeWhiteList[name];
/* </ltIE9> */
} else {
this.setAttribute(name, '' + value);
/* <ltIE9> */
if (pollutesGetAttribute) attributeWhiteList[name] = true;
/* </ltIE9> */
}
}
return this;
},
setProperties: function(attributes){
for (var attribute in attributes) this.setProperty(attribute, attributes[attribute]);
return this;
},
getProperty: function(name){
var getter = propertyGetters[name.toLowerCase()];
if (getter) return getter(this);
/* <ltIE9> */
if (pollutesGetAttribute){
var attr = this.getAttributeNode(name), attributeWhiteList = this.retrieve('$attributeWhiteList', {});
if (!attr) return null;
if (attr.expando && !attributeWhiteList[name]){
var outer = this.outerHTML;
// segment by the opening tag and find mention of attribute name
if (outer.substr(0, outer.search(/\/?['"]?>(?![^<]*<['"])/)).indexOf(name) < 0) return null;
attributeWhiteList[name] = true;
}
}
/* </ltIE9> */
var result = Slick.getAttribute(this, name);
return (!result && !Slick.hasAttribute(this, name)) ? null : result;
},
getProperties: function(){
var args = Array.from(arguments);
return args.map(this.getProperty, this).associate(args);
},
removeProperty: function(name){
return this.setProperty(name, null);
},
removeProperties: function(){
Array.each(arguments, this.removeProperty, this);
return this;
},
set: function(prop, value){
var property = Element.Properties[prop];
(property && property.set) ? property.set.call(this, value) : this.setProperty(prop, value);
}.overloadSetter(),
get: function(prop){
var property = Element.Properties[prop];
return (property && property.get) ? property.get.apply(this) : this.getProperty(prop);
}.overloadGetter(),
erase: function(prop){
var property = Element.Properties[prop];
(property && property.erase) ? property.erase.apply(this) : this.removeProperty(prop);
return this;
},
hasClass: function(className){
return this.className.clean().contains(className, ' ');
},
addClass: function(className){
if (!this.hasClass(className)) this.className = (this.className + ' ' + className).clean();
return this;
},
removeClass: function(className){
this.className = this.className.replace(new RegExp('(^|\\s)' + className + '(?:\\s|$)'), '$1');
return this;
},
toggleClass: function(className, force){
if (force == null) force = !this.hasClass(className);
return (force) ? this.addClass(className) : this.removeClass(className);
},
adopt: function(){
var parent = this, fragment, elements = Array.flatten(arguments), length = elements.length;
if (length > 1) parent = fragment = document.createDocumentFragment();
for (var i = 0; i < length; i++){
var element = document.id(elements[i], true);
if (element) parent.appendChild(element);
}
if (fragment) this.appendChild(fragment);
return this;
},
appendText: function(text, where){
return this.grab(this.getDocument().newTextNode(text), where);
},
grab: function(el, where){
inserters[where || 'bottom'](document.id(el, true), this);
return this;
},
inject: function(el, where){
inserters[where || 'bottom'](this, document.id(el, true));
return this;
},
replaces: function(el){
el = document.id(el, true);
el.parentNode.replaceChild(this, el);
return this;
},
wraps: function(el, where){
el = document.id(el, true);
return this.replaces(el).grab(el, where);
},
getSelected: function(){
this.selectedIndex; // Safari 3.2.1
return new Elements(Array.from(this.options).filter(function(option){
return option.selected;
}));
},
toQueryString: function(){
var queryString = [];
this.getElements('input, select, textarea').each(function(el){
var type = el.type;
if (!el.name || el.disabled || type == 'submit' || type == 'reset' || type == 'file' || type == 'image') return;
var value = (el.get('tag') == 'select') ? el.getSelected().map(function(opt){
// IE
return document.id(opt).get('value');
}) : ((type == 'radio' || type == 'checkbox') && !el.checked) ? null : el.get('value');
Array.from(value).each(function(val){
if (typeof val != 'undefined') queryString.push(encodeURIComponent(el.name) + '=' + encodeURIComponent(val));
});
});
return queryString.join('&');
}
});
var collected = {}, storage = {};
var get = function(uid){
return (storage[uid] || (storage[uid] = {}));
};
var clean = function(item){
var uid = item.uniqueNumber;
if (item.removeEvents) item.removeEvents();
if (item.clearAttributes) item.clearAttributes();
if (uid != null){
delete collected[uid];
delete storage[uid];
}
return item;
};
var formProps = {input: 'checked', option: 'selected', textarea: 'value'};
Element.implement({
destroy: function(){
var children = clean(this).getElementsByTagName('*');
Array.each(children, clean);
Element.dispose(this);
return null;
},
empty: function(){
Array.from(this.childNodes).each(Element.dispose);
return this;
},
dispose: function(){
return (this.parentNode) ? this.parentNode.removeChild(this) : this;
},
clone: function(contents, keepid){
contents = contents !== false;
var clone = this.cloneNode(contents), ce = [clone], te = [this], i;
if (contents){
ce.append(Array.from(clone.getElementsByTagName('*')));
te.append(Array.from(this.getElementsByTagName('*')));
}
for (i = ce.length; i--;){
var node = ce[i], element = te[i];
if (!keepid) node.removeAttribute('id');
/*<ltIE9>*/
if (node.clearAttributes){
node.clearAttributes();
node.mergeAttributes(element);
node.removeAttribute('uniqueNumber');
if (node.options){
var no = node.options, eo = element.options;
for (var j = no.length; j--;) no[j].selected = eo[j].selected;
}
}
/*</ltIE9>*/
var prop = formProps[element.tagName.toLowerCase()];
if (prop && element[prop]) node[prop] = element[prop];
}
/*<ltIE9>*/
if (Browser.ie){
var co = clone.getElementsByTagName('object'), to = this.getElementsByTagName('object');
for (i = co.length; i--;) co[i].outerHTML = to[i].outerHTML;
}
/*</ltIE9>*/
return document.id(clone);
}
});
[Element, Window, Document].invoke('implement', {
addListener: function(type, fn){
if (type == 'unload'){
var old = fn, self = this;
fn = function(){
self.removeListener('unload', fn);
old();
};
} else {
collected[Slick.uidOf(this)] = this;
}
if (this.addEventListener) this.addEventListener(type, fn, !!arguments[2]);
else this.attachEvent('on' + type, fn);
return this;
},
removeListener: function(type, fn){
if (this.removeEventListener) this.removeEventListener(type, fn, !!arguments[2]);
else this.detachEvent('on' + type, fn);
return this;
},
retrieve: function(property, dflt){
var storage = get(Slick.uidOf(this)), prop = storage[property];
if (dflt != null && prop == null) prop = storage[property] = dflt;
return prop != null ? prop : null;
},
store: function(property, value){
var storage = get(Slick.uidOf(this));
storage[property] = value;
return this;
},
eliminate: function(property){
var storage = get(Slick.uidOf(this));
delete storage[property];
return this;
}
});
/*<ltIE9>*/
if (window.attachEvent && !window.addEventListener) window.addListener('unload', function(){
Object.each(collected, clean);
if (window.CollectGarbage) CollectGarbage();
});
/*</ltIE9>*/
Element.Properties = {};
Element.Properties.style = {
set: function(style){
this.style.cssText = style;
},
get: function(){
return this.style.cssText;
},
erase: function(){
this.style.cssText = '';
}
};
Element.Properties.tag = {
get: function(){
return this.tagName.toLowerCase();
}
};
Element.Properties.html = {
set: function(html){
if (html == null) html = '';
else if (typeOf(html) == 'array') html = html.join('');
this.innerHTML = html;
},
erase: function(){
this.innerHTML = '';
}
};
/*<ltIE9>*/
// technique by jdbarlett - http://jdbartlett.com/innershiv/
var div = document.createElement('div');
div.innerHTML = '<nav></nav>';
var supportsHTML5Elements = (div.childNodes.length == 1);
if (!supportsHTML5Elements){
var tags = 'abbr article aside audio canvas datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video'.split(' '),
fragment = document.createDocumentFragment(), l = tags.length;
while (l--) fragment.createElement(tags[l]);
}
div = null;
/*</ltIE9>*/
/*<IE>*/
var supportsTableInnerHTML = Function.attempt(function(){
var table = document.createElement('table');
table.innerHTML = '<tr><td></td></tr>';
return true;
});
/*<ltFF4>*/
var tr = document.createElement('tr'), html = '<td></td>';
tr.innerHTML = html;
var supportsTRInnerHTML = (tr.innerHTML == html);
tr = null;
/*</ltFF4>*/
if (!supportsTableInnerHTML || !supportsTRInnerHTML || !supportsHTML5Elements){
Element.Properties.html.set = (function(set){
var translations = {
table: [1, '<table>', '</table>'],
select: [1, '<select>', '</select>'],
tbody: [2, '<table><tbody>', '</tbody></table>'],
tr: [3, '<table><tbody><tr>', '</tr></tbody></table>']
};
translations.thead = translations.tfoot = translations.tbody;
return function(html){
var wrap = translations[this.get('tag')];
if (!wrap && !supportsHTML5Elements) wrap = [0, '', ''];
if (!wrap) return set.call(this, html);
var level = wrap[0], wrapper = document.createElement('div'), target = wrapper;
if (!supportsHTML5Elements) fragment.appendChild(wrapper);
wrapper.innerHTML = [wrap[1], html, wrap[2]].flatten().join('');
while (level--) target = target.firstChild;
this.empty().adopt(target.childNodes);
if (!supportsHTML5Elements) fragment.removeChild(wrapper);
wrapper = null;
};
})(Element.Properties.html.set);
}
/*</IE>*/
/*<ltIE9>*/
var testForm = document.createElement('form');
testForm.innerHTML = '<select><option>s</option></select>';
if (testForm.firstChild.value != 's') Element.Properties.value = {
set: function(value){
var tag = this.get('tag');
if (tag != 'select') return this.setProperty('value', value);
var options = this.getElements('option');
for (var i = 0; i < options.length; i++){
var option = options[i],
attr = option.getAttributeNode('value'),
optionValue = (attr && attr.specified) ? option.value : option.get('text');
if (optionValue == value) return option.selected = true;
}
},
get: function(){
var option = this, tag = option.get('tag');
if (tag != 'select' && tag != 'option') return this.getProperty('value');
if (tag == 'select' && !(option = option.getSelected()[0])) return '';
var attr = option.getAttributeNode('value');
return (attr && attr.specified) ? option.value : option.get('text');
}
};
testForm = null;
/*</ltIE9>*/
/*<IE>*/
if (document.createElement('div').getAttributeNode('id')) Element.Properties.id = {
set: function(id){
this.id = this.getAttributeNode('id').value = id;
},
get: function(){
return this.id || null;
},
erase: function(){
this.id = this.getAttributeNode('id').value = '';
}
};
/*</IE>*/
})();
/*
---
name: Element.Style
description: Contains methods for interacting with the styles of Elements in a fashionable way.
license: MIT-style license.
requires: Element
provides: Element.Style
...
*/
(function(){
var html = document.html;
//<ltIE9>
// Check for oldIE, which does not remove styles when they're set to null
var el = document.createElement('div');
el.style.color = 'red';
el.style.color = null;
var doesNotRemoveStyles = el.style.color == 'red';
el = null;
//</ltIE9>
Element.Properties.styles = {set: function(styles){
this.setStyles(styles);
}};
var hasOpacity = (html.style.opacity != null),
hasFilter = (html.style.filter != null),
reAlpha = /alpha\(opacity=([\d.]+)\)/i;
var setVisibility = function(element, opacity){
element.store('$opacity', opacity);
element.style.visibility = opacity > 0 || opacity == null ? 'visible' : 'hidden';
};
var setOpacity = (hasOpacity ? function(element, opacity){
element.style.opacity = opacity;
} : (hasFilter ? function(element, opacity){
var style = element.style;
if (!element.currentStyle || !element.currentStyle.hasLayout) style.zoom = 1;
if (opacity == null || opacity == 1) opacity = '';
else opacity = 'alpha(opacity=' + (opacity * 100).limit(0, 100).round() + ')';
var filter = style.filter || element.getComputedStyle('filter') || '';
style.filter = reAlpha.test(filter) ? filter.replace(reAlpha, opacity) : filter + opacity;
if (!style.filter) style.removeAttribute('filter');
} : setVisibility));
var getOpacity = (hasOpacity ? function(element){
var opacity = element.style.opacity || element.getComputedStyle('opacity');
return (opacity == '') ? 1 : opacity.toFloat();
} : (hasFilter ? function(element){
var filter = (element.style.filter || element.getComputedStyle('filter')),
opacity;
if (filter) opacity = filter.match(reAlpha);
return (opacity == null || filter == null) ? 1 : (opacity[1] / 100);
} : function(element){
var opacity = element.retrieve('$opacity');
if (opacity == null) opacity = (element.style.visibility == 'hidden' ? 0 : 1);
return opacity;
}));
var floatName = (html.style.cssFloat == null) ? 'styleFloat' : 'cssFloat';
Element.implement({
getComputedStyle: function(property){
if (this.currentStyle) return this.currentStyle[property.camelCase()];
var defaultView = Element.getDocument(this).defaultView,
computed = defaultView ? defaultView.getComputedStyle(this, null) : null;
return (computed) ? computed.getPropertyValue((property == floatName) ? 'float' : property.hyphenate()) : null;
},
setStyle: function(property, value){
if (property == 'opacity'){
if (value != null) value = parseFloat(value);
setOpacity(this, value);
return this;
}
property = (property == 'float' ? floatName : property).camelCase();
if (typeOf(value) != 'string'){
var map = (Element.Styles[property] || '@').split(' ');
value = Array.from(value).map(function(val, i){
if (!map[i]) return '';
return (typeOf(val) == 'number') ? map[i].replace('@', Math.round(val)) : val;
}).join(' ');
} else if (value == String(Number(value))){
value = Math.round(value);
}
this.style[property] = value;
//<ltIE9>
if ((value == '' || value == null) && doesNotRemoveStyles && this.style.removeAttribute){
this.style.removeAttribute(property);
}
//</ltIE9>
return this;
},
getStyle: function(property){
if (property == 'opacity') return getOpacity(this);
property = (property == 'float' ? floatName : property).camelCase();
var result = this.style[property];
if (!result || property == 'zIndex'){
result = [];
for (var style in Element.ShortStyles){
if (property != style) continue;
for (var s in Element.ShortStyles[style]) result.push(this.getStyle(s));
return result.join(' ');
}
result = this.getComputedStyle(property);
}
if (result){
result = String(result);
var color = result.match(/rgba?\([\d\s,]+\)/);
if (color) result = result.replace(color[0], color[0].rgbToHex());
}
if (Browser.opera || Browser.ie){
if ((/^(height|width)$/).test(property) && !(/px$/.test(result))){
var values = (property == 'width') ? ['left', 'right'] : ['top', 'bottom'], size = 0;
values.each(function(value){
size += this.getStyle('border-' + value + '-width').toInt() + this.getStyle('padding-' + value).toInt();
}, this);
return this['offset' + property.capitalize()] - size + 'px';
}
if (Browser.ie && (/^border(.+)Width|margin|padding/).test(property) && isNaN(parseFloat(result))){
return '0px';
}
}
return result;
},
setStyles: function(styles){
for (var style in styles) this.setStyle(style, styles[style]);
return this;
},
getStyles: function(){
var result = {};
Array.flatten(arguments).each(function(key){
result[key] = this.getStyle(key);
}, this);
return result;
}
});
Element.Styles = {
left: '@px', top: '@px', bottom: '@px', right: '@px',
width: '@px', height: '@px', maxWidth: '@px', maxHeight: '@px', minWidth: '@px', minHeight: '@px',
backgroundColor: 'rgb(@, @, @)', backgroundPosition: '@px @px', color: 'rgb(@, @, @)',
fontSize: '@px', letterSpacing: '@px', lineHeight: '@px', clip: 'rect(@px @px @px @px)',
margin: '@px @px @px @px', padding: '@px @px @px @px', border: '@px @ rgb(@, @, @) @px @ rgb(@, @, @) @px @ rgb(@, @, @)',
borderWidth: '@px @px @px @px', borderStyle: '@ @ @ @', borderColor: 'rgb(@, @, @) rgb(@, @, @) rgb(@, @, @) rgb(@, @, @)',
zIndex: '@', 'zoom': '@', fontWeight: '@', textIndent: '@px', opacity: '@'
};
Element.ShortStyles = {margin: {}, padding: {}, border: {}, borderWidth: {}, borderStyle: {}, borderColor: {}};
['Top', 'Right', 'Bottom', 'Left'].each(function(direction){
var Short = Element.ShortStyles;
var All = Element.Styles;
['margin', 'padding'].each(function(style){
var sd = style + direction;
Short[style][sd] = All[sd] = '@px';
});
var bd = 'border' + direction;
Short.border[bd] = All[bd] = '@px @ rgb(@, @, @)';
var bdw = bd + 'Width', bds = bd + 'Style', bdc = bd + 'Color';
Short[bd] = {};
Short.borderWidth[bdw] = Short[bd][bdw] = All[bdw] = '@px';
Short.borderStyle[bds] = Short[bd][bds] = All[bds] = '@';
Short.borderColor[bdc] = Short[bd][bdc] = All[bdc] = 'rgb(@, @, @)';
});
})();
/*
---
name: Element.Event
description: Contains Element methods for dealing with events. This file also includes mouseenter and mouseleave custom Element Events, if necessary.
license: MIT-style license.
requires: [Element, Event]
provides: Element.Event
...
*/
(function(){
Element.Properties.events = {set: function(events){
this.addEvents(events);
}};
[Element, Window, Document].invoke('implement', {
addEvent: function(type, fn){
var events = this.retrieve('events', {});
if (!events[type]) events[type] = {keys: [], values: []};
if (events[type].keys.contains(fn)) return this;
events[type].keys.push(fn);
var realType = type,
custom = Element.Events[type],
condition = fn,
self = this;
if (custom){
if (custom.onAdd) custom.onAdd.call(this, fn, type);
if (custom.condition){
condition = function(event){
if (custom.condition.call(this, event, type)) return fn.call(this, event);
return true;
};
}
if (custom.base) realType = Function.from(custom.base).call(this, type);
}
var defn = function(){
return fn.call(self);
};
var nativeEvent = Element.NativeEvents[realType];
if (nativeEvent){
if (nativeEvent == 2){
defn = function(event){
event = new DOMEvent(event, self.getWindow());
if (condition.call(self, event) === false) event.stop();
};
}
this.addListener(realType, defn, arguments[2]);
}
events[type].values.push(defn);
return this;
},
removeEvent: function(type, fn){
var events = this.retrieve('events');
if (!events || !events[type]) return this;
var list = events[type];
var index = list.keys.indexOf(fn);
if (index == -1) return this;
var value = list.values[index];
delete list.keys[index];
delete list.values[index];
var custom = Element.Events[type];
if (custom){
if (custom.onRemove) custom.onRemove.call(this, fn, type);
if (custom.base) type = Function.from(custom.base).call(this, type);
}
return (Element.NativeEvents[type]) ? this.removeListener(type, value, arguments[2]) : this;
},
addEvents: function(events){
for (var event in events) this.addEvent(event, events[event]);
return this;
},
removeEvents: function(events){
var type;
if (typeOf(events) == 'object'){
for (type in events) this.removeEvent(type, events[type]);
return this;
}
var attached = this.retrieve('events');
if (!attached) return this;
if (!events){
for (type in attached) this.removeEvents(type);
this.eliminate('events');
} else if (attached[events]){
attached[events].keys.each(function(fn){
this.removeEvent(events, fn);
}, this);
delete attached[events];
}
return this;
},
fireEvent: function(type, args, delay){
var events = this.retrieve('events');
if (!events || !events[type]) return this;
args = Array.from(args);
events[type].keys.each(function(fn){
if (delay) fn.delay(delay, this, args);
else fn.apply(this, args);
}, this);
return this;
},
cloneEvents: function(from, type){
from = document.id(from);
var events = from.retrieve('events');
if (!events) return this;
if (!type){
for (var eventType in events) this.cloneEvents(from, eventType);
} else if (events[type]){
events[type].keys.each(function(fn){
this.addEvent(type, fn);
}, this);
}
return this;
}
});
Element.NativeEvents = {
click: 2, dblclick: 2, mouseup: 2, mousedown: 2, contextmenu: 2, //mouse buttons
mousewheel: 2, DOMMouseScroll: 2, //mouse wheel
mouseover: 2, mouseout: 2, mousemove: 2, selectstart: 2, selectend: 2, //mouse movement
keydown: 2, keypress: 2, keyup: 2, //keyboard
orientationchange: 2, // mobile
touchstart: 2, touchmove: 2, touchend: 2, touchcancel: 2, // touch
gesturestart: 2, gesturechange: 2, gestureend: 2, // gesture
focus: 2, blur: 2, change: 2, reset: 2, select: 2, submit: 2, paste: 2, input: 2, //form elements
load: 2, unload: 1, beforeunload: 2, resize: 1, move: 1, DOMContentLoaded: 1, readystatechange: 1, //window
error: 1, abort: 1, scroll: 1 //misc
};
Element.Events = {mousewheel: {
base: (Browser.firefox) ? 'DOMMouseScroll' : 'mousewheel'
}};
if ('onmouseenter' in document.documentElement){
Element.NativeEvents.mouseenter = Element.NativeEvents.mouseleave = 2;
} else {
var check = function(event){
var related = event.relatedTarget;
if (related == null) return true;
if (!related) return false;
return (related != this && related.prefix != 'xul' && typeOf(this) != 'document' && !this.contains(related));
};
Element.Events.mouseenter = {
base: 'mouseover',
condition: check
};
Element.Events.mouseleave = {
base: 'mouseout',
condition: check
};
}
/*<ltIE9>*/
if (!window.addEventListener){
Element.NativeEvents.propertychange = 2;
Element.Events.change = {
base: function(){
var type = this.type;
return (this.get('tag') == 'input' && (type == 'radio' || type == 'checkbox')) ? 'propertychange' : 'change'
},
condition: function(event){
return this.type != 'radio' || (event.event.propertyName == 'checked' && this.checked);
}
}
}
/*</ltIE9>*/
})();
/*
---
name: Element.Delegation
description: Extends the Element native object to include the delegate method for more efficient event management.
license: MIT-style license.
requires: [Element.Event]
provides: [Element.Delegation]
...
*/
(function(){
var eventListenerSupport = !!window.addEventListener;
Element.NativeEvents.focusin = Element.NativeEvents.focusout = 2;
var bubbleUp = function(self, match, fn, event, target){
while (target && target != self){
if (match(target, event)) return fn.call(target, event, target);
target = document.id(target.parentNode);
}
};
var map = {
mouseenter: {
base: 'mouseover'
},
mouseleave: {
base: 'mouseout'
},
focus: {
base: 'focus' + (eventListenerSupport ? '' : 'in'),
capture: true
},
blur: {
base: eventListenerSupport ? 'blur' : 'focusout',
capture: true
}
};
/*<ltIE9>*/
var _key = '$delegation:';
var formObserver = function(type){
return {
base: 'focusin',
remove: function(self, uid){
var list = self.retrieve(_key + type + 'listeners', {})[uid];
if (list && list.forms) for (var i = list.forms.length; i--;){
list.forms[i].removeEvent(type, list.fns[i]);
}
},
listen: function(self, match, fn, event, target, uid){
var form = (target.get('tag') == 'form') ? target : event.target.getParent('form');
if (!form) return;
var listeners = self.retrieve(_key + type + 'listeners', {}),
listener = listeners[uid] || {forms: [], fns: []},
forms = listener.forms, fns = listener.fns;
if (forms.indexOf(form) != -1) return;
forms.push(form);
var _fn = function(event){
bubbleUp(self, match, fn, event, target);
};
form.addEvent(type, _fn);
fns.push(_fn);
listeners[uid] = listener;
self.store(_key + type + 'listeners', listeners);
}
};
};
var inputObserver = function(type){
return {
base: 'focusin',
listen: function(self, match, fn, event, target){
var events = {blur: function(){
this.removeEvents(events);
}};
events[type] = function(event){
bubbleUp(self, match, fn, event, target);
};
event.target.addEvents(events);
}
};
};
if (!eventListenerSupport) Object.append(map, {
submit: formObserver('submit'),
reset: formObserver('reset'),
change: inputObserver('change'),
select: inputObserver('select')
});
/*</ltIE9>*/
var proto = Element.prototype,
addEvent = proto.addEvent,
removeEvent = proto.removeEvent;
var relay = function(old, method){
return function(type, fn, useCapture){
if (type.indexOf(':relay') == -1) return old.call(this, type, fn, useCapture);
var parsed = Slick.parse(type).expressions[0][0];
if (parsed.pseudos[0].key != 'relay') return old.call(this, type, fn, useCapture);
var newType = parsed.tag;
parsed.pseudos.slice(1).each(function(pseudo){
newType += ':' + pseudo.key + (pseudo.value ? '(' + pseudo.value + ')' : '');
});
old.call(this, type, fn);
return method.call(this, newType, parsed.pseudos[0].value, fn);
};
};
var delegation = {
addEvent: function(type, match, fn){
var storage = this.retrieve('$delegates', {}), stored = storage[type];
if (stored) for (var _uid in stored){
if (stored[_uid].fn == fn && stored[_uid].match == match) return this;
}
var _type = type, _match = match, _fn = fn, _map = map[type] || {};
type = _map.base || _type;
match = function(target){
return Slick.match(target, _match);
};
var elementEvent = Element.Events[_type];
if (elementEvent && elementEvent.condition){
var __match = match, condition = elementEvent.condition;
match = function(target, event){
return __match(target, event) && condition.call(target, event, type);
};
}
var self = this, uid = String.uniqueID();
var delegator = _map.listen ? function(event, target){
if (!target && event && event.target) target = event.target;
if (target) _map.listen(self, match, fn, event, target, uid);
} : function(event, target){
if (!target && event && event.target) target = event.target;
if (target) bubbleUp(self, match, fn, event, target);
};
if (!stored) stored = {};
stored[uid] = {
match: _match,
fn: _fn,
delegator: delegator
};
storage[_type] = stored;
return addEvent.call(this, type, delegator, _map.capture);
},
removeEvent: function(type, match, fn, _uid){
var storage = this.retrieve('$delegates', {}), stored = storage[type];
if (!stored) return this;
if (_uid){
var _type = type, delegator = stored[_uid].delegator, _map = map[type] || {};
type = _map.base || _type;
if (_map.remove) _map.remove(this, _uid);
delete stored[_uid];
storage[_type] = stored;
return removeEvent.call(this, type, delegator);
}
var __uid, s;
if (fn) for (__uid in stored){
s = stored[__uid];
if (s.match == match && s.fn == fn) return delegation.removeEvent.call(this, type, match, fn, __uid);
} else for (__uid in stored){
s = stored[__uid];
if (s.match == match) delegation.removeEvent.call(this, type, match, s.fn, __uid);
}
return this;
}
};
[Element, Window, Document].invoke('implement', {
addEvent: relay(addEvent, delegation.addEvent),
removeEvent: relay(removeEvent, delegation.removeEvent)
});
})();
/*
---
name: Element.Dimensions
description: Contains methods to work with size, scroll, or positioning of Elements and the window object.
license: MIT-style license.
credits:
- Element positioning based on the [qooxdoo](http://qooxdoo.org/) code and smart browser fixes, [LGPL License](http://www.gnu.org/licenses/lgpl.html).
- Viewport dimensions based on [YUI](http://developer.yahoo.com/yui/) code, [BSD License](http://developer.yahoo.com/yui/license.html).
requires: [Element, Element.Style]
provides: [Element.Dimensions]
...
*/
(function(){
var element = document.createElement('div'),
child = document.createElement('div');
element.style.height = '0';
element.appendChild(child);
var brokenOffsetParent = (child.offsetParent === element);
element = child = null;
var isOffset = function(el){
return styleString(el, 'position') != 'static' || isBody(el);
};
var isOffsetStatic = function(el){
return isOffset(el) || (/^(?:table|td|th)$/i).test(el.tagName);
};
Element.implement({
scrollTo: function(x, y){
if (isBody(this)){
this.getWindow().scrollTo(x, y);
} else {
this.scrollLeft = x;
this.scrollTop = y;
}
return this;
},
getSize: function(){
if (isBody(this)) return this.getWindow().getSize();
return {x: this.offsetWidth, y: this.offsetHeight};
},
getScrollSize: function(){
if (isBody(this)) return this.getWindow().getScrollSize();
return {x: this.scrollWidth, y: this.scrollHeight};
},
getScroll: function(){
if (isBody(this)) return this.getWindow().getScroll();
return {x: this.scrollLeft, y: this.scrollTop};
},
getScrolls: function(){
var element = this.parentNode, position = {x: 0, y: 0};
while (element && !isBody(element)){
position.x += element.scrollLeft;
position.y += element.scrollTop;
element = element.parentNode;
}
return position;
},
getOffsetParent: brokenOffsetParent ? function(){
var element = this;
if (isBody(element) || styleString(element, 'position') == 'fixed') return null;
var isOffsetCheck = (styleString(element, 'position') == 'static') ? isOffsetStatic : isOffset;
while ((element = element.parentNode)){
if (isOffsetCheck(element)) return element;
}
return null;
} : function(){
var element = this;
if (isBody(element) || styleString(element, 'position') == 'fixed') return null;
try {
return element.offsetParent;
} catch(e) {}
return null;
},
getOffsets: function(){
if (this.getBoundingClientRect && !Browser.Platform.ios){
var bound = this.getBoundingClientRect(),
html = document.id(this.getDocument().documentElement),
htmlScroll = html.getScroll(),
elemScrolls = this.getScrolls(),
isFixed = (styleString(this, 'position') == 'fixed');
return {
x: bound.left.toInt() + elemScrolls.x + ((isFixed) ? 0 : htmlScroll.x) - html.clientLeft,
y: bound.top.toInt() + elemScrolls.y + ((isFixed) ? 0 : htmlScroll.y) - html.clientTop
};
}
var element = this, position = {x: 0, y: 0};
if (isBody(this)) return position;
while (element && !isBody(element)){
position.x += element.offsetLeft;
position.y += element.offsetTop;
if (Browser.firefox){
if (!borderBox(element)){
position.x += leftBorder(element);
position.y += topBorder(element);
}
var parent = element.parentNode;
if (parent && styleString(parent, 'overflow') != 'visible'){
position.x += leftBorder(parent);
position.y += topBorder(parent);
}
} else if (element != this && Browser.safari){
position.x += leftBorder(element);
position.y += topBorder(element);
}
element = element.offsetParent;
}
if (Browser.firefox && !borderBox(this)){
position.x -= leftBorder(this);
position.y -= topBorder(this);
}
return position;
},
getPosition: function(relative){
var offset = this.getOffsets(),
scroll = this.getScrolls();
var position = {
x: offset.x - scroll.x,
y: offset.y - scroll.y
};
if (relative && (relative = document.id(relative))){
var relativePosition = relative.getPosition();
return {x: position.x - relativePosition.x - leftBorder(relative), y: position.y - relativePosition.y - topBorder(relative)};
}
return position;
},
getCoordinates: function(element){
if (isBody(this)) return this.getWindow().getCoordinates();
var position = this.getPosition(element),
size = this.getSize();
var obj = {
left: position.x,
top: position.y,
width: size.x,
height: size.y
};
obj.right = obj.left + obj.width;
obj.bottom = obj.top + obj.height;
return obj;
},
computePosition: function(obj){
return {
left: obj.x - styleNumber(this, 'margin-left'),
top: obj.y - styleNumber(this, 'margin-top')
};
},
setPosition: function(obj){
return this.setStyles(this.computePosition(obj));
}
});
[Document, Window].invoke('implement', {
getSize: function(){
var doc = getCompatElement(this);
return {x: doc.clientWidth, y: doc.clientHeight};
},
getScroll: function(){
var win = this.getWindow(), doc = getCompatElement(this);
return {x: win.pageXOffset || doc.scrollLeft, y: win.pageYOffset || doc.scrollTop};
},
getScrollSize: function(){
var doc = getCompatElement(this),
min = this.getSize(),
body = this.getDocument().body;
return {x: Math.max(doc.scrollWidth, body.scrollWidth, min.x), y: Math.max(doc.scrollHeight, body.scrollHeight, min.y)};
},
getPosition: function(){
return {x: 0, y: 0};
},
getCoordinates: function(){
var size = this.getSize();
return {top: 0, left: 0, bottom: size.y, right: size.x, height: size.y, width: size.x};
}
});
// private methods
var styleString = Element.getComputedStyle;
function styleNumber(element, style){
return styleString(element, style).toInt() || 0;
}
function borderBox(element){
return styleString(element, '-moz-box-sizing') == 'border-box';
}
function topBorder(element){
return styleNumber(element, 'border-top-width');
}
function leftBorder(element){
return styleNumber(element, 'border-left-width');
}
function isBody(element){
return (/^(?:body|html)$/i).test(element.tagName);
}
function getCompatElement(element){
var doc = element.getDocument();
return (!doc.compatMode || doc.compatMode == 'CSS1Compat') ? doc.html : doc.body;
}
})();
//aliases
Element.alias({position: 'setPosition'}); //compatability
[Window, Document, Element].invoke('implement', {
getHeight: function(){
return this.getSize().y;
},
getWidth: function(){
return this.getSize().x;
},
getScrollTop: function(){
return this.getScroll().y;
},
getScrollLeft: function(){
return this.getScroll().x;
},
getScrollHeight: function(){
return this.getScrollSize().y;
},
getScrollWidth: function(){
return this.getScrollSize().x;
},
getTop: function(){
return this.getPosition().y;
},
getLeft: function(){
return this.getPosition().x;
}
});
/*
---
name: Fx
description: Contains the basic animation logic to be extended by all other Fx Classes.
license: MIT-style license.
requires: [Chain, Events, Options]
provides: Fx
...
*/
(function(){
var Fx = this.Fx = new Class({
Implements: [Chain, Events, Options],
options: {
/*
onStart: nil,
onCancel: nil,
onComplete: nil,
*/
fps: 60,
unit: false,
duration: 500,
frames: null,
frameSkip: true,
link: 'ignore'
},
initialize: function(options){
this.subject = this.subject || this;
this.setOptions(options);
},
getTransition: function(){
return function(p){
return -(Math.cos(Math.PI * p) - 1) / 2;
};
},
step: function(now){
if (this.options.frameSkip){
var diff = (this.time != null) ? (now - this.time) : 0, frames = diff / this.frameInterval;
this.time = now;
this.frame += frames;
} else {
this.frame++;
}
if (this.frame < this.frames){
var delta = this.transition(this.frame / this.frames);
this.set(this.compute(this.from, this.to, delta));
} else {
this.frame = this.frames;
this.set(this.compute(this.from, this.to, 1));
this.stop();
}
},
set: function(now){
return now;
},
compute: function(from, to, delta){
return Fx.compute(from, to, delta);
},
check: function(){
if (!this.isRunning()) return true;
switch (this.options.link){
case 'cancel': this.cancel(); return true;
case 'chain': this.chain(this.caller.pass(arguments, this)); return false;
}
return false;
},
start: function(from, to){
if (!this.check(from, to)) return this;
this.from = from;
this.to = to;
this.frame = (this.options.frameSkip) ? 0 : -1;
this.time = null;
this.transition = this.getTransition();
var frames = this.options.frames, fps = this.options.fps, duration = this.options.duration;
this.duration = Fx.Durations[duration] || duration.toInt();
this.frameInterval = 1000 / fps;
this.frames = frames || Math.round(this.duration / this.frameInterval);
this.fireEvent('start', this.subject);
pushInstance.call(this, fps);
return this;
},
stop: function(){
if (this.isRunning()){
this.time = null;
pullInstance.call(this, this.options.fps);
if (this.frames == this.frame){
this.fireEvent('complete', this.subject);
if (!this.callChain()) this.fireEvent('chainComplete', this.subject);
} else {
this.fireEvent('stop', this.subject);
}
}
return this;
},
cancel: function(){
if (this.isRunning()){
this.time = null;
pullInstance.call(this, this.options.fps);
this.frame = this.frames;
this.fireEvent('cancel', this.subject).clearChain();
}
return this;
},
pause: function(){
if (this.isRunning()){
this.time = null;
pullInstance.call(this, this.options.fps);
}
return this;
},
resume: function(){
if ((this.frame < this.frames) && !this.isRunning()) pushInstance.call(this, this.options.fps);
return this;
},
isRunning: function(){
var list = instances[this.options.fps];
return list && list.contains(this);
}
});
Fx.compute = function(from, to, delta){
return (to - from) * delta + from;
};
Fx.Durations = {'short': 250, 'normal': 500, 'long': 1000};
// global timers
var instances = {}, timers = {};
var loop = function(){
var now = Date.now();
for (var i = this.length; i--;){
var instance = this[i];
if (instance) instance.step(now);
}
};
var pushInstance = function(fps){
var list = instances[fps] || (instances[fps] = []);
list.push(this);
if (!timers[fps]) timers[fps] = loop.periodical(Math.round(1000 / fps), list);
};
var pullInstance = function(fps){
var list = instances[fps];
if (list){
list.erase(this);
if (!list.length && timers[fps]){
delete instances[fps];
timers[fps] = clearInterval(timers[fps]);
}
}
};
})();
/*
---
name: Fx.CSS
description: Contains the CSS animation logic. Used by Fx.Tween, Fx.Morph, Fx.Elements.
license: MIT-style license.
requires: [Fx, Element.Style]
provides: Fx.CSS
...
*/
Fx.CSS = new Class({
Extends: Fx,
//prepares the base from/to object
prepare: function(element, property, values){
values = Array.from(values);
var from = values[0], to = values[1];
if (to == null){
to = from;
from = element.getStyle(property);
var unit = this.options.unit;
// adapted from: https://github.com/ryanmorr/fx/blob/master/fx.js#L299
if (unit && from.slice(-unit.length) != unit && parseFloat(from) != 0){
element.setStyle(property, to + unit);
var value = element.getComputedStyle(property);
// IE and Opera support pixelLeft or pixelWidth
if (!(/px$/.test(value))){
value = element.style[('pixel-' + property).camelCase()];
if (value == null){
// adapted from Dean Edwards' http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
var left = element.style.left;
element.style.left = to + unit;
value = element.style.pixelLeft;
element.style.left = left;
}
}
from = (to || 1) / (parseFloat(value) || 1) * (parseFloat(from) || 0);
element.setStyle(property, from + unit);
}
}
return {from: this.parse(from), to: this.parse(to)};
},
//parses a value into an array
parse: function(value){
value = Function.from(value)();
value = (typeof value == 'string') ? value.split(' ') : Array.from(value);
return value.map(function(val){
val = String(val);
var found = false;
Object.each(Fx.CSS.Parsers, function(parser, key){
if (found) return;
var parsed = parser.parse(val);
if (parsed || parsed === 0) found = {value: parsed, parser: parser};
});
found = found || {value: val, parser: Fx.CSS.Parsers.String};
return found;
});
},
//computes by a from and to prepared objects, using their parsers.
compute: function(from, to, delta){
var computed = [];
(Math.min(from.length, to.length)).times(function(i){
computed.push({value: from[i].parser.compute(from[i].value, to[i].value, delta), parser: from[i].parser});
});
computed.$family = Function.from('fx:css:value');
return computed;
},
//serves the value as settable
serve: function(value, unit){
if (typeOf(value) != 'fx:css:value') value = this.parse(value);
var returned = [];
value.each(function(bit){
returned = returned.concat(bit.parser.serve(bit.value, unit));
});
return returned;
},
//renders the change to an element
render: function(element, property, value, unit){
element.setStyle(property, this.serve(value, unit));
},
//searches inside the page css to find the values for a selector
search: function(selector){
if (Fx.CSS.Cache[selector]) return Fx.CSS.Cache[selector];
var to = {}, selectorTest = new RegExp('^' + selector.escapeRegExp() + '$');
Array.each(document.styleSheets, function(sheet, j){
var href = sheet.href;
if (href && href.contains('://') && !href.contains(document.domain)) return;
var rules = sheet.rules || sheet.cssRules;
Array.each(rules, function(rule, i){
if (!rule.style) return;
var selectorText = (rule.selectorText) ? rule.selectorText.replace(/^\w+/, function(m){
return m.toLowerCase();
}) : null;
if (!selectorText || !selectorTest.test(selectorText)) return;
Object.each(Element.Styles, function(value, style){
if (!rule.style[style] || Element.ShortStyles[style]) return;
value = String(rule.style[style]);
to[style] = ((/^rgb/).test(value)) ? value.rgbToHex() : value;
});
});
});
return Fx.CSS.Cache[selector] = to;
}
});
Fx.CSS.Cache = {};
Fx.CSS.Parsers = {
Color: {
parse: function(value){
if (value.match(/^#[0-9a-f]{3,6}$/i)) return value.hexToRgb(true);
return ((value = value.match(/(\d+),\s*(\d+),\s*(\d+)/))) ? [value[1], value[2], value[3]] : false;
},
compute: function(from, to, delta){
return from.map(function(value, i){
return Math.round(Fx.compute(from[i], to[i], delta));
});
},
serve: function(value){
return value.map(Number);
}
},
Number: {
parse: parseFloat,
compute: Fx.compute,
serve: function(value, unit){
return (unit) ? value + unit : value;
}
},
String: {
parse: Function.from(false),
compute: function(zero, one){
return one;
},
serve: function(zero){
return zero;
}
}
};
/*
---
name: Fx.Tween
description: Formerly Fx.Style, effect to transition any CSS property for an element.
license: MIT-style license.
requires: Fx.CSS
provides: [Fx.Tween, Element.fade, Element.highlight]
...
*/
Fx.Tween = new Class({
Extends: Fx.CSS,
initialize: function(element, options){
this.element = this.subject = document.id(element);
this.parent(options);
},
set: function(property, now){
if (arguments.length == 1){
now = property;
property = this.property || this.options.property;
}
this.render(this.element, property, now, this.options.unit);
return this;
},
start: function(property, from, to){
if (!this.check(property, from, to)) return this;
var args = Array.flatten(arguments);
this.property = this.options.property || args.shift();
var parsed = this.prepare(this.element, this.property, args);
return this.parent(parsed.from, parsed.to);
}
});
Element.Properties.tween = {
set: function(options){
this.get('tween').cancel().setOptions(options);
return this;
},
get: function(){
var tween = this.retrieve('tween');
if (!tween){
tween = new Fx.Tween(this, {link: 'cancel'});
this.store('tween', tween);
}
return tween;
}
};
Element.implement({
tween: function(property, from, to){
this.get('tween').start(property, from, to);
return this;
},
fade: function(how){
var fade = this.get('tween'), method, args = ['opacity'].append(arguments), toggle;
if (args[1] == null) args[1] = 'toggle';
switch (args[1]){
case 'in': method = 'start'; args[1] = 1; break;
case 'out': method = 'start'; args[1] = 0; break;
case 'show': method = 'set'; args[1] = 1; break;
case 'hide': method = 'set'; args[1] = 0; break;
case 'toggle':
var flag = this.retrieve('fade:flag', this.getStyle('opacity') == 1);
method = 'start';
args[1] = flag ? 0 : 1;
this.store('fade:flag', !flag);
toggle = true;
break;
default: method = 'start';
}
if (!toggle) this.eliminate('fade:flag');
fade[method].apply(fade, args);
var to = args[args.length - 1];
if (method == 'set' || to != 0) this.setStyle('visibility', to == 0 ? 'hidden' : 'visible');
else fade.chain(function(){
this.element.setStyle('visibility', 'hidden');
this.callChain();
});
return this;
},
highlight: function(start, end){
if (!end){
end = this.retrieve('highlight:original', this.getStyle('background-color'));
end = (end == 'transparent') ? '#fff' : end;
}
var tween = this.get('tween');
tween.start('background-color', start || '#ffff88', end).chain(function(){
this.setStyle('background-color', this.retrieve('highlight:original'));
tween.callChain();
}.bind(this));
return this;
}
});
/*
---
name: Fx.Morph
description: Formerly Fx.Styles, effect to transition any number of CSS properties for an element using an object of rules, or CSS based selector rules.
license: MIT-style license.
requires: Fx.CSS
provides: Fx.Morph
...
*/
Fx.Morph = new Class({
Extends: Fx.CSS,
initialize: function(element, options){
this.element = this.subject = document.id(element);
this.parent(options);
},
set: function(now){
if (typeof now == 'string') now = this.search(now);
for (var p in now) this.render(this.element, p, now[p], this.options.unit);
return this;
},
compute: function(from, to, delta){
var now = {};
for (var p in from) now[p] = this.parent(from[p], to[p], delta);
return now;
},
start: function(properties){
if (!this.check(properties)) return this;
if (typeof properties == 'string') properties = this.search(properties);
var from = {}, to = {};
for (var p in properties){
var parsed = this.prepare(this.element, p, properties[p]);
from[p] = parsed.from;
to[p] = parsed.to;
}
return this.parent(from, to);
}
});
Element.Properties.morph = {
set: function(options){
this.get('morph').cancel().setOptions(options);
return this;
},
get: function(){
var morph = this.retrieve('morph');
if (!morph){
morph = new Fx.Morph(this, {link: 'cancel'});
this.store('morph', morph);
}
return morph;
}
};
Element.implement({
morph: function(props){
this.get('morph').start(props);
return this;
}
});
/*
---
name: Fx.Transitions
description: Contains a set of advanced transitions to be used with any of the Fx Classes.
license: MIT-style license.
credits:
- Easing Equations by Robert Penner, <http://www.robertpenner.com/easing/>, modified and optimized to be used with MooTools.
requires: Fx
provides: Fx.Transitions
...
*/
Fx.implement({
getTransition: function(){
var trans = this.options.transition || Fx.Transitions.Sine.easeInOut;
if (typeof trans == 'string'){
var data = trans.split(':');
trans = Fx.Transitions;
trans = trans[data[0]] || trans[data[0].capitalize()];
if (data[1]) trans = trans['ease' + data[1].capitalize() + (data[2] ? data[2].capitalize() : '')];
}
return trans;
}
});
Fx.Transition = function(transition, params){
params = Array.from(params);
var easeIn = function(pos){
return transition(pos, params);
};
return Object.append(easeIn, {
easeIn: easeIn,
easeOut: function(pos){
return 1 - transition(1 - pos, params);
},
easeInOut: function(pos){
return (pos <= 0.5 ? transition(2 * pos, params) : (2 - transition(2 * (1 - pos), params))) / 2;
}
});
};
Fx.Transitions = {
linear: function(zero){
return zero;
}
};
Fx.Transitions.extend = function(transitions){
for (var transition in transitions) Fx.Transitions[transition] = new Fx.Transition(transitions[transition]);
};
Fx.Transitions.extend({
Pow: function(p, x){
return Math.pow(p, x && x[0] || 6);
},
Expo: function(p){
return Math.pow(2, 8 * (p - 1));
},
Circ: function(p){
return 1 - Math.sin(Math.acos(p));
},
Sine: function(p){
return 1 - Math.cos(p * Math.PI / 2);
},
Back: function(p, x){
x = x && x[0] || 1.618;
return Math.pow(p, 2) * ((x + 1) * p - x);
},
Bounce: function(p){
var value;
for (var a = 0, b = 1; 1; a += b, b /= 2){
if (p >= (7 - 4 * a) / 11){
value = b * b - Math.pow((11 - 6 * a - 11 * p) / 4, 2);
break;
}
}
return value;
},
Elastic: function(p, x){
return Math.pow(2, 10 * --p) * Math.cos(20 * p * Math.PI * (x && x[0] || 1) / 3);
}
});
['Quad', 'Cubic', 'Quart', 'Quint'].each(function(transition, i){
Fx.Transitions[transition] = new Fx.Transition(function(p){
return Math.pow(p, i + 2);
});
});
/*
---
name: Request
description: Powerful all purpose Request Class. Uses XMLHTTPRequest.
license: MIT-style license.
requires: [Object, Element, Chain, Events, Options, Browser]
provides: Request
...
*/
(function(){
var empty = function(){},
progressSupport = ('onprogress' in new Browser.Request);
var Request = this.Request = new Class({
Implements: [Chain, Events, Options],
options: {/*
onRequest: function(){},
onLoadstart: function(event, xhr){},
onProgress: function(event, xhr){},
onUploadProgress: function(event, xhr){},
onComplete: function(){},
onCancel: function(){},
onSuccess: function(responseText, responseXML){},
onFailure: function(xhr){},
onException: function(headerName, value){},
onTimeout: function(){},
user: '',
password: '',*/
url: '',
data: '',
processData: true,
responseType: null,
headers: {
'X-Requested-With': 'XMLHttpRequest',
'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
},
async: true,
format: false,
method: 'post',
link: 'ignore',
isSuccess: null,
emulation: true,
urlEncoded: true,
encoding: 'utf-8',
evalScripts: false,
evalResponse: false,
timeout: 0,
noCache: false
},
initialize: function(options){
this.xhr = new Browser.Request();
this.setOptions(options);
if ((typeof ArrayBuffer != 'undefined' && options.data instanceof ArrayBuffer) || (typeof Blob != 'undefined' && options.data instanceof Blob) || (typeof Uint8Array != 'undefined' && options.data instanceof Uint8Array)){
// set data in directly if we're passing binary data because
// otherwise setOptions will convert the data into an empty object
this.options.data = options.data;
}
this.headers = this.options.headers;
},
onStateChange: function(){
var xhr = this.xhr;
if (xhr.readyState != 4 || !this.running) return;
this.running = false;
this.status = 0;
Function.attempt(function(){
var status = xhr.status;
this.status = (status == 1223) ? 204 : status;
}.bind(this));
xhr.onreadystatechange = empty;
if (progressSupport) xhr.onprogress = xhr.onloadstart = empty;
clearTimeout(this.timer);
this.response = {text: (!this.options.responseType && this.xhr.responseText) || '', xml: (!this.options.responseType && this.xhr.responseXML)};
if (this.options.isSuccess.call(this, this.status))
this.success(this.options.responseType ? this.xhr.response : this.response.text, this.response.xml);
else
this.failure();
},
isSuccess: function(){
var status = this.status;
return (status >= 200 && status < 300);
},
isRunning: function(){
return !!this.running;
},
processScripts: function(text){
if (typeof text != 'string') return text;
if (this.options.evalResponse || (/(ecma|java)script/).test(this.getHeader('Content-type'))) return Browser.exec(text);
return text.stripScripts(this.options.evalScripts);
},
success: function(text, xml){
this.onSuccess(this.processScripts(text), xml);
},
onSuccess: function(){
this.fireEvent('complete', arguments).fireEvent('success', arguments).callChain();
},
failure: function(){
this.onFailure();
},
onFailure: function(){
this.fireEvent('complete').fireEvent('failure', this.xhr);
},
loadstart: function(event){
this.fireEvent('loadstart', [event, this.xhr]);
},
progress: function(event){
this.fireEvent('progress', [event, this.xhr]);
},
uploadprogress: function(event){
this.fireEvent('uploadprogress', [event, this.xhr]);
},
timeout: function(){
this.fireEvent('timeout', this.xhr);
},
setHeader: function(name, value){
this.headers[name] = value;
return this;
},
getHeader: function(name){
return Function.attempt(function(){
return this.xhr.getResponseHeader(name);
}.bind(this));
},
check: function(){
if (!this.running) return true;
switch (this.options.link){
case 'cancel': this.cancel(); return true;
case 'chain': this.chain(this.caller.pass(arguments, this)); return false;
}
return false;
},
send: function(options){
if (!this.check(options)) return this;
this.options.isSuccess = this.options.isSuccess || this.isSuccess;
this.running = true;
var type = typeOf(options);
if (type == 'string' || type == 'element') options = {data: options};
var old = this.options;
options = Object.append({data: old.data, url: old.url, method: old.method}, options);
var data = options.data, url = String(options.url), method = options.method.toLowerCase();
if (this.options.processData || method == 'get' || method == 'delete'){
switch (typeOf(data)){
case 'element': data = document.id(data).toQueryString(); break;
case 'object': case 'hash': data = Object.toQueryString(data);
}
if (this.options.format){
var format = 'format=' + this.options.format;
data = (data) ? format + '&' + data : format;
}
if (this.options.emulation && !['get', 'post'].contains(method)){
var _method = '_method=' + method;
data = (data) ? _method + '&' + data : _method;
method = 'post';
}
}
if (this.options.urlEncoded && ['post', 'put'].contains(method)){
var encoding = (this.options.encoding) ? '; charset=' + this.options.encoding : '';
this.headers['Content-type'] = 'application/x-www-form-urlencoded' + encoding;
}
if (!url) url = document.location.pathname;
var trimPosition = url.lastIndexOf('/');
if (trimPosition > -1 && (trimPosition = url.indexOf('#')) > -1) url = url.substr(0, trimPosition);
if (this.options.noCache)
url += (url.contains('?') ? '&' : '?') + String.uniqueID();
if (data && method == 'get'){
url += (url.contains('?') ? '&' : '?') + data;
data = null;
}
var xhr = this.xhr;
if (progressSupport){
xhr.onloadstart = this.loadstart.bind(this);
xhr.onprogress = this.progress.bind(this);
if(xhr.upload) xhr.upload.onprogress = this.uploadprogress.bind(this);
}
xhr.open(method.toUpperCase(), url, this.options.async, this.options.user, this.options.password);
if (this.options.user && 'withCredentials' in xhr) xhr.withCredentials = true;
xhr.onreadystatechange = this.onStateChange.bind(this);
Object.each(this.headers, function(value, key){
try {
xhr.setRequestHeader(key, value);
} catch (e){
this.fireEvent('exception', [key, value]);
}
}, this);
if (this.options.responseType){
xhr.responseType = this.options.responseType.toLowerCase();
}
this.fireEvent('request');
xhr.send(data);
if (!this.options.async) this.onStateChange();
else if (this.options.timeout) this.timer = this.timeout.delay(this.options.timeout, this);
return this;
},
cancel: function(){
if (!this.running) return this;
this.running = false;
var xhr = this.xhr;
xhr.abort();
clearTimeout(this.timer);
xhr.onreadystatechange = empty;
if (progressSupport) xhr.onprogress = xhr.onloadstart = empty;
this.xhr = new Browser.Request();
this.fireEvent('cancel');
return this;
}
});
var methods = {};
['get', 'post', 'put', 'delete', 'GET', 'POST', 'PUT', 'DELETE'].each(function(method){
methods[method] = function(data){
var object = {
method: method
};
if (data != null) object.data = data;
return this.send(object);
};
});
Request.implement(methods);
Element.Properties.send = {
set: function(options){
var send = this.get('send').cancel();
send.setOptions(options);
return this;
},
get: function(){
var send = this.retrieve('send');
if (!send){
send = new Request({
data: this, link: 'cancel', method: this.get('method') || 'post', url: this.get('action')
});
this.store('send', send);
}
return send;
}
};
Element.implement({
send: function(url){
var sender = this.get('send');
sender.send({data: this, url: url || sender.options.url});
return this;
}
});
})();
/*
---
name: Request.HTML
description: Extends the basic Request Class with additional methods for interacting with HTML responses.
license: MIT-style license.
requires: [Element, Request]
provides: Request.HTML
...
*/
Request.HTML = new Class({
Extends: Request,
options: {
update: false,
append: false,
evalScripts: true,
filter: false,
headers: {
Accept: 'text/html, application/xml, text/xml, */*'
}
},
success: function(text){
var options = this.options, response = this.response;
response.html = text.stripScripts(function(script){
response.javascript = script;
});
var match = response.html.match(/<body[^>]*>([\s\S]*?)<\/body>/i);
if (match) response.html = match[1];
var temp = new Element('div').set('html', response.html);
response.tree = temp.childNodes;
response.elements = temp.getElements(options.filter || '*');
if (options.filter) response.tree = response.elements;
if (options.update){
var update = document.id(options.update).empty();
if (options.filter) update.adopt(response.elements);
else update.set('html', response.html);
} else if (options.append){
var append = document.id(options.append);
if (options.filter) response.elements.reverse().inject(append);
else append.adopt(temp.getChildren());
}
if (options.evalScripts) Browser.exec(response.javascript);
this.onSuccess(response.tree, response.elements, response.html, response.javascript);
}
});
Element.Properties.load = {
set: function(options){
var load = this.get('load').cancel();
load.setOptions(options);
return this;
},
get: function(){
var load = this.retrieve('load');
if (!load){
load = new Request.HTML({data: this, link: 'cancel', update: this, method: 'get'});
this.store('load', load);
}
return load;
}
};
Element.implement({
load: function(){
this.get('load').send(Array.link(arguments, {data: Type.isObject, url: Type.isString}));
return this;
}
});
/*
---
name: JSON
description: JSON encoder and decoder.
license: MIT-style license.
SeeAlso: <http://www.json.org/>
requires: [Array, String, Number, Function]
provides: JSON
...
*/
if (typeof JSON == 'undefined') this.JSON = {};
(function(){
var special = {'\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\'};
var escape = function(chr){
return special[chr] || '\\u' + ('0000' + chr.charCodeAt(0).toString(16)).slice(-4);
};
JSON.validate = function(string){
string = string.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, '');
return (/^[\],:{}\s]*$/).test(string);
};
JSON.encode = JSON.stringify ? function(obj){
return JSON.stringify(obj);
} : function(obj){
if (obj && obj.toJSON) obj = obj.toJSON();
switch (typeOf(obj)){
case 'string':
return '"' + obj.replace(/[\x00-\x1f\\"]/g, escape) + '"';
case 'array':
return '[' + obj.map(JSON.encode).clean() + ']';
case 'object': case 'hash':
var string = [];
Object.each(obj, function(value, key){
var json = JSON.encode(value);
if (json) string.push(JSON.encode(key) + ':' + json);
});
return '{' + string + '}';
case 'number': case 'boolean': return '' + obj;
case 'null': return 'null';
}
return null;
};
JSON.decode = function(string, secure){
if (!string || typeOf(string) != 'string') return null;
if (secure || JSON.secure){
if (JSON.parse) return JSON.parse(string);
if (!JSON.validate(string)) throw new Error('JSON could not decode the input; security is enabled and the value is not secure.');
}
return eval('(' + string + ')');
};
})();
/*
---
name: Request.JSON
description: Extends the basic Request Class with additional methods for sending and receiving JSON data.
license: MIT-style license.
requires: [Request, JSON]
provides: Request.JSON
...
*/
Request.JSON = new Class({
Extends: Request,
options: {
/*onError: function(text, error){},*/
secure: true
},
initialize: function(options){
this.parent(options);
Object.append(this.headers, {
'Accept': 'application/json',
'X-Request': 'JSON'
});
},
success: function(text){
var json;
try {
json = this.response.json = JSON.decode(text, this.options.secure);
} catch (error){
this.fireEvent('error', [text, error]);
return;
}
if (json == null) this.onFailure();
else this.onSuccess(json, text);
}
});
/*
---
name: Cookie
description: Class for creating, reading, and deleting browser Cookies.
license: MIT-style license.
credits:
- Based on the functions by Peter-Paul Koch (http://quirksmode.org).
requires: [Options, Browser]
provides: Cookie
...
*/
var Cookie = new Class({
Implements: Options,
options: {
path: '/',
domain: false,
duration: false,
secure: false,
document: document,
encode: true
},
initialize: function(key, options){
this.key = key;
this.setOptions(options);
},
write: function(value){
if (this.options.encode) value = encodeURIComponent(value);
if (this.options.domain) value += '; domain=' + this.options.domain;
if (this.options.path) value += '; path=' + this.options.path;
if (this.options.duration){
var date = new Date();
date.setTime(date.getTime() + this.options.duration * 24 * 60 * 60 * 1000);
value += '; expires=' + date.toGMTString();
}
if (this.options.secure) value += '; secure';
this.options.document.cookie = this.key + '=' + value;
return this;
},
read: function(){
var value = this.options.document.cookie.match('(?:^|;)\\s*' + this.key.escapeRegExp() + '=([^;]*)');
return (value) ? decodeURIComponent(value[1]) : null;
},
dispose: function(){
new Cookie(this.key, Object.merge({}, this.options, {duration: -1})).write('');
return this;
}
});
Cookie.write = function(key, value, options){
return new Cookie(key, options).write(value);
};
Cookie.read = function(key){
return new Cookie(key).read();
};
Cookie.dispose = function(key, options){
return new Cookie(key, options).dispose();
};
/*
---
name: DOMReady
description: Contains the custom event domready.
license: MIT-style license.
requires: [Browser, Element, Element.Event]
provides: [DOMReady, DomReady]
...
*/
(function(window, document){
var ready,
loaded,
checks = [],
shouldPoll,
timer,
testElement = document.createElement('div');
var domready = function(){
clearTimeout(timer);
if (ready) return;
Browser.loaded = ready = true;
document.removeListener('DOMContentLoaded', domready).removeListener('readystatechange', check);
document.fireEvent('domready');
window.fireEvent('domready');
};
var check = function(){
for (var i = checks.length; i--;) if (checks[i]()){
domready();
return true;
}
return false;
};
var poll = function(){
clearTimeout(timer);
if (!check()) timer = setTimeout(poll, 10);
};
document.addListener('DOMContentLoaded', domready);
/*<ltIE8>*/
// doScroll technique by Diego Perini http://javascript.nwbox.com/IEContentLoaded/
// testElement.doScroll() throws when the DOM is not ready, only in the top window
var doScrollWorks = function(){
try {
testElement.doScroll();
return true;
} catch (e){}
return false;
};
// If doScroll works already, it can't be used to determine domready
// e.g. in an iframe
if (testElement.doScroll && !doScrollWorks()){
checks.push(doScrollWorks);
shouldPoll = true;
}
/*</ltIE8>*/
if (document.readyState) checks.push(function(){
var state = document.readyState;
return (state == 'loaded' || state == 'complete');
});
if ('onreadystatechange' in document) document.addListener('readystatechange', check);
else shouldPoll = true;
if (shouldPoll) poll();
Element.Events.domready = {
onAdd: function(fn){
if (ready) fn.call(this);
}
};
// Make sure that domready fires before load
Element.Events.load = {
base: 'load',
onAdd: function(fn){
if (loaded && this == window) fn.call(this);
},
condition: function(){
if (this == window){
domready();
delete Element.Events.load;
}
return true;
}
};
// This is based on the custom load event
window.addEvent('load', function(){
loaded = true;
});
})(window, document);
|
Template.HostList.events({
});
Template.HostList.helpers({
// Get list of Hosts sorted by the sort field.
hosts: function () {
return Hosts.find({}, {sort: {sort: 1}});
}
});
Template.HostList.rendered = function () {
// Make rows sortable/draggable using Jquery-UI.
this.$('#sortable').sortable({
stop: function (event, ui) {
// Define target row items.
target = ui.item.get(0);
before = ui.item.prev().get(0);
after = ui.item.next().get(0);
// Change the sort value dependnig on target location.
// If target is now first, subtract 1 from sort value.
if (!before) {
newSort = Blaze.getData(after).sort - 1;
// If target is now last, add 1 to sort value.
} else if (!after) {
newSort = Blaze.getData(before).sort + 1;
// Get value of prev and next elements
// to determine new target sort value.
} else {
newSort = (Blaze.getData(after).sort +
Blaze.getData(before).sort) / 2;
}
// Update the database with new sort value.
Hosts.update({_id: Blaze.getData(target)._id}, {
$set: {
sort: newSort
}
});
}
});
};
|
import Helper, { states } from './_helper';
import { module, test } from 'qunit';
module('Integration | ORM | Has Many | Named Reflexive | association #set', function(hooks) {
hooks.beforeEach(function() {
this.helper = new Helper();
});
/*
The model can update its association via parent, for all states
*/
states.forEach((state) => {
test(`a ${state} can update its association to a list of saved children`, function(assert) {
let [ tag, originalTags ] = this.helper[state]();
let savedTag = this.helper.savedChild();
tag.labels = [ savedTag ];
assert.ok(tag.labels.includes(savedTag));
assert.equal(tag.labelIds[0], savedTag.id);
assert.ok(savedTag.labels.includes(tag), 'the inverse was set');
tag.save();
originalTags.forEach(originalTag => {
originalTag.reload();
assert.notOk(originalTag.labels.includes(tag), 'old inverses were cleared');
});
});
test(`a ${state} can update its association to a new parent`, function(assert) {
let [ tag, originalTags ] = this.helper[state]();
let newTag = this.helper.newChild();
tag.labels = [ newTag ];
assert.ok(tag.labels.includes(newTag));
assert.equal(tag.labelIds[0], undefined);
assert.ok(newTag.labels.includes(tag), 'the inverse was set');
tag.save();
originalTags.forEach(originalTag => {
originalTag.reload();
assert.notOk(originalTag.labels.includes(tag), 'old inverses were cleared');
});
});
test(`a ${state} can clear its association via an empty list`, function(assert) {
let [ tag, originalTags ] = this.helper[state]();
tag.labels = [ ];
assert.deepEqual(tag.labelIds, [ ]);
assert.equal(tag.labels.models.length, 0);
tag.save();
originalTags.forEach(originalTag => {
originalTag.reload();
assert.notOk(originalTag.labels.includes(tag), 'old inverses were cleared');
});
});
test(`a ${state} can clear its association via an empty list`, function(assert) {
let [ tag, originalTags ] = this.helper[state]();
tag.labels = null;
assert.deepEqual(tag.labelIds, [ ]);
assert.equal(tag.labels.models.length, 0);
tag.save();
originalTags.forEach(originalTag => {
originalTag.reload();
assert.notOk(originalTag.labels.includes(tag), 'old inverses were cleared');
});
});
});
});
|
/* describe, it, afterEach, beforeEach */
import './snoocore-mocha';
import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';
chai.use(chaiAsPromised);
let expect = chai.expect;
import config from '../config';
import util from './util';
import ResponseError from '../../src/ResponseError';
import Endpoint from '../../src/Endpoint';
describe(__filename, function () {
this.timeout(config.testTimeout);
it('should get a proper response error', function() {
var message = 'oh hello there';
var response = { _status: 200, _body: 'a response body' };
var userConfig = util.getScriptUserConfig();
var endpoint = new Endpoint(userConfig,
userConfig.serverOAuth,
'get',
'/some/path',
{}, // headers
{ some: 'args' });
var responseError = new ResponseError(message,
response,
endpoint);
expect(responseError instanceof ResponseError);
expect(responseError.status).to.eql(200);
expect(responseError.url).to.eql('https://oauth.reddit.com/some/path');
expect(responseError.args).to.eql({ some: 'args', api_type: 'json' });
expect(responseError.message.indexOf('oh hello there')).to.not.eql(-1);
expect(responseError.message.indexOf('Response Status')).to.not.eql(-1);
expect(responseError.message.indexOf('Endpoint URL')).to.not.eql(-1);
expect(responseError.message.indexOf('Arguments')).to.not.eql(-1);
expect(responseError.message.indexOf('Response Body')).to.not.eql(-1);
});
});
|
function someFunctionWithAVeryLongName(firstParameter='something',
secondParameter='booooo',
third=null, fourthParameter=false,
fifthParameter=123.12,
sixthParam=true
){
}
function someFunctionWithAVeryLongName2(
firstParameter='something',
secondParameter='booooo',
) {
}
function blah() {
}
function blah()
{
}
var object =
{
someFunctionWithAVeryLongName: function(
firstParameter='something',
secondParameter='booooo',
third=null,
fourthParameter=false,
fifthParameter=123.12,
sixthParam=true
) /** w00t */ {
}
someFunctionWithAVeryLongName2: function (firstParameter='something',
secondParameter='booooo',
third=null
) {
}
someFunctionWithAVeryLongName3: function (
firstParameter, secondParameter, third=null
) {
}
someFunctionWithAVeryLongName4: function (
firstParameter, secondParameter
) {
}
someFunctionWithAVeryLongName5: function (
firstParameter,
secondParameter=array(1,2,3),
third=null
) {
}
}
var a = Function('return 1+1');
|
#!/usr/bin/env node
require("babel/register")({
"stage": 1
});
var fs = require("fs");
GLOBAL.WALLACEVERSION = "Err";
GLOBAL.PLUGIN_CONTRIBUTORS = [];
try {
var p = JSON.parse(fs.readFileSync(__dirname+"/package.json"));
GLOBAL.WALLACEVERSION = p.version;
}
catch(e) {}
var Core = require("./core/Core.js");
process.on('uncaughtException', function (err) {
console.error(err);
});
GLOBAL.core = new Core();
|
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
'use strict';
/*global cEngine */
/*eslint no-console:0*/
(function (cEngine) {
cEngine.extend('__name__', {
create: function create(config) {
config = config || {};
var __name__ = {
cEnginePlugin: {
name: '__name__',
version: '0.0.1'
},
init: function init(engine) {
console.log('init', engine);
},
start: function start() {
console.log('start');
},
stop: function stop() {
console.log('stop');
},
preStep: function preStep(context, width, height, dt) {
console.log('preStep', context, width, height, dt);
},
postStep: function postStep(context, width, height, dt) {
console.log('postStep', context, width, height, dt);
},
destroy: function destroy() {
console.log('destroy');
}
};
return __name__;
}
});
})(cEngine);
},{}]},{},[1]) |
// Copyright (c) 2015 Uber Technologies, Inc.
//
// 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.
'use strict';
var EventEmitter = require('./lib/event_emitter');
var stat = require('./lib/stat');
var inherits = require('util').inherits;
var errors = require('./errors');
var States = require('./reqres_states');
function TChannelOutResponse(id, options) {
options = options || {};
var self = this;
EventEmitter.call(self);
self.errorEvent = self.defineEvent('error');
self.spanEvent = self.defineEvent('span');
self.finishEvent = self.defineEvent('finish');
self.channel = options.channel;
self.inreq = options.inreq;
self.logger = options.logger;
self.random = options.random;
self.timers = options.timers;
self.start = 0;
self.end = 0;
self.state = States.Initial;
self.id = id || 0;
self.code = options.code || 0;
self.tracing = options.tracing || null;
self.headers = options.headers || {};
self.checksumType = options.checksumType || 0;
self.checksum = options.checksum || null;
self.ok = self.code === 0;
self.span = options.span || null;
self.streamed = false;
self._argstream = null;
self.arg1 = null;
self.arg2 = null;
self.arg3 = null;
self.codeString = null;
self.message = null;
}
inherits(TChannelOutResponse, EventEmitter);
TChannelOutResponse.prototype.type = 'tchannel.outgoing-response';
TChannelOutResponse.prototype._sendCallResponse = function _sendCallResponse(args, isLast) {
var self = this;
throw errors.UnimplementedMethod({
className: self.constructor.name,
methodName: '_sendCallResponse'
});
};
TChannelOutResponse.prototype._sendCallResponseCont = function _sendCallResponseCont(args, isLast) {
var self = this;
throw errors.UnimplementedMethod({
className: self.constructor.name,
methodName: '_sendCallResponseCont'
});
};
TChannelOutResponse.prototype._sendError = function _sendError(codeString, message) {
var self = this;
throw errors.UnimplementedMethod({
className: self.constructor.name,
methodName: '_sendError'
});
};
TChannelOutResponse.prototype.sendParts = function sendParts(parts, isLast) {
var self = this;
switch (self.state) {
case States.Initial:
self.sendCallResponseFrame(parts, isLast);
break;
case States.Streaming:
self.sendCallResponseContFrame(parts, isLast);
break;
case States.Done:
self.errorEvent.emit(self, errors.ResponseFrameState({
attempted: 'arg parts',
state: 'Done'
}));
break;
case States.Error:
// TODO: log warn
break;
default:
self.channel.logger.error('TChannelOutResponse is in a wrong state', {
state: self.state
});
break;
}
};
TChannelOutResponse.prototype.sendCallResponseFrame = function sendCallResponseFrame(args, isLast) {
var self = this;
switch (self.state) {
case States.Initial:
self.start = self.timers.now();
self._sendCallResponse(args, isLast);
if (self.span) {
self.span.annotate('ss');
}
if (isLast) self.state = States.Done;
else self.state = States.Streaming;
break;
case States.Streaming:
self.errorEvent.emit(self, errors.ResponseFrameState({
attempted: 'call response',
state: 'Streaming'
}));
break;
case States.Done:
case States.Error:
var arg2 = args[1] || '';
var arg3 = args[2] || '';
self.errorEvent.emit(self, errors.ResponseAlreadyDone({
attempted: 'call response',
state: self.state,
method: 'sendCallResponseFrame',
bufArg2: arg2.slice(0, 50),
arg2: String(arg2).slice(0, 50),
bufArg3: arg3.slice(0, 50),
arg3: String(arg3).slice(0, 50)
}));
}
};
TChannelOutResponse.prototype.sendCallResponseContFrame = function sendCallResponseContFrame(args, isLast) {
var self = this;
switch (self.state) {
case States.Initial:
self.errorEvent.emit(self, errors.ResponseFrameState({
attempted: 'call response continuation',
state: 'Initial'
}));
break;
case States.Streaming:
self._sendCallResponseCont(args, isLast);
if (isLast) self.state = States.Done;
break;
case States.Done:
case States.Error:
self.errorEvent.emit(self, errors.ResponseAlreadyDone({
attempted: 'call response continuation',
state: self.state,
method: 'sendCallResponseContFrame'
}));
}
};
TChannelOutResponse.prototype.sendError = function sendError(codeString, message) {
var self = this;
if (self.state === States.Done || self.state === States.Error) {
self.errorEvent.emit(self, errors.ResponseAlreadyDone({
attempted: 'send error frame: ' + codeString + ': ' + message,
currentState: self.state,
method: 'sendError',
codeString: codeString,
errMessage: message
}));
} else {
if (self.span) {
self.span.annotate('ss');
}
self.state = States.Error;
self.codeString = codeString;
self.message = message;
self.channel.inboundCallsSystemErrorsStat.increment(1, {
'calling-service': self.inreq.headers.cn,
'service': self.inreq.serviceName,
'endpoint': String(self.inreq.arg1),
'type': self.codeString
});
self._sendError(codeString, message);
self.emitFinish();
}
};
TChannelOutResponse.prototype.emitFinish = function emitFinish() {
var self = this;
var now = self.timers.now();
if (self.end) {
self.logger.warn('out response double emitFinish', {
end: self.end,
now: now,
serviceName: self.inreq.serviceName,
cn: self.inreq.headers.cn,
endpoint: String(self.inreq.arg1),
codeString: self.codeString,
errorMessage: self.message,
remoteAddr: self.inreq.connection.socketRemoteAddr,
state: self.state,
isOk: self.ok
});
return;
}
self.end = now;
var latency = self.end - self.inreq.start;
self.channel.emitFastStat(self.channel.buildStat(
'tchannel.inbound.calls.latency',
'timing',
latency,
new stat.InboundCallsLatencyTags(
self.inreq.headers.cn,
self.inreq.serviceName,
self.inreq.endpoint
)
));
if (self.span) {
self.spanEvent.emit(self, self.span);
}
self.finishEvent.emit(self);
};
TChannelOutResponse.prototype.setOk = function setOk(ok) {
var self = this;
if (self.state !== States.Initial) {
self.errorEvent.emit(self, errors.ResponseAlreadyStarted({
state: self.state,
method: 'setOk',
ok: ok
}));
return false;
}
self.ok = ok;
self.code = ok ? 0 : 1; // TODO: too coupled to v2 specifics?
return true;
};
TChannelOutResponse.prototype.sendOk = function sendOk(res1, res2) {
var self = this;
self.setOk(true);
self.send(res1, res2);
};
TChannelOutResponse.prototype.sendNotOk = function sendNotOk(res1, res2) {
var self = this;
if (self.state === States.Error) {
self.logger.error('cannot send application error, already sent error frame', {
res1: res1,
res2: res2
});
} else {
self.setOk(false);
self.send(res1, res2);
}
};
TChannelOutResponse.prototype.send = function send(res1, res2) {
var self = this;
/* send calls after finish() should be swallowed */
if (self.end) {
var logOptions = {
serviceName: self.inreq.serviceName,
cn: self.inreq.headers.cn,
endpoint: self.inreq.endpoint,
remoteAddr: self.inreq.remoteAddr,
end: self.end,
codeString: self.codeString,
errorMessage: self.message,
isOk: self.ok,
hasResponse: !!self.arg3,
state: self.state
};
if (self.inreq && self.inreq.timedOut) {
self.logger.info('OutResponse.send() after inreq timed out', logOptions);
} else {
self.logger.warn('OutResponse called send() after end', logOptions);
}
return;
}
self.arg2 = res1;
self.arg3 = res2;
if (self.ok) {
self.channel.emitFastStat(self.channel.buildStat(
'tchannel.inbound.calls.success',
'counter',
1,
new stat.InboundCallsSuccessTags(
self.inreq.headers.cn,
self.inreq.serviceName,
self.inreq.endpoint
)
));
} else {
// TODO: add outResponse.setErrorType()
self.channel.emitFastStat(self.channel.buildStat(
'tchannel.inbound.calls.app-errors',
'counter',
1,
new stat.InboundCallsAppErrorsTags(
self.inreq.headers.cn,
self.inreq.serviceName,
self.inreq.endpoint,
'unknown'
)
));
}
self.sendCallResponseFrame([self.arg1, res1, res2], true);
self.emitFinish();
return self;
};
module.exports = TChannelOutResponse;
|
#!/usr/bin/env node
/**
* Release this package.
*/
"use strict";
process.chdir(__dirname + '/..');
const apeTasking = require('ape-tasking'),
apeReleasing = require('ape-releasing');
apeTasking.runTasks('release', [
(callback) => {
apeReleasing.releasePackage({
beforeRelease: [
'./ci/build.js',
'./ci/test.js'
]
}, callback);
}
], true);
|
/*global d3 */
// asynchronously load data from the Lagotto API
queue()
.defer(d3.json, encodeURI("/api/agents/"))
.await(function(error, a) {
if (error) { return console.warn(error); }
agentsViz(a.agents);
});
// add data to page
function agentsViz(data) {
for (var i=0; i<data.length; i++) {
var agent = data[i];
// responses tab
d3.select("#response_count_" + agent.id)
.text(numberWithDelimiter(agent.responses.count));
d3.select("#average_count_" + agent.id)
.text(numberWithDelimiter(agent.responses.average));
}
}
|
var test = require("tape").test
var level = require("level-test")()
var testdb = level("test-versionstream")
var version = require("../")
var db = version(testdb)
var lastVersion
test("stuff some datas", function (t) {
t.plan(2)
db.put("pet", "fluffy", {version: 0})
db.put("pet", "spot", {version: 1})
db.put("pet", "scratch", {version: 334})
db.put("watch", "calculator", {version: 11})
db.put("watch", "casio", {version: 14})
db.put("pet", "sparky", function (err, version) {
t.notOk(err, "no error")
t.ok(version > Date.now() - 1000, "Default version is a recent timestamp")
lastVersion = version
})
})
test("versionstream pets", function (t) {
t.plan(5)
var versions = []
db.createVersionStream("pet")
.on("data", function (record) {
t.ok(record.version != null, "record has a version")
versions.push(record.version)
})
.on("end", function () {
t.deepEqual(versions, [lastVersion, 334, 1, 0], "Versions came out in the correct order")
})
})
test("versionstream pets version no min", function (t) {
t.plan(2)
var versions = []
db.createVersionStream("pet", {maxVersion: 500, limit: 1})
.on("data", function (record) {
t.ok(record.version != null, "record has a version")
versions.push(record.version)
})
.on("end", function () {
t.deepEqual(versions, [334], "Versions came out in the correct order")
})
})
test("versionstream pets version reverse no min", function (t) {
t.plan(2)
var versions = []
db.createVersionStream("pet", {maxVersion: 500, limit: 1, reverse: true})
.on("data", function (record) {
t.ok(record.version != null, "record has a version")
versions.push(record.version)
})
.on("end", function () {
t.deepEqual(versions, [0], "Versions came out in the correct order")
})
})
test("versionstream pets version range no max", function (t) {
t.plan(2)
var versions = []
db.createVersionStream("pet", {minVersion: 10, limit: 1})
.on("data", function (record) {
t.ok(record.version != null, "record has a version")
versions.push(record.version)
})
.on("end", function () {
t.deepEqual(versions, [lastVersion], "Versions came out in the correct order")
})
})
test("versionstream pets version range", function (t) {
t.plan(2)
var versions = []
db.createVersionStream("pet", {minVersion: 10, maxVersion: 500, limit: 1})
.on("data", function (record) {
t.ok(record.version != null, "record has a version")
versions.push(record.version)
})
.on("end", function () {
t.deepEqual(versions, [334], "Versions came out in the correct order")
})
})
test("versionstream watches", function (t) {
t.plan(3)
var versions = []
db.createVersionStream("watch")
.on("data", function (record) {
t.ok(record.version != null, "record has a version")
versions.push(record.version)
})
.on("end", function () {
t.deepEqual(versions, [14, 11], "Versions came out in the correct order")
})
})
test("alias", function (t) {
var versions = []
db.versionStream("pet")
.on("data", function (record) {
t.ok(record.version != null, "record has a version")
versions.push(record.version)
})
.on("end", function () {
t.deepEqual(versions, [lastVersion, 334, 1, 0], "Versions came out in the correct order")
t.end()
})
})
|
"use strict";
const lua = require("../src/lua.js");
const lauxlib = require("../src/lauxlib.js");
const {to_luastring} = require("../src/fengaricore.js");
const toByteCode = function(luaCode) {
let L = lauxlib.luaL_newstate();
if (!L) throw Error("failed to create lua state");
if (lauxlib.luaL_loadstring(L, to_luastring(luaCode)) !== lua.LUA_OK)
throw Error(lua.lua_tojsstring(L, -1));
let b = [];
if (lua.lua_dump(L, function(L, b, size, B) {
B.push(...b.slice(0, size));
return 0;
}, b, false) !== 0)
throw Error("unable to dump given function");
return Uint8Array.from(b);
};
module.exports.toByteCode = toByteCode;
|
/* Get Programming with JavaScript
* Listing 4.01
* Displaying an object's properties on the console
*/
var movie1;
movie1 = {
title: "Inside Out",
actors: "Amy Poehler, Bill Hader",
directors: "Pete Doctor, Ronaldo Del Carmen"
};
console.log("Movie information for " + movie1.title);
console.log("------------------------------");
console.log("Actors: " + movie1.actors);
console.log("Directors: " + movie1.directors);
console.log("------------------------------");
/* Further Adventures
*
* 1) Add a second movie and display the same info for it.
*
* 2) Create an object to represent a blog post.
*
* 3) Write code to display info about the blog post.
*
*/
|
describe('Component: Product Search', function(){
var scope,
q,
oc,
state,
_ocParameters,
parameters,
mockProductList
;
beforeEach(module(function($provide) {
$provide.value('Parameters', {searchTerm: null, page: null, pageSize: null, sortBy: null});
}));
beforeEach(module('orderCloud'));
beforeEach(module('orderCloud.sdk'));
beforeEach(inject(function($rootScope, $q, OrderCloud, ocParameters, $state, Parameters){
scope = $rootScope.$new();
q = $q;
oc = OrderCloud;
state = $state;
_ocParameters = ocParameters;
parameters = Parameters;
mockProductList = {
Items:['product1', 'product2'],
Meta:{
ItemRange:[1, 3],
TotalCount: 50
}
};
}));
describe('State: productSearchResults', function(){
var state;
beforeEach(inject(function($state){
state = $state.get('productSearchResults');
spyOn(_ocParameters, 'Get');
spyOn(oc.Me, 'ListProducts');
}));
it('should resolve Parameters', inject(function($injector){
$injector.invoke(state.resolve.Parameters);
expect(_ocParameters.Get).toHaveBeenCalled();
}));
it('should resolve ProductList', inject(function($injector){
parameters.filters = {ParentID:'12'};
$injector.invoke(state.resolve.ProductList);
expect(oc.Me.ListProducts).toHaveBeenCalled();
}));
});
describe('Controller: ProductSearchController', function(){
var productSearchCtrl;
beforeEach(inject(function($state, $controller){
var state = $state;
productSearchCtrl = $controller('ProductSearchCtrl', {
$state: state,
ocParameters: _ocParameters,
$scope: scope,
ProductList: mockProductList
});
spyOn(_ocParameters, 'Create');
spyOn(state, 'go');
}));
describe('filter', function(){
it('should reload state and call ocParameters.Create with any parameters', function(){
productSearchCtrl.parameters = {pageSize: 1};
productSearchCtrl.filter(true);
expect(state.go).toHaveBeenCalled();
expect(_ocParameters.Create).toHaveBeenCalledWith({pageSize:1}, true);
});
});
describe('updateSort', function(){
it('should reload page with value and sort order, if both are defined', function(){
productSearchCtrl.updateSort('!ID');
expect(state.go).toHaveBeenCalled();
expect(_ocParameters.Create).toHaveBeenCalledWith({searchTerm: null, page: null, pageSize: null, sortBy: '!ID'}, false);
});
it('should reload page with just value, if no order is defined', function(){
productSearchCtrl.updateSort('ID');
expect(state.go).toHaveBeenCalled();
expect(_ocParameters.Create).toHaveBeenCalledWith({searchTerm: null, page: null, pageSize: null, sortBy: 'ID'}, false);
});
});
describe('updatePageSize', function(){
it('should reload state with the new pageSize', function(){
productSearchCtrl.updatePageSize('25');
expect(state.go).toHaveBeenCalled();
expect(_ocParameters.Create).toHaveBeenCalledWith({searchTerm: null, page: null, pageSize: '25', sortBy: null}, true);
});
});
describe('pageChanged', function(){
it('should reload state with the new page', function(){
productSearchCtrl.pageChanged('newPage');
expect(state.go).toHaveBeenCalled();
expect(_ocParameters.Create).toHaveBeenCalledWith({searchTerm: null, page: 'newPage', pageSize: null, sortBy: null}, false);
});
});
describe('reverseSort', function(){
it('should reload state with a reverse sort call', function(){
productSearchCtrl.parameters.sortBy = 'ID';
productSearchCtrl.reverseSort();
expect(_ocParameters.Create).toHaveBeenCalledWith({searchTerm: null, page: null, pageSize: null, sortBy: '!ID'}, false);
});
});
});
describe('Component Directive: ordercloudProductSearch', function(){
var productSearchComponentCtrl,
timeout
;
beforeEach(inject(function($componentController, $timeout){
timeout = $timeout;
productSearchComponentCtrl = $componentController('ordercloudProductSearch', {
$state:state,
$timeout: timeout,
$scope: scope,
OrderCloud:oc
});
spyOn(state, 'go');
}));
describe('getSearchResults', function(){
beforeEach(function(){
var defer = q.defer();
defer.resolve();
spyOn(oc.Me, 'ListProducts').and.returnValue(defer.promise);
});
it('should call Me.ListProducts with given search term and max products', function(){
productSearchComponentCtrl.searchTerm = 'Product1';
productSearchComponentCtrl.maxProducts = 12;
productSearchComponentCtrl.getSearchResults();
expect(oc.Me.ListProducts).toHaveBeenCalledWith('Product1', 1, 12);
});
it('should default max products to five, if none is provided', function(){
productSearchComponentCtrl.searchTerm = 'Product1';
productSearchComponentCtrl.getSearchResults();
expect(oc.Me.ListProducts).toHaveBeenCalledWith('Product1', 1, 5);
});
});
describe('onSelect', function(){
it('should route user to productDetail state for the selected product id', function(){
productSearchComponentCtrl.onSelect(12);
expect(state.go).toHaveBeenCalledWith('productDetail', {productid:12});
});
});
describe('onHardEnter', function(){
it('should route user to search results page for the provided search term', function(){
productSearchComponentCtrl.onHardEnter('bikes');
expect(state.go).toHaveBeenCalledWith('productSearchResults', {searchTerm: 'bikes'});
});
});
});
}); |
(function () {
'use strict';
angular.module('common')
.directive('svLumxUsersDropdown', function () {
return {
templateUrl: 'scripts/common/directives/sv-lumx-users-dropdown.html',
scope: {
btnTitle: '@',
actionCounter: '@',
userAvatar: '@',
userName: '@',
userFirstName: '@',
userLastName: '@',
iconType: '@',
iconName: '@'
},
link: function ($scope, el, attrs) {
}
};
});
})();
|
/*
* Copyright (c) 2015 by Rafael Angel Aznar Aparici (rafaaznar at gmail dot com)
*
* sisane: The stunning micro-library that helps you to develop easily
* AJAX web applications by using Angular.js 1.x & sisane-server
* sisane is distributed under the MIT License (MIT)
* Sources at https://github.com/rafaelaznar/
*
* 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.
*
*/
'use strict';
moduloEpisodio.controller('EpisodioViewpopController', ['$scope', '$routeParams', 'serverService', 'episodioService', '$location', '$uibModalInstance', 'id',
function ($scope, $routeParams, serverService, episodioService, $location, $uibModalInstance, id) {
$scope.fields = episodioService.getFields();
$scope.obtitle = episodioService.getObTitle();
$scope.icon = episodioService.getIcon();
$scope.ob = episodioService.getTitle();
$scope.title = "Vista de " + $scope.obtitle;
$scope.id = id;
$scope.status = null;
$scope.debugging = serverService.debugging();
serverService.promise_getOne($scope.ob, $scope.id).then(function (response) {
if (response.status == 200) {
if (response.data.status == 200) {
$scope.status = null;
$scope.bean = response.data.message;
var filter = "and,id_medico,equa," + $scope.bean.obj_medico.id;
serverService.promise_getPage("usuario", 1, 1, filter).then(function (data) {
if (data.data.message.length > 0)
$scope.medico = data.data.message[0];
});
} else {
$scope.status = "Error en la recepción de datos del servidor";
}
} else {
$scope.status = "Error en la recepción de datos del servidor";
}
}).catch(function (data) {
$scope.status = "Error en la recepción de datos del servidor";
});
$scope.cancel = function () {
$uibModalInstance.dismiss('cancel');
}
}]); |
'use strict';
var path = require('path');
var gulp = require('gulp');
var conf = require('./conf');
var browserSync = require('browser-sync');
function isOnlyChange(event) {
return event.type === 'changed';
}
gulp.task('watch', ['inject'], function () {
gulp.watch([path.join(conf.paths.src, '/*.html'), 'bower.json'], ['inject']);
gulp.watch([
path.join(conf.paths.src, '/assets/styles/css/**/*.css'),
path.join(conf.paths.src, '/assets/styles/less/**/*.less')
], function(event) {
if(isOnlyChange(event)) {
gulp.start('own-styles');
} else {
gulp.start('inject');
}
});
gulp.watch([
path.join(conf.paths.src, '/app/**/*.css'),
path.join(conf.paths.src, '/app/**/*.less')
], function(event) {
if(isOnlyChange(event)) {
gulp.start('styles');
} else {
gulp.start('inject');
}
});
gulp.watch(path.join(conf.paths.src, '/app/**/*.js'), function(event) {
if(isOnlyChange(event)) {
gulp.start('scripts');
} else {
gulp.start('inject');
}
});
gulp.watch(path.join(conf.paths.src, '/app/**/*.html'), function(event) {
browserSync.reload(event.path);
});
});
|
var assert = require('assert');
var _ = require('@sailshq/lodash');
var SchemaBuilder = require('../lib/waterline-schema');
describe('Has Many Through :: ', function() {
describe('Junction Tables', function() {
var schema;
before(function() {
var fixtures = [
{
identity: 'user',
primaryKey: 'id',
attributes: {
id: {
type: 'number'
},
cars: {
collection: 'car',
through: 'drive',
via: 'user'
}
}
},
{
identity: 'drive',
primaryKey: 'id',
attributes: {
id: {
type: 'number'
},
car: {
model: 'car'
},
user: {
model: 'user'
}
}
},
{
identity: 'car',
primaryKey: 'id',
attributes: {
id: {
type: 'number'
},
drivers: {
collection: 'user',
through: 'drive',
via: 'car'
}
}
}
];
var collections = _.map(fixtures, function(obj) {
var collection = function() {};
collection.prototype = obj;
return collection;
});
// Build the schema
schema = SchemaBuilder(collections);
});
it('should flag the "through" table and not mark it as a junction table', function() {
assert(schema.drive);
assert(!schema.drive.junctionTable);
assert(schema.drive.throughTable);
});
});
describe('Reference Mapping', function() {
var schema;
before(function() {
var fixtures = [
{
identity: 'foo',
primaryKey: 'id',
attributes: {
id: {
type: 'number'
},
bars: {
collection: 'bar',
through: 'foobar',
via: 'foo'
}
}
},
{
identity: 'foobar',
primaryKey: 'id',
attributes: {
id: {
type: 'number'
},
type: {
type: 'string'
},
foo: {
model: 'foo',
columnName: 'foo_id'
},
bar: {
model: 'bar',
columnName: 'bar_id'
}
}
},
{
identity: 'bar',
primaryKey: 'id',
attributes: {
id: {
type: 'number'
},
foo: {
collection: 'foo',
through: 'foobar',
via: 'bar'
}
}
}
];
var collections = _.map(fixtures, function(obj) {
var collection = function() {};
collection.prototype = obj;
return collection;
});
// Build the schema
schema = SchemaBuilder(collections);
});
it('should update the parent collection to point to the join table', function() {
assert.equal(schema.foo.schema.bars.references, 'foobar');
assert.equal(schema.foo.schema.bars.on, 'foo_id');
});
});
});
|
module('lively.ide.DirectoryWatcher').requires('lively.Network').toRun(function() {
// depends on the DirectoryWatcherServer
Object.extend(lively.ide.DirectoryWatcher, {
watchServerURL: new URL(Config.nodeJSURL+'/DirectoryWatchServer/'),
dirs: {},
reset: function() {
// lively.ide.DirectoryWatcher.reset()
this.dirs = {};
this.watchServerURL.withFilename('reset').asWebResource().post();
},
request: function(url, thenDo) {
return url.asWebResource().beAsync().withJSONWhenDone(function(json, status) {
thenDo(!json || json.error, json); }).get();
},
getFiles: function(dir, thenDo) {
this.request(this.watchServerURL.withFilename('files').withQuery({dir: dir}), thenDo);
},
getChanges: function(dir, since, startWatchTime, thenDo) {
this.request(this.watchServerURL.withFilename('changes').withQuery({
startWatchTime: startWatchTime, since: since, dir: dir}), thenDo);
},
withFilesOfDir: function(dir, doFunc) {
// Retrieves efficiently the files of dir. Uses a server side watcher that
// sends infos about file changes, deletions, creations.
// This methods synchs those with the cached state held in this object
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// dir = lively.shell.exec('pwd', {sync:true}).resultString()
// lively.ide.DirectoryWatcher.dirs
// lively.ide.DirectoryWatcher.withFilesOfDir(dir, function(files) { show(Object.keys(files).length); })
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
var watchState = this.dirs[dir] || (this.dirs[dir] = {updateInProgress: false, callbacks: []});
doFunc && watchState.callbacks.push(doFunc);
if (watchState.updateInProgress) { return; }
watchState.updateInProgress = true;
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
if (!watchState.files) { // first time called
this.getFiles(dir, function(err, result) {
if (err) show("dir watch error: %s", err);
result.files && Properties.forEachOwn(result.files, function(path, stat) { extend(stat); })
Object.extend(watchState, {
files: result.files,
lastUpdated: result.startTime,
startTime: result.startTime
});
whenDone();
});
return;
}
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
var timeSinceLastUpdate = Date.now() - (watchState.lastUpdated || 0);
if (timeSinceLastUpdate < 10 * 1000) { whenDone(); } // recently updated
// get updates
this.getChanges(dir, watchState.lastUpdated, watchState.startTime, function(err, result) {
if (!result.changes || result.changes.length === 0) { whenDone(); return; }
watchState.lastUpdated = result.changes[0].time;
console.log('%s files changed in %s: %s', result.changes.length, dir, result.changes.pluck('path').join('\n'));
result.changes.forEach(function(change) {
switch (change.type) {
case 'removal': delete watchState.files[change.path]; break;
case 'creation': case 'change': watchState.files[change.path] = extend(change.stat); break;
}
});
whenDone();
});
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
function whenDone() {
watchState.updateInProgress = false;
var cb;
while ((cb = watchState.callbacks.shift())) cb(watchState.files);
}
function extend(statObj) { // convert date string into a date object
if (!statObj) statObj = {};
statObj.isDirectory = !!(statObj.mode & 0x4000);
['atime', 'mtime', 'ctime'].forEach(function(field) {
if (statObj[field]) statObj[field] = new Date(statObj[field]); });
return statObj;
}
}
});
}) // end of module
|
// Generated by CoffeeScript 1.3.1
|
'use strict';
require('../common');
// This test ensures that zlib throws a RangeError if the final buffer needs to
// be larger than kMaxLength and concatenation fails.
// https://github.com/nodejs/node/pull/1811
const assert = require('assert');
// Change kMaxLength for zlib to trigger the error without having to allocate
// large Buffers.
const buffer = require('buffer');
const oldkMaxLength = buffer.kMaxLength;
buffer.kMaxLength = 64;
const zlib = require('zlib');
buffer.kMaxLength = oldkMaxLength;
const encoded = Buffer.from('G38A+CXCIrFAIAM=', 'base64');
// Async
zlib.brotliDecompress(encoded, function(err) {
assert.ok(err instanceof RangeError);
});
// Sync
assert.throws(function() {
zlib.brotliDecompressSync(encoded);
}, RangeError);
|
const {createAddColumnMigration} = require('../../utils');
module.exports = createAddColumnMigration('posts_meta', 'email_only', {
type: 'bool',
nullable: false,
defaultTo: false
});
|
//currently commented out as TokenTester is causing a OOG error due to the Factory being too big
//Not fully needed as factory & separate tests cover token creation.
/*contract("TokenTester", function(accounts) {
it("creates 10000 initial tokens", function(done) {
var tester = TokenTester.at(TokenTester.deployed_address);
tester.tokenContractAddress.call()
.then(function(tokenContractAddr) {
var tokenContract = HumanStandardToken.at(tokenContractAddr);
return tokenContract.balanceOf.call(TokenTester.deployed_address);
}).then(function (result) {
assert.strictEqual(result.toNumber(), 10000); // 10000 as specified in TokenTester.sol
done();
}).catch(done);
});
//todo:add test on retrieving addresses
});*/
|
module.exports = {
"extends": "airbnb",
"parser": "babel-eslint",
"plugins": [
"react"
],
"rules": {
"react/prop-types": 0,
"react/jsx-boolean-value": 0,
"consistent-return": 0,
"guard-for-in": 0,
"no-use-before-define": 0,
"space-before-function-paren": [2, { "anonymous": "never", "named": "always" }]
}
};
|
//>>built
define("clipart/SpinInput",["dojo/_base/declare","clipart/_clipart"],function(_1,_2){
return _1("clipart.SpinInput",[_2],{});
});
|
/**
* Created by jiangli on 15/1/6.
*/
"use strict";
var request = require('request');
var iconv = require('iconv-lite');
var crypto = require('crypto');
var Buffer = require('buffer').Buffer;
/**
* [_parseYouku 解析优酷网]
* @param [type] $url [description]
* @return [type] [description]
*/
module.exports = function($url,callback){
var $matches = $url.match(/id\_([\w=]+)/);
if ($matches&&$matches.length>1){
return _getYouku($matches[1].trim(),callback);
}else{
return null;
}
}
function _getYouku($vid,callback){
var $base = "http://v.youku.com/player/getPlaylist/VideoIDS/";
var $blink = $base+$vid;
var $link = $blink+"/Pf/4/ctype/12/ev/1";
request($link, function(er, response,body) {
if (er)
return callback(er);
var $retval = body;
if($retval){
var $rs = JSON.parse($retval);
request($blink, function(er, response,body) {
if (er)
return callback(er);
var $data = {
'1080Phd3':[],
'超清hd2':[],
'高清mp4':[],
'高清flvhd':[],
'标清flv':[],
'高清3gphd':[],
'3gp':[]
};
var $bretval = body;
var $brs = JSON.parse($bretval);
var $rs_data = $rs.data[0];
var $brs_data = $brs.data[0];
if($rs_data.error){
return callback(null, $data['error'] = $rs_data.error);
}
var $streamtypes = $rs_data.streamtypes; //可以输出的视频清晰度
var $streamfileids = $rs_data.streamfileids;
var $seed = $rs_data.seed;
var $segs = $rs_data.segs;
var $ip = $rs_data.ip;
var $bsegs = $brs_data.segs;
var yk_e_result = yk_e('becaf9be', yk_na($rs_data.ep)).split('_');
var $sid = yk_e_result[0], $token = yk_e_result[1];
for(var $key in $segs){
if(in_array($key,$streamtypes)){
var $segs_key_val = $segs[$key];
for(var kk=0;kk<$segs_key_val.length;kk++){
var $v = $segs_key_val[kk];
var $no = $v.no.toString(16).toUpperCase(); //转换为16进制 大写
if($no.length == 1){
$no ="0"+$no; //no 为每段视频序号
}
//构建视频地址K值
var $_k = $v.k;
if ((!$_k || $_k == '') || $_k == '-1') {
$_k = $bsegs[$key][kk].k;
}
var $fileId = getFileid($streamfileids[$key],$seed);
$fileId = $fileId.substr(0,8)+$no+$fileId.substr(10);
var m0 = yk_e('bf7e5f01', $sid + '_' + $fileId + '_' + $token);
var m1 = yk_d(m0);
var iconv_result = iconv.decode(new Buffer(m1), 'UTF-8');
if(iconv_result!=""){
var $ep = urlencode(iconv_result);
var $typeArray = [];
$typeArray['flv']= 'flv';
$typeArray['mp4']= 'mp4';
$typeArray['hd2']= 'flv';
$typeArray['3gphd']= 'mp4';
$typeArray['3gp']= 'flv';
$typeArray['hd3']= 'flv';
//判断视频清晰度
var $sharpness = []; //清晰度 数组
$sharpness['flv']= '标清flv';
$sharpness['flvhd']= '高清flvhd';
$sharpness['mp4']= '高清mp4';
$sharpness['hd2']= '超清hd2';
$sharpness['3gphd']= '高清3gphd';
$sharpness['3gp']= '3gp';
$sharpness['hd3']= '1080Phd3';
var $fileType = $typeArray[$key];
$data[$sharpness[$key]][kk] = "http://k.youku.com/player/getFlvPath/sid/"+$sid+"_00/st/"+$fileType+"/fileid/"+$fileId+"?K="+$_k+"&hd=1&myp=0&ts="+((((($v['seconds']+'&ypp=0&ctype=12&ev=1&token=')+$token)+'&oip=')+$ip)+'&ep=')+$ep;
}
}
}
}
//返回 图片 标题 链接 时长 视频地址
$data['coverImg'] = $rs['data'][0]['logo'];
$data['title'] = $rs['data'][0]['title'];
$data['seconds'] = $rs['data'][0]['seconds'];
return callback(null,$data);
});
}else{
return callback(null,null);
}
})
}
function urlencode(str) {
str = (str + '').toString();
return encodeURIComponent(str)
.replace(/!/g, '%21')
.replace(/'/g, '%27')
.replace(/\(/g, '%28')
.replace(/\)/g, '%29')
.replace(/\*/g, '%2A')
.replace(/%20/g, '+');
};
function in_array(needle, haystack, argStrict) {
var key = '',
strict = !! argStrict;
if (strict) {
for (key in haystack) {
if (haystack[key] === needle) {
return true;
}
}
} else {
for (key in haystack) {
if (haystack[key] == needle) {
return true;
}
}
}
return false;
};
//start 获得优酷视频需要用到的方法
function getSid(){
var $sid = new Date().getTime()+(Math.random() * 9001+10000);
return $sid;
}
function getKey($key1,$key2){
var $a = parseInt($key1,16);
var $b = $a ^0xA55AA5A5;
var $b = $b.toString(16);
return $key2+$b;
}
function getFileid($fileId,$seed){
var $mixed = getMixString($seed);
var $ids = $fileId.replace(/(\**$)/g, "").split('*'); //去掉末尾的*号分割为数组
var $realId = "";
for (var $i=0;$i<$ids.length;$i++){
var $idx = $ids[$i];
$realId += $mixed.substr($idx,1);
}
return $realId;
}
function getMixString($seed){
var $mixed = "";
var $source = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/\\:._-1234567890";
var $len = $source.length;
for(var $i=0;$i<$len;$i++){
$seed = ($seed * 211 + 30031)%65536;
var $index = ($seed / 65536 * $source.length);
var $c = $source.substr($index,1);
$mixed += $c;
$source = $source.replace($c,"");
}
return $mixed;
}
function yk_d($a){
if (!$a) {
return '';
}
var $f = $a.length;
var $b = 0;
var $str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
for (var $c = ''; $b < $f;) {
var $e = charCodeAt($a, $b++) & 255;
if ($b == $f) {
$c += charAt($str, $e >> 2);
$c += charAt($str, ($e & 3) << 4);
$c += '==';
break;
}
var $g = charCodeAt($a, $b++);
if ($b == $f) {
$c += charAt($str, $e >> 2);
$c += charAt($str, ($e & 3) << 4 | ($g & 240) >> 4);
$c += charAt($str, ($g & 15) << 2);
$c += '=';
break;
}
var $h = charCodeAt($a, $b++);
$c += charAt($str, $e >> 2);
$c += charAt($str, ($e & 3) << 4 | ($g & 240) >> 4);
$c += charAt($str, ($g & 15) << 2 | ($h & 192) >> 6);
$c += charAt($str, $h & 63);
}
return $c;
}
function yk_na($a){
if (!$a) {
return '';
}
var $sz = '-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-1,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1';
var $h = $sz.split(',');
var $i = $a.length;
var $f = 0;
for (var $e = ''; $f < $i;) {
var $c;
do {
$c = $h[charCodeAt($a, $f++) & 255];
} while ($f < $i && -1 == $c);
if (-1 == $c) {
break;
}
var $b;
do {
$b = $h[charCodeAt($a, $f++) & 255];
} while ($f < $i && -1 == $b);
if (-1 == $b) {
break;
}
$e += String.fromCharCode($c << 2 | ($b & 48) >> 4);
do {
$c = charCodeAt($a, $f++) & 255;
if (61 == $c) {
return $e;
}
$c = $h[$c];
} while ($f < $i && -1 == $c);
if (-1 == $c) {
break;
}
$e += String.fromCharCode(($b & 15) << 4 | ($c & 60) >> 2);
do {
$b = charCodeAt($a, $f++) & 255;
if (61 == $b) {
return $e;
}
$b = $h[$b];
} while ($f < $i && -1 == $b);
if (-1 == $b) {
break;
}
$e += String.fromCharCode(($c & 3) << 6 | $b);
}
return $e;
}
function yk_e($a, $c){
var $b = [];
for (var $f = 0, $i, $e = '', $h = 0; 256 > $h; $h++) {
$b[$h] = $h;
}
for ($h = 0; 256 > $h; $h++) {
$f = (($f + $b[$h]) + charCodeAt($a, $h % $a.length)) % 256;
$i = $b[$h];
$b[$h] = $b[$f];
$b[$f] = $i;
}
for (var $q = ($f = ($h = 0)); $q < $c.length; $q++) {
$h = ($h + 1) % 256;
$f = ($f + $b[$h]) % 256;
$i = $b[$h];
$b[$h] = $b[$f];
$b[$f] = $i;
$e += String.fromCharCode(charCodeAt($c, $q) ^ $b[($b[$h] + $b[$f]) % 256]);
}
return $e;
}
function md5(str){
var shasum = crypto.createHash('md5');
shasum.update(str);
return shasum.digest('hex');
}
function charCodeAt($str, $index){
var $charCode = [];
var $key = md5($str);
$index = $index + 1;
if ($charCode[$key]) {
return $charCode[$key][$index];
}
$charCode[$key] = unpack('C*', $str);
return $charCode[$key][$index];
}
function charAt($str, $index){
return $str.substr($index, 1);
}
function unpack(format, data) {
var formatPointer = 0, dataPointer = 0, result = {}, instruction = '',
quantifier = '', label = '', currentData = '', i = 0, j = 0,
word = '', fbits = 0, ebits = 0, dataByteLength = 0;
var fromIEEE754 = function(bytes, ebits, fbits) {
// Bytes to bits
var bits = [];
for (var i = bytes.length; i; i -= 1) {
var m_byte = bytes[i - 1];
for (var j = 8; j; j -= 1) {
bits.push(m_byte % 2 ? 1 : 0); m_byte = m_byte >> 1;
}
}
bits.reverse();
var str = bits.join('');
// Unpack sign, exponent, fraction
var bias = (1 << (ebits - 1)) - 1;
var s = parseInt(str.substring(0, 1), 2) ? -1 : 1;
var e = parseInt(str.substring(1, 1 + ebits), 2);
var f = parseInt(str.substring(1 + ebits), 2);
// Produce number
if (e === (1 << ebits) - 1) {
return f !== 0 ? NaN : s * Infinity;
}
else if (e > 0) {
return s * Math.pow(2, e - bias) * (1 + f / Math.pow(2, fbits));
}
else if (f !== 0) {
return s * Math.pow(2, -(bias-1)) * (f / Math.pow(2, fbits));
}
else {
return s * 0;
}
}
while (formatPointer < format.length) {
instruction = format.charAt(formatPointer);
// Start reading 'quantifier'
quantifier = '';
formatPointer++;
while ((formatPointer < format.length) &&
(format.charAt(formatPointer).match(/[\d\*]/) !== null)) {
quantifier += format.charAt(formatPointer);
formatPointer++;
}
if (quantifier === '') {
quantifier = '1';
}
// Start reading label
label = '';
while ((formatPointer < format.length) &&
(format.charAt(formatPointer) !== '/')) {
label += format.charAt(formatPointer);
formatPointer++;
}
if (format.charAt(formatPointer) === '/') {
formatPointer++;
}
// Process given instruction
switch (instruction) {
case 'a': // NUL-padded string
case 'A': // SPACE-padded string
if (quantifier === '*') {
quantifier = data.length - dataPointer;
} else {
quantifier = parseInt(quantifier, 10);
}
currentData = data.substr(dataPointer, quantifier);
dataPointer += quantifier;
var currentResult;
if (instruction === 'a') {
currentResult = currentData.replace(/\0+$/, '');
} else {
currentResult = currentData.replace(/ +$/, '');
}
result[label] = currentResult;
break;
case 'h': // Hex string, low nibble first
case 'H': // Hex string, high nibble first
if (quantifier === '*') {
quantifier = data.length - dataPointer;
} else {
quantifier = parseInt(quantifier, 10);
}
currentData = data.substr(dataPointer, quantifier);
dataPointer += quantifier;
if (quantifier > currentData.length) {
throw new Error('Warning: unpack(): Type ' + instruction +
': not enough input, need ' + quantifier);
}
currentResult = '';
for (i = 0; i < currentData.length; i++) {
word = currentData.charCodeAt(i).toString(16);
if (instruction === 'h') {
word = word[1] + word[0];
}
currentResult += word;
}
result[label] = currentResult;
break;
case 'c': // signed char
case 'C': // unsigned c
if (quantifier === '*') {
quantifier = data.length - dataPointer;
} else {
quantifier = parseInt(quantifier, 10);
}
currentData = data.substr(dataPointer, quantifier);
dataPointer += quantifier;
for (i = 0; i < currentData.length; i++) {
currentResult = currentData.charCodeAt(i);
if ((instruction === 'c') && (currentResult >= 128)) {
currentResult -= 256;
}
result[label + (quantifier > 1 ?
(i + 1) :
'')] = currentResult;
}
break;
case 'S': // unsigned short (always 16 bit, machine byte order)
case 's': // signed short (always 16 bit, machine byte order)
case 'v': // unsigned short (always 16 bit, little endian byte order)
if (quantifier === '*') {
quantifier = (data.length - dataPointer) / 2;
} else {
quantifier = parseInt(quantifier, 10);
}
currentData = data.substr(dataPointer, quantifier * 2);
dataPointer += quantifier * 2;
for (i = 0; i < currentData.length; i += 2) {
// sum per word;
currentResult = ((currentData.charCodeAt(i + 1) & 0xFF) << 8) +
(currentData.charCodeAt(i) & 0xFF);
if ((instruction === 's') && (currentResult >= 32768)) {
currentResult -= 65536;
}
result[label + (quantifier > 1 ?
((i / 2) + 1) :
'')] = currentResult;
}
break;
case 'n': // unsigned short (always 16 bit, big endian byte order)
if (quantifier === '*') {
quantifier = (data.length - dataPointer) / 2;
} else {
quantifier = parseInt(quantifier, 10);
}
currentData = data.substr(dataPointer, quantifier * 2);
dataPointer += quantifier * 2;
for (i = 0; i < currentData.length; i += 2) {
// sum per word;
currentResult = ((currentData.charCodeAt(i) & 0xFF) << 8) +
(currentData.charCodeAt(i + 1) & 0xFF);
result[label + (quantifier > 1 ?
((i / 2) + 1) :
'')] = currentResult;
}
break;
case 'i': // signed integer (machine dependent size and byte order)
case 'I': // unsigned integer (machine dependent size & byte order)
case 'l': // signed long (always 32 bit, machine byte order)
case 'L': // unsigned long (always 32 bit, machine byte order)
case 'V': // unsigned long (always 32 bit, little endian byte order)
if (quantifier === '*') {
quantifier = (data.length - dataPointer) / 4;
} else {
quantifier = parseInt(quantifier, 10);
}
currentData = data.substr(dataPointer, quantifier * 4);
dataPointer += quantifier * 4;
for (i = 0; i < currentData.length; i += 4) {
currentResult =
((currentData.charCodeAt(i + 3) & 0xFF) << 24) +
((currentData.charCodeAt(i + 2) & 0xFF) << 16) +
((currentData.charCodeAt(i + 1) & 0xFF) << 8) +
((currentData.charCodeAt(i) & 0xFF));
result[label + (quantifier > 1 ?
((i / 4) + 1) :
'')] = currentResult;
}
break;
case 'N': // unsigned long (always 32 bit, little endian byte order)
if (quantifier === '*') {
quantifier = (data.length - dataPointer) / 4;
} else {
quantifier = parseInt(quantifier, 10);
}
currentData = data.substr(dataPointer, quantifier * 4);
dataPointer += quantifier * 4;
for (i = 0; i < currentData.length; i += 4) {
currentResult =
((currentData.charCodeAt(i) & 0xFF) << 24) +
((currentData.charCodeAt(i + 1) & 0xFF) << 16) +
((currentData.charCodeAt(i + 2) & 0xFF) << 8) +
((currentData.charCodeAt(i + 3) & 0xFF));
result[label + (quantifier > 1 ?
((i / 4) + 1) :
'')] = currentResult;
}
break;
case 'f': //float
case 'd': //double
ebits = 8;
fbits = (instruction === 'f') ? 23 : 52;
dataByteLength = 4;
if (instruction === 'd') {
ebits = 11;
dataByteLength = 8;
}
if (quantifier === '*') {
quantifier = (data.length - dataPointer) / dataByteLength;
} else {
quantifier = parseInt(quantifier, 10);
}
currentData = data.substr(dataPointer, quantifier * dataByteLength);
dataPointer += quantifier * dataByteLength;
for (i = 0; i < currentData.length; i += dataByteLength) {
data = currentData.substr(i, dataByteLength);
var bytes = [];
for (j = data.length - 1; j >= 0; --j) {
bytes.push(data.charCodeAt(j));
}
result[label + (quantifier > 1 ?
((i / 4) + 1) :
'')] = fromIEEE754(bytes, ebits, fbits);
}
break;
case 'x': // NUL byte
case 'X': // Back up one byte
case '@': // NUL byte
if (quantifier === '*') {
quantifier = data.length - dataPointer;
} else {
quantifier = parseInt(quantifier, 10);
}
if (quantifier > 0) {
if (instruction === 'X') {
dataPointer -= quantifier;
} else {
if (instruction === 'x') {
dataPointer += quantifier;
} else {
dataPointer = quantifier;
}
}
}
break;
default:
throw new Error('Warning: unpack() Type ' + instruction +
': unknown format code');
}
}
return result;
} |
// This file has been autogenerated.
exports.setEnvironment = function() {
process.env['AZURE_SUBSCRIPTION_ID'] = 'e0b81f36-36ba-44f7-b550-7c9344a35893';
};
exports.scopes = [[function (nock) {
var result =
nock('http://management.azure.com:443')
.get('/subscriptions/e0b81f36-36ba-44f7-b550-7c9344a35893/resourceGroups/nodetestrg/providers/Microsoft.Devices/IotHubs/nodeTestHub/eventHubEndpoints/events/ConsumerGroups/testconsumergroup?api-version=2017-07-01')
.reply(200, "{\"tags\":null,\"id\":\"/subscriptions/e0b81f36-36ba-44f7-b550-7c9344a35893/resourceGroups/nodetestrg/providers/Microsoft.Devices/IotHubs/nodeTestHub\",\"name\":\"testconsumergroup\"}", { 'cache-control': 'no-cache',
pragma: 'no-cache',
'content-length': '173',
'content-type': 'application/json; charset=utf-8',
expires: '-1',
server: 'Microsoft-HTTPAPI/2.0',
'x-ms-ratelimit-remaining-subscription-reads': '14953',
'x-ms-request-id': 'be4cc550-e523-4bc7-898a-9c2a5aa64725',
'x-ms-correlation-request-id': 'be4cc550-e523-4bc7-898a-9c2a5aa64725',
'x-ms-routing-request-id': 'WESTUS:20170502T195224Z:be4cc550-e523-4bc7-898a-9c2a5aa64725',
'strict-transport-security': 'max-age=31536000; includeSubDomains',
date: 'Tue, 02 May 2017 19:52:23 GMT',
connection: 'close' });
return result; },
function (nock) {
var result =
nock('https://management.azure.com:443')
.get('/subscriptions/e0b81f36-36ba-44f7-b550-7c9344a35893/resourceGroups/nodetestrg/providers/Microsoft.Devices/IotHubs/nodeTestHub/eventHubEndpoints/events/ConsumerGroups/testconsumergroup?api-version=2017-07-01')
.reply(200, "{\"tags\":null,\"id\":\"/subscriptions/e0b81f36-36ba-44f7-b550-7c9344a35893/resourceGroups/nodetestrg/providers/Microsoft.Devices/IotHubs/nodeTestHub\",\"name\":\"testconsumergroup\"}", { 'cache-control': 'no-cache',
pragma: 'no-cache',
'content-length': '173',
'content-type': 'application/json; charset=utf-8',
expires: '-1',
server: 'Microsoft-HTTPAPI/2.0',
'x-ms-ratelimit-remaining-subscription-reads': '14953',
'x-ms-request-id': 'be4cc550-e523-4bc7-898a-9c2a5aa64725',
'x-ms-correlation-request-id': 'be4cc550-e523-4bc7-898a-9c2a5aa64725',
'x-ms-routing-request-id': 'WESTUS:20170502T195224Z:be4cc550-e523-4bc7-898a-9c2a5aa64725',
'strict-transport-security': 'max-age=31536000; includeSubDomains',
date: 'Tue, 02 May 2017 19:52:23 GMT',
connection: 'close' });
return result; }]]; |
module.exports = {
getMeta: function(meta) {
var d = meta.metaDescription || meta.description || meta.Description;
if (d && d instanceof Array) {
d = d[0];
}
return {
description: d
}
}
}; |
/*
* Treeview 1.5pre - jQuery plugin to hide and show branches of a tree
*
* http://bassistance.de/jquery-plugins/jquery-plugin-treeview/
* http://docs.jquery.com/Plugins/Treeview
*
* Copyright (c) 2007 Jörn Zaefferer
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
* Revision: $Id: jquery.treeview.js 5759 2008-07-01 07:50:28Z joern.zaefferer $
*
*/
;(function($) {
// TODO rewrite as a widget, removing all the extra plugins
$.extend($.fn, {
swapClass: function(c1, c2) {
var c1Elements = this.filter('.' + c1);
this.filter('.' + c2).removeClass(c2).addClass(c1);
c1Elements.removeClass(c1).addClass(c2);
return this;
},
replaceClass: function(c1, c2) {
return this.filter('.' + c1).removeClass(c1).addClass(c2).end();
},
hoverClass: function(className) {
className = className || "hover";
return this.hover(function() {
$(this).addClass(className);
}, function() {
$(this).removeClass(className);
});
},
heightToggle: function(animated, callback) {
animated ?
this.animate({ height: "toggle" }, animated, callback) :
this.each(function(){
jQuery(this)[ jQuery(this).is(":hidden") ? "show" : "hide" ]();
if(callback)
callback.apply(this, arguments);
});
},
heightHide: function(animated, callback) {
if (animated) {
this.animate({ height: "hide" }, animated, callback);
} else {
this.hide();
if (callback)
this.each(callback);
}
},
prepareBranches: function(settings) {
if (!settings.prerendered) {
// mark last tree items
this.filter(":last-child:not(ul)").addClass(CLASSES.last);
// collapse whole tree, or only those marked as closed, anyway except those marked as open
this.filter((settings.collapsed ? "" : "." + CLASSES.closed) + ":not(." + CLASSES.open + ")").find(">ul").hide();
}
// return all items with sublists
return this.filter(":has(>ul)");
},
applyClasses: function(settings, toggler) {
// TODO use event delegation
this.filter(":has(>ul):not(:has(>a))").find(">span").unbind("click.treeview").bind("click.treeview", function(event) {
// don't handle click events on children, eg. checkboxes
if ( this == event.target )
toggler.apply($(this).next());
}).add( $("a", this) ).hoverClass();
if (!settings.prerendered) {
// handle closed ones first
this.filter(":has(>ul:hidden)")
.addClass(CLASSES.expandable)
.replaceClass(CLASSES.last, CLASSES.lastExpandable);
// handle open ones
this.not(":has(>ul:hidden)")
.addClass(CLASSES.collapsable)
.replaceClass(CLASSES.last, CLASSES.lastCollapsable);
// create hitarea if not present
var hitarea = this.find("div." + CLASSES.hitarea);
if (!hitarea.length)
hitarea = this.prepend("<div class=\"" + CLASSES.hitarea + "\"/>").find("div." + CLASSES.hitarea);
hitarea.removeClass().addClass(CLASSES.hitarea).each(function() {
var classes = "";
$.each($(this).parent().attr("class").split(" "), function() {
classes += this + "-hitarea ";
});
$(this).addClass( classes );
})
}
// apply event to hitarea
this.find("div." + CLASSES.hitarea).click( toggler );
},
treeview: function(settings) {
settings = $.extend({
cookieId: "treeview"
}, settings);
if ( settings.toggle ) {
var callback = settings.toggle;
settings.toggle = function() {
return callback.apply($(this).parent()[0], arguments);
};
}
// factory for treecontroller
function treeController(tree, control) {
// factory for click handlers
function handler(filter) {
return function() {
// reuse toggle event handler, applying the elements to toggle
// start searching for all hitareas
toggler.apply( $("div." + CLASSES.hitarea, tree).filter(function() {
// for plain toggle, no filter is provided, otherwise we need to check the parent element
return filter ? $(this).parent("." + filter).length : true;
}) );
return false;
};
}
// click on first element to collapse tree
$("a:eq(0)", control).click( handler(CLASSES.collapsable) );
// click on second to expand tree
$("a:eq(1)", control).click( handler(CLASSES.expandable) );
// click on third to toggle tree
$("a:eq(2)", control).click( handler() );
}
// handle toggle event
function toggler() {
$(this)
.parent()
// swap classes for hitarea
.find(">.hitarea")
.swapClass( CLASSES.collapsableHitarea, CLASSES.expandableHitarea )
.swapClass( CLASSES.lastCollapsableHitarea, CLASSES.lastExpandableHitarea )
.end()
// swap classes for parent li
.swapClass( CLASSES.collapsable, CLASSES.expandable )
.swapClass( CLASSES.lastCollapsable, CLASSES.lastExpandable )
// find child lists
.find( ">ul" )
// toggle them
.heightToggle( settings.animated, settings.toggle );
if ( settings.unique ) {
$(this).parent()
.siblings()
// swap classes for hitarea
.find(">.hitarea")
.replaceClass( CLASSES.collapsableHitarea, CLASSES.expandableHitarea )
.replaceClass( CLASSES.lastCollapsableHitarea, CLASSES.lastExpandableHitarea )
.end()
.replaceClass( CLASSES.collapsable, CLASSES.expandable )
.replaceClass( CLASSES.lastCollapsable, CLASSES.lastExpandable )
.find( ">ul" )
.heightHide( settings.animated, settings.toggle );
}
}
this.data("toggler", toggler);
function serialize() {
function binary(arg) {
return arg ? 1 : 0;
}
var data = [];
branches.each(function(i, e) {
data[i] = $(e).is(":has(>ul:visible)") ? 1 : 0;
});
$.cookie(settings.cookieId, data.join(""), settings.cookieOptions );
}
function deserialize() {
var stored = $.cookie(settings.cookieId);
if ( stored ) {
var data = stored.split("");
branches.each(function(i, e) {
$(e).find(">ul")[ parseInt(data[i]) ? "show" : "hide" ]();
});
}
}
// add treeview class to activate styles
this.addClass("treeview");
// prepare branches and find all tree items with child lists
var branches = this.find("li").prepareBranches(settings);
switch(settings.persist) {
case "cookie":
var toggleCallback = settings.toggle;
settings.toggle = function() {
serialize();
if (toggleCallback) {
toggleCallback.apply(this, arguments);
}
};
deserialize();
break;
case "location":
var current = this.find("a").filter(function() {
return this.href.toLowerCase() == location.href.toLowerCase();
});
if ( current.length ) {
// TODO update the open/closed classes
var items = current.addClass("selected").parents("ul, li").add( current.next() ).show();
if (settings.prerendered) {
// if prerendered is on, replicate the basic class swapping
items.filter("li")
.swapClass( CLASSES.collapsable, CLASSES.expandable )
.swapClass( CLASSES.lastCollapsable, CLASSES.lastExpandable )
.find(">.hitarea")
.swapClass( CLASSES.collapsableHitarea, CLASSES.expandableHitarea )
.swapClass( CLASSES.lastCollapsableHitarea, CLASSES.lastExpandableHitarea );
}
}
break;
}
branches.applyClasses(settings, toggler);
// if control option is set, create the treecontroller and show it
if ( settings.control ) {
treeController(this, settings.control);
$(settings.control).show();
}
return this;
}
});
// classes used by the plugin
// need to be styled via external stylesheet, see first example
$.treeview = {};
var CLASSES = ($.treeview.classes = {
open: "open",
closed: "closed",
expandable: "expandable",
expandableHitarea: "expandable-hitarea",
lastExpandableHitarea: "lastExpandable-hitarea",
collapsable: "collapsable",
collapsableHitarea: "collapsable-hitarea",
lastCollapsableHitarea: "lastCollapsable-hitarea",
lastCollapsable: "lastCollapsable",
lastExpandable: "lastExpandable",
last: "last",
hitarea: "hitarea"
});
})(jQuery);
|
!((document, $) => {
var clip = new Clipboard('.copy-button');
clip.on('success', function(e) {
$('.copied').show();
$('.copied').fadeOut(2000);
});
})(document, jQuery);
|
var binary = require('node-pre-gyp');
var path = require('path');
var binding_path = binary.find(path.resolve(path.join(__dirname,'./package.json')));
var binding = require(binding_path);
var Stream = require('stream').Stream,
inherits = require('util').inherits;
function Snapshot() {}
Snapshot.prototype.getHeader = function() {
return {
typeId: this.typeId,
uid: this.uid,
title: this.title
}
}
/**
* @param {Snapshot} other
* @returns {Object}
*/
Snapshot.prototype.compare = function(other) {
var selfHist = nodesHist(this),
otherHist = nodesHist(other),
keys = Object.keys(selfHist).concat(Object.keys(otherHist)),
diff = {};
keys.forEach(function(key) {
if (key in diff) return;
var selfCount = selfHist[key] || 0,
otherCount = otherHist[key] || 0;
diff[key] = otherCount - selfCount;
});
return diff;
};
function ExportStream() {
Stream.Transform.call(this);
this._transform = function noTransform(chunk, encoding, done) {
done(null, chunk);
}
}
inherits(ExportStream, Stream.Transform);
/**
* @param {Stream.Writable|function} dataReceiver
* @returns {Stream|undefined}
*/
Snapshot.prototype.export = function(dataReceiver) {
dataReceiver = dataReceiver || new ExportStream();
var toStream = dataReceiver instanceof Stream,
chunks = toStream ? null : [];
function onChunk(chunk, len) {
if (toStream) dataReceiver.write(chunk);
else chunks.push(chunk);
}
function onDone() {
if (toStream) dataReceiver.end();
else dataReceiver(null, chunks.join(''));
}
this.serialize(onChunk, onDone);
return toStream ? dataReceiver : undefined;
};
function nodes(snapshot) {
var n = snapshot.nodesCount, i, nodes = [];
for (i = 0; i < n; i++) {
nodes[i] = snapshot.getNode(i);
}
return nodes;
};
function nodesHist(snapshot) {
var objects = {};
nodes(snapshot).forEach(function(node){
var key = node.type === "Object" ? node.name : node.type;
objects[key] = objects[node.name] || 0;
objects[key]++;
});
return objects;
};
function CpuProfile() {}
CpuProfile.prototype.getHeader = function() {
return {
typeId: this.typeId,
uid: this.uid,
title: this.title
}
}
CpuProfile.prototype.export = function(dataReceiver) {
dataReceiver = dataReceiver || new ExportStream();
var toStream = dataReceiver instanceof Stream;
var error, result;
try {
result = JSON.stringify(this);
} catch (err) {
error = err;
}
process.nextTick(function() {
if (toStream) {
if (error) {
dataReceiver.emit('error', error);
}
dataReceiver.end(result);
} else {
dataReceiver(error, result);
}
});
return toStream ? dataReceiver : undefined;
};
var startTime, endTime;
var activeProfiles = [];
var profiler = {
/*HEAP PROFILER API*/
get snapshots() { return binding.heap.snapshots; },
takeSnapshot: function(name, control) {
var snapshot = binding.heap.takeSnapshot.apply(null, arguments);
snapshot.__proto__ = Snapshot.prototype;
snapshot.title = name;
return snapshot;
},
getSnapshot: function(index) {
var snapshot = binding.heap.snapshots[index];
if (!snapshot) return;
snapshot.__proto__ = Snapshot.prototype;
return snapshot;
},
findSnapshot: function(uid) {
var snapshot = binding.heap.snapshots.filter(function(snapshot) {
return snapshot.uid == uid;
})[0];
if (!snapshot) return;
snapshot.__proto__ = Snapshot.prototype;
return snapshot;
},
deleteAllSnapshots: function () {
binding.heap.snapshots.forEach(function(snapshot) {
snapshot.delete();
});
},
startTrackingHeapObjects: binding.heap.startTrackingHeapObjects,
stopTrackingHeapObjects: binding.heap.stopTrackingHeapObjects,
getHeapStats: binding.heap.getHeapStats,
getObjectByHeapObjectId: binding.heap.getObjectByHeapObjectId,
/*CPU PROFILER API*/
get profiles() { return binding.cpu.profiles; },
startProfiling: function(name, recsamples) {
if (activeProfiles.length == 0 && typeof process._startProfilerIdleNotifier == "function")
process._startProfilerIdleNotifier();
name = name || "";
if (activeProfiles.indexOf(name) < 0)
activeProfiles.push(name)
startTime = Date.now();
binding.cpu.startProfiling(name, recsamples);
},
stopProfiling: function(name) {
var index = activeProfiles.indexOf(name);
if (name && index < 0)
return;
var profile = binding.cpu.stopProfiling(name);
endTime = Date.now();
profile.__proto__ = CpuProfile.prototype;
if (!profile.startTime) profile.startTime = startTime;
if (!profile.endTime) profile.endTime = endTime;
if (name)
activeProfiles.splice(index, 1);
else
activeProfiles.length = activeProfiles.length - 1;
if (activeProfiles.length == 0 && typeof process._stopProfilerIdleNotifier == "function")
process._stopProfilerIdleNotifier();
return profile;
},
getProfile: function(index) {
return binding.cpu.profiles[index];
},
findProfile: function(uid) {
var profile = binding.cpu.profiles.filter(function(profile) {
return profile.uid == uid;
})[0];
return profile;
},
deleteAllProfiles: function() {
binding.cpu.profiles.forEach(function(profile) {
profile.delete();
});
}
};
module.exports = profiler;
process.profiler = profiler;
|
/**
* webdriverio
* https://github.com/Camme/webdriverio
*
* A WebDriver module for nodejs. Either use the super easy help commands or use the base
* Webdriver wire protocol commands. Its totally inspired by jellyfishs webdriver, but the
* goal is to make all the webdriver protocol items available, as near the original as possible.
*
* Copyright (c) 2013 Camilo Tapia <[email protected]>
* Licensed under the MIT license.
*
* Contributors:
* Dan Jenkins <[email protected]>
* Christian Bromann <[email protected]>
* Vincent Voyer <[email protected]>
*/
import WebdriverIO from './lib/webdriverio'
import Multibrowser from './lib/multibrowser'
import ErrorHandler from './lib/utils/ErrorHandler'
import getImplementedCommands from './lib/helpers/getImplementedCommands'
import pkg from './package.json'
const IMPLEMENTED_COMMANDS = getImplementedCommands()
const VERSION = pkg.version
let remote = function (options = {}, modifier) {
/**
* initialise monad
*/
let wdio = WebdriverIO(options, modifier)
/**
* build prototype: commands
*/
for (let commandName of Object.keys(IMPLEMENTED_COMMANDS)) {
wdio.lift(commandName, IMPLEMENTED_COMMANDS[commandName])
}
let prototype = wdio()
prototype.defer.resolve()
return prototype
}
let multiremote = function (options) {
let multibrowser = new Multibrowser()
for (let browserName of Object.keys(options)) {
multibrowser.addInstance(
browserName,
remote(options[browserName], multibrowser.getInstanceModifier())
)
}
return remote(options, multibrowser.getModifier())
}
export { remote, multiremote, VERSION, ErrorHandler }
|
Subsets and Splits