text
stringlengths 2
1.05M
|
|---|
import apisauce from 'apisauce'
// our "constructor"
const create = (baseURL = 'https://gofdrones.herokuapp.com/api/v1') => {
// ------
// Configuration
// ------
const api = apisauce.create({
baseURL,
headers: {
'Cache-Control': 'no-cache',
},
timeout: 10000,
})
// ------
// Services
// ------
const getWeapons = () => api.get('/weapons')
// ------
// Interface
// ------
return {
getWeapons,
}
}
export default {
create,
}
|
/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/ */
/**
* This test is designed to test responsiveness while performing actions
* on various context menus in both content and chrome.
*/
Components.utils.import("resource://mozmill/driver/mozmill.js");
let c = getBrowserController();
// Open mozilla.org and wait for the page to load
c.open("http://mozilla.org");
c.waitForPageLoad();
// Perform our first action, reload.
// It is very important to only place things that we
// are interested in testing inside of a performAction call
pep.performAction('content_reload', function() {
// controller.rootElement is the global window object
// wrapped inside of a MozMillElement
c.rootElement.rightClick();
c.rootElement.keypress('r');
});
c.waitForPageLoad();
c.open("http://mozillians.org");
c.waitForPageLoad();
// Perform our second action, go back
pep.performAction('content_back', function() {
c.rootElement.rightClick();
c.rootElement.keypress('b');
});
// Bug 699400 - waitForPageLoad times out when pressing back button
c.sleep(500);
// get a reference to the element with id 'home'
page = findElement.ID(c.tabs.activeTab, 'home');
// Perform our third action, scroll through context menu
pep.performAction('content_scroll', function() {
page.rightClick();
for (let i = 0; i < 15; ++i) {
page.keypress('VK_DOWN');
// Sleep to better emulate a user
c.sleep(10);
}
});
// close the context menu
page.keypress('VK_ESCAPE');
// Now test context menus in chrome
let bar = findElement.ID(c.window.document, "toolbar-menubar");
bar.click();
pep.performAction('chrome_navigation', function() {
bar.rightClick();
bar.keypress('n');
c.sleep(100);
bar.rightClick();
bar.keypress('n');
});
pep.performAction('chrome_scroll', function() {
bar.rightClick();
for (let i = 0; i < 15; ++i) {
bar.keypress('VK_DOWN');
// Sleep to better emulate a user
c.sleep(10);
}
});
bar.keypress('VK_ESCAPE');
|
import assert from 'assert';
import fs from 'fs';
import { format } from 'util';
import vm from 'vm';
import validator from '../src/index';
let validator_js = fs.readFileSync(require.resolve('../validator.js')).toString();
function test(options) {
let args = options.args || [];
args.unshift(null);
if (options.error) {
options.error.forEach((error) => {
args[0] = error;
try {
assert.throws(() => validator[options.validator](...args));
} catch (err) {
let warning = format(
'validator.%s(%s) passed but should error',
options.validator, args.join(', ')
);
throw new Error(warning);
}
});
}
if (options.valid) {
options.valid.forEach((valid) => {
args[0] = valid;
if (validator[options.validator](...args) !== true) {
let warning = format(
'validator.%s(%s) failed but should have passed',
options.validator, args.join(', ')
);
throw new Error(warning);
}
});
}
if (options.invalid) {
options.invalid.forEach((invalid) => {
args[0] = invalid;
if (validator[options.validator](...args) !== false) {
let warning = format(
'validator.%s(%s) passed but should have failed',
options.validator, args.join(', ')
);
throw new Error(warning);
}
});
}
}
function repeat(str, count) {
let result = '';
for (; count; count--) {
result += str;
}
return result;
}
describe('Validators', () => {
it('should validate email addresses', () => {
test({
validator: 'isEmail',
valid: [
'foo@bar.com',
'x@x.au',
'foo@bar.com.au',
'foo+bar@bar.com',
'hans.m端ller@test.com',
'hans@m端ller.com',
'test|123@m端ller.com',
'test123+ext@gmail.com',
'some.name.midd.leNa.me+extension@GoogleMail.com',
'"foobar"@example.com',
'" foo m端ller "@example.com',
'"foo\\@bar"@example.com',
`${repeat('a', 64)}@${repeat('a', 63)}.com`,
`${repeat('a', 64)}@${repeat('a', 63)}.com`,
`${repeat('a', 31)}@gmail.com`,
'test@gmail.com',
'test.1@gmail.com',
],
invalid: [
'invalidemail@',
'invalid.com',
'@invalid.com',
'foo@bar.com.',
'somename@gmail.com',
'foo@bar.co.uk.',
'z@co.c',
'gmailgmailgmailgmailgmail@gmail.com',
`${repeat('a', 64)}@${repeat('a', 251)}.com`,
`${repeat('a', 65)}@${repeat('a', 250)}.com`,
`${repeat('a', 64)}@${repeat('a', 64)}.com`,
`${repeat('a', 64)}@${repeat('a', 63)}.${repeat('a', 63)}.${repeat('a', 63)}.${repeat('a', 58)}.com`,
'test1@invalid.co m',
'test2@invalid.co m',
'test3@invalid.co m',
'test4@invalid.co m',
'test5@invalid.co m',
'test6@invalid.co m',
'test7@invalid.co m',
'test8@invalid.co m',
'test9@invalid.co m',
'test10@invalid.co m',
'test11@invalid.co m',
'test12@invalid.co m',
'test13@invalid.co m',
'multiple..dots@stillinvalid.com',
'test123+invalid! sub_address@gmail.com',
'gmail...ignores...dots...@gmail.com',
'ends.with.dot.@gmail.com',
'multiple..dots@gmail.com',
'wrong()[]",:;<>@@gmail.com',
'"wrong()[]",:;<>@@gmail.com',
],
});
});
it('should validate email addresses with domain specific validation', () => {
test({
validator: 'isEmail',
args: [{ domain_specific_validation: true }],
valid: [
'foobar@gmail.com',
'foo.bar@gmail.com',
'foo.bar@googlemail.com',
`${repeat('a', 30)}@gmail.com`,
],
invalid: [
`${repeat('a', 31)}@gmail.com`,
'test@gmail.com',
'test.1@gmail.com',
'.foobar@gmail.com',
],
});
});
it('should validate email addresses without UTF8 characters in local part', () => {
test({
validator: 'isEmail',
args: [{ allow_utf8_local_part: false }],
valid: [
'foo@bar.com',
'x@x.au',
'foo@bar.com.au',
'foo+bar@bar.com',
'hans@m端ller.com',
'test|123@m端ller.com',
'test123+ext@gmail.com',
'some.name.midd.leNa.me+extension@GoogleMail.com',
'"foobar"@example.com',
'"foo\\@bar"@example.com',
'" foo bar "@example.com',
],
invalid: [
'invalidemail@',
'invalid.com',
'@invalid.com',
'foo@bar.com.',
'foo@bar.co.uk.',
'somename@gmail.com',
'hans.m端ller@test.com',
'z@co.c',
'tüst@invalid.com',
],
});
});
it('should validate email addresses with display names', () => {
test({
validator: 'isEmail',
args: [{ allow_display_name: true }],
valid: [
'foo@bar.com',
'x@x.au',
'foo@bar.com.au',
'foo+bar@bar.com',
'hans.m端ller@test.com',
'hans@m端ller.com',
'test|123@m端ller.com',
'test123+ext@gmail.com',
'some.name.midd.leNa.me+extension@GoogleMail.com',
'Some Name <foo@bar.com>',
'Some Name <x@x.au>',
'Some Name <foo@bar.com.au>',
'Some Name <foo+bar@bar.com>',
'Some Name <hans.m端ller@test.com>',
'Some Name <hans@m端ller.com>',
'Some Name <test|123@m端ller.com>',
'Some Name <test123+ext@gmail.com>',
'\'Foo Bar, Esq\'<foo@bar.com>',
'Some Name <some.name.midd.leNa.me+extension@GoogleMail.com>',
'Some Middle Name <some.name.midd.leNa.me+extension@GoogleMail.com>',
'Name <some.name.midd.leNa.me+extension@GoogleMail.com>',
'Name<some.name.midd.leNa.me+extension@GoogleMail.com>',
'Some Name <foo@gmail.com>',
'Name🍓With🍑Emoji🚴♀️🏆<test@aftership.com>',
'🍇🍗🍑<only_emoji@aftership.com>',
'"<displayNameInBrackets>"<jh@gmail.com>',
'"\\"quotes\\""<jh@gmail.com>',
'"name;"<jh@gmail.com>',
'"name;" <jh@gmail.com>',
],
invalid: [
'invalidemail@',
'invalid.com',
'@invalid.com',
'foo@bar.com.',
'foo@bar.co.uk.',
'Some Name <invalidemail@>',
'Some Name <invalid.com>',
'Some Name <@invalid.com>',
'Some Name <foo@bar.com.>',
'Some Name <foo@bar.co.uk.>',
'Some Name foo@bar.co.uk.>',
'Some Name <foo@bar.co.uk.',
'Some Name < foo@bar.co.uk >',
'Name foo@bar.co.uk',
'Some Name <some..name@gmail.com>',
'Some Name<emoji_in_address🍈@aftership.com>',
'invisibleCharacter\u001F<jh@gmail.com>',
'<displayNameInBrackets><jh@gmail.com>',
'\\"quotes\\"<jh@gmail.com>',
'""quotes""<jh@gmail.com>',
'name;<jh@gmail.com>',
' <jh@gmail.com>',
'" "<jh@gmail.com>',
],
});
});
it('should validate email addresses with required display names', () => {
test({
validator: 'isEmail',
args: [{ require_display_name: true }],
valid: [
'Some Name <foo@bar.com>',
'Some Name <x@x.au>',
'Some Name <foo@bar.com.au>',
'Some Name <foo+bar@bar.com>',
'Some Name <hans.m端ller@test.com>',
'Some Name <hans@m端ller.com>',
'Some Name <test|123@m端ller.com>',
'Some Name <test123+ext@gmail.com>',
'Some Name <some.name.midd.leNa.me+extension@GoogleMail.com>',
'Some Middle Name <some.name.midd.leNa.me+extension@GoogleMail.com>',
'Name <some.name.midd.leNa.me+extension@GoogleMail.com>',
'Name<some.name.midd.leNa.me+extension@GoogleMail.com>',
],
invalid: [
'some.name.midd.leNa.me+extension@GoogleMail.com',
'foo@bar.com',
'x@x.au',
'foo@bar.com.au',
'foo+bar@bar.com',
'hans.m端ller@test.com',
'hans@m端ller.com',
'test|123@m端ller.com',
'test123+ext@gmail.com',
'invalidemail@',
'invalid.com',
'@invalid.com',
'foo@bar.com.',
'foo@bar.co.uk.',
'Some Name <invalidemail@>',
'Some Name <invalid.com>',
'Some Name <@invalid.com>',
'Some Name <foo@bar.com.>',
'Some Name <foo@bar.co.uk.>',
'Some Name foo@bar.co.uk.>',
'Some Name <foo@bar.co.uk.',
'Some Name < foo@bar.co.uk >',
'Name foo@bar.co.uk',
],
});
});
it('should validate email addresses with allowed IPs', () => {
test({
validator: 'isEmail',
args: [{ allow_ip_domain: true }],
valid: [
'email@[123.123.123.123]',
'email@255.255.255.255',
],
invalid: [
'email@0.0.0.256',
'email@26.0.0.256',
'email@[266.266.266.266]',
],
});
});
it('should validate URLs', () => {
test({
validator: 'isURL',
valid: [
'foobar.com',
'www.foobar.com',
'foobar.com/',
'valid.au',
'http://www.foobar.com/',
'HTTP://WWW.FOOBAR.COM/',
'https://www.foobar.com/',
'HTTPS://WWW.FOOBAR.COM/',
'http://www.foobar.com:23/',
'http://www.foobar.com:65535/',
'http://www.foobar.com:5/',
'https://www.foobar.com/',
'ftp://www.foobar.com/',
'http://www.foobar.com/~foobar',
'http://user:pass@www.foobar.com/',
'http://user:@www.foobar.com/',
'http://127.0.0.1/',
'http://10.0.0.0/',
'http://189.123.14.13/',
'http://duckduckgo.com/?q=%2F',
'http://foobar.com/t$-_.+!*\'(),',
'http://foobar.com/?foo=bar#baz=qux',
'http://foobar.com?foo=bar',
'http://foobar.com#baz=qux',
'http://www.xn--froschgrn-x9a.net/',
'http://xn--froschgrn-x9a.com/',
'http://foo--bar.com',
'http://høyfjellet.no',
'http://xn--j1aac5a4g.xn--j1amh',
'http://xn------eddceddeftq7bvv7c4ke4c.xn--p1ai',
'http://кулік.укр',
'test.com?ref=http://test2.com',
'http://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80/index.html',
'http://[1080:0:0:0:8:800:200C:417A]/index.html',
'http://[3ffe:2a00:100:7031::1]',
'http://[1080::8:800:200C:417A]/foo',
'http://[::192.9.5.5]/ipng',
'http://[::FFFF:129.144.52.38]:80/index.html',
'http://[2010:836B:4179::836B:4179]',
'http://example.com/example.json#/foo/bar',
],
invalid: [
'http://localhost:3000/',
'//foobar.com',
'xyz://foobar.com',
'invalid/',
'invalid.x',
'invalid.',
'.com',
'http://com/',
'http://300.0.0.1/',
'mailto:foo@bar.com',
'rtmp://foobar.com',
'http://www.xn--.com/',
'http://xn--.com/',
'http://www.foobar.com:0/',
'http://www.foobar.com:70000/',
'http://www.foobar.com:99999/',
'http://www.-foobar.com/',
'http://www.foobar-.com/',
'http://foobar/# lol',
'http://foobar/? lol',
'http://foobar/ lol/',
'http://lol @foobar.com/',
'http://lol:lol @foobar.com/',
'http://lol:lol:lol@foobar.com/',
'http://lol: @foobar.com/',
'http://www.foo_bar.com/',
'http://www.foobar.com/\t',
'http://\n@www.foobar.com/',
'',
`http://foobar.com/${new Array(2083).join('f')}`,
'http://*.foo.com',
'*.foo.com',
'!.foo.com',
'http://example.com.',
'http://localhost:61500this is an invalid url!!!!',
'////foobar.com',
'http:////foobar.com',
'https://example.com/foo/<script>alert(\'XSS\')</script>/',
],
});
});
it('should validate URLs with custom protocols', () => {
test({
validator: 'isURL',
args: [{
protocols: ['rtmp'],
}],
valid: [
'rtmp://foobar.com',
],
invalid: [
'http://foobar.com',
],
});
});
it('should validate file URLs without a host', () => {
test({
validator: 'isURL',
args: [{
protocols: ['file'],
require_host: false,
require_tld: false,
}],
valid: [
'file://localhost/foo.txt',
'file:///foo.txt',
'file:///',
],
invalid: [
'http://foobar.com',
'file://',
],
});
});
it('should validate URLs with any protocol', () => {
test({
validator: 'isURL',
args: [{
require_valid_protocol: false,
}],
valid: [
'rtmp://foobar.com',
'http://foobar.com',
'test://foobar.com',
],
invalid: [
'mailto:test@example.com',
],
});
});
it('should validate URLs with underscores', () => {
test({
validator: 'isURL',
args: [{
allow_underscores: true,
}],
valid: [
'http://foo_bar.com',
'http://pr.example_com.294.example.com/',
'http://foo__bar.com',
],
invalid: [],
});
});
it('should validate URLs that do not have a TLD', () => {
test({
validator: 'isURL',
args: [{
require_tld: false,
}],
valid: [
'http://foobar.com/',
'http://foobar/',
'http://localhost/',
'foobar/',
'foobar',
],
invalid: [],
});
});
it('should validate URLs with a trailing dot option', () => {
test({
validator: 'isURL',
args: [{
allow_trailing_dot: true,
require_tld: false,
}],
valid: [
'http://example.com.',
'foobar.',
],
});
});
it('should validate protocol relative URLs', () => {
test({
validator: 'isURL',
args: [{
allow_protocol_relative_urls: true,
}],
valid: [
'//foobar.com',
'http://foobar.com',
'foobar.com',
],
invalid: [
'://foobar.com',
'/foobar.com',
'////foobar.com',
'http:////foobar.com',
],
});
});
it('should not validate protocol relative URLs when require protocol is true', () => {
test({
validator: 'isURL',
args: [{
allow_protocol_relative_urls: true,
require_protocol: true,
}],
valid: [
'http://foobar.com',
],
invalid: [
'//foobar.com',
'://foobar.com',
'/foobar.com',
'foobar.com',
],
});
});
it('should let users specify whether URLs require a protocol', () => {
test({
validator: 'isURL',
args: [{
require_protocol: true,
}],
valid: [
'http://foobar.com/',
],
invalid: [
'http://localhost/',
'foobar.com',
'foobar',
],
});
});
it('should let users specify a host whitelist', () => {
test({
validator: 'isURL',
args: [{
host_whitelist: ['foo.com', 'bar.com'],
}],
valid: [
'http://bar.com/',
'http://foo.com/',
],
invalid: [
'http://foobar.com',
'http://foo.bar.com/',
'http://qux.com',
],
});
});
it('should allow regular expressions in the host whitelist', () => {
test({
validator: 'isURL',
args: [{
host_whitelist: ['bar.com', 'foo.com', /\.foo\.com$/],
}],
valid: [
'http://bar.com/',
'http://foo.com/',
'http://images.foo.com/',
'http://cdn.foo.com/',
'http://a.b.c.foo.com/',
],
invalid: [
'http://foobar.com',
'http://foo.bar.com/',
'http://qux.com',
],
});
});
it('should let users specify a host blacklist', () => {
test({
validator: 'isURL',
args: [{
host_blacklist: ['foo.com', 'bar.com'],
}],
valid: [
'http://foobar.com',
'http://foo.bar.com/',
'http://qux.com',
],
invalid: [
'http://bar.com/',
'http://foo.com/',
],
});
});
it('should allow regular expressions in the host blacklist', () => {
test({
validator: 'isURL',
args: [{
host_blacklist: ['bar.com', 'foo.com', /\.foo\.com$/],
}],
valid: [
'http://foobar.com',
'http://foo.bar.com/',
'http://qux.com',
],
invalid: [
'http://bar.com/',
'http://foo.com/',
'http://images.foo.com/',
'http://cdn.foo.com/',
'http://a.b.c.foo.com/',
],
});
});
it('should allow rejecting urls containing authentication information', () => {
test({
validator: 'isURL',
args: [{ disallow_auth: true }],
valid: [
'doe.com',
],
invalid: [
'john@doe.com',
'john:john@doe.com',
],
});
});
it('should validate MAC addresses', () => {
test({
validator: 'isMACAddress',
valid: [
'ab:ab:ab:ab:ab:ab',
'FF:FF:FF:FF:FF:FF',
'01:02:03:04:05:ab',
'01:AB:03:04:05:06',
'A9 C5 D4 9F EB D3',
'01 02 03 04 05 ab',
'01-02-03-04-05-ab',
],
invalid: [
'abc',
'01:02:03:04:05',
'01:02:03:04::ab',
'1:2:3:4:5:6',
'AB:CD:EF:GH:01:02',
'A9C5 D4 9F EB D3',
'01-02 03:04 05 ab',
],
});
});
it('should validate MAC addresses without colons', () => {
test({
validator: 'isMACAddress',
args: [{
no_colons: true,
}],
valid: [
'abababababab',
'FFFFFFFFFFFF',
'0102030405ab',
'01AB03040506',
],
invalid: [
'abc',
'01:02:03:04:05',
'01:02:03:04::ab',
'1:2:3:4:5:6',
'AB:CD:EF:GH:01:02',
'ab:ab:ab:ab:ab:ab',
'FF:FF:FF:FF:FF:FF',
'01:02:03:04:05:ab',
'01:AB:03:04:05:06',
'0102030405',
'01020304ab',
'123456',
'ABCDEFGH0102',
],
});
});
it('should validate IP addresses', () => {
test({
validator: 'isIP',
valid: [
'127.0.0.1',
'0.0.0.0',
'255.255.255.255',
'1.2.3.4',
'::1',
'2001:db8:0000:1:1:1:1:1',
'2001:41d0:2:a141::1',
'::ffff:127.0.0.1',
'::0000',
'0000::',
'1::',
'1111:1:1:1:1:1:1:1',
'fe80::a6db:30ff:fe98:e946',
'::',
'::ffff:127.0.0.1',
'0:0:0:0:0:ffff:127.0.0.1',
],
invalid: [
'abc',
'256.0.0.0',
'0.0.0.256',
'26.0.0.256',
'0200.200.200.200',
'200.0200.200.200',
'200.200.0200.200',
'200.200.200.0200',
'::banana',
'banana::',
'::1banana',
'::1::',
'1:',
':1',
':1:1:1::2',
'1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1',
'::11111',
'11111:1:1:1:1:1:1:1',
'2001:db8:0000:1:1:1:1::1',
'0:0:0:0:0:0:ffff:127.0.0.1',
'0:0:0:0:ffff:127.0.0.1',
],
});
test({
validator: 'isIP',
args: [4],
valid: [
'127.0.0.1',
'0.0.0.0',
'255.255.255.255',
'1.2.3.4',
],
invalid: [
'::1',
'2001:db8:0000:1:1:1:1:1',
'::ffff:127.0.0.1',
],
});
test({
validator: 'isIP',
args: [6],
valid: [
'::1',
'2001:db8:0000:1:1:1:1:1',
'::ffff:127.0.0.1',
'fe80::1234%1',
'ff08::9abc%10',
'ff08::9abc%interface10',
'ff02::5678%pvc1.3',
],
invalid: [
'127.0.0.1',
'0.0.0.0',
'255.255.255.255',
'1.2.3.4',
'::ffff:287.0.0.1',
'%',
'fe80::1234%',
'fe80::1234%1%3%4',
'fe80%fe80%',
],
});
test({
validator: 'isIP',
args: [10],
valid: [],
invalid: [
'127.0.0.1',
'0.0.0.0',
'255.255.255.255',
'1.2.3.4',
'::1',
'2001:db8:0000:1:1:1:1:1',
],
});
});
it('should validate isIPRange', () => {
test({
validator: 'isIPRange',
valid: [
'127.0.0.1/24',
'0.0.0.0/0',
'255.255.255.0/32',
],
invalid: [
'127.200.230.1/35',
'127.200.230.1/-1',
'1.1.1.1/011',
'::1/64',
'1.1.1/24.1',
'1.1.1.1/01',
'1.1.1.1/1.1',
'1.1.1.1/1.',
'1.1.1.1/1/1',
'1.1.1.1',
],
});
});
it('should validate FQDN', () => {
test({
validator: 'isFQDN',
valid: [
'domain.com',
'dom.plato',
'a.domain.co',
'foo--bar.com',
'xn--froschgrn-x9a.com',
'rebecca.blackfriday',
],
invalid: [
'abc',
'256.0.0.0',
'_.com',
'*.some.com',
's!ome.com',
'domain.com/',
'/more.com',
],
});
});
it('should validate FQDN with trailing dot option', () => {
test({
validator: 'isFQDN',
args: [
{ allow_trailing_dot: true },
],
valid: [
'example.com.',
],
});
});
it('should validate alpha strings', () => {
test({
validator: 'isAlpha',
valid: [
'abc',
'ABC',
'FoObar',
],
invalid: [
'abc1',
' foo ',
'',
'ÄBC',
'FÜübar',
'Jön',
'Heiß',
],
});
});
it('should validate bulgarian alpha strings', () => {
test({
validator: 'isAlpha',
args: ['bg-BG'],
valid: [
'абв',
'АБВ',
'жаба',
'яГоДа',
],
invalid: [
'abc1',
' foo ',
'',
'ЁЧПС',
'_аз_обичам_обувки_',
'ехо!',
],
});
});
it('should validate czech alpha strings', () => {
test({
validator: 'isAlpha',
args: ['cs-CZ'],
valid: [
'žluťoučký',
'KŮŇ',
'Pěl',
'Ďábelské',
'ódy',
],
invalid: [
'ábc1',
' fůj ',
'',
],
});
});
it('should validate slovak alpha strings', () => {
test({
validator: 'isAlpha',
args: ['sk-SK'],
valid: [
'môj',
'ľúbím',
'mäkčeň',
'stĹp',
'vŕba',
'ňorimberk',
'ťava',
'žanéta',
'Ďábelské',
'ódy',
],
invalid: [
'1moj',
'你好世界',
' Привет мир ',
'مرحبا العا ',
],
});
});
it('should validate danish alpha strings', () => {
test({
validator: 'isAlpha',
args: ['da-DK'],
valid: [
'aøå',
'Ære',
'Øre',
'Åre',
],
invalid: [
'äbc123',
'ÄBC11',
'',
],
});
});
it('should validate dutch alpha strings', () => {
test({
validator: 'isAlpha',
args: ['nl-NL'],
valid: [
'Kán',
'één',
'vóór',
'nú',
'héél',
],
invalid: [
'äca ',
'abcß',
'Øre',
],
});
});
it('should validate german alpha strings', () => {
test({
validator: 'isAlpha',
args: ['de-DE'],
valid: [
'äbc',
'ÄBC',
'FöÖbär',
'Heiß',
],
invalid: [
'äbc1',
' föö ',
'',
],
});
});
it('should validate hungarian alpha strings', () => {
test({
validator: 'isAlpha',
args: ['hu-HU'],
valid: [
'árvíztűrőtükörfúrógép',
'ÁRVÍZTŰRŐTÜKÖRFÚRÓGÉP',
],
invalid: [
'äbc1',
' fäö ',
'Heiß',
'',
],
});
});
it('should validate portuguese alpha strings', () => {
test({
validator: 'isAlpha',
args: ['pt-PT'],
valid: [
'palíndromo',
'órgão',
'qwértyúão',
'àäãcëüïÄÏÜ',
],
invalid: [
'12abc',
'Heiß',
'Øre',
'æøå',
'',
],
});
});
it('should validate italian alpha strings', () => {
test({
validator: 'isAlpha',
args: ['it-IT'],
valid: [
'àéèìîóòù',
'correnti',
'DEFINIZIONE',
'compilazione',
'metró',
'pèsca',
'PÉSCA',
'genî',
],
invalid: [
'äbc123',
'ÄBC11',
'æøå',
'',
],
});
});
it('should validate arabic alpha strings', () => {
test({
validator: 'isAlpha',
args: ['ar'],
valid: [
'أبت',
'اَبِتَثّجً',
],
invalid: [
'١٢٣أبت',
'١٢٣',
'abc1',
' foo ',
'',
'ÄBC',
'FÜübar',
'Jön',
'Heiß',
],
});
});
it('should validate farsi alpha strings', () => {
test({
validator: 'isAlpha',
args: ['fa-IR'],
valid: [
'پدر',
'مادر',
'برادر',
'خواهر',
],
invalid: [
'فارسی۱۲۳',
'۱۶۴',
'abc1',
' foo ',
'',
'ÄBC',
'FÜübar',
'Jön',
'Heiß',
],
});
});
it('should validate kurdish alpha strings', () => {
test({
validator: 'isAlpha',
args: ['ku-IQ'],
valid: [
'ئؤڤگێ',
'کوردستان',
],
invalid: [
'ئؤڤگێ١٢٣',
'١٢٣',
'abc1',
' foo ',
'',
'ÄBC',
'FÜübar',
'Jön',
'Heiß',
],
});
});
it('should validate norwegian alpha strings', () => {
test({
validator: 'isAlpha',
args: ['nb-NO'],
valid: [
'aøå',
'Ære',
'Øre',
'Åre',
],
invalid: [
'äbc123',
'ÄBC11',
'',
],
});
});
it('should validate polish alpha strings', () => {
test({
validator: 'isAlpha',
args: ['pl-PL'],
valid: [
'kreską',
'zamknięte',
'zwykłe',
'kropką',
'przyjęły',
'święty',
'Pozwól',
],
invalid: [
'12řiď ',
'blé!!',
'föö!2!',
],
});
});
it('should validate serbian cyrillic alpha strings', () => {
test({
validator: 'isAlpha',
args: ['sr-RS'],
valid: [
'ШћжЂљЕ',
'ЧПСТЋЏ',
],
invalid: [
'řiď ',
'blé33!!',
'föö!!',
],
});
});
it('should validate serbian latin alpha strings', () => {
test({
validator: 'isAlpha',
args: ['sr-RS@latin'],
valid: [
'ŠAabčšđćž',
'ŠATROĆčđš',
],
invalid: [
'12řiď ',
'blé!!',
'föö!2!',
],
});
});
it('should validate spanish alpha strings', () => {
test({
validator: 'isAlpha',
args: ['es-ES'],
valid: [
'ábcó',
'ÁBCÓ',
'dormís',
'volvés',
'español',
],
invalid: [
'äca ',
'abcß',
'föö!!',
],
});
});
it('should validate swedish alpha strings', () => {
test({
validator: 'isAlpha',
args: ['sv-SE'],
valid: [
'religiös',
'stjäla',
'västgöte',
'Åre',
],
invalid: [
'AİıÖöÇ窺ĞğÜüZ',
'religiös23',
'',
],
});
});
it('should validate defined arabic locales alpha strings', () => {
test({
validator: 'isAlpha',
args: ['ar-SY'],
valid: [
'أبت',
'اَبِتَثّجً',
],
invalid: [
'١٢٣أبت',
'١٢٣',
'abc1',
' foo ',
'',
'ÄBC',
'FÜübar',
'Jön',
'Heiß',
],
});
});
it('should validate turkish alpha strings', () => {
test({
validator: 'isAlpha',
args: ['tr-TR'],
valid: [
'AİıÖöÇ窺ĞğÜüZ',
],
invalid: [
'0AİıÖöÇ窺ĞğÜüZ1',
' AİıÖöÇ窺ĞğÜüZ ',
'abc1',
' foo ',
'',
'ÄBC',
'Heiß',
],
});
});
it('should validate urkrainian alpha strings', () => {
test({
validator: 'isAlpha',
args: ['uk-UA'],
valid: [
'АБВГҐДЕЄЖЗИIЇЙКЛМНОПРСТУФХЦШЩЬЮЯ',
],
invalid: [
'0AİıÖöÇ窺ĞğÜüZ1',
' AİıÖöÇ窺ĞğÜüZ ',
'abc1',
' foo ',
'',
'ÄBC',
'Heiß',
'ЫыЪъЭэ',
],
});
});
it('should validate greek alpha strings', () => {
test({
validator: 'isAlpha',
args: ['el-GR'],
valid: [
'αβγδεζηθικλμνξοπρςστυφχψω',
'ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ',
],
invalid: [
'0AİıÖöÇ窺ĞğÜüZ1',
' AİıÖöÇ窺ĞğÜüZ ',
'ÄBC',
'Heiß',
'ЫыЪъЭэ',
'120',
'jαckγ',
],
});
});
it('should validate Hebrew alpha strings', () => {
test({
validator: 'isAlpha',
args: ['he'],
valid: [
'בדיקה',
'שלום',
],
invalid: [
'בדיקה123',
' foo ',
'abc1',
'',
],
});
});
it('should error on invalid locale', () => {
test({
validator: 'isAlpha',
args: ['is-NOT'],
error: [
'abc',
'ABC',
],
});
});
it('should validate alphanumeric strings', () => {
test({
validator: 'isAlphanumeric',
valid: [
'abc123',
'ABC11',
],
invalid: [
'abc ',
'foo!!',
'ÄBC',
'FÜübar',
'Jön',
],
});
});
it('should validate defined english aliases', () => {
test({
validator: 'isAlphanumeric',
args: ['en-GB'],
valid: [
'abc123',
'ABC11',
],
invalid: [
'abc ',
'foo!!',
'ÄBC',
'FÜübar',
'Jön',
],
});
});
it('should validate bulgarian alphanumeric strings', () => {
test({
validator: 'isAlphanumeric',
args: ['bg-BG'],
valid: [
'абв1',
'4АБ5В6',
'жаба',
'яГоДа2',
'йЮя',
'123',
],
invalid: [
' ',
'789 ',
'hello000',
],
});
});
it('should validate czech alphanumeric strings', () => {
test({
validator: 'isAlphanumeric',
args: ['cs-CZ'],
valid: [
'řiť123',
'KŮŇ11',
],
invalid: [
'řiď ',
'blé!!',
],
});
});
it('should validate slovak alphanumeric strings', () => {
test({
validator: 'isAlphanumeric',
args: ['sk-SK'],
valid: [
'1môj',
'2ľúbím',
'3mäkčeň',
'4stĹp',
'5vŕba',
'6ňorimberk',
'7ťava',
'8žanéta',
'9Ďábelské',
'10ódy',
],
invalid: [
'1moj!',
'你好世界',
' Привет мир ',
],
});
});
it('should validate danish alphanumeric strings', () => {
test({
validator: 'isAlphanumeric',
args: ['da-DK'],
valid: [
'ÆØÅ123',
'Ære321',
'321Øre',
'123Åre',
],
invalid: [
'äbc123',
'ÄBC11',
'',
],
});
});
it('should validate dutch alphanumeric strings', () => {
test({
validator: 'isAlphanumeric',
args: ['nl-NL'],
valid: [
'Kán123',
'één354',
'v4óór',
'nú234',
'hé54él',
],
invalid: [
'1äca ',
'ab3cß',
'Øre',
],
});
});
it('should validate german alphanumeric strings', () => {
test({
validator: 'isAlphanumeric',
args: ['de-DE'],
valid: [
'äbc123',
'ÄBC11',
],
invalid: [
'äca ',
'föö!!',
],
});
});
it('should validate hungarian alphanumeric strings', () => {
test({
validator: 'isAlphanumeric',
args: ['hu-HU'],
valid: [
'0árvíztűrőtükörfúrógép123',
'0ÁRVÍZTŰRŐTÜKÖRFÚRÓGÉP123',
],
invalid: [
'1időúr!',
'äbc1',
' fäö ',
'Heiß!',
'',
],
});
});
it('should validate portuguese alphanumeric strings', () => {
test({
validator: 'isAlphanumeric',
args: ['pt-PT'],
valid: [
'palíndromo',
'2órgão',
'qwértyúão9',
'àäãcë4üïÄÏÜ',
],
invalid: [
'!abc',
'Heiß',
'Øre',
'æøå',
'',
],
});
});
it('should validate italian alphanumeric strings', () => {
test({
validator: 'isAlphanumeric',
args: ['it-IT'],
valid: [
'123àéèìîóòù',
'123correnti',
'DEFINIZIONE321',
'compil123azione',
'met23ró',
'pès56ca',
'PÉS45CA',
'gen45î',
],
invalid: [
'äbc123',
'ÄBC11',
'æøå',
'',
],
});
});
it('should validate spanish alphanumeric strings', () => {
test({
validator: 'isAlphanumeric',
args: ['es-ES'],
valid: [
'ábcó123',
'ÁBCÓ11',
],
invalid: [
'äca ',
'abcß',
'föö!!',
],
});
});
it('should validate arabic alphanumeric strings', () => {
test({
validator: 'isAlphanumeric',
args: ['ar'],
valid: [
'أبت123',
'أبتَُِ١٢٣',
],
invalid: [
'äca ',
'abcß',
'föö!!',
],
});
});
it('should validate farsi alphanumeric strings', () => {
test({
validator: 'isAlphanumeric',
args: ['fa-IR'],
valid: [
'پارسی۱۲۳',
'۱۴۵۶',
'مژگان9',
],
invalid: [
'äca ',
'abcßة',
'föö!!',
'٤٥٦',
],
});
});
it('should validate kurdish alphanumeric strings', () => {
test({
validator: 'isAlphanumeric',
args: ['ku-IQ'],
valid: [
'ئؤڤگێ١٢٣',
],
invalid: [
'äca ',
'abcß',
'föö!!',
],
});
});
it('should validate defined arabic aliases', () => {
test({
validator: 'isAlphanumeric',
args: ['ar-SY'],
valid: [
'أبت123',
'أبتَُِ١٢٣',
],
invalid: [
'abc ',
'foo!!',
'ÄBC',
'FÜübar',
'Jön',
],
});
});
it('should validate norwegian alphanumeric strings', () => {
test({
validator: 'isAlphanumeric',
args: ['nb-NO'],
valid: [
'ÆØÅ123',
'Ære321',
'321Øre',
'123Åre',
],
invalid: [
'äbc123',
'ÄBC11',
'',
],
});
});
it('should validate polish alphanumeric strings', () => {
test({
validator: 'isAlphanumeric',
args: ['pl-PL'],
valid: [
'kre123ską',
'zam21knięte',
'zw23ykłe',
'123',
'prz23yjęły',
'świ23ęty',
'Poz1322wól',
],
invalid: [
'12řiď ',
'blé!!',
'föö!2!',
],
});
});
it('should validate serbian cyrillic alphanumeric strings', () => {
test({
validator: 'isAlphanumeric',
args: ['sr-RS'],
valid: [
'ШћжЂљЕ123',
'ЧПСТ132ЋЏ',
],
invalid: [
'řiď ',
'blé!!',
'föö!!',
],
});
});
it('should validate serbian latin alphanumeric strings', () => {
test({
validator: 'isAlphanumeric',
args: ['sr-RS@latin'],
valid: [
'ŠAabčšđćž123',
'ŠATRO11Ćčđš',
],
invalid: [
'řiď ',
'blé!!',
'föö!!',
],
});
});
it('should validate swedish alphanumeric strings', () => {
test({
validator: 'isAlphanumeric',
args: ['sv-SE'],
valid: [
'religiös13',
'st23jäla',
'västgöte123',
'123Åre',
],
invalid: [
'AİıÖöÇ窺ĞğÜüZ',
'foo!!',
'',
],
});
});
it('should validate turkish alphanumeric strings', () => {
test({
validator: 'isAlphanumeric',
args: ['tr-TR'],
valid: [
'AİıÖöÇ窺ĞğÜüZ123',
],
invalid: [
'AİıÖöÇ窺ĞğÜüZ ',
'foo!!',
'ÄBC',
],
});
});
it('should validate urkrainian alphanumeric strings', () => {
test({
validator: 'isAlphanumeric',
args: ['uk-UA'],
valid: [
'АБВГҐДЕЄЖЗИIЇЙКЛМНОПРСТУФХЦШЩЬЮЯ123',
],
invalid: [
'éeoc ',
'foo!!',
'ÄBC',
'ЫыЪъЭэ',
],
});
});
it('should validate greek alphanumeric strings', () => {
test({
validator: 'isAlphanumeric',
args: ['el-GR'],
valid: [
'αβγδεζηθικλμνξοπρςστυφχψω',
'ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ',
'20θ',
'1234568960',
],
invalid: [
'0AİıÖöÇ窺ĞğÜüZ1',
' AİıÖöÇ窺ĞğÜüZ ',
'ÄBC',
'Heiß',
'ЫыЪъЭэ',
'jαckγ',
],
});
});
it('should validate Hebrew alphanumeric strings', () => {
test({
validator: 'isAlphanumeric',
args: ['he'],
valid: [
'אבג123',
'שלום11',
],
invalid: [
'אבג ',
'לא!!',
'abc',
' foo ',
],
});
});
it('should error on invalid locale', () => {
test({
validator: 'isAlphanumeric',
args: ['is-NOT'],
error: [
'1234568960',
'abc123',
],
});
});
it('should validate numeric strings', () => {
test({
validator: 'isNumeric',
valid: [
'123',
'00123',
'-00123',
'0',
'-0',
'+123',
'123.123',
'+000000',
],
invalid: [
' ',
'',
'.',
],
});
});
it('should validate numeric strings without symbols', () => {
test({
validator: 'isNumeric',
args: [{
no_symbols: true,
}],
valid: [
'123',
'00123',
'0',
],
invalid: [
'-0',
'+000000',
'',
'+123',
'123.123',
'-00123',
' ',
'.',
],
});
});
it('should validate ports', () => {
test({
validator: 'isPort',
valid: [
'0',
'22',
'80',
'443',
'3000',
'8080',
'65535',
],
invalid: [
'',
'-1',
'65536',
],
});
});
it('should validate decimal numbers', () => {
test({
validator: 'isDecimal',
valid: [
'123',
'00123',
'-00123',
'0',
'-0',
'+123',
'0.01',
'.1',
'1.0',
'-.25',
'-0',
'0.0000000000001',
],
invalid: [
'0,01',
',1',
'1,0',
'-,25',
'0,0000000000001',
'0٫01',
'٫1',
'1٫0',
'-٫25',
'0٫0000000000001',
'....',
' ',
'',
'-',
'+',
'.',
'0.1a',
'a',
'\n',
],
});
test({
validator: 'isDecimal',
args: [{ locale: 'en-AU' }],
valid: [
'123',
'00123',
'-00123',
'0',
'-0',
'+123',
'0.01',
'.1',
'1.0',
'-.25',
'-0',
'0.0000000000001',
],
invalid: [
'0,01',
',1',
'1,0',
'-,25',
'0,0000000000001',
'0٫01',
'٫1',
'1٫0',
'-٫25',
'0٫0000000000001',
'....',
' ',
'',
'-',
'+',
'.',
'0.1a',
'a',
'\n',
],
});
test({
validator: 'isDecimal',
args: [{ locale: ['bg-BG'] }],
valid: [
'123',
'00123',
'-00123',
'0',
'-0',
'+123',
'0,01',
',1',
'1,0',
'-,25',
'-0',
'0,0000000000001',
],
invalid: [
'0.0000000000001',
'0.01',
'.1',
'1.0',
'-.25',
'0٫01',
'٫1',
'1٫0',
'-٫25',
'0٫0000000000001',
'....',
' ',
'',
'-',
'+',
'.',
'0.1a',
'a',
'\n',
],
});
test({
validator: 'isDecimal',
args: [{ locale: ['cs-CZ'] }],
valid: [
'123',
'00123',
'-00123',
'0',
'-0',
'+123',
'0,01',
',1',
'1,0',
'-,25',
'-0',
'0,0000000000001',
],
invalid: [
'0.0000000000001',
'0.01',
'.1',
'1.0',
'-.25',
'0٫01',
'٫1',
'1٫0',
'-٫25',
'0٫0000000000001',
'....',
' ',
'',
'-',
'+',
'.',
'0.1a',
'a',
'\n',
],
});
test({
validator: 'isDecimal',
args: [{ locale: ['ar-JO'] }],
valid: [
'123',
'00123',
'-00123',
'0',
'-0',
'+123',
'0٫01',
'٫1',
'1٫0',
'-٫25',
'-0',
'0٫0000000000001',
],
invalid: [
'0,0000000000001',
'0,01',
',1',
'1,0',
'-,25',
'0.0000000000001',
'0.01',
'.1',
'1.0',
'-.25',
'....',
' ',
'',
'-',
'+',
'.',
'0.1a',
'a',
'\n',
],
});
test({
validator: 'isDecimal',
args: [{ locale: ['ar-EG'] }],
valid: [
'0.01',
],
invalid: [
'0,01',
],
});
test({
validator: 'isDecimal',
args: [{ locale: ['en-ZM'] }],
valid: [
'0,01',
],
invalid: [
'0.01',
],
});
test({
validator: 'isDecimal',
args: [{ force_decimal: true }],
valid: [
'0.01',
'.1',
'1.0',
'-.25',
'0.0000000000001',
],
invalid: [
'-0',
'123',
'00123',
'-00123',
'0',
'-0',
'+123',
'0,0000000000001',
'0,01',
',1',
'1,0',
'-,25',
'....',
' ',
'',
'-',
'+',
'.',
'0.1a',
'a',
'\n',
],
});
test({
validator: 'isDecimal',
args: [{ decimal_digits: '2,3' }],
valid: [
'123',
'00123',
'-00123',
'0',
'-0',
'+123',
'0.01',
'1.043',
'.15',
'-.255',
'-0',
],
invalid: [
'0.0000000000001',
'0.0',
'.1',
'1.0',
'-.2564',
'0.0',
'٫1',
'1٫0',
'-٫25',
'0٫0000000000001',
'....',
' ',
'',
'-',
'+',
'.',
'0.1a',
'a',
'\n',
],
});
});
it('should error on invalid locale', () => {
test({
validator: 'isDecimal',
args: [{ locale: ['is-NOT'] }],
error: [
'123',
'0.01',
'0,01',
],
});
});
it('should validate lowercase strings', () => {
test({
validator: 'isLowercase',
valid: [
'abc',
'abc123',
'this is lowercase.',
'tr竪s 端ber',
],
invalid: [
'fooBar',
'123A',
],
});
});
it('should validate uppercase strings', () => {
test({
validator: 'isUppercase',
valid: [
'ABC',
'ABC123',
'ALL CAPS IS FUN.',
' .',
],
invalid: [
'fooBar',
'123abc',
],
});
});
it('should validate integers', () => {
test({
validator: 'isInt',
valid: [
'13',
'123',
'0',
'123',
'-0',
'+1',
'01',
'-01',
'000',
],
invalid: [
'100e10',
'123.123',
' ',
'',
],
});
test({
validator: 'isInt',
args: [{ allow_leading_zeroes: false }],
valid: [
'13',
'123',
'0',
'123',
'-0',
'+1',
],
invalid: [
'01',
'-01',
'000',
'100e10',
'123.123',
' ',
'',
],
});
test({
validator: 'isInt',
args: [{ allow_leading_zeroes: true }],
valid: [
'13',
'123',
'0',
'123',
'-0',
'+1',
'01',
'-01',
'000',
'-000',
'+000',
],
invalid: [
'100e10',
'123.123',
' ',
'',
],
});
test({
validator: 'isInt',
args: [{
min: 10,
}],
valid: [
'15',
'80',
'99',
],
invalid: [
'9',
'6',
'3.2',
'a',
],
});
test({
validator: 'isInt',
args: [{
min: 10,
max: 15,
}],
valid: [
'15',
'11',
'13',
],
invalid: [
'9',
'2',
'17',
'3.2',
'33',
'a',
],
});
test({
validator: 'isInt',
args: [{
gt: 10,
lt: 15,
}],
valid: [
'14',
'11',
'13',
],
invalid: [
'10',
'15',
'17',
'3.2',
'33',
'a',
],
});
});
it('should validate floats', () => {
test({
validator: 'isFloat',
valid: [
'123',
'123.',
'123.123',
'-123.123',
'-0.123',
'+0.123',
'0.123',
'.0',
'-.123',
'+.123',
'01.123',
'-0.22250738585072011e-307',
],
invalid: [
'+',
'-',
' ',
'',
'.',
'foo',
],
});
test({
validator: 'isFloat',
args: [{ locale: 'en-AU' }],
valid: [
'123',
'123.',
'123.123',
'-123.123',
'-0.123',
'+0.123',
'0.123',
'.0',
'-.123',
'+.123',
'01.123',
'-0.22250738585072011e-307',
],
invalid: [
'123٫123',
'123,123',
' ',
'',
'.',
'foo',
],
});
test({
validator: 'isFloat',
args: [{ locale: 'de-DE' }],
valid: [
'123',
'123,',
'123,123',
'-123,123',
'-0,123',
'+0,123',
'0,123',
',0',
'-,123',
'+,123',
'01,123',
'-0,22250738585072011e-307',
],
invalid: [
'123.123',
'123٫123',
' ',
'',
'.',
'foo',
],
});
test({
validator: 'isFloat',
args: [{ locale: 'ar-JO' }],
valid: [
'123',
'123٫',
'123٫123',
'-123٫123',
'-0٫123',
'+0٫123',
'0٫123',
'٫0',
'-٫123',
'+٫123',
'01٫123',
'-0٫22250738585072011e-307',
],
invalid: [
'123,123',
'123.123',
' ',
'',
'.',
'foo',
],
});
test({
validator: 'isFloat',
args: [{
min: 3.7,
}],
valid: [
'3.888',
'3.92',
'4.5',
'50',
'3.7',
'3.71',
],
invalid: [
'3.6',
'3.69',
'3',
'1.5',
'a',
],
});
test({
validator: 'isFloat',
args: [{
min: 0.1,
max: 1.0,
}],
valid: [
'0.1',
'1.0',
'0.15',
'0.33',
'0.57',
'0.7',
],
invalid: [
'0',
'0.0',
'a',
'1.3',
'0.05',
'5',
],
});
test({
validator: 'isFloat',
args: [{
gt: -5.5,
lt: 10,
}],
valid: [
'9.9',
'1.0',
'0',
'-1',
'7',
'-5.4',
],
invalid: [
'10',
'-5.5',
'a',
'-20.3',
'20e3',
'10.00001',
],
});
test({
validator: 'isFloat',
args: [{
min: -5.5,
max: 10,
gt: -5.5,
lt: 10,
}],
valid: [
'9.99999',
'-5.499999',
],
invalid: [
'10',
'-5.5',
],
});
test({
validator: 'isFloat',
args: [{
locale: 'de-DE',
min: 3.1,
}],
valid: [
'123',
'123,',
'123,123',
'3,1',
'3,100001',
],
invalid: [
'3,09',
'-,123',
'+,123',
'01,123',
'-0,22250738585072011e-307',
'-123,123',
'-0,123',
'+0,123',
'0,123',
',0',
'123.123',
'123٫123',
' ',
'',
'.',
'foo',
],
});
});
it('should validate hexadecimal strings', () => {
test({
validator: 'isHexadecimal',
valid: [
'deadBEEF',
'ff0044',
'0xff0044',
'0XfF0044',
'0x0123456789abcDEF',
'0X0123456789abcDEF',
'0hfedCBA9876543210',
'0HfedCBA9876543210',
'0123456789abcDEF',
],
invalid: [
'abcdefg',
'',
'..',
'0xa2h',
'0xa20x',
'0x0123456789abcDEFq',
'0hfedCBA9876543210q',
'01234q56789abcDEF',
],
});
});
it('should validate octal strings', () => {
test({
validator: 'isOctal',
valid: [
'076543210',
'0o01234567',
],
invalid: [
'abcdefg',
'012345678',
'012345670c',
'00c12345670c',
'',
'..',
],
});
});
it('should validate hexadecimal color strings', () => {
test({
validator: 'isHexColor',
valid: [
'#ff0034',
'#CCCCCC',
'fff',
'#f00',
],
invalid: [
'#ff',
'fff0',
'#ff12FG',
],
});
});
it('should validate ISRC code strings', () => {
test({
validator: 'isISRC',
valid: [
'USAT29900609',
'GBAYE6800011',
'USRC15705223',
'USCA29500702',
],
invalid: [
'USAT2990060',
'SRC15705223',
'US-CA29500702',
'USARC15705223',
],
});
});
it('should validate md5 strings', () => {
test({
validator: 'isMD5',
valid: [
'd94f3f016ae679c3008de268209132f2',
'751adbc511ccbe8edf23d486fa4581cd',
'88dae00e614d8f24cfd5a8b3f8002e93',
'0bf1c35032a71a14c2f719e5a14c1e96',
],
invalid: [
'KYT0bf1c35032a71a14c2f719e5a14c1',
'q94375dj93458w34',
'39485729348',
'%&FHKJFvk',
],
});
});
it('should validate hash strings', () => {
['md5', 'md4', 'ripemd128', 'tiger128'].forEach((algorithm) => {
test({
validator: 'isHash',
args: [algorithm],
valid: [
'd94f3f016ae679c3008de268209132f2',
'751adbc511ccbe8edf23d486fa4581cd',
'88dae00e614d8f24cfd5a8b3f8002e93',
'0bf1c35032a71a14c2f719e5a14c1e96',
'd94f3F016Ae679C3008de268209132F2',
'88DAE00e614d8f24cfd5a8b3f8002E93',
],
invalid: [
'q94375dj93458w34',
'39485729348',
'%&FHKJFvk',
'KYT0bf1c35032a71a14c2f719e5a1',
],
});
});
['crc32', 'crc32b'].forEach((algorithm) => {
test({
validator: 'isHash',
args: [algorithm],
valid: [
'd94f3f01',
'751adbc5',
'88dae00e',
'0bf1c350',
'88DAE00e',
'751aDBc5',
],
invalid: [
'KYT0bf1c35032a71a14c2f719e5a14c1',
'q94375dj93458w34',
'q943',
'39485729348',
'%&FHKJFvk',
],
});
});
['sha1', 'tiger160', 'ripemd160'].forEach((algorithm) => {
test({
validator: 'isHash',
args: [algorithm],
valid: [
'3ca25ae354e192b26879f651a51d92aa8a34d8d3',
'aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d',
'beb8c3f30da46be179b8df5f5ecb5e4b10508230',
'efd5d3b190e893ed317f38da2420d63b7ae0d5ed',
'AAF4c61ddCC5e8a2dabede0f3b482cd9AEA9434D',
'3ca25AE354e192b26879f651A51d92aa8a34d8D3',
],
invalid: [
'KYT0bf1c35032a71a14c2f719e5a14c1',
'KYT0bf1c35032a71a14c2f719e5a14c1dsjkjkjkjkkjk',
'q94375dj93458w34',
'39485729348',
'%&FHKJFvk',
],
});
});
test({
validator: 'isHash',
args: ['sha256'],
valid: [
'2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824',
'1d996e033d612d9af2b44b70061ee0e868bfd14c2dd90b129e1edeb7953e7985',
'80f70bfeaed5886e33536bcfa8c05c60afef5a0e48f699a7912d5e399cdcc441',
'579282cfb65ca1f109b78536effaf621b853c9f7079664a3fbe2b519f435898c',
'2CF24dba5FB0a30e26E83b2AC5b9E29E1b161e5C1fa7425E73043362938b9824',
'80F70bFEAed5886e33536bcfa8c05c60aFEF5a0e48f699a7912d5e399cdCC441',
],
invalid: [
'KYT0bf1c35032a71a14c2f719e5a14c1',
'KYT0bf1c35032a71a14c2f719e5a14c1dsjkjkjkjkkjk',
'q94375dj93458w34',
'39485729348',
'%&FHKJFvk',
],
});
test({
validator: 'isHash',
args: ['sha384'],
valid: [
'3fed1f814d28dc5d63e313f8a601ecc4836d1662a19365cbdcf6870f6b56388850b58043f7ebf2418abb8f39c3a42e31',
'b330f4e575db6e73500bd3b805db1a84b5a034e5d21f0041d91eec85af1dfcb13e40bb1c4d36a72487e048ac6af74b58',
'bf547c3fc5841a377eb1519c2890344dbab15c40ae4150b4b34443d2212e5b04aa9d58865bf03d8ae27840fef430b891',
'fc09a3d11368386530f985dacddd026ae1e44e0e297c805c3429d50744e6237eb4417c20ffca8807b071823af13a3f65',
'3fed1f814d28dc5d63e313f8A601ecc4836d1662a19365CBDCf6870f6b56388850b58043f7ebf2418abb8f39c3a42e31',
'b330f4E575db6e73500bd3b805db1a84b5a034e5d21f0041d91EEC85af1dfcb13e40bb1c4d36a72487e048ac6af74b58',
],
invalid: [
'KYT0bf1c35032a71a14c2f719e5a14c1',
'KYT0bf1c35032a71a14c2f719e5a14c1dsjkjkjkjkkjk',
'q94375dj93458w34',
'39485729348',
'%&FHKJFvk',
],
});
test({
validator: 'isHash',
args: ['sha512'],
valid: [
'9b71d224bd62f3785d96d46ad3ea3d73319bfbc2890caadae2dff72519673ca72323c3d99ba5c11d7c7acc6e14b8c5da0c4663475c2e5c3adef46f73bcdec043',
'83c586381bf5ba94c8d9ba8b6b92beb0997d76c257708742a6c26d1b7cbb9269af92d527419d5b8475f2bb6686d2f92a6649b7f174c1d8306eb335e585ab5049',
'45bc5fa8cb45ee408c04b6269e9f1e1c17090c5ce26ffeeda2af097735b29953ce547e40ff3ad0d120e5361cc5f9cee35ea91ecd4077f3f589b4d439168f91b9',
'432ac3d29e4f18c7f604f7c3c96369a6c5c61fc09bf77880548239baffd61636d42ed374f41c261e424d20d98e320e812a6d52865be059745fdb2cb20acff0ab',
'9B71D224bd62f3785D96d46ad3ea3d73319bFBC2890CAAdae2dff72519673CA72323C3d99ba5c11d7c7ACC6e14b8c5DA0c4663475c2E5c3adef46f73bcDEC043',
'432AC3d29E4f18c7F604f7c3c96369A6C5c61fC09Bf77880548239baffd61636d42ed374f41c261e424d20d98e320e812a6d52865be059745fdb2cb20acff0ab',
],
invalid: [
'KYT0bf1c35032a71a14c2f719e5a14c1',
'KYT0bf1c35032a71a14c2f719e5a14c1dsjkjkjkjkkjk',
'q94375dj93458w34',
'39485729348',
'%&FHKJFvk',
],
});
test({
validator: 'isHash',
args: ['tiger192'],
valid: [
'6281a1f098c5e7290927ed09150d43ff3990a0fe1a48267c',
'56268f7bc269cf1bc83d3ce42e07a85632394737918f4760',
'46fc0125a148788a3ac1d649566fc04eb84a746f1a6e4fa7',
'7731ea1621ae99ea3197b94583d034fdbaa4dce31a67404a',
'6281A1f098c5e7290927ed09150d43ff3990a0fe1a48267C',
'46FC0125a148788a3AC1d649566fc04eb84A746f1a6E4fa7',
],
invalid: [
'KYT0bf1c35032a71a14c2f719e5a14c1',
'KYT0bf1c35032a71a14c2f719e5a14c1dsjkjkjkjkkjk',
'q94375dj93458w34',
'39485729348',
'%&FHKJFvk',
],
});
});
it('should validate JWT tokens', () => {
test({
validator: 'isJWT',
valid: [
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJsb2dnZWRJbkFzIjoiYWRtaW4iLCJpYXQiOjE0MjI3Nzk2Mzh9.gzSraSYS8EXBxLN_oWnFSRgCzcmJmMjLiuyu5CSpyHI',
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJsb3JlbSI6Imlwc3VtIn0.ymiJSsMJXR6tMSr8G9usjQ15_8hKPDv_CArLhxw28MI',
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkb2xvciI6InNpdCIsImFtZXQiOlsibG9yZW0iLCJpcHN1bSJdfQ.rRpe04zbWbbJjwM43VnHzAboDzszJtGrNsUxaqQ-GQ8',
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqb2huIjp7ImFnZSI6MjUsImhlaWdodCI6MTg1fSwiamFrZSI6eyJhZ2UiOjMwLCJoZWlnaHQiOjI3MH19.YRLPARDmhGMC3BBk_OhtwwK21PIkVCqQe8ncIRPKo-E',
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ', // No signature
],
invalid: [
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9',
'$Zs.ewu.su84',
'ks64$S/9.dy$§kz.3sd73b',
],
});
});
it('should validate null strings', () => {
test({
validator: 'isEmpty',
valid: [
'',
],
invalid: [
' ',
'foo',
'3',
],
});
test({
validator: 'isEmpty',
args: [{ ignore_whitespace: false }],
valid: [
'',
],
invalid: [
' ',
'foo',
'3',
],
});
test({
validator: 'isEmpty',
args: [{ ignore_whitespace: true }],
valid: [
'',
' ',
],
invalid: [
'foo',
'3',
],
});
});
it('should validate strings against an expected value', () => {
test({
validator: 'equals', args: ['abc'], valid: ['abc'], invalid: ['Abc', '123'],
});
});
it('should validate strings contain another string', () => {
test({
validator: 'contains',
args: ['foo'],
valid: ['foo', 'foobar', 'bazfoo'],
invalid: ['bar', 'fobar'],
});
});
it('should validate strings against a pattern', () => {
test({
validator: 'matches',
args: [/abc/],
valid: ['abc', 'abcdef', '123abc'],
invalid: ['acb', 'Abc'],
});
test({
validator: 'matches',
args: ['abc'],
valid: ['abc', 'abcdef', '123abc'],
invalid: ['acb', 'Abc'],
});
test({
validator: 'matches',
args: ['abc', 'i'],
valid: ['abc', 'abcdef', '123abc', 'AbC'],
invalid: ['acb'],
});
});
it('should validate strings by length (deprecated api)', () => {
test({
validator: 'isLength',
args: [2],
valid: ['abc', 'de', 'abcd'],
invalid: ['', 'a'],
});
test({
validator: 'isLength',
args: [2, 3],
valid: ['abc', 'de'],
invalid: ['', 'a', 'abcd'],
});
test({
validator: 'isLength',
args: [2, 3],
valid: ['干𩸽', '𠮷野家'],
invalid: ['', '𠀋', '千竈通り'],
});
test({
validator: 'isLength',
args: [0, 0],
valid: [''],
invalid: ['a', 'ab'],
});
});
it('should validate strings by byte length (deprecated api)', () => {
test({
validator: 'isByteLength',
args: [2],
valid: ['abc', 'de', 'abcd', 'gmail'],
invalid: ['', 'a'],
});
test({
validator: 'isByteLength',
args: [2, 3],
valid: ['abc', 'de', 'g'],
invalid: ['', 'a', 'abcd', 'gm'],
});
test({
validator: 'isByteLength',
args: [0, 0],
valid: [''],
invalid: ['g', 'a'],
});
});
it('should validate strings by length', () => {
test({
validator: 'isLength',
args: [{ min: 2 }],
valid: ['abc', 'de', 'abcd'],
invalid: ['', 'a'],
});
test({
validator: 'isLength',
args: [{ min: 2, max: 3 }],
valid: ['abc', 'de'],
invalid: ['', 'a', 'abcd'],
});
test({
validator: 'isLength',
args: [{ min: 2, max: 3 }],
valid: ['干𩸽', '𠮷野家'],
invalid: ['', '𠀋', '千竈通り'],
});
test({
validator: 'isLength',
args: [{ max: 3 }],
valid: ['abc', 'de', 'a', ''],
invalid: ['abcd'],
});
test({
validator: 'isLength',
args: [{ max: 0 }],
valid: [''],
invalid: ['a', 'ab'],
});
test({
validator: 'isLength',
valid: ['a', '', 'asds'],
});
});
it('should validate strings by byte length', () => {
test({
validator: 'isByteLength',
args: [{ min: 2 }],
valid: ['abc', 'de', 'abcd', 'gmail'],
invalid: ['', 'a'],
});
test({
validator: 'isByteLength',
args: [{ min: 2, max: 3 }],
valid: ['abc', 'de', 'g'],
invalid: ['', 'a', 'abcd', 'gm'],
});
test({
validator: 'isByteLength',
args: [{ max: 3 }],
valid: ['abc', 'de', 'g', 'a', ''],
invalid: ['abcd', 'gm'],
});
test({
validator: 'isByteLength',
args: [{ max: 0 }],
valid: [''],
invalid: ['g', 'a'],
});
});
it('should validate UUIDs', () => {
test({
validator: 'isUUID',
valid: [
'A987FBC9-4BED-3078-CF07-9141BA07C9F3',
'A987FBC9-4BED-4078-8F07-9141BA07C9F3',
'A987FBC9-4BED-5078-AF07-9141BA07C9F3',
],
invalid: [
'',
'xxxA987FBC9-4BED-3078-CF07-9141BA07C9F3',
'A987FBC9-4BED-3078-CF07-9141BA07C9F3xxx',
'A987FBC94BED3078CF079141BA07C9F3',
'934859',
'987FBC9-4BED-3078-CF07A-9141BA07C9F3',
'AAAAAAAA-1111-1111-AAAG-111111111111',
],
});
test({
validator: 'isUUID',
args: [3],
valid: [
'A987FBC9-4BED-3078-CF07-9141BA07C9F3',
],
invalid: [
'',
'xxxA987FBC9-4BED-3078-CF07-9141BA07C9F3',
'934859',
'AAAAAAAA-1111-1111-AAAG-111111111111',
'A987FBC9-4BED-4078-8F07-9141BA07C9F3',
'A987FBC9-4BED-5078-AF07-9141BA07C9F3',
],
});
test({
validator: 'isUUID',
args: [4],
valid: [
'713ae7e3-cb32-45f9-adcb-7c4fa86b90c1',
'625e63f3-58f5-40b7-83a1-a72ad31acffb',
'57b73598-8764-4ad0-a76a-679bb6640eb1',
'9c858901-8a57-4791-81fe-4c455b099bc9',
],
invalid: [
'',
'xxxA987FBC9-4BED-3078-CF07-9141BA07C9F3',
'934859',
'AAAAAAAA-1111-1111-AAAG-111111111111',
'A987FBC9-4BED-5078-AF07-9141BA07C9F3',
'A987FBC9-4BED-3078-CF07-9141BA07C9F3',
],
});
test({
validator: 'isUUID',
args: [5],
valid: [
'987FBC97-4BED-5078-AF07-9141BA07C9F3',
'987FBC97-4BED-5078-BF07-9141BA07C9F3',
'987FBC97-4BED-5078-8F07-9141BA07C9F3',
'987FBC97-4BED-5078-9F07-9141BA07C9F3',
],
invalid: [
'',
'xxxA987FBC9-4BED-3078-CF07-9141BA07C9F3',
'934859',
'AAAAAAAA-1111-1111-AAAG-111111111111',
'9c858901-8a57-4791-81fe-4c455b099bc9',
'A987FBC9-4BED-3078-CF07-9141BA07C9F3',
],
});
});
it('should validate a string that is in another string or array', () => {
test({
validator: 'isIn',
args: ['foobar'],
valid: ['foo', 'bar', 'foobar', ''],
invalid: ['foobarbaz', 'barfoo'],
});
test({
validator: 'isIn',
args: [['foo', 'bar']],
valid: ['foo', 'bar'],
invalid: ['foobar', 'barfoo', ''],
});
test({
validator: 'isIn',
args: [['1', '2', '3']],
valid: ['1', '2', '3'],
invalid: ['4', ''],
});
test({
validator: 'isIn',
args: [['1', '2', '3', { foo: 'bar' }, () => 5, { toString: 'test' }]],
valid: ['1', '2', '3', ''],
invalid: ['4'],
});
test({ validator: 'isIn', invalid: ['foo', ''] });
});
it('should validate a string that is in another object', () => {
test({
validator: 'isIn',
args: [{ foo: 1, bar: 2, foobar: 3 }],
valid: ['foo', 'bar', 'foobar'],
invalid: ['foobarbaz', 'barfoo', ''],
});
test({
validator: 'isIn',
args: [{ 1: 3, 2: 0, 3: 1 }],
valid: ['1', '2', '3'],
invalid: ['4', ''],
});
});
it('should validate dates against a start date', () => {
test({
validator: 'isAfter',
args: ['2011-08-03'],
valid: ['2011-08-04', new Date(2011, 8, 10).toString()],
invalid: ['2010-07-02', '2011-08-03', new Date(0).toString(), 'foo'],
});
test({
validator: 'isAfter',
valid: ['2100-08-04', new Date(Date.now() + 86400000).toString()],
invalid: ['2010-07-02', new Date(0).toString()],
});
test({
validator: 'isAfter',
args: ['2011-08-03'],
valid: ['2015-09-17'],
invalid: ['invalid date'],
});
test({
validator: 'isAfter',
args: ['invalid date'],
invalid: ['invalid date', '2015-09-17'],
});
});
it('should validate dates against an end date', () => {
test({
validator: 'isBefore',
args: ['08/04/2011'],
valid: ['2010-07-02', '2010-08-04', new Date(0).toString()],
invalid: ['08/04/2011', new Date(2011, 9, 10).toString()],
});
test({
validator: 'isBefore',
args: [new Date(2011, 7, 4).toString()],
valid: ['2010-07-02', '2010-08-04', new Date(0).toString()],
invalid: ['08/04/2011', new Date(2011, 9, 10).toString()],
});
test({
validator: 'isBefore',
valid: [
'2000-08-04',
new Date(0).toString(),
new Date(Date.now() - 86400000).toString(),
],
invalid: ['2100-07-02', new Date(2217, 10, 10).toString()],
});
test({
validator: 'isBefore',
args: ['2011-08-03'],
valid: ['1999-12-31'],
invalid: ['invalid date'],
});
test({
validator: 'isBefore',
args: ['invalid date'],
invalid: ['invalid date', '1999-12-31'],
});
});
it('should validate BIC codes', () => {
test({
validator: 'isBIC',
valid: [
'SBICKEN1345',
'SBICKEN1',
'SBICKENY',
'SBICKEN1YYP',
],
invalid: [
'SBIC23NXXX',
'S23CKENXXXX',
'SBICKENXX',
'SBICKENXX9',
'SBICKEN13458',
'SBICKEN',
],
});
});
it('should validate that integer strings are divisible by a number', () => {
test({
validator: 'isDivisibleBy',
args: [2],
valid: ['2', '4', '100', '1000'],
invalid: [
'1',
'2.5',
'101',
'foo',
'',
],
});
});
it('should validate credit cards', () => {
test({
validator: 'isCreditCard',
valid: [
'375556917985515',
'36050234196908',
'4716461583322103',
'4716-2210-5188-5662',
'4929 7226 5379 7141',
'5398228707871527',
'6283875070985593',
'6263892624162870',
'6234917882863855',
'6234698580215388',
'6226050967750613',
'6246281879460688',
'2222155765072228',
'2225855203075256',
'2720428011723762',
'2718760626256570',
'6765780016990268',
],
invalid: [
'foo',
'foo',
'5398228707871528',
'2718760626256571',
'2721465526338453',
'2220175103860763',
'375556917985515999999993',
'899999996234917882863855',
'prefix6234917882863855',
'623491788middle2863855',
'6234917882863855suffix',
],
});
});
it('should validate identity cards', () => {
const fixtures = [
{
locale: 'ES',
valid: [
'99999999R',
'12345678Z',
'01234567L',
'01234567l',
'X1234567l',
'x1234567l',
'X1234567L',
'Y1234567X',
'Z1234567R',
],
invalid: [
'123456789',
'12345678A',
'12345 678Z',
'12345678-Z',
'1234*6789',
'1234*678Z',
'12345678!',
'1234567L',
'A1234567L',
'X1234567A',
'Y1234567B',
'Z1234567C',
],
},
{
locale: 'he-IL',
valid: [
'219472156',
'219486610',
'219488962',
'219566726',
'219640216',
'219645041',
'334795465',
'335211686',
'335240479',
'335472171',
'336999842',
'337090443',
],
invalid: [
'123456789',
'12345678A',
'12345 678Z',
'12345678-Z',
'1234*6789',
'1234*678Z',
'12345678!',
'1234567L',
'A1234567L',
'X1234567A',
'Y1234567B',
'Z1234567C',
'219772156',
'219487710',
'334705465',
'336000842',
],
},
{
locale: 'zh-TW',
valid: [
'B176944193',
'K101189797',
'F112866121',
'A219758834',
'A244144802',
'A146047171',
'Q170219004',
'Z277018381',
'X231071923',
],
invalid: [
'123456789',
'A185034995',
'X431071923',
'GE9800as98',
'X231071922',
'1234*678Z',
'12345678!',
'1234567L',
'A1234567L',
'X1234567A',
'Y1234567B',
'Z1234567C',
'219772156',
'219487710',
'334705465',
'336000842',
],
},
];
let allValid = [];
let allInvalid = [];
// Test fixtures
fixtures.forEach((fixture) => {
if (fixture.valid) allValid = allValid.concat(fixture.valid);
if (fixture.invalid) allInvalid = allInvalid.concat(fixture.invalid);
test({
validator: 'isIdentityCard',
valid: fixture.valid,
invalid: fixture.invalid,
args: [fixture.locale],
});
});
// Test generics
test({
validator: 'isIdentityCard',
valid: [
...allValid,
],
invalid: [
'foo',
...allInvalid,
],
args: ['any'],
});
});
it('should error on invalid locale', () => {
test({
validator: 'isIdentityCard',
args: ['is-NOT'],
error: [
'99999999R',
'12345678Z',
],
});
});
it('should validate ISINs', () => {
test({
validator: 'isISIN',
valid: [
'AU0000XVGZA3',
'DE000BAY0017',
'BE0003796134',
'SG1G55870362',
'GB0001411924',
'DE000WCH8881',
'PLLWBGD00016',
],
invalid: [
'DE000BAY0018',
'PLLWBGD00019',
'foo',
'5398228707871528',
],
});
});
it('should validate ISBNs', () => {
test({
validator: 'isISBN',
args: [10],
valid: [
'3836221195', '3-8362-2119-5', '3 8362 2119 5',
'1617290858', '1-61729-085-8', '1 61729 085-8',
'0007269706', '0-00-726970-6', '0 00 726970 6',
'3423214120', '3-423-21412-0', '3 423 21412 0',
'340101319X', '3-401-01319-X', '3 401 01319 X',
],
invalid: [
'3423214121', '3-423-21412-1', '3 423 21412 1',
'978-3836221191', '9783836221191',
'123456789a', 'foo', '',
],
});
test({
validator: 'isISBN',
args: [13],
valid: [
'9783836221191', '978-3-8362-2119-1', '978 3 8362 2119 1',
'9783401013190', '978-3401013190', '978 3401013190',
'9784873113685', '978-4-87311-368-5', '978 4 87311 368 5',
],
invalid: [
'9783836221190', '978-3-8362-2119-0', '978 3 8362 2119 0',
'3836221195', '3-8362-2119-5', '3 8362 2119 5',
'01234567890ab', 'foo', '',
],
});
test({
validator: 'isISBN',
valid: [
'340101319X',
'9784873113685',
],
invalid: [
'3423214121',
'9783836221190',
],
});
test({
validator: 'isISBN',
args: ['foo'],
invalid: [
'340101319X',
'9784873113685',
],
});
});
it('should validate ISSNs', () => {
test({
validator: 'isISSN',
valid: [
'0378-5955',
'0000-0000',
'2434-561X',
'2434-561x',
'01896016',
'20905076',
],
invalid: [
'0378-5954',
'0000-0001',
'0378-123',
'037-1234',
'0',
'2434-561c',
'1684-5370',
'19960791',
'',
],
});
test({
validator: 'isISSN',
args: [{ case_sensitive: true }],
valid: [
'2434-561X',
'2434561X',
'0378-5955',
'03785955',
],
invalid: [
'2434-561x',
'2434561x',
],
});
test({
validator: 'isISSN',
args: [{ require_hyphen: true }],
valid: [
'2434-561X',
'2434-561x',
'0378-5955',
],
invalid: [
'2434561X',
'2434561x',
'03785955',
],
});
test({
validator: 'isISSN',
args: [{ case_sensitive: true, require_hyphen: true }],
valid: [
'2434-561X',
'0378-5955',
],
invalid: [
'2434-561x',
'2434561X',
'2434561x',
'03785955',
],
});
});
it('should validate JSON', () => {
test({
validator: 'isJSON',
valid: [
'{ "key": "value" }',
'{}',
],
invalid: [
'{ key: "value" }',
'{ \'key\': \'value\' }',
'null',
'1234',
'false',
'"nope"',
],
});
});
it('should validate multibyte strings', () => {
test({
validator: 'isMultibyte',
valid: [
'ひらがな・カタカナ、.漢字',
'あいうえお foobar',
'test@example.com',
'1234abcDExyz',
'カタカナ',
'中文',
],
invalid: [
'abc',
'abc123',
'<>@" *.',
],
});
});
it('should validate ascii strings', () => {
test({
validator: 'isAscii',
valid: [
'foobar',
'0987654321',
'test@example.com',
'1234abcDEF',
],
invalid: [
'foobar',
'xyz098',
'123456',
'カタカナ',
],
});
});
it('should validate full-width strings', () => {
test({
validator: 'isFullWidth',
valid: [
'ひらがな・カタカナ、.漢字',
'3ー0 a@com',
'Fカタカナ゙ᆲ',
'Good=Parts',
],
invalid: [
'abc',
'abc123',
'!"#$%&()<>/+=-_? ~^|.,@`{}[]',
],
});
});
it('should validate half-width strings', () => {
test({
validator: 'isHalfWidth',
valid: [
'!"#$%&()<>/+=-_? ~^|.,@`{}[]',
'l-btn_02--active',
'abc123い',
'カタカナ゙ᆲ←',
],
invalid: [
'あいうえお',
'0011',
],
});
});
it('should validate variable-width strings', () => {
test({
validator: 'isVariableWidth',
valid: [
'ひらがなカタカナ漢字ABCDE',
'3ー0123',
'Fカタカナ゙ᆲ',
'Good=Parts',
],
invalid: [
'abc',
'abc123',
'!"#$%&()<>/+=-_? ~^|.,@`{}[]',
'ひらがな・カタカナ、.漢字',
'123456',
'カタカナ゙ᆲ',
],
});
});
it('should validate surrogate pair strings', () => {
test({
validator: 'isSurrogatePair',
valid: [
'𠮷野𠮷',
'𩸽',
'ABC千𥧄1-2-3',
],
invalid: [
'吉野竈',
'鮪',
'ABC1-2-3',
],
});
});
it('should validate base32 strings', () => {
test({
validator: 'isBase32',
valid: [
'ZG======',
'JBSQ====',
'JBSWY===',
'JBSWY3A=',
'JBSWY3DP',
'JBSWY3DPEA======',
'K5SWYY3PNVSSA5DPEBXG6ZA=',
'K5SWYY3PNVSSA5DPEBXG6===',
],
invalid: [
'12345',
'',
'JBSWY3DPtesting123',
'ZG=====',
'Z======',
'Zm=8JBSWY3DP',
'=m9vYg==',
'Zm9vYm/y====',
],
});
});
it('should validate base64 strings', () => {
test({
validator: 'isBase64',
valid: [
'Zg==',
'Zm8=',
'Zm9v',
'Zm9vYg==',
'Zm9vYmE=',
'Zm9vYmFy',
'TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4=',
'Vml2YW11cyBmZXJtZW50dW0gc2VtcGVyIHBvcnRhLg==',
'U3VzcGVuZGlzc2UgbGVjdHVzIGxlbw==',
'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuMPNS1Ufof9EW/M98FNw' +
'UAKrwflsqVxaxQjBQnHQmiI7Vac40t8x7pIb8gLGV6wL7sBTJiPovJ0V7y7oc0Ye' +
'rhKh0Rm4skP2z/jHwwZICgGzBvA0rH8xlhUiTvcwDCJ0kc+fh35hNt8srZQM4619' +
'FTgB66Xmp4EtVyhpQV+t02g6NzK72oZI0vnAvqhpkxLeLiMCyrI416wHm5Tkukhx' +
'QmcL2a6hNOyu0ixX/x2kSFXApEnVrJ+/IxGyfyw8kf4N2IZpW5nEP847lpfj0SZZ' +
'Fwrd1mnfnDbYohX2zRptLy2ZUn06Qo9pkG5ntvFEPo9bfZeULtjYzIl6K8gJ2uGZ' +
'HQIDAQAB',
],
invalid: [
'12345',
'',
'Vml2YW11cyBmZXJtZtesting123',
'Zg=',
'Z===',
'Zm=8',
'=m9vYg==',
'Zm9vYmFy====',
],
});
for (let i = 0, str = '', encoded; i < 1000; i++) {
str += String.fromCharCode(Math.random() * 26 | 97); // eslint-disable-line no-bitwise
encoded = Buffer.from(str).toString('base64');
if (!validator.isBase64(encoded)) {
let msg = format('validator.isBase64() failed with "%s"', encoded);
throw new Error(msg);
}
}
});
it('should validate hex-encoded MongoDB ObjectId', () => {
test({
validator: 'isMongoId',
valid: [
'507f1f77bcf86cd799439011',
],
invalid: [
'507f1f77bcf86cd7994390',
'507f1f77bcf86cd79943901z',
'',
'507f1f77bcf86cd799439011 ',
],
});
});
it('should define the module using an AMD-compatible loader', () => {
let window = {
validator: null,
define(module) {
window.validator = module();
},
};
window.define.amd = true;
let sandbox = vm.createContext(window);
vm.runInContext(validator_js, sandbox);
assert.equal(window.validator.trim(' foobar '), 'foobar');
});
it('should bind validator to the window if no module loaders are available', () => {
let window = {};
let sandbox = vm.createContext(window);
vm.runInContext(validator_js, sandbox);
assert.equal(window.validator.trim(' foobar '), 'foobar');
});
it('should validate mobile phone number', () => {
let fixtures = [
{
locale: 'ar-AE',
valid: [
'+971502674453',
'+971521247658',
'+971541255684',
'+971555454458',
'+971561498855',
'+971585215778',
'971585215778',
'0585215778',
'585215778',
],
invalid: [
'12345',
'+971511498855',
'+9715614988556',
'+9745614988556',
'',
'+9639626626262',
'+963332210972',
'0114152198',
'962796477263',
],
},
{
locale: 'ar-BH',
valid: [
'+97335078110',
'+97339534385',
'+97366331055',
'+97333146000',
'97335078110',
'35078110',
'66331055',
],
invalid: [
'12345',
'+973350781101',
'+97379534385',
'+973035078110',
'',
'+9639626626262',
'+963332210972',
'0114152198',
'962796477263',
'035078110',
'16331055',
'hello',
'+9733507811a',
],
},
{
locale: 'ar-EG',
valid: [
'+201004513789',
'+201111453489',
'+201221204610',
'+201144621154',
'+201200124304',
'+201011201564',
'+201124679001',
'+201064790156',
'+201274652177',
'+201280134679',
'+201090124576',
'+201583728900',
'201599495596',
'201090124576',
'01090124576',
'01538920744',
'1593075993',
'1090124576',
],
invalid: [
'+221004513789',
'+201404513789',
'12345',
'',
'+9639626626262',
'+963332210972',
'0114152198',
'962796477263',
],
},
{
locale: 'ar-JO',
valid: [
'0796477263',
'0777866254',
'0786725261',
'+962796477263',
'+962777866254',
'+962786725261',
'962796477263',
'962777866254',
'962786725261',
],
invalid: [
'00962786725261',
'00962796477263',
'12345',
'',
'+9639626626262',
'+963332210972',
'0114152198',
],
},
{
locale: 'ar-KW',
valid: [
'96550000000',
'96560000000',
'96590000000',
'+96550000000',
'+96550000220',
'+96551111220',
],
invalid: [
'+96570000220',
'00962786725261',
'00962796477263',
'12345',
'',
'+9639626626262',
'+963332210972',
'0114152198',
],
},
{
locale: 'ar-SY',
valid: [
'0944549710',
'+963944549710',
'956654379',
'0944549710',
'0962655597',
],
invalid: [
'12345',
'',
'+9639626626262',
'+963332210972',
'0114152198',
],
},
{
locale: 'ar-SA',
valid: [
'0556578654',
'+966556578654',
'966556578654',
'596578654',
'572655597',
],
invalid: [
'12345',
'',
'+9665626626262',
'+96633221097',
'0114152198',
],
},
{
locale: 'ar-TN',
valid: [
'23456789',
'+21623456789',
'21623456789',
],
invalid: [
'12345',
'75200123',
'+216512345678',
'13520459',
'85479520',
],
},
{
locale: 'bg-BG',
valid: [
'+359897123456',
'+359898888888',
'0897123123',
],
invalid: [
'',
'0898123',
'+359212555666',
'18001234567',
'12125559999',
],
},
{
locale: 'bn-BD',
valid: [
'+8801794626846',
'01399098893',
'8801671163269',
'01717112029',
'8801898765432',
'+8801312345678',
'01494676946',
],
invalid: [
'',
'0174626346',
'017943563469',
'18001234567',
'0131234567',
],
},
{
locale: 'cs-CZ',
valid: [
'+420 123 456 789',
'+420 123456789',
'+420123456789',
'123 456 789',
'123456789',
],
invalid: [
'',
'+42012345678',
'+421 123 456 789',
'+420 023456789',
'+4201234567892',
],
},
{
locale: 'sk-SK',
valid: [
'+421 123 456 789',
'+421 123456789',
'+421123456789',
'123 456 789',
'123456789',
],
invalid: [
'',
'+42112345678',
'+422 123 456 789',
'+421 023456789',
'+4211234567892',
],
},
{
locale: 'de-DE',
valid: [
'+49015123456789',
'+4915123456789',
'015123456789',
'15123456789',
'15623456789',
'15623456789',
'1601234567',
'16012345678',
'1621234567',
'1631234567',
'1701234567',
'17612345678',
],
invalid: [
'15345678910',
'15412345678',
'16212345678',
'1761234567',
'16412345678',
'17012345678',
'12345678910',
'+4912345678910',
],
},
{
locale: 'de-AT',
valid: [
'+436761234567',
'06761234567',
'00436123456789',
'+436123456789',
'01999',
'+4372876',
'06434908989562345',
],
invalid: [
'167612345678',
'1234',
'064349089895623459',
],
},
{
locale: 'pt-BR',
valid: [
'+55-12-996551215',
'+55-15-97661234',
'55-17-96332-2155',
'55-17-6332-2155',
'55-15-976612345',
'55-15-75661234',
'+5512984567890',
'+551283456789',
'5512984567890',
'551283456789',
'015994569878',
'01593456987',
'022995678947',
'02299567894',
],
invalid: [
'0819876543',
'08158765432',
'+55-15-7566123',
'+017-123456789',
'5501599623874',
'+55012962308',
'+55-015-1234-3214',
],
},
{
locale: 'zh-CN',
valid: [
'15323456787',
'13523333233',
'13898728332',
'+8613238234822',
'+8613487234567',
'+8617823492338',
'+8617823492338',
'16637108167',
'+8616637108167',
'+8616637108167',
'+8616712341234',
'008618812341234',
'008618812341234',
'+8619912341234',
'+8619812341234',
'+8619112341234',
'17269427292',
'+8617269427292',
'008617269427292',
],
invalid: [
'12345',
'',
'+08613811211114',
'+008613811211114',
'08613811211114',
'0086-13811211114',
'0086-138-1121-1114',
'Vml2YW11cyBmZXJtZtesting123',
'010-38238383',
],
},
{
locale: 'zh-TW',
valid: [
'0987123456',
'+886987123456',
'886987123456',
'+886-987123456',
'886-987123456',
],
invalid: [
'12345',
'',
'Vml2YW11cyBmZXJtZtesting123',
'0-987123456',
],
},
{
locale: 'en-ZA',
valid: [
'0821231234',
'+27821231234',
'27821231234',
],
invalid: [
'082123',
'08212312345',
'21821231234',
'+21821231234',
'+0821231234',
],
},
{
locale: 'en-AU',
valid: [
'61404111222',
'+61411222333',
'0417123456',
],
invalid: [
'082123',
'08212312345',
'21821231234',
'+21821231234',
'+0821231234',
'04123456789',
],
},
{
locale: 'en-GG',
valid: [
'+441481123456',
'+441481789123',
'441481123456',
'441481789123',
],
invalid: [
'999',
'+441481123456789',
'+447123456789',
],
},
{
locale: 'en-GH',
valid: [
'0202345671',
'0502345671',
'0242345671',
'0542345671',
'0272345671',
'0572345671',
'0262345671',
'0562345671',
'0232345671',
'0282345671',
'+233202345671',
'+233502345671',
'+233242345671',
'+233542345671',
'+233272345671',
'+233572345671',
'+233262345671',
'+233562345671',
'+233232345671',
'+233282345671',
],
invalid: [
'082123',
'232345671',
'0292345671',
'+233292345671',
],
},
{
locale: 'en-HK',
valid: [
'91234567',
'9123-4567',
'61234567',
'51234567',
'+85291234567',
'+852-91234567',
'+852-9123-4567',
'852-91234567',
],
invalid: [
'999',
'+852-912345678',
'123456789',
'+852-1234-56789',
],
},
{
locale: 'en-MO',
valid: [
'61234567',
'+85361234567',
'+853-61234567',
'+853-6123-4567',
'853-61234567',
],
invalid: [
'999',
'12345678',
'612345678',
'+853-12345678',
'+853-612345678',
'+853-1234-5678',
'+853-6123-45678',
],
},
{
locale: 'en-IE',
valid: [
'+353871234567',
'353831234567',
'353851234567',
'353861234567',
'353871234567',
'353881234567',
'353891234567',
'0871234567',
'0851234567',
],
invalid: [
'999',
'+353341234567',
'+33589484858',
'353841234567',
'353811234567',
],
},
{
locale: 'en-KE',
valid: [
'+254728590432',
'+254733875610',
'254728590234',
'0733346543',
'0700459022',
'0110934567',
'+254110456794',
'254198452389',
],
invalid: [
'999',
'+25489032',
'123456789',
'+254800723845',
],
},
{
locale: 'en-MT',
valid: [
'+35699000000',
'+35679000000',
'99000000',
],
invalid: [
'356',
'+35699000',
'+35610000000',
],
},
{
locale: 'en-UG',
valid: [
'+256728590432',
'+256733875610',
'256728590234',
'0773346543',
'0700459022',
],
invalid: [
'999',
'+254728590432',
'+25489032',
'123456789',
'+254800723845',
],
},
{
locale: 'en-RW',
valid: [
'+250728590432',
'+250733875610',
'250738590234',
'0753346543',
'0780459022',
],
invalid: [
'999',
'+254728590432',
'+25089032',
'123456789',
'+250800723845',
],
},
{
locale: 'en-TZ',
valid: [
'+255728590432',
'+255733875610',
'255628590234',
'0673346543',
'0600459022',
],
invalid: [
'999',
'+254728590432',
'+25589032',
'123456789',
'+255800723845',
],
},
{
locale: 'fr-FR',
valid: [
'0612457898',
'+33612457898',
'33612457898',
'0712457898',
'+33712457898',
'33712457898',
],
invalid: [
'061245789',
'06124578980',
'0112457898',
'0212457898',
'0312457898',
'0412457898',
'0512457898',
'0812457898',
'0912457898',
'+34612457898',
'+336124578980',
'+3361245789',
],
},
{
locale: 'fr-GF',
valid: [
'0612457898',
'+594612457898',
'594612457898',
'0712457898',
'+594712457898',
'594712457898',
],
invalid: [
'061245789',
'06124578980',
'0112457898',
'0212457898',
'0312457898',
'0412457898',
'0512457898',
'0812457898',
'0912457898',
'+54612457898',
'+5946124578980',
'+59461245789',
],
},
{
locale: 'fr-GP',
valid: [
'0612457898',
'+590612457898',
'590612457898',
'0712457898',
'+590712457898',
'590712457898',
],
invalid: [
'061245789',
'06124578980',
'0112457898',
'0212457898',
'0312457898',
'0412457898',
'0512457898',
'0812457898',
'0912457898',
'+594612457898',
'+5906124578980',
'+59061245789',
],
},
{
locale: 'fr-MQ',
valid: [
'0612457898',
'+596612457898',
'596612457898',
'0712457898',
'+596712457898',
'596712457898',
],
invalid: [
'061245789',
'06124578980',
'0112457898',
'0212457898',
'0312457898',
'0412457898',
'0512457898',
'0812457898',
'0912457898',
'+594612457898',
'+5966124578980',
'+59661245789',
],
},
{
locale: 'fr-RE',
valid: [
'0612457898',
'+262612457898',
'262612457898',
'0712457898',
'+262712457898',
'262712457898',
],
invalid: [
'061245789',
'06124578980',
'0112457898',
'0212457898',
'0312457898',
'0412457898',
'0512457898',
'0812457898',
'0912457898',
'+264612457898',
'+2626124578980',
'+26261245789',
],
},
{
locale: 'el-GR',
valid: [
'+306944848966',
'6944848966',
'306944848966',
],
invalid: [
'2102323234',
'+302646041461',
'120000000',
'20000000000',
'68129485729',
'6589394827',
'298RI89572',
],
},
{
locale: 'en-GB',
valid: [
'447789345856',
'+447861235675',
'07888814488',
],
invalid: [
'67699567',
'0773894868',
'077389f8688',
'+07888814488',
'0152456999',
'442073456754',
'+443003434751',
'05073456754',
'08001123123',
],
},
{
locale: 'en-SG',
valid: [
'87654321',
'98765432',
'+6587654321',
'+6598765432',
],
invalid: [
'987654321',
'876543219',
'8765432',
'9876543',
'12345678',
'+98765432',
'+9876543212',
'+15673628910',
'19876543210',
'8005552222',
],
},
{
locale: 'en-US',
valid: [
'19876543210',
'8005552222',
'+15673628910',
'+1(567)3628910',
'+1(567)362-8910',
'+1(567) 362-8910',
'1(567)362-8910',
'1(567)362 8910',
'223-456-7890',
],
invalid: [
'564785',
'0123456789',
'1437439210',
'+10345672645',
'11435213543',
'1(067)362-8910',
'1(167)362-8910',
'+2(267)362-8910',
'+3365520145',
],
},
{
locale: 'en-CA',
valid: ['19876543210', '8005552222', '+15673628910'],
invalid: [
'564785',
'0123456789',
'1437439210',
'+10345672645',
'11435213543',
],
},
{
locale: 'en-ZM',
valid: [
'0956684590',
'0966684590',
'0976684590',
'+260956684590',
'+260966684590',
'+260976684590',
'260976684590',
],
invalid: [
'12345',
'',
'Vml2YW11cyBmZXJtZtesting123',
'010-38238383',
'966684590',
],
},
{
locale: 'ru-RU',
valid: [
'+79676338855',
'79676338855',
'89676338855',
'9676338855',
],
invalid: [
'12345',
'',
'Vml2YW11cyBmZXJtZtesting123',
'010-38238383',
'+9676338855',
'19676338855',
'6676338855',
'+99676338855',
],
},
{
locale: 'sr-RS',
valid: [
'0640133338',
'063333133',
'0668888878',
'+381645678912',
'+381611314000',
'0655885010',
],
invalid: [
'12345',
'',
'Vml2YW11cyBmZXJtZtesting123',
'010-38238383',
'+9676338855',
'19676338855',
'6676338855',
'+99676338855',
],
},
{
locale: 'en-NZ',
valid: [
'+6427987035',
'642240512347',
'0293981646',
'029968425',
],
invalid: [
'12345',
'',
'Vml2YW11cyBmZXJtZtesting123',
'+642956696123566',
'+02119620856',
'+9676338855',
'19676338855',
'6676338855',
'+99676338855',
],
},
{
locale: 'en-MU',
valid: [
'+23012341234',
'12341234',
'012341234',
],
invalid: [
'41234',
'',
'+230',
'+2301',
'+23012',
'+230123',
'+2301234',
'+23012341',
'+230123412',
'+2301234123',
'+230123412341',
'+2301234123412',
'+23012341234123',
],
},
{
locale: ['nb-NO', 'nn-NO'], // for multiple locales
valid: [
'+4796338855',
'+4746338855',
'4796338855',
'4746338855',
'46338855',
'96338855',
],
invalid: [
'12345',
'',
'Vml2YW11cyBmZXJtZtesting123',
'+4676338855',
'19676338855',
'+4726338855',
'4736338855',
'66338855',
],
},
{
locale: ['ne-NP'],
valid: [
'+9779817385479',
'+9779717385478',
'+9779862002615',
'+9779853660020',
],
invalid: [
'12345',
'',
'Vml2YW11cyBmZXJtZtesting123',
'+97796123456789',
'+9771234567',
'+977981234',
'4736338855',
'66338855',
],
},
{
locale: 'vi-VN',
valid: [
'0336012403',
'+84586012403',
'84981577798',
'0708001240',
'84813601243',
'0523803765',
'0863803732',
'0883805866',
'0892405867',
'+84888696413',
],
invalid: [
'12345',
'',
'Vml2YW11cyBmZXJtZtesting123',
'010-38238383',
'260976684590',
'01678912345',
'+841698765432',
'841626543219',
'0533803765',
],
},
{
locale: 'es-CL',
valid: [
'+56733875615',
'56928590234',
'0928590294',
'0208590294',
],
invalid: [
'1234',
'+5633875615',
'563875615',
'56109834567',
'56069834567',
],
},
{
locale: 'es-EC',
valid: [
'+593987654321',
'593987654321',
'0987654321',
'027332615',
'+59323456789',
],
invalid: [
'03321321',
'+593387561',
'59312345677',
'02344635',
'593123456789',
'081234567',
'+593912345678',
'+593902345678',
'+593287654321',
'593287654321',
],
},
{
locale: 'es-ES',
valid: [
'+34654789321',
'654789321',
'+34714789321',
'714789321',
'+34744789321',
'744789321',
],
invalid: [
'12345',
'',
'Vml2YW11cyBmZXJtZtesting123',
'+3465478932',
'65478932',
'+346547893210',
'6547893210',
'+34704789321',
'704789321',
'+34754789321',
'754789321',
],
},
{
locale: 'es-MX',
valid: [
'+52019654789321',
'+52199654789321',
'+5201965478932',
'+5219654789321',
'52019654789321',
'52199654789321',
'5201965478932',
'5219654789321',
'87654789321',
'8654789321',
'0187654789321',
'18654789321',
],
invalid: [
'12345',
'',
'Vml2YW11cyBmZXJtZtesting123',
'+3465478932',
'65478932',
'+346547893210',
'+34704789321',
'704789321',
'+34754789321',
],
},
{
locale: 'es-PA',
valid: [
'+5076784565',
'+5074321557',
'5073331112',
'+50723431212',
],
invalid: [
'+50755555',
'+207123456',
'2001236542',
'+507987643254',
'+507jjjghtf',
],
},
{
locale: 'es-PY',
valid: [
'+595991372649',
'+595992847352',
'+595993847593',
'+595994857473',
'+595995348532',
'+595996435231',
'+595981847362',
'+595982435452',
'+595983948502',
'+595984342351',
'+595985403481',
'+595986384012',
'+595971435231',
'+595972103924',
'+595973438542',
'+595974425864',
'+595975425843',
'+595976342546',
'+595961435234',
'+595963425043',
],
invalid: [
'12345',
'',
'Vml2YW11cyBmZXJtZtesting123',
'65478932',
'+59599384712',
'+5959938471234',
'+595547893218',
'+591993546843',
],
},
{
locale: 'es-UY',
valid: [
'+59899123456',
'099123456',
'+59894654321',
'091111111',
],
invalid: [
'54321',
'montevideo',
'',
'+598099123456',
'090883338',
'099 999 999',
],
},
{
locale: 'et-EE',
valid: [
'+372 512 34 567',
'372 512 34 567',
'+37251234567',
'51234567',
'81234567',
'+372842345678',
],
invalid: [
'12345',
'',
'NotANumber',
'+333 51234567',
'61234567',
'+51234567',
'+372 539 57 4',
'+372 900 1234',
'12345678',
],
},
{
locale: 'pl-PL',
valid: [
'+48512689767',
'+48 56 376 87 47',
'56 566 78 46',
'657562855',
'+48657562855',
'+48 887472765',
'+48 56 6572724',
'+48 67 621 5461',
'48 67 621 5461',
],
invalid: [
'+48 67 621 5461',
'+55657562855',
'3454535',
'teststring',
'',
'1800-88-8687',
'+6019-5830837',
'357562855',
],
},
{
locale: 'fa-IR',
valid: [
'+989123456789',
'989223456789',
'09323456789',
'09021456789',
'+98-990-345-6789',
'+98 938 345 6789',
'0938 345 6789',
],
invalid: [
'',
'+989623456789',
'+981123456789',
'01234567890',
'09423456789',
'09823456789',
'9123456789',
'091234567890',
'0912345678',
'+98 912 3456 6789',
'0912 345 678',
],
},
{
locale: 'fi-FI',
valid: [
'+358505557171',
'0455571',
'0505557171',
'358505557171',
'04412345',
'0457 123 45 67',
'+358457 123 45 67',
'+358 50 555 7171',
],
invalid: [
'12345',
'',
'045557',
'045555717112312332423423421',
'Vml2YW11cyBmZXJtZtesting123',
'010-38238383',
'+3-585-0555-7171',
'+9676338855',
'19676338855',
'6676338855',
'+99676338855',
'044123',
'019123456789012345678901',
],
},
{
locale: 'fj-FJ',
valid: [
'+6799898679',
'6793788679',
'+679 989 8679',
'679 989 8679',
'679 3456799',
'679908 8909',
],
invalid: [
'12345',
'',
'04555792',
'902w99900030900000000099',
'8uiuiuhhyy&GUU88d',
'010-38238383',
'19676338855',
'679 9 89 8679',
'6793 45679',
],
},
{
locale: 'ms-MY',
valid: [
'+60128228789',
'+60195830837',
'+6019-5830837',
'+6019-5830837',
'+6010-4357675',
'+60172012370',
'0128737867',
'0172012370',
'01468987837',
'01112347345',
'016-2838768',
'016 2838768',
],
invalid: [
'12345',
'601238788657',
'088387675',
'16-2838768',
'032551433',
'6088-387888',
'088-261987',
'1800-88-8687',
'088-320000',
],
},
{
locale: 'ko-KR',
valid: [
'+82-010-1234-5678',
'+82-10-1234-5678',
'82-010-1234-5678',
'82-10-1234-5678',
'+82 10 1234 5678',
'010-123-5678',
'10-1234-5678',
'+82 10 1234 5678',
'011 1234 5678',
'+820112345678',
'01012345678',
'+82 016 1234 5678',
'82 19 1234 5678',
'+82 010 12345678',
],
invalid: [
'abcdefghi',
'+82 10 1234 567',
'+82 10o 1234 1234',
'+82 101 1234 5678',
'+82 10 12 5678',
'+011 7766 1234',
'011_7766_1234',
'+820 11 7766 1234',
],
},
{
locale: 'ja-JP',
valid: [
'09012345678',
'08012345678',
'07012345678',
'06012345678',
'090 1234 5678',
'+8190-1234-5678',
'+81 (0)90-1234-5678',
'+819012345678',
'+81-(0)90-1234-5678',
'+81 90 1234 5678',
],
invalid: [
'12345',
'',
'045555717112312332423423421',
'Vml2YW11cyBmZXJtZtesting123',
'+3-585-0555-7171',
'0 1234 5689',
'16 1234 5689',
'03_1234_5689',
'0312345678',
'0721234567',
'06 1234 5678',
'072 123 4567',
'0729 12 3456',
'07296 1 2345',
'072961 2345',
'03-1234-5678',
'+81312345678',
'+816-1234-5678',
'+81 090 1234 5678',
'+8109012345678',
'+81-090-1234-5678',
'90 1234 5678',
],
},
{
locale: 'it-IT',
valid: [
'370 3175423',
'333202925',
'+39 310 7688449',
'+39 3339847632',
],
invalid: [
'011 7387545',
'12345',
'+45 345 6782395',
],
},
{
locale: 'fr-BE',
valid: [
'0470123456',
'+32470123456',
'32470123456',
'021234567',
'+3221234567',
'3221234567',
],
invalid: [
'12345',
'+3212345',
'3212345',
'04701234567',
'+3204701234567',
'3204701234567',
'0212345678',
'+320212345678',
'320212345678',
],
},
{
locale: 'nl-BE',
valid: [
'0470123456',
'+32470123456',
'32470123456',
'021234567',
'+3221234567',
'3221234567',
],
invalid: [
'12345',
'+3212345',
'3212345',
'04701234567',
'+3204701234567',
'3204701234567',
'0212345678',
'+320212345678',
'320212345678',
],
},
{
locale: 'nl-NL',
valid: [
'0670123456',
'+31670123456',
'31670123456',
'021234567',
'+3121234567',
'3121234567',
],
invalid: [
'12345',
'+3112345',
'3112345',
'06701234567',
'+3104701234567',
'3104701234567',
'0212345678',
'+310212345678',
'310212345678',
],
},
{
locale: 'ro-RO',
valid: [
'+40740123456',
'+40 740123456',
'+40740 123 456',
'+40740.123.456',
'+40740-123-456',
'40740123456',
'40 740123456',
'40740 123 456',
'40740.123.456',
'40740-123-456',
'0740123456',
'0740/123456',
'0740 123 456',
'0740.123.456',
'0740-123-456',
],
invalid: [
'',
'Vml2YW11cyBmZXJtZtesting123',
'123456',
'740123456',
'+40640123456',
'+40210123456',
],
},
{
locale: 'id-ID',
valid: [
'0811 778 998',
'0811 7785 9983',
'0812 7784 9984',
'0813 7782 9982',
'0821 1234 1234',
'0822 1234 1234',
'0823 1234 1234',
'0852 1234 6764',
'0853 1234 6764',
'0851 1234 6764',
'0814 7782 9982',
'0815 7782 9982',
'0816 7782 9982',
'0855 7782 9982',
'0856 7782 9982',
'0857 7782 9982',
'0858 7782 9982',
'0817 7785 9983',
'0818 7784 9984',
'0819 7782 9982',
'0859 1234 1234',
'0877 1234 1234',
'0878 1234 1234',
'0895 7785 9983',
'0896 7784 9984',
'0897 7782 9982',
'0898 1234 1234',
'0899 1234 1234',
'0881 7785 9983',
'0882 7784 9984',
'0883 7782 9982',
'0884 1234 1234',
'0886 1234 1234',
'0887 1234 1234',
'0888 7785 9983',
'0889 7784 9984',
'0828 7784 9984',
'0838 7784 9984',
'0831 7784 9984',
'0832 7784 9984',
'0833 7784 9984',
'089931236181900',
'62811 778 998',
'62811778998',
'628993123618190',
'62898 740123456',
'62899 7401 2346',
'+62811 778 998',
'+62811778998',
'+62812 9650 3508',
'08197231819',
'085361008008',
'+62811787391',
],
invalid: [
'0899312361819001',
'0217123456',
'622178878890',
'6221 740123456',
'0341 8123456',
'0778 89800910',
'0741 123456',
'+6221740123456',
'+65740 123 456',
'',
'ASDFGJKLmZXJtZtesting123',
'123456',
'740123456',
'+65640123456',
'+64210123456',
],
},
{
locale: 'lt-LT',
valid: [
'+37051234567',
'851234567',
],
invalid: [
'+65740 123 456',
'',
'ASDFGJKLmZXJtZtesting123',
'123456',
'740123456',
'+65640123456',
'+64210123456',
],
},
{
locale: 'uk-UA',
valid: [
'+380982345679',
'380982345679',
'80982345679',
'0982345679',
],
invalid: [
'+30982345679',
'982345679',
'+380 98 234 5679',
'+380-98-234-5679',
'',
'ASDFGJKLmZXJtZtesting123',
'123456',
'740123456',
],
},
{
locale: 'da-DK',
valid: [
'12345678',
'12 34 56 78',
'45 12345678',
'4512345678',
'45 12 34 56 78',
'+45 12 34 56 78',
],
invalid: [
'',
'+45010203',
'ASDFGJKLmZXJtZtesting123',
'123456',
'12 34 56',
'123 123 12',
],
},
{
locale: 'sv-SE',
valid: [
'+46701234567',
'46701234567',
'0721234567',
'073-1234567',
'0761-234567',
'079-123 45 67',
],
invalid: [
'12345',
'+4670123456',
'+46301234567',
'+0731234567',
'0731234 56',
'+7312345678',
'',
],
},
{
locale: 'fo-FO',
valid: [
'123456',
'12 34 56',
'298 123456',
'298123456',
'298 12 34 56',
'+298 12 34 56',
],
invalid: [
'',
'+4501020304',
'ASDFGJKLmZXJtZtesting123',
'12345678',
'12 34 56 78',
],
},
{
locale: 'kl-GL',
valid: [
'123456',
'12 34 56',
'299 123456',
'299123456',
'299 12 34 56',
'+299 12 34 56',
],
invalid: [
'',
'+4501020304',
'ASDFGJKLmZXJtZtesting123',
'12345678',
'12 34 56 78',
],
},
{
locale: 'kk-KZ',
valid: [
'+77254716212',
'77254716212',
'87254716212',
'7254716212',
],
invalid: [
'12345',
'',
'ASDFGJKLmZXJtZtesting123',
'010-38238383',
'+9676338855',
'19676338855',
'6676338855',
'+99676338855',
],
},
{
locale: 'be-BY',
valid: [
'+375241234567',
'+375251234567',
'+375291234567',
'+375331234567',
'+375441234567',
'375331234567',
],
invalid: [
'12345',
'',
'ASDFGJKLmZXJtZtesting123',
'010-38238383',
'+9676338855',
'19676338855',
'6676338855',
'+99676338855',
],
},
{
locale: 'th-TH',
valid: [
'0912345678',
'+66912345678',
'66912345678',
],
invalid: [
'99123456789',
'12345',
'67812345623',
'081234567891',
],
},
{
locale: ['en-ZA', 'be-BY'],
valid: [
'0821231234',
'+27821231234',
'27821231234',
'+375241234567',
'+375251234567',
'+375291234567',
'+375331234567',
'+375441234567',
'375331234567',
],
invalid: [
'082123',
'08212312345',
'21821231234',
'+21821231234',
'+0821231234',
'12345',
'',
'ASDFGJKLmZXJtZtesting123',
'010-38238383',
'+9676338855',
'19676338855',
'6676338855',
'+99676338855',
],
},
];
let allValid = [];
fixtures.forEach((fixture) => {
// to be used later on for validating 'any' locale
if (fixture.valid) allValid = allValid.concat(fixture.valid);
if (Array.isArray(fixture.locale)) {
test({
validator: 'isMobilePhone',
valid: fixture.valid,
invalid: fixture.invalid,
args: [fixture.locale],
});
} else {
test({
validator: 'isMobilePhone',
valid: fixture.valid,
invalid: fixture.invalid,
args: [fixture.locale],
});
}
});
test({
validator: 'isMobilePhone',
valid: allValid,
invalid: [
'',
'asdf',
'1',
'ASDFGJKLmZXJtZtesting123',
'Vml2YW11cyBmZXJtZtesting123',
],
args: ['any'],
});
// strict mode
test({
validator: 'isMobilePhone',
valid: [
'+254728530234',
'+299 12 34 56',
],
invalid: [
'254728530234',
'0728530234',
'+728530234',
],
args: ['any', { strictMode: true }],
});
// falsey locale defaults to 'any'
test({
validator: 'isMobilePhone',
valid: allValid,
invalid: [
'',
'asdf',
'1',
'ASDFGJKLmZXJtZtesting123',
'Vml2YW11cyBmZXJtZtesting123',
],
args: [],
});
});
it('should error on invalid locale', () => {
test({
validator: 'isMobilePhone',
args: [{ locale: ['is-NOT'] }],
error: [
'+123456789',
'012345',
],
});
});
it('should validate currency', () => {
// -$##,###.## (en-US, en-CA, en-AU, en-NZ, en-HK)
test({
validator: 'isCurrency',
valid: [
'-$10,123.45',
'$10,123.45',
'$10123.45',
'10,123.45',
'10123.45',
'10,123',
'1,123,456',
'1123456',
'1.39',
'.03',
'0.10',
'$0.10',
'-$0.01',
'-$.99',
'$100,234,567.89',
'$10,123',
'10,123',
'-10123',
],
invalid: [
'1.234',
'$1.1',
'$ 32.50',
'500$',
'.0001',
'$.001',
'$0.001',
'12,34.56',
'123456,123,123456',
'123,4',
',123',
'$-,123',
'$',
'.',
',',
'00',
'$-',
'$-,.',
'-',
'-$',
'',
'- $',
],
});
// -$##,###.## (en-US, en-CA, en-AU, en-NZ, en-HK)
test({
validator: 'isCurrency',
args: [
{
allow_decimal: false,
},
],
valid: [
'-$10,123',
'$10,123',
'$10123',
'10,123',
'10123',
'10,123',
'1,123,456',
'1123456',
'1',
'0',
'$0',
'-$0',
'$100,234,567',
'$10,123',
'10,123',
'-10123',
],
invalid: [
'-$10,123.45',
'$10,123.45',
'$10123.45',
'10,123.45',
'10123.45',
'1.39',
'.03',
'0.10',
'$0.10',
'-$0.01',
'-$.99',
'$100,234,567.89',
'1.234',
'$1.1',
'$ 32.50',
'.0001',
'$.001',
'$0.001',
'12,34.56',
'123,4',
',123',
'$-,123',
'$',
'.',
',',
'00',
'$-',
'$-,.',
'-',
'-$',
'',
'- $',
],
});
// -$##,###.## (en-US, en-CA, en-AU, en-NZ, en-HK)
test({
validator: 'isCurrency',
args: [
{
require_decimal: true,
},
],
valid: [
'-$10,123.45',
'$10,123.45',
'$10123.45',
'10,123.45',
'10123.45',
'10,123.00',
'1.39',
'.03',
'0.10',
'$0.10',
'-$0.01',
'-$.99',
'$100,234,567.89',
],
invalid: [
'$10,123',
'10,123',
'-10123',
'1,123,456',
'1123456',
'1.234',
'$1.1',
'$ 32.50',
'500$',
'.0001',
'$.001',
'$0.001',
'12,34.56',
'123456,123,123456',
'123,4',
',123',
'$-,123',
'$',
'.',
',',
'00',
'$-',
'$-,.',
'-',
'-$',
'',
'- $',
],
});
// -$##,###.## (en-US, en-CA, en-AU, en-NZ, en-HK)
test({
validator: 'isCurrency',
args: [
{
digits_after_decimal: [1, 3],
},
],
valid: [
'-$10,123.4',
'$10,123.454',
'$10123.452',
'10,123.453',
'10123.450',
'10,123',
'1,123,456',
'1123456',
'1.3',
'.030',
'0.100',
'$0.1',
'-$0.0',
'-$.9',
'$100,234,567.893',
'$10,123',
'10,123.123',
'-10123.1',
],
invalid: [
'1.23',
'$1.13322',
'$ 32.50',
'500$',
'.0001',
'$.01',
'$0.01',
'12,34.56',
'123456,123,123456',
'123,4',
',123',
'$-,123',
'$',
'.',
',',
'00',
'$-',
'$-,.',
'-',
'-$',
'',
'- $',
],
});
// -$##,###.## with $ required (en-US, en-CA, en-AU, en-NZ, en-HK)
test({
validator: 'isCurrency',
args: [
{
require_symbol: true,
},
],
valid: [
'-$10,123.45',
'$10,123.45',
'$10123.45',
'$10,123.45',
'$10,123',
'$1,123,456',
'$1123456',
'$1.39',
'$.03',
'$0.10',
'$0.10',
'-$0.01',
'-$.99',
'$100,234,567.89',
'$10,123',
'-$10123',
],
invalid: [
'1.234',
'$1.234',
'1.1',
'$1.1',
'$ 32.50',
' 32.50',
'500',
'10,123,456',
'.0001',
'$.001',
'$0.001',
'1,234.56',
'123456,123,123456',
'$123456,123,123456',
'123.4',
'$123.4',
',123',
'$,123',
'$-,123',
'$',
'.',
'$.',
',',
'$,',
'00',
'$00',
'$-',
'$-,.',
'-',
'-$',
'',
'$ ',
'- $',
],
});
// ¥-##,###.## (zh-CN)
test({
validator: 'isCurrency',
args: [
{
symbol: '¥',
negative_sign_before_digits: true,
},
],
valid: [
'123,456.78',
'-123,456.78',
'¥6,954,231',
'¥-6,954,231',
'¥10.03',
'¥-10.03',
'10.03',
'1.39',
'.03',
'0.10',
'¥-10567.01',
'¥0.01',
'¥1,234,567.89',
'¥10,123',
'¥-10,123',
'¥-10,123.45',
'10,123',
'10123',
'¥-100',
],
invalid: [
'1.234',
'¥1.1',
'5,00',
'.0001',
'¥.001',
'¥0.001',
'12,34.56',
'123456,123,123456',
'123 456',
',123',
'¥-,123',
'',
' ',
'¥',
'¥-',
'¥-,.',
'-',
'- ¥',
'-¥',
],
});
test({
validator: 'isCurrency',
args: [
{
negative_sign_after_digits: true,
},
],
valid: [
'$10,123.45-',
'$10,123.45',
'$10123.45',
'10,123.45',
'10123.45',
'10,123',
'1,123,456',
'1123456',
'1.39',
'.03',
'0.10',
'$0.10',
'$0.01-',
'$.99-',
'$100,234,567.89',
'$10,123',
'10,123',
'10123-',
],
invalid: [
'-123',
'1.234',
'$1.1',
'$ 32.50',
'500$',
'.0001',
'$.001',
'$0.001',
'12,34.56',
'123456,123,123456',
'123,4',
',123',
'$-,123',
'$',
'.',
',',
'00',
'$-',
'$-,.',
'-',
'-$',
'',
'- $',
],
});
// ¥##,###.## with no negatives (zh-CN)
test({
validator: 'isCurrency',
args: [
{
symbol: '¥',
allow_negatives: false,
},
],
valid: [
'123,456.78',
'¥6,954,231',
'¥10.03',
'10.03',
'1.39',
'.03',
'0.10',
'¥0.01',
'¥1,234,567.89',
'¥10,123',
'10,123',
'10123',
'¥100',
],
invalid: [
'1.234',
'-123,456.78',
'¥-6,954,231',
'¥-10.03',
'¥-10567.01',
'¥1.1',
'¥-10,123',
'¥-10,123.45',
'5,00',
'¥-100',
'.0001',
'¥.001',
'¥-.001',
'¥0.001',
'12,34.56',
'123456,123,123456',
'123 456',
',123',
'¥-,123',
'',
' ',
'¥',
'¥-',
'¥-,.',
'-',
'- ¥',
'-¥',
],
});
// R ## ###,## and R-10 123,25 (el-ZA)
test({
validator: 'isCurrency',
args: [
{
symbol: 'R',
negative_sign_before_digits: true,
thousands_separator: ' ',
decimal_separator: ',',
allow_negative_sign_placeholder: true,
},
],
valid: [
'123 456,78',
'-10 123',
'R-10 123',
'R 6 954 231',
'R10,03',
'10,03',
'1,39',
',03',
'0,10',
'R10567,01',
'R0,01',
'R1 234 567,89',
'R10 123',
'R 10 123',
'R 10123',
'R-10123',
'10 123',
'10123',
],
invalid: [
'1,234',
'R -10123',
'R- 10123',
'R,1',
',0001',
'R,001',
'R0,001',
'12 34,56',
'123456 123 123456',
' 123',
'- 123',
'123 ',
'',
' ',
'R',
'R- .1',
'R-',
'-',
'-R 10123',
'R00',
'R -',
'-R',
],
});
// -€ ##.###,## (it-IT)
test({
validator: 'isCurrency',
args: [
{
symbol: '€',
thousands_separator: '.',
decimal_separator: ',',
allow_space_after_symbol: true,
},
],
valid: [
'123.456,78',
'-123.456,78',
'€6.954.231',
'-€6.954.231',
'€ 896.954.231',
'-€ 896.954.231',
'16.954.231',
'-16.954.231',
'€10,03',
'-€10,03',
'10,03',
'-10,03',
'-1,39',
',03',
'0,10',
'-€10567,01',
'-€ 10567,01',
'€ 0,01',
'€1.234.567,89',
'€10.123',
'10.123',
'-€10.123',
'€ 10.123',
'€10.123',
'€ 10123',
'10.123',
'-10123',
],
invalid: [
'1,234',
'€ 1,1',
'50#,50',
'123,@€ ',
'€€500',
',0001',
'€ ,001',
'€0,001',
'12.34,56',
'123456.123.123456',
'€123€',
'',
' ',
'€',
' €',
'€ ',
'€€',
' 123',
'- 123',
'.123',
'-€.123',
'123 ',
'€-',
'- €',
'€ - ',
'-',
'- ',
'-€',
],
});
// -##.###,## € (el-GR)
test({
validator: 'isCurrency',
args: [
{
symbol: '€',
thousands_separator: '.',
symbol_after_digits: true,
decimal_separator: ',',
allow_space_after_digits: true,
},
],
valid: [
'123.456,78',
'-123.456,78',
'6.954.231 €',
'-6.954.231 €',
'896.954.231',
'-896.954.231',
'16.954.231',
'-16.954.231',
'10,03€',
'-10,03€',
'10,03',
'-10,03',
'1,39',
',03',
'-,03',
'-,03 €',
'-,03€',
'0,10',
'10567,01€',
'0,01 €',
'1.234.567,89€',
'10.123€',
'10.123',
'10.123€',
'10.123 €',
'10123 €',
'10.123',
'10123',
],
invalid: [
'1,234',
'1,1 €',
',0001',
',001 €',
'0,001€',
'12.34,56',
'123456.123.123456',
'€123€',
'',
' ',
'€',
' €',
'€ ',
' 123',
'- 123',
'.123',
'-.123€',
'-.123 €',
'123 ',
'-€',
'- €',
'-',
'- ',
],
});
// kr. -##.###,## (da-DK)
test({
validator: 'isCurrency',
args: [
{
symbol: 'kr.',
negative_sign_before_digits: true,
thousands_separator: '.',
decimal_separator: ',',
allow_space_after_symbol: true,
},
],
valid: [
'123.456,78',
'-10.123',
'kr. -10.123',
'kr.-10.123',
'kr. 6.954.231',
'kr.10,03',
'kr. -10,03',
'10,03',
'1,39',
',03',
'0,10',
'kr. 10567,01',
'kr. 0,01',
'kr. 1.234.567,89',
'kr. -1.234.567,89',
'10.123',
'kr. 10.123',
'kr.10.123',
'10123',
'10.123',
'kr.-10123',
],
invalid: [
'1,234',
'kr. -10123',
'kr.,1',
',0001',
'kr. ,001',
'kr.0,001',
'12.34,56',
'123456.123.123456',
'.123',
'kr.-.123',
'kr. -.123',
'- 123',
'123 ',
'',
' ',
'kr.',
' kr.',
'kr. ',
'kr.-',
'kr. -',
'kr. - ',
' - ',
'-',
'- kr.',
'-kr.',
],
});
// kr. ##.###,## with no negatives (da-DK)
test({
validator: 'isCurrency',
args: [
{
symbol: 'kr.',
allow_negatives: false,
negative_sign_before_digits: true,
thousands_separator: '.',
decimal_separator: ',',
allow_space_after_symbol: true,
},
],
valid: [
'123.456,78',
'10.123',
'kr. 10.123',
'kr.10.123',
'kr. 6.954.231',
'kr.10,03',
'kr. 10,03',
'10,03',
'1,39',
',03',
'0,10',
'kr. 10567,01',
'kr. 0,01',
'kr. 1.234.567,89',
'kr.1.234.567,89',
'10.123',
'kr. 10.123',
'kr.10.123',
'10123',
'10.123',
'kr.10123',
],
invalid: [
'1,234',
'-10.123',
'kr. -10.123',
'kr. -1.234.567,89',
'kr.-10123',
'kr. -10123',
'kr.-10.123',
'kr. -10,03',
'kr.,1',
',0001',
'kr. ,001',
'kr.0,001',
'12.34,56',
'123456.123.123456',
'.123',
'kr.-.123',
'kr. -.123',
'- 123',
'123 ',
'',
' ',
'kr.',
' kr.',
'kr. ',
'kr.-',
'kr. -',
'kr. - ',
' - ',
'-',
'- kr.',
'-kr.',
],
});
// ($##,###.##) (en-US, en-HK)
test({
validator: 'isCurrency',
args: [
{
parens_for_negatives: true,
},
],
valid: [
'1,234',
'(1,234)',
'($6,954,231)',
'$10.03',
'(10.03)',
'($10.03)',
'1.39',
'.03',
'(.03)',
'($.03)',
'0.10',
'$10567.01',
'($0.01)',
'$1,234,567.89',
'$10,123',
'(10,123)',
'10123',
],
invalid: [
'1.234',
'($1.1)',
'-$1.10',
'$ 32.50',
'500$',
'.0001',
'$.001',
'($0.001)',
'12,34.56',
'123456,123,123456',
'( 123)',
',123',
'$-,123',
'',
' ',
' ',
' ',
'$',
'$ ',
' $',
' 123',
'(123) ',
'.',
',',
'00',
'$-',
'$ - ',
'$- ',
' - ',
'-',
'- $',
'-$',
'()',
'( )',
'( -)',
'( - )',
'( - )',
'(-)',
'(-$)',
],
});
// $##,###.## with no negatives (en-US, en-CA, en-AU, en-HK)
test({
validator: 'isCurrency',
args: [
{ allow_negatives: false },
],
valid: [
'$10,123.45',
'$10123.45',
'10,123.45',
'10123.45',
'10,123',
'1,123,456',
'1123456',
'1.39',
'.03',
'0.10',
'$0.10',
'$100,234,567.89',
'$10,123',
'10,123',
],
invalid: [
'1.234',
'-1.234',
'-10123',
'-$0.01',
'-$.99',
'$1.1',
'-$1.1',
'$ 32.50',
'500$',
'.0001',
'$.001',
'$0.001',
'12,34.56',
'123456,123,123456',
'-123456,123,123456',
'123,4',
',123',
'$-,123',
'$',
'.',
',',
'00',
'$-',
'$-,.',
'-',
'-$',
'',
'- $',
'-$10,123.45',
],
});
});
it('should validate booleans', () => {
test({
validator: 'isBoolean',
valid: [
'true',
'false',
'0',
'1',
],
invalid: [
'1.0',
'0.0',
'true ',
'False',
'True',
'yes',
],
});
});
const validISO8601 = [
'2009-12T12:34',
'2009',
'2009-05-19',
'2009-05-19',
'20090519',
'2009123',
'2009-05',
'2009-123',
'2009-222',
'2009-001',
'2009-W01-1',
'2009-W51-1',
'2009-W511',
'2009-W33',
'2009W511',
'2009-05-19',
'2009-05-19 00:00',
'2009-05-19 14',
'2009-05-19 14:31',
'2009-05-19 14:39:22',
'2009-05-19T14:39Z',
'2009-W21-2',
'2009-W21-2T01:22',
'2009-139',
'2009-05-19 14:39:22-06:00',
'2009-05-19 14:39:22+0600',
'2009-05-19 14:39:22-01',
'20090621T0545Z',
'2007-04-06T00:00',
'2007-04-05T24:00',
'2010-02-18T16:23:48.5',
'2010-02-18T16:23:48,444',
'2010-02-18T16:23:48,3-06:00',
'2010-02-18T16:23.4',
'2010-02-18T16:23,25',
'2010-02-18T16:23.33+0600',
'2010-02-18T16.23334444',
'2010-02-18T16,2283',
'2009-05-19 143922.500',
'2009-05-19 1439,55',
'2009-10-10',
'2020-366',
'2000-366',
];
const invalidISO8601 = [
'200905',
'2009367',
'2009-',
'2007-04-05T24:50',
'2009-000',
'2009-M511',
'2009M511',
'2009-05-19T14a39r',
'2009-05-19T14:3924',
'2009-0519',
'2009-05-1914:39',
'2009-05-19 14:',
'2009-05-19r14:39',
'2009-05-19 14a39a22',
'200912-01',
'2009-05-19 14:39:22+06a00',
'2009-05-19 146922.500',
'2010-02-18T16.5:23.35:48',
'2010-02-18T16:23.35:48',
'2010-02-18T16:23.35:48.45',
'2009-05-19 14.5.44',
'2010-02-18T16:23.33.600',
'2010-02-18T16,25:23:48,444',
'2010-13-1',
];
it('should validate ISO 8601 dates', () => {
// from http://www.pelagodesign.com/blog/2009/05/20/iso-8601-date-validation-that-doesnt-suck/
test({
validator: 'isISO8601',
valid: validISO8601,
invalid: invalidISO8601,
});
});
it('should validate ISO 8601 dates, with strict = true (regression)', () => {
test({
validator: 'isISO8601',
args: [
{ strict: true },
],
valid: validISO8601,
invalid: invalidISO8601,
});
});
it('should validate ISO 8601 dates, with strict = true', () => {
test({
validator: 'isISO8601',
args: [
{ strict: true },
],
valid: [
'2000-02-29',
'2009-123',
'2009-222',
'2020-366',
'2400-366',
],
invalid: [
'2010-02-30',
'2009-02-29',
'2009-366',
'2019-02-31',
],
});
});
it('should validate RFC 3339 dates', () => {
test({
validator: 'isRFC3339',
valid: [
'2009-05-19 14:39:22-06:00',
'2009-05-19 14:39:22+06:00',
'2009-05-19 14:39:22Z',
'2009-05-19T14:39:22-06:00',
'2009-05-19T14:39:22Z',
'2010-02-18T16:23:48.3-06:00',
'2010-02-18t16:23:33+06:00',
'2010-02-18t16:23:33+06:00',
'2010-02-18t16:12:23.23334444z',
'2010-02-18T16:23:55.2283Z',
'2009-05-19 14:39:22.500Z',
'2009-05-19 14:39:55Z',
'2009-05-31 14:39:55Z',
'2009-05-31 14:53:60Z',
'2010-02-18t00:23:23.33+06:00',
'2010-02-18t00:23:32.33+00:00',
'2010-02-18t00:23:32.33+23:00',
],
invalid: [
'2010-02-18t00:23:32.33+24:00',
'2009-05-31 14:60:55Z',
'2010-02-18t24:23.33+0600',
'2009-05-00 1439,55Z',
'2009-13-19 14:39:22-06:00',
'2009-05-00 14:39:22+0600',
'2009-00-1 14:39:22Z',
'2009-05-19T14:39:22',
],
});
});
it('should validate ISO 3166-1 alpha 2 country codes', () => {
// from https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2
test({
validator: 'isISO31661Alpha2',
valid: [
'FR',
'fR',
'GB',
'PT',
'CM',
'JP',
'PM',
'ZW',
'MM',
'cc',
'GG',
],
invalid: [
'',
'FRA',
'AA',
'PI',
'RP',
'WV',
'WL',
'UK',
'ZZ',
],
});
});
it('should validate ISO 3166-1 alpha 3 country codes', () => {
// from https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3
test({
validator: 'isISO31661Alpha3',
valid: [
'ABW',
'HND',
'KHM',
'RWA',
],
invalid: [
'',
'FR',
'fR',
'GB',
'PT',
'CM',
'JP',
'PM',
'ZW',
],
});
});
it('should validate whitelisted characters', () => {
test({
validator: 'isWhitelisted',
args: ['abcdefghijklmnopqrstuvwxyz-'],
valid: ['foo', 'foobar', 'baz-foo'],
invalid: ['foo bar', 'fo.bar', 'türkçe'],
});
});
it('should error on non-string input', () => {
test({
validator: 'isEmpty',
error: [undefined, null, [], NaN],
});
});
it('should validate dataURI', () => {
/* eslint-disable max-len */
test({
validator: 'isDataURI',
valid: [
'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAABlBMVEUAAAD///+l2Z/dAAAAM0lEQVR4nGP4/5/h/1+G/58ZDrAz3D/McH8yw83NDDeNGe4Ug9C9zwz3gVLMDA/A6P9/AFGGFyjOXZtQAAAAAElFTkSuQmCC',
'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAIBAMAAAA2IaO4AAAAFVBMVEXk5OTn5+ft7e319fX29vb5+fn///++GUmVAAAALUlEQVQIHWNICnYLZnALTgpmMGYIFWYIZTA2ZFAzTTFlSDFVMwVyQhmAwsYMAKDaBy0axX/iAAAAAElFTkSuQmCC',
' data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAIBAMAAAA2IaO4AAAAFVBMVEXk5OTn5+ft7e319fX29vb5+fn///++GUmVAAAALUlEQVQIHWNICnYLZnALTgpmMGYIFWYIZTA2ZFAzTTFlSDFVMwVyQhmAwsYMAKDaBy0axX/iAAAAAElFTkSuQmCC ',
'data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%22100%22%20height%3D%22100%22%3E%3Crect%20fill%3D%22%2300B1FF%22%20width%3D%22100%22%20height%3D%22100%22%2F%3E%3C%2Fsvg%3E',
'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMDAiIGhlaWdodD0iMTAwIj48cmVjdCBmaWxsPSIjMDBCMUZGIiB3aWR0aD0iMTAwIiBoZWlnaHQ9IjEwMCIvPjwvc3ZnPg==',
' data:,Hello%2C%20World!',
' data:,Hello World!',
' data:text/plain;base64,SGVsbG8sIFdvcmxkIQ%3D%3D',
' data:text/html,%3Ch1%3EHello%2C%20World!%3C%2Fh1%3E',
'data:,A%20brief%20note',
'data:text/html;charset=US-ASCII,%3Ch1%3EHello!%3C%2Fh1%3E',
],
invalid: [
'dataxbase64',
'data:HelloWorld',
'data:,A%20brief%20invalid%20[note',
'file:text/plain;base64,SGVsbG8sIFdvcmxkIQ%3D%3D',
'data:text/html;charset=,%3Ch1%3EHello!%3C%2Fh1%3E',
'data:text/html;charset,%3Ch1%3EHello!%3C%2Fh1%3E', 'data:base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAABlBMVEUAAAD///+l2Z/dAAAAM0lEQVR4nGP4/5/h/1+G/58ZDrAz3D/McH8yw83NDDeNGe4Ug9C9zwz3gVLMDA/A6P9/AFGGFyjOXZtQAAAAAElFTkSuQmCC',
'',
'http://wikipedia.org',
'base64',
'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAABlBMVEUAAAD///+l2Z/dAAAAM0lEQVR4nGP4/5/h/1+G/58ZDrAz3D/McH8yw83NDDeNGe4Ug9C9zwz3gVLMDA/A6P9/AFGGFyjOXZtQAAAAAElFTkSuQmCC',
],
});
/* eslint-enable max-len */
});
it('should validate magnetURI', () => {
/* eslint-disable max-len */
test({
validator: 'isMagnetURI',
valid: [
'magnet:?xt=urn:btih:06E2A9683BF4DA92C73A661AC56F0ECC9C63C5B4&dn=helloword2000&tr=udp://helloworld:1337/announce',
'magnet:?xt=urn:btih:3E30322D5BFC7444B7B1D8DD42404B75D0531DFB&dn=world&tr=udp://world.com:1337',
'magnet:?xt=urn:btih:4ODKSDJBVMSDSNJVBCBFYFBKNRU875DW8D97DWC6&dn=helloworld&tr=udp://helloworld.com:1337',
'magnet:?xt=urn:btih:1GSHJVBDVDVJFYEHKFHEFIO8573898434JBFEGHD&dn=foo&tr=udp://foo.com:1337',
'magnet:?xt=urn:btih:MCJDCYUFHEUD6E2752T7UJNEKHSUGEJFGTFHVBJS&dn=bar&tr=udp://bar.com:1337',
'magnet:?xt=urn:btih:LAKDHWDHEBFRFVUFJENBYYTEUY837562JH2GEFYH&dn=foobar&tr=udp://foobar.com:1337',
'magnet:?xt=urn:btih:MKCJBHCBJDCU725TGEB3Y6RE8EJ2U267UNJFGUID&dn=test&tr=udp://test.com:1337',
'magnet:?xt=urn:btih:UHWY2892JNEJ2GTEYOMDNU67E8ICGICYE92JDUGH&dn=baz&tr=udp://baz.com:1337',
'magnet:?xt=urn:btih:HS263FG8U3GFIDHWD7829BYFCIXB78XIHG7CWCUG&dn=foz&tr=udp://foz.com:1337',
],
invalid: [
'',
':?xt=urn:btih:06E2A9683BF4DA92C73A661AC56F0ECC9C63C5B4&dn=helloword2000&tr=udp://helloworld:1337/announce',
'magnett:?xt=urn:btih:3E30322D5BFC7444B7B1D8DD42404B75D0531DFB&dn=world&tr=udp://world.com:1337',
'xt=urn:btih:4ODKSDJBVMSDSNJVBCBFYFBKNRU875DW8D97DWC6&dn=helloworld&tr=udp://helloworld.com:1337',
'magneta:?xt=urn:btih:1GSHJVBDVDVJFYEHKFHEFIO8573898434JBFEGHD&dn=foo&tr=udp://foo.com:1337',
'magnet:?xt=uarn:btih:MCJDCYUFHEUD6E2752T7UJNEKHSUGEJFGTFHVBJS&dn=bar&tr=udp://bar.com:1337',
'magnet:?xt=urn:btihz&dn=foobar&tr=udp://foobar.com:1337',
'magnet:?xat=urn:btih:MKCJBHCBJDCU725TGEB3Y6RE8EJ2U267UNJFGUID&dn=test&tr=udp://test.com:1337',
'magnet::?xt=urn:btih:UHWY2892JNEJ2GTEYOMDNU67E8ICGICYE92JDUGH&dn=baz&tr=udp://baz.com:1337',
'magnet:?xt:btih:HS263FG8U3GFIDHWD7829BYFCIXB78XIHG7CWCUG&dn=foz&tr=udp://foz.com:1337',
],
});
/* eslint-enable max-len */
});
it('should validate LatLong', () => {
test({
validator: 'isLatLong',
valid: [
'(-17.738223, 85.605469)',
'(-12.3456789, +12.3456789)',
'(-60.978437, -0.175781)',
'(77.719772, -37.529297)',
'(7.264394, 165.058594)',
'0.955766, -19.863281',
'(31.269161,164.355469)',
'+12.3456789, -12.3456789',
'-15.379543, -137.285156',
'(11.770570, -162.949219)',
'-55.034319, 113.027344',
'58.025555, 36.738281',
'55.720923,-28.652344',
'-90.00000,-180.00000',
'(-71, -146)',
'(-71.616864, -146.616864)',
'-0.55, +0.22',
'90, 180',
'+90, -180',
'-90,+180',
'90,180',
'0, 0',
],
invalid: [
'(020.000000, 010.000000000)',
'89.9999999989, 360.0000000',
'90.1000000, 180.000000',
'+90.000000, -180.00001',
'090.0000, 0180.0000',
'126, -158',
'(-126.400010, -158.400010)',
'-95, -96',
'-95.738043, -96.738043',
'137, -148',
'(-137.5942, -148.5942)',
'(-120, -203)',
'(-119, -196)',
'+119.821728, -196.821728',
'(-110, -223)',
'-110.369532, 223.369532',
'(-120.969949, +203.969949)',
'-116, -126',
'-116.894222, -126.894222',
'-112, -160',
'-112.96381, -160.96381',
'-90., -180.',
'+90.1, -180.1',
'(-17.738223, 85.605469',
'0.955766, -19.863281)',
'+,-',
'(,)',
',',
' ',
],
});
});
it('should validate postal code', () => {
const fixtures = [
{
locale: 'AU',
valid: [
'4000',
'2620',
'3000',
'2017',
'0800',
],
},
{
locale: 'CA',
valid: [
'L4T 0A5',
'G1A-0A2',
'A1A 1A1',
'X0A-0H0',
'V5K 0A1',
],
},
{
locale: 'JP',
valid: [
'135-0000',
'874-8577',
'669-1161',
'470-0156',
'672-8031',
],
},
{
locale: 'GR',
valid: [
'022 93',
'29934',
'90293',
'299 42',
'94944',
],
},
{
locale: 'GB',
valid: [
'TW8 9GS',
'BS98 1TL',
'DE99 3GG',
'DE55 4SW',
'DH98 1BT',
'DH99 1NS',
'GIR0aa',
'SA99',
'W1N 4DJ',
'AA9A 9AA',
'AA99 9AA',
'BS98 1TL',
'DE993GG',
],
},
{
locale: 'FR',
valid: [
'75008',
'44 522',
'98025',
'38 499',
'39940',
],
},
{
locale: 'ID',
valid: [
'10210',
'40181',
'55161',
'60233',
],
},
{
locale: 'IE',
valid: [
'A65 TF12',
'A6W U9U9',
],
invalid: [
'123',
'75690HG',
'AW5 TF12',
'AW5 TF12',
'756 90HG',
'A65T F12',
],
},
{
locale: 'IN',
valid: [
'364240',
'360005',
],
invalid: [
'123',
'012345',
'011111',
'101123',
'291123',
'351123',
'541123',
'551123',
'651123',
'661123',
'861123',
'871123',
'881123',
'891123',
],
},
{
locale: 'BG',
valid: [
'1000',
],
},
{
locale: 'CZ',
valid: [
'20134',
'392 90',
'39919',
'938 29',
'39949',
],
},
{
locale: 'NL',
valid: [
'1012 SZ',
'3432FE',
'1118 BH',
'3950IO',
'3997 GH',
],
},
{
locale: 'PL',
valid: [
'47-260',
'12-930',
'78-399',
'39-490',
'38-483',
],
},
{
locale: 'TW',
valid: [
'360',
'90312',
'399',
'935',
'38842',
],
},
{
locale: 'LI',
valid: [
'9485',
'9497',
'9491',
'9489',
'9496',
],
},
{
locale: 'PT',
valid: [
'4829-489',
'0294-348',
'8156-392',
],
},
{
locale: 'SE',
valid: [
'12994',
'284 39',
'39556',
'489 39',
'499 49',
],
},
{
locale: 'AD',
valid: [
'AD100',
'AD200',
'AD300',
'AD400',
'AD500',
'AD600',
'AD700',
],
},
{
locale: 'UA',
valid: [
'65000',
'65080',
'01000',
],
},
{
locale: 'BR',
valid: [
'39100-000',
'22040-020',
'39400-152',
],
invalid: [
'79800A12',
'13165-00',
'38175-abc',
'81470-2763',
'78908',
'13010|111',
],
},
{
locale: 'NZ',
valid: [
'7843',
'3581',
'0449',
'0984',
'4144',
],
},
{
locale: 'MT',
valid: [
'VLT2345',
'VLT 2345',
'ATD1234',
'MSK8723',
],
},
{
locale: 'PR',
valid: [
'00979',
'00631',
'00786',
'00987',
],
},
];
let allValid = [];
// Test fixtures
fixtures.forEach((fixture) => {
if (fixture.valid) allValid = allValid.concat(fixture.valid);
test({
validator: 'isPostalCode',
valid: fixture.valid,
invalid: fixture.invalid,
args: [fixture.locale],
});
});
// Test generics
test({
validator: 'isPostalCode',
valid: [
...allValid,
'1234',
'6900',
'1292',
'9400',
'27616',
'90210',
'10001',
'21201',
'33142',
'060623',
'123456',
'293940',
'002920',
],
invalid: [
'asdf',
'1',
'ASDFGJKLmZXJtZtesting123',
'Vml2YW11cyBmZXJtZtesting123',
'48380480343',
'29923-329393-2324',
'4294924224',
'13',
],
args: ['any'],
});
});
it('should error on invalid locale', () => {
test({
validator: 'isPostalCode',
args: ['is-NOT'],
error: [
'293940',
'1234',
],
});
});
it('should validate MIME types', () => {
test({
validator: 'isMimeType',
valid: [
'application/json',
'application/xhtml+xml',
'audio/mp4',
'image/bmp',
'font/woff2',
'message/http',
'model/vnd.gtw',
'multipart/form-data',
'multipart/form-data; boundary=something',
'multipart/form-data; charset=utf-8; boundary=something',
'multipart/form-data; boundary=something; charset=utf-8',
'multipart/form-data; boundary=something; charset="utf-8"',
'multipart/form-data; boundary="something"; charset=utf-8',
'multipart/form-data; boundary="something"; charset="utf-8"',
'text/css',
'text/plain; charset=utf8',
'Text/HTML;Charset="utf-8"',
'text/html;charset=UTF-8',
'Text/html;charset=UTF-8',
'text/html; charset=us-ascii',
'text/html; charset=us-ascii (Plain text)',
'text/html; charset="us-ascii"',
'video/mp4',
],
invalid: [
'',
' ',
'/',
'f/b',
'application',
'application\\json',
'application/json/text',
'application/json; charset=utf-8',
'audio/mp4; charset=utf-8',
'image/bmp; charset=utf-8',
'font/woff2; charset=utf-8',
'message/http; charset=utf-8',
'model/vnd.gtw; charset=utf-8',
'video/mp4; charset=utf-8',
],
});
});
it('should validate slug', () => {
test({
validator: 'isSlug',
args: ['cs_67CZ'],
valid: ['cs-cz', 'cscz'],
invalid: [
'not-----------slug',
'@#_$@',
'-not-slug',
'not-slug-',
'_not-slug',
'not-slug_',
],
});
});
});
|
// Require the Express Module
var express = require('express');
// Create an Express App
var app = express();
// Require body-parser (to receive post data from clients)
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/ArrakisSandworms');
mongoose.Promise = global.Promise;
var SandwormSchema = new mongoose.Schema({
name: {type: String},
region: {type: String},
age: {type: Number},
mass: {type: Number},
length: {type: Number},
created_on : {type: Date, default: Date.now },
},{timestamps: true });
mongoose.model('Sandworm', SandwormSchema);
var Sandworm = mongoose.model('Sandworm');
// Integrate body-parser with our App
app.use(bodyParser.urlencoded({ extended: true }));
// Require path
var path = require('path');
// Setting our Static Folder Directory
app.use(express.static(path.join(__dirname, './static')));
// Setting our Views Folder Directory
app.set('views', path.join(__dirname, './views'));
// Setting our View Engine set to EJS
app.set('view engine', 'ejs');
// Routes
// Root Request
app.get('/', function(req, res) {
Sandworm.find({}, function(err, sandworms) {
if(err){
res.render('error', {errors: err})
}
else{
res.render('index', { sandworms });
}
})
})
//Add Sandworm Info
app.get('/sandworms/new', function(req, res){
res.render('new');
})
//Get Sandworm ID
app.get('/sandworms/:id', function(req, res){
var worm_id = req.params.id;
Sandworm.findOne({_id: worm_id}, function(err, sandworm) {
if(err){
res.render('error', {errors: err})
}
else{
res.render('view',{ sandworm } );
}
})
})
//Process sandworm info
app.post('/sandworms', function(req, res) {
var sandworm = new Sandworm({
name: req.body.name,
region: req.body.region,
age: req.body.age,
mass: req.body.mass,
length: req.body.length,
});
sandworm.save(function(err){
if(err){
res.render('error', {errors: err})
}
else {
res.redirect('/');
}
})
})
//Edit sandworm info
app.get('/sandworms/edit/:id', function(req, res){
var worm_id = req.params.id;
Sandworm.findOne({_id: worm_id}, function(err, sandworm) {
if(err){
res.render('error', {errors: err})
}
else{
res.render('edit',{ sandworm } );
}
})
})
//Process sandworm edit
app.post('/sandworms/:id', function(req, res){
var worm_id = req.params.id;
Sandworm.findOne({_id: worm_id}, function(err, sandworm) {
if(err){
res.render('error', {errors: err})
}
else{
sandworm.name = req.body.name;
sandworm.region = req.body.region;
sandworm.age = req.body.age;
sandworm.mass = req.body.mass;
sandworm.length = req.body.length;
sandworm.save(function(err){
if(err){
res.render('error', {errors: err})
}
else {
res.redirect('/');
}
})
}
})
})
//Delete sandworm
app.post('/sandworms/destroy/:id', function(req, res){
var worm_id = req.params.id;
Sandworm.remove({_id: worm_id }, function(err){
res.redirect("/");
})
})
// Setting our Server to Listen on Port: 8000
app.listen(8000, function() {
console.log("listening on port 8000");
})
|
import React, { useEffect, useState } from "react"
//redux
import { connect } from "react-redux"
//axios
import { getRecipe } from "../actions"
import Recipe from './Recipe'
import '../App.scss'
//props = state from mapstatetoprops
//{getRecipe} is an action from redux (actions.js) for the reducer
const RecipeList = (props) => {
const [search, setSearch] = useState('')
const getRecipe = props.getRecipe
//console.log(props.recipes) // redux state
useEffect(() => {
//dispatch action from redux here
getRecipe()
}, []) //[getRecipe] return this after im done playing with edit
const handleChange = (e) => {
setSearch(e.target.value)
}
const filterSearch = () => {
return props.recipes.filter(recipe => {
// console.log(recipe)
if (recipe.title.toLowerCase().includes(search.toLowerCase())
||
recipe.category.toLowerCase().includes(search.toLowerCase())) {
return recipe
}
return null
})
}
return (
<>
{/* inserted map here that will also return the Recipe component */}
{/* adding search bar */}
<input
className='searchbar'
type="text"
placeholder="search recepies"
name="searchbar"
value={search}
onChange={handleChange}
/>
{filterSearch().map((recipe) => {
return <Recipe key={recipe.id} recipe={recipe} />
})}
{/* {props.recipes.map(item => {
return (
<div>
{item.title}
</div>
)
})} */}
</>
)
}
const mapStateToProps = state => {
return {
recipes: state.recipes,
error: state.error
}
}
export default connect(mapStateToProps, { getRecipe })(RecipeList)
|
var InputMnagement;
(function (InputMnagement) {
var GameButtonID;
(function (GameButtonID) {
GameButtonID[GameButtonID["start"] = 0] = "start";
GameButtonID[GameButtonID["up"] = 1] = "up";
GameButtonID[GameButtonID["right"] = 2] = "right";
GameButtonID[GameButtonID["down"] = 3] = "down";
GameButtonID[GameButtonID["left"] = 4] = "left";
GameButtonID[GameButtonID["attack"] = 5] = "attack";
GameButtonID[GameButtonID["shield"] = 6] = "shield";
GameButtonID[GameButtonID["maxID"] = 6] = "maxID";
})(GameButtonID || (GameButtonID = {}));
var GameAnalogStickID;
(function (GameAnalogStickID) {
GameAnalogStickID[GameAnalogStickID["move"] = 0] = "move";
GameAnalogStickID[GameAnalogStickID["direction"] = 1] = "direction";
GameAnalogStickID[GameAnalogStickID["accel"] = 2] = "accel";
GameAnalogStickID[GameAnalogStickID["maxID"] = 2] = "maxID";
})(GameAnalogStickID || (GameAnalogStickID = {}));
var GamePointerInputID;
(function (GamePointerInputID) {
GamePointerInputID[GamePointerInputID["target"] = 0] = "target";
GamePointerInputID[GamePointerInputID["maxID"] = 0] = "maxID";
})(GamePointerInputID || (GamePointerInputID = {}));
var SampleInputSet = (function () {
function SampleInputSet() {
}
return SampleInputSet;
}());
var Main = (function () {
function Main() {
this.logicalScreenWidth = 640.0;
this.logicalScreenHeight = 360.0;
this.display = null;
this.inputManager = new PTWTipsInput.InputManager();
this.mouse = new PTWTipsInput.MouseDevice();
this.keyboard = new PTWTipsInput.KeyboardDevice();
this.gamepad = new PTWTipsInput.GamepadDevice();
this.input = new SampleInputSet();
this.config = [
{
deviceName: 'keyboard',
mappings: [
[' ', 'start',],
['Enter', 'start'],
['ArrowUp', 'up'],
['ArrowRight', 'right'],
['ArrowDown', 'down'],
['ArrowLeft', 'left'],
['w', 'up'],
['d', 'right'],
['s', 'down'],
['a', 'left'],
['z', 'attack'],
['j', 'attack'],
['x', 'shield'],
['k', 'shield'],
]
},
{
deviceName: 'mouse',
mappings: [
['button1', 'attack'],
['button3', 'shield'],
['location', 'pointer'],
['wheel', 'analog3'],
]
},
{
deviceName: 'gamepad',
mappings: [
['crossButton1', 'up'],
['crossButton2', 'right'],
['crossButton3', 'down'],
['crossButton4', 'left'],
['button1', 'attack'],
['button2', 'shield'],
['button10', 'start'],
['stick1', 'analog1'],
['stick2', 'analog2'],
]
}
];
this.buttonLetter = ['|---', '-|--', '--|-', '---|'];
this.doublePressButtonLetter = ['-', '-', '*', '*'];
this.tempVec = [0.0, 0.0, 0.0];
this.isLoaded = false;
}
Main.prototype.initialize = function (canvas, display) {
canvas.width = this.logicalScreenWidth;
canvas.height = this.logicalScreenHeight;
this.display = display;
// Set up input devices and mappings
this.initializeInput(canvas);
};
Main.prototype.initializeInput = function (canvas) {
this.inputManager.addDevice('keyboard', this.keyboard);
this.inputManager.addDevice('mouse', this.mouse);
this.inputManager.addDevice('gamepad', this.gamepad);
this.input.up = this.inputManager.addButton('up');
this.input.right = this.inputManager.addButton('right');
this.input.down = this.inputManager.addButton('down');
this.input.left = this.inputManager.addButton('left');
this.input.attack = this.inputManager.addButton('attack');
this.input.shield = this.inputManager.addButton('shield');
this.input.start = this.inputManager.addButton('start');
this.input.analog1 = this.inputManager.addAxis('analog1');
this.input.analog2 = this.inputManager.addAxis('analog2');
this.input.analog3 = this.inputManager.addAxis('analog3');
this.input.pointer = this.inputManager.addPointingInput('pointer');
this.inputManager.setMappingFromConfig(this.config);
this.inputManager.setEvents(canvas);
};
Main.prototype.processLoading = function () {
// Loading finished
this.isLoaded = true;
};
Main.prototype.run = function () {
var time = DateGetTime();
this.inputManager.processPolling(time);
};
Main.prototype.draw = function () {
var texts = [];
var tab1 = ' ';
texts.push('[Integrated]');
texts.push('up' + this.getIntegratedButtonStateText(this.input.up)
+ ' right' + this.getIntegratedButtonStateText(this.input.right)
+ ' down' + this.getIntegratedButtonStateText(this.input.down)
+ ' left' + this.getIntegratedButtonStateText(this.input.left));
texts.push('attack' + this.getIntegratedButtonStateText(this.input.attack)
+ ' shield' + this.getIntegratedButtonStateText(this.input.shield)
+ ' start' + this.getIntegratedButtonStateText(this.input.start));
this.input.analog1.getAxis(this.tempVec);
texts.push('analog1' + '(' + this.tempVec[0].toFixed(2) + ',' + this.tempVec[1].toFixed(2) + ')');
this.input.analog2.getAxis(this.tempVec);
texts.push('analog2' + '(' + this.tempVec[0].toFixed(2) + ',' + this.tempVec[1].toFixed(2) + ')');
this.input.analog3.getAxis(this.tempVec);
texts.push('analog3' + '(' + this.tempVec[0].toFixed(2) + ',' + this.tempVec[1].toFixed(2) + ')');
texts.push('');
texts.push('[Keyboard]');
var buttonTexts = [];
for (var key in this.keyboard.buttons) {
var button = this.keyboard.buttons[key];
if (button == null) {
continue;
}
buttonTexts.push(button.name + this.getButtonStateText(button));
}
texts.push(buttonTexts.join(' '));
texts.push('');
texts.push('[Mouse]: ' + this.mouse.location.x.toFixed(2) + ', ' + this.mouse.location.y.toFixed(2)
+ ' Left' + this.getButtonStateText(this.mouse.buttons[0])
+ ' Middle' + this.getButtonStateText(this.mouse.buttons[1])
+ ' Right' + this.getButtonStateText(this.mouse.buttons[2])
+ ' Wheel' + this.mouse.wheel.y);
texts.push('');
texts.push('[Gamepad]');
var padButtonTexts = [];
for (var _i = 0, _a = this.gamepad.buttons; _i < _a.length; _i++) {
var button = _a[_i];
if (button == null) {
continue;
}
padButtonTexts.push(button.name + this.getButtonStateText(button));
}
texts.push(padButtonTexts.join(' '));
var padAxisTexts = [];
for (var _b = 0, _c = this.gamepad.sticks; _b < _c.length; _b++) {
var stickAxis = _c[_b];
if (stickAxis == null) {
continue;
}
padAxisTexts.push(stickAxis.name + '(' + stickAxis.x.toFixed(2) + ',' + stickAxis.y.toFixed(2) + ')');
}
texts.push(padAxisTexts.join(' '));
this.display.innerHTML = texts.join('<br />');
this.inputManager.updateStates();
};
Main.prototype.getIntegratedButtonStateText = function (button) {
return '(' + this.buttonLetter[button.getState()] + ' ' + this.doublePressButtonLetter[button.getDoublePressState()] + ')';
};
Main.prototype.getButtonStateText = function (button) {
return '(' + this.buttonLetter[button.singlePressState] + ' ' + this.doublePressButtonLetter[button.doublePressState] + ')';
};
return Main;
}());
var _Main;
window.onload = function () {
var canvas = document.getElementById('canvas');
var display = document.getElementById('display');
_Main = new Main();
_Main.initialize(canvas, display);
setTimeout(run, 1000 / 30);
};
function run() {
if (_Main.isLoaded) {
_Main.run();
_Main.draw();
}
else {
_Main.processLoading();
}
setTimeout(run, 1000 / 30);
}
})(InputMnagement || (InputMnagement = {}));
|
'use strict';
var fbSeating = new Firebase('https://hrr-kitchen.firebaseio.com/seating');
/* App Module */
var kitchenApp = angular.module('kitchenApp', [
'ui.bootstrap',
'ngRoute',
'appControllers'
],
function($interpolateProvider) {
$interpolateProvider.startSymbol('{%');
$interpolateProvider.endSymbol('%}');
}
);
kitchenApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/index', {
templateUrl: '/partials/kitchenView.html',
controller: 'kitchenCtrl'
}).
otherwise({
redirectTo: '/index'
});
}]);
|
const hexDump = require('hexy').hexy;
/**
* Prints an hexadecimal dump in console
*/
exports.hexDump = function (data) {
console.log(hexDump(data))
}
/**
* Get file extension
*
* @param {String} name Filename
* @returns {String} Extension (without the dot)
*/
exports.ext = function (name) {
if (!name) return ''
return name.substring(name.lastIndexOf('.') + 1, name.length).toLowerCase()
}
exports.hex = function (n, len) {
n = (n * 1).toString(16)
while (n.length < len) n = '0' + n
return n
}
exports.IPv4toInt32LE = function (IPv4) {
var ip = IPv4.split('.')
ip = (ip[0] * 1) + (ip[1] * 0x100) + (ip[2] * 0x10000) + (ip[3] * 0x1000000)
if (ip < 0) log.error(ip)
return ip
}
/**
* Get file type based on file extension. The file type can be one on these:
* 'video', 'audio', 'image', 'pro'.
*
* @param {String} name Filename
* @returns {String} File type
*/
exports.getFileType = function (name) {
var extensions = {
video:
'3gp,aaf,asf,avchd,avi,fla,flv,m1v,m2v,m4v,mp4,mpg,mpe,mpeg,mov,mkv,mp4,' +
'ogg,rm,svi'
.split(','),
audio:
'aiff,au,wav,flac,la,pac,m4a,ape,rka,shn,tta,wv,wma,brstm,amr,mp2,mp3,' +
'ogg,aac,m4a,mpc,ra,ots,vox,voc,mid,mod,s3m,xm,it,asf'
.split(','),
image:
'cr2,pdn,pgm,pict,bmp,png,dib,djvu,gif,psd,pdd,icns,ico,rle,tga,jpeg,' +
'jpg,tiff,tif,jp2,jps,mng,xbm,xcf,pcx'
.split(','),
pro:
'7z,ace,arc,arj,bzip2,cab,gzip,rar,tar,zip,iso,nrg,img,adf,dmg,cue,bin,' +
'cif,ccd,sub,raw'.split(','),
}
if (!typeof name == 'string') {
return ''
}
var ext = exports.ext(name)
if (extensions.video.indexOf(ext) >= 0) return 'Video'
if (extensions.audio.indexOf(ext) >= 0) return 'Audio'
if (extensions.image.indexOf(ext) >= 0) return 'Image'
if (extensions.pro.indexOf(ext) >= 0) return 'Pro'
return ''
}
/**
* Returns true if the given parameter is valid eD2K/eMule protocol number
*
* @param {Integer} protocol
* @returns {Boolean}
*/
exports.isProtocol = function (protocol) {
return
(protocol == PR_ED2K) ||
(protocol == PR_EMULE) ||
(protocol == PR_ZLIB)
}
exports.isFunction = function (something) {
return typeof (something) == 'function'
}
/**
* Draws an ASCII box around some text
*/
exports.box = function (text) {
var l = text.length + 2
var s = ''
while (l--) s += '-'
s = '+' + s + '+'
return s + '\n' + '| ' + text + ' |' + '\n' + s
}
/**
* Returns a UNIX timestamp
*/
exports.unixTimestamp = function () {
return Math.round((new Date()).getTime() / 1000)
}
|
import { Chin } from './Chin'
import { Full } from './Full'
import { FullMajestic } from './FullMajestic'
import { FullMedium } from './FullMedium'
import { Goatee } from './Goatee'
import { GoateeCircle } from './GoateeCircle'
import { MoustacheDali } from './MoustacheDali'
import { MoustacheHandlebar } from './MoustacheHandlebar'
import { MoustacheImperial } from './MoustacheImperial'
import { MoustachePainters } from './MoustachePainters'
import { MoustachePaintersFilled } from './MoustachePaintersFilled'
import { MoustacheSwashbuckler } from './MoustacheSwashbuckler'
import { MoustacheThin } from './MoustacheThin'
import { MoustacheYosemite } from './MoustacheYosemite'
export const FacialHair = {
Chin,
Full,
FullMajestic,
FullMedium,
Goatee,
GoateeCircle,
MoustacheDali,
MoustacheHandlebar,
MoustacheImperial,
MoustachePainters,
MoustachePaintersFilled,
MoustacheSwashbuckler,
MoustacheThin,
MoustacheYosemite
}
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var _superagent = _interopRequireDefault(require("superagent"));
var _querystring = _interopRequireDefault(require("querystring"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
/**
* @module ApiClient
* @version 1.2.7
*/
/**
* Manages low level client-server communications, parameter marshalling, etc. There should not be any need for an
* application to use this class directly - the *Api and model classes provide the public API for the service. The
* contents of this file should be regarded as internal but are documented for completeness.
* @alias module:ApiClient
* @class
*/
var ApiClient = /*#__PURE__*/function () {
function ApiClient() {
_classCallCheck(this, ApiClient);
/**
* The base URL against which to resolve every API call's (relative) path.
* @type {String}
* @default https://finnhub.io/api/v1
*/
this.basePath = 'https://finnhub.io/api/v1'.replace(/\/+$/, '');
/**
* The authentication methods to be included for all API calls.
* @type {Array.<String>}
*/
this.authentications = {
'api_key': {
type: 'apiKey',
'in': 'query',
name: 'token'
}
};
/**
* The default HTTP headers to be included for all API calls.
* @type {Array.<String>}
* @default {}
*/
this.defaultHeaders = {
'User-Agent': 'OpenAPI-Generator/1.2.7/Javascript'
};
/**
* The default HTTP timeout for all API calls.
* @type {Number}
* @default 60000
*/
this.timeout = 60000;
/**
* If set to false an additional timestamp parameter is added to all API GET calls to
* prevent browser caching
* @type {Boolean}
* @default true
*/
this.cache = true;
/**
* If set to true, the client will save the cookies from each server
* response, and return them in the next request.
* @default false
*/
this.enableCookies = false;
/*
* Used to save and return cookies in a node.js (non-browser) setting,
* if this.enableCookies is set to true.
*/
if (typeof window === 'undefined') {
this.agent = new _superagent["default"].agent();
}
/*
* Allow user to override superagent agent
*/
this.requestAgent = null;
/*
* Allow user to add superagent plugins
*/
this.plugins = null;
}
/**
* Returns a string representation for an actual parameter.
* @param param The actual parameter.
* @returns {String} The string representation of <code>param</code>.
*/
_createClass(ApiClient, [{
key: "paramToString",
value: function paramToString(param) {
if (param == undefined || param == null) {
return '';
}
if (param instanceof Date) {
return param.toJSON();
}
if (ApiClient.canBeJsonified(param)) {
return JSON.stringify(param);
}
return param.toString();
}
/**
* Returns a boolean indicating if the parameter could be JSON.stringified
* @param param The actual parameter
* @returns {Boolean} Flag indicating if <code>param</code> can be JSON.stringified
*/
}, {
key: "buildUrl",
/**
* Builds full URL by appending the given path to the base URL and replacing path parameter place-holders with parameter values.
* NOTE: query parameters are not handled here.
* @param {String} path The path to append to the base URL.
* @param {Object} pathParams The parameter values to append.
* @param {String} apiBasePath Base path defined in the path, operation level to override the default one
* @returns {String} The encoded path with parameter values substituted.
*/
value: function buildUrl(path, pathParams, apiBasePath) {
var _this = this;
if (!path.match(/^\//)) {
path = '/' + path;
}
var url = this.basePath + path; // use API (operation, path) base path if defined
if (apiBasePath !== null && apiBasePath !== undefined) {
url = apiBasePath + path;
}
url = url.replace(/\{([\w-\.]+)\}/g, function (fullMatch, key) {
var value;
if (pathParams.hasOwnProperty(key)) {
value = _this.paramToString(pathParams[key]);
} else {
value = fullMatch;
}
return encodeURIComponent(value);
});
return url;
}
/**
* Checks whether the given content type represents JSON.<br>
* JSON content type examples:<br>
* <ul>
* <li>application/json</li>
* <li>application/json; charset=UTF8</li>
* <li>APPLICATION/JSON</li>
* </ul>
* @param {String} contentType The MIME content type to check.
* @returns {Boolean} <code>true</code> if <code>contentType</code> represents JSON, otherwise <code>false</code>.
*/
}, {
key: "isJsonMime",
value: function isJsonMime(contentType) {
return Boolean(contentType != null && contentType.match(/^application\/json(;.*)?$/i));
}
/**
* Chooses a content type from the given array, with JSON preferred; i.e. return JSON if included, otherwise return the first.
* @param {Array.<String>} contentTypes
* @returns {String} The chosen content type, preferring JSON.
*/
}, {
key: "jsonPreferredMime",
value: function jsonPreferredMime(contentTypes) {
for (var i = 0; i < contentTypes.length; i++) {
if (this.isJsonMime(contentTypes[i])) {
return contentTypes[i];
}
}
return contentTypes[0];
}
/**
* Checks whether the given parameter value represents file-like content.
* @param param The parameter to check.
* @returns {Boolean} <code>true</code> if <code>param</code> represents a file.
*/
}, {
key: "isFileParam",
value: function isFileParam(param) {
// fs.ReadStream in Node.js and Electron (but not in runtime like browserify)
if (typeof require === 'function') {
var fs;
try {
fs = require('fs');
} catch (err) {}
if (fs && fs.ReadStream && param instanceof fs.ReadStream) {
return true;
}
} // Buffer in Node.js
if (typeof Buffer === 'function' && param instanceof Buffer) {
return true;
} // Blob in browser
if (typeof Blob === 'function' && param instanceof Blob) {
return true;
} // File in browser (it seems File object is also instance of Blob, but keep this for safe)
if (typeof File === 'function' && param instanceof File) {
return true;
}
return false;
}
/**
* Normalizes parameter values:
* <ul>
* <li>remove nils</li>
* <li>keep files and arrays</li>
* <li>format to string with `paramToString` for other cases</li>
* </ul>
* @param {Object.<String, Object>} params The parameters as object properties.
* @returns {Object.<String, Object>} normalized parameters.
*/
}, {
key: "normalizeParams",
value: function normalizeParams(params) {
var newParams = {};
for (var key in params) {
if (params.hasOwnProperty(key) && params[key] != undefined && params[key] != null) {
var value = params[key];
if (this.isFileParam(value) || Array.isArray(value)) {
newParams[key] = value;
} else {
newParams[key] = this.paramToString(value);
}
}
}
return newParams;
}
/**
* Builds a string representation of an array-type actual parameter, according to the given collection format.
* @param {Array} param An array parameter.
* @param {module:ApiClient.CollectionFormatEnum} collectionFormat The array element separator strategy.
* @returns {String|Array} A string representation of the supplied collection, using the specified delimiter. Returns
* <code>param</code> as is if <code>collectionFormat</code> is <code>multi</code>.
*/
}, {
key: "buildCollectionParam",
value: function buildCollectionParam(param, collectionFormat) {
if (param == null) {
return null;
}
switch (collectionFormat) {
case 'csv':
return param.map(this.paramToString, this).join(',');
case 'ssv':
return param.map(this.paramToString, this).join(' ');
case 'tsv':
return param.map(this.paramToString, this).join('\t');
case 'pipes':
return param.map(this.paramToString, this).join('|');
case 'multi':
//return the array directly as SuperAgent will handle it as expected
return param.map(this.paramToString, this);
case 'passthrough':
return param;
default:
throw new Error('Unknown collection format: ' + collectionFormat);
}
}
/**
* Applies authentication headers to the request.
* @param {Object} request The request object created by a <code>superagent()</code> call.
* @param {Array.<String>} authNames An array of authentication method names.
*/
}, {
key: "applyAuthToRequest",
value: function applyAuthToRequest(request, authNames) {
var _this2 = this;
authNames.forEach(function (authName) {
var auth = _this2.authentications[authName];
switch (auth.type) {
case 'basic':
if (auth.username || auth.password) {
request.auth(auth.username || '', auth.password || '');
}
break;
case 'bearer':
if (auth.accessToken) {
var localVarBearerToken = typeof auth.accessToken === 'function' ? auth.accessToken() : auth.accessToken;
request.set({
'Authorization': 'Bearer ' + localVarBearerToken
});
}
break;
case 'apiKey':
if (auth.apiKey) {
var data = {};
if (auth.apiKeyPrefix) {
data[auth.name] = auth.apiKeyPrefix + ' ' + auth.apiKey;
} else {
data[auth.name] = auth.apiKey;
}
if (auth['in'] === 'header') {
request.set(data);
} else {
request.query(data);
}
}
break;
case 'oauth2':
if (auth.accessToken) {
request.set({
'Authorization': 'Bearer ' + auth.accessToken
});
}
break;
default:
throw new Error('Unknown authentication type: ' + auth.type);
}
});
}
/**
* Deserializes an HTTP response body into a value of the specified type.
* @param {Object} response A SuperAgent response object.
* @param {(String|Array.<String>|Object.<String, Object>|Function)} returnType The type to return. Pass a string for simple types
* or the constructor function for a complex type. Pass an array containing the type name to return an array of that type. To
* return an object, pass an object with one property whose name is the key type and whose value is the corresponding value type:
* all properties on <code>data<code> will be converted to this type.
* @returns A value of the specified type.
*/
}, {
key: "deserialize",
value: function deserialize(response, returnType) {
if (response == null || returnType == null || response.status == 204) {
return null;
} // Rely on SuperAgent for parsing response body.
// See http://visionmedia.github.io/superagent/#parsing-response-bodies
var data = response.body;
if (data == null || _typeof(data) === 'object' && typeof data.length === 'undefined' && !Object.keys(data).length) {
// SuperAgent does not always produce a body; use the unparsed response as a fallback
data = response.text;
}
return ApiClient.convertToType(data, returnType);
}
/**
* Callback function to receive the result of the operation.
* @callback module:ApiClient~callApiCallback
* @param {String} error Error message, if any.
* @param data The data returned by the service call.
* @param {String} response The complete HTTP response.
*/
/**
* Invokes the REST service using the supplied settings and parameters.
* @param {String} path The base URL to invoke.
* @param {String} httpMethod The HTTP method to use.
* @param {Object.<String, String>} pathParams A map of path parameters and their values.
* @param {Object.<String, Object>} queryParams A map of query parameters and their values.
* @param {Object.<String, Object>} headerParams A map of header parameters and their values.
* @param {Object.<String, Object>} formParams A map of form parameters and their values.
* @param {Object} bodyParam The value to pass as the request body.
* @param {Array.<String>} authNames An array of authentication type names.
* @param {Array.<String>} contentTypes An array of request MIME types.
* @param {Array.<String>} accepts An array of acceptable response MIME types.
* @param {(String|Array|ObjectFunction)} returnType The required type to return; can be a string for simple types or the
* constructor for a complex type.
* @param {String} apiBasePath base path defined in the operation/path level to override the default one
* @param {module:ApiClient~callApiCallback} callback The callback function.
* @returns {Object} The SuperAgent request object.
*/
}, {
key: "callApi",
value: function callApi(path, httpMethod, pathParams, queryParams, headerParams, formParams, bodyParam, authNames, contentTypes, accepts, returnType, apiBasePath, callback) {
var _this3 = this;
var url = this.buildUrl(path, pathParams, apiBasePath);
var request = (0, _superagent["default"])(httpMethod, url);
if (this.plugins !== null) {
for (var index in this.plugins) {
if (this.plugins.hasOwnProperty(index)) {
request.use(this.plugins[index]);
}
}
} // apply authentications
this.applyAuthToRequest(request, authNames); // set query parameters
if (httpMethod.toUpperCase() === 'GET' && this.cache === false) {
queryParams['_'] = new Date().getTime();
}
request.query(this.normalizeParams(queryParams)); // set header parameters
request.set(this.defaultHeaders).set(this.normalizeParams(headerParams)); // set requestAgent if it is set by user
if (this.requestAgent) {
request.agent(this.requestAgent);
} // set request timeout
request.timeout(this.timeout);
var contentType = this.jsonPreferredMime(contentTypes);
if (contentType) {
// Issue with superagent and multipart/form-data (https://github.com/visionmedia/superagent/issues/746)
if (contentType != 'multipart/form-data') {
request.type(contentType);
}
}
if (contentType === 'application/x-www-form-urlencoded') {
request.send(_querystring["default"].stringify(this.normalizeParams(formParams)));
} else if (contentType == 'multipart/form-data') {
var _formParams = this.normalizeParams(formParams);
for (var key in _formParams) {
if (_formParams.hasOwnProperty(key)) {
var _formParamsValue = _formParams[key];
if (this.isFileParam(_formParamsValue)) {
// file field
request.attach(key, _formParamsValue);
} else if (Array.isArray(_formParamsValue) && _formParamsValue.length && this.isFileParam(_formParamsValue[0])) {
// multiple files
_formParamsValue.forEach(function (file) {
return request.attach(key, file);
});
} else {
request.field(key, _formParamsValue);
}
}
}
} else if (bodyParam !== null && bodyParam !== undefined) {
if (!request.header['Content-Type']) {
request.type('application/json');
}
request.send(bodyParam);
}
var accept = this.jsonPreferredMime(accepts);
if (accept) {
request.accept(accept);
}
if (returnType === 'Blob') {
request.responseType('blob');
} else if (returnType === 'String') {
request.responseType('string');
} // Attach previously saved cookies, if enabled
if (this.enableCookies) {
if (typeof window === 'undefined') {
this.agent._attachCookies(request);
} else {
request.withCredentials();
}
}
request.end(function (error, response) {
if (callback) {
var data = null;
if (!error) {
try {
data = _this3.deserialize(response, returnType);
if (_this3.enableCookies && typeof window === 'undefined') {
_this3.agent._saveCookies(response);
}
} catch (err) {
error = err;
}
}
callback(error, data, response);
}
});
return request;
}
/**
* Parses an ISO-8601 string representation or epoch representation of a date value.
* @param {String} str The date value as a string.
* @returns {Date} The parsed date object.
*/
}, {
key: "hostSettings",
/**
* Gets an array of host settings
* @returns An array of host settings
*/
value: function hostSettings() {
return [{
'url': "https://finnhub.io/api/v1",
'description': "No description provided"
}];
}
}, {
key: "getBasePathFromSettings",
value: function getBasePathFromSettings(index) {
var variables = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var servers = this.hostSettings(); // check array index out of bound
if (index < 0 || index >= servers.length) {
throw new Error("Invalid index " + index + " when selecting the host settings. Must be less than " + servers.length);
}
var server = servers[index];
var url = server['url']; // go through variable and assign a value
for (var variable_name in server['variables']) {
if (variable_name in variables) {
var variable = server['variables'][variable_name];
if (!('enum_values' in variable) || variable['enum_values'].includes(variables[variable_name])) {
url = url.replace("{" + variable_name + "}", variables[variable_name]);
} else {
throw new Error("The variable `" + variable_name + "` in the host URL has invalid value " + variables[variable_name] + ". Must be " + server['variables'][variable_name]['enum_values'] + ".");
}
} else {
// use default value
url = url.replace("{" + variable_name + "}", server['variables'][variable_name]['default_value']);
}
}
return url;
}
/**
* Constructs a new map or array model from REST data.
* @param data {Object|Array} The REST data.
* @param obj {Object|Array} The target object or array.
*/
}], [{
key: "canBeJsonified",
value: function canBeJsonified(str) {
if (typeof str !== 'string' && _typeof(str) !== 'object') return false;
try {
var type = str.toString();
return type === '[object Object]' || type === '[object Array]';
} catch (err) {
return false;
}
}
}, {
key: "parseDate",
value: function parseDate(str) {
if (isNaN(str)) {
return new Date(str.replace(/(\d)(T)(\d)/i, '$1 $3'));
}
return new Date(+str);
}
/**
* Converts a value to the specified type.
* @param {(String|Object)} data The data to convert, as a string or object.
* @param {(String|Array.<String>|Object.<String, Object>|Function)} type The type to return. Pass a string for simple types
* or the constructor function for a complex type. Pass an array containing the type name to return an array of that type. To
* return an object, pass an object with one property whose name is the key type and whose value is the corresponding value type:
* all properties on <code>data<code> will be converted to this type.
* @returns An instance of the specified type or null or undefined if data is null or undefined.
*/
}, {
key: "convertToType",
value: function convertToType(data, type) {
if (data === null || data === undefined) return data;
switch (type) {
case 'Boolean':
return Boolean(data);
case 'Integer':
return parseInt(data, 10);
case 'Number':
return parseFloat(data);
case 'String':
return String(data);
case 'Date':
return ApiClient.parseDate(String(data));
case 'Blob':
return data;
default:
if (type === Object) {
// generic object, return directly
return data;
} else if (typeof type.constructFromObject === 'function') {
// for model type like User and enum class
return type.constructFromObject(data);
} else if (Array.isArray(type)) {
// for array type like: ['String']
var itemType = type[0];
return data.map(function (item) {
return ApiClient.convertToType(item, itemType);
});
} else if (_typeof(type) === 'object') {
// for plain object type like: {'String': 'Integer'}
var keyType, valueType;
for (var k in type) {
if (type.hasOwnProperty(k)) {
keyType = k;
valueType = type[k];
break;
}
}
var result = {};
for (var k in data) {
if (data.hasOwnProperty(k)) {
var key = ApiClient.convertToType(k, keyType);
var value = ApiClient.convertToType(data[k], valueType);
result[key] = value;
}
}
return result;
} else {
// for unknown type, return the data directly
return data;
}
}
}
}, {
key: "constructFromObject",
value: function constructFromObject(data, obj, itemType) {
if (Array.isArray(data)) {
for (var i = 0; i < data.length; i++) {
if (data.hasOwnProperty(i)) obj[i] = ApiClient.convertToType(data[i], itemType);
}
} else {
for (var k in data) {
if (data.hasOwnProperty(k)) obj[k] = ApiClient.convertToType(data[k], itemType);
}
}
}
}]);
return ApiClient;
}();
/**
* Enumeration of collection format separator strategies.
* @enum {String}
* @readonly
*/
ApiClient.CollectionFormatEnum = {
/**
* Comma-separated values. Value: <code>csv</code>
* @const
*/
CSV: ',',
/**
* Space-separated values. Value: <code>ssv</code>
* @const
*/
SSV: ' ',
/**
* Tab-separated values. Value: <code>tsv</code>
* @const
*/
TSV: '\t',
/**
* Pipe(|)-separated values. Value: <code>pipes</code>
* @const
*/
PIPES: '|',
/**
* Native array. Value: <code>multi</code>
* @const
*/
MULTI: 'multi'
};
/**
* The default API client implementation.
* @type {module:ApiClient}
*/
ApiClient.instance = new ApiClient();
var _default = ApiClient;
exports["default"] = _default;
|
import m from 'mithril'
import { Sprite } from 'Components/Sprite'
import { hooks } from './hooks'
import style from './enemies.scss'
export function Enemies() {
const state = {
options: {},
sprites: [],
}
return {
...hooks,
...state,
view() {
return (
<div class={ style.body }>
<Sprite name="enemy.saucer"/>
</div>
)
}
}
}
|
define(['pubsub',
'site/pubSubTable',
'rcap/js/ui/controls/gridControl',
'rcap/js/ui/properties/textProperty',
'rcap/js/ui/properties/stringValueProperty',
'utils/variableHandler',
'text!controlTemplates/dataUpload.tpl'
], function (PubSub, pubSubTable, GridControl, TextProperty, StringValueProperty, variableHandler, tpl) {
'use strict';
var DataUploadControl = GridControl.extend({
init: function () {
this._super({
type: 'dataupload',
controlCategory: 'Dynamic',
label: 'Data Upload',
icon: 'cloud-upload',
initialSize: [2, 2],
controlProperties: [
new TextProperty({
uid: 'variablename',
label: 'Variable',
helpText: 'The variable associated with this data upload',
isRequired: true
}),
new TextProperty({
uid: 'allowedtypes',
label: 'Allowed types',
helpText: 'List of allowed file types, comma-separated, e.g. csv,tsv. Leave blank for "all"',
isRequired: false
}),
new TextProperty({
uid: 'buttontext',
label: 'Button Text',
defaultValue: '',
helpText: 'The text that appears on the button',
isRequired: true
}),
new StringValueProperty({
uid: 'path',
label: 'Save path',
defaultValue: '',
helpText: 'The file path under which uploaded files will be saved',
codeHelpText: 'The R function that returns the path under which uploaded files will be saved',
isRequired: true
})
]
});
},
getVariableData: function () {
},
render: function () {
var template = _.template(tpl);
return template({
control: this
});
},
initialiseViewerItems: function () {
$('[data-controltype="dataupload"]').click(function () {
var params = $(this).data();
params.controlId = this.id;
PubSub.publish(pubSubTable.showDataUploadDialog, params);
});
}
});
return DataUploadControl;
});
|
var i, j;
for (i = 2; i < 100; i++) {
for (j = 2; j <= i; j++)
if (!(i % j)) {
//if dividable by any integer
break;
}
if (j > i / j) {
console.log(i, "is prime");
}
}
|
export { css } from './css'
export { cx } from './cx'
export { jsx } from './jsx'
export { createGlobalStyle } from './createGlobalStyle'
export { styled as default } from './styled'
export * from './Box'
export * from './colorModes'
export {
withEmotionCache,
CacheProvider,
ThemeContext,
Global,
ClassNames,
} from '@emotion/core'
export { ThemeProvider, withTheme, useTheme } from 'emotion-theming'
export * from './breakpoints'
export * from '@xstyled/system'
|
'use strict';
// +----------------------------------------------------------------------
// | 项目:InsunAPIServer
// | 版权:Copyright (c) 1974~2019 http://insunsoft.com All rights reserved.
// | 授权:Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// | 作者: insunsoft-濮堂.陈剑 <951241056@QQ.com>
// | 用途: token权限认证中间件
// | 路径: \server\middleware\authHeard.js
// | 使用:
// | 备注:已完成 100% 但可以随时增添参数以及赋值
// +----------------------------------------------------------------------
const jwt = require('jsonwebtoken')
const config = require('../config')
const Insun = require('../units');
module.exports = async (ctx, next) => {
// 从 Request Headers 的 Authorization 字段中获取 token
const authorization = ctx.get('Authorization')
const token = authorization.split(' ')[1]
// 如果获取不到 token,则抛出错误
if (!token) {
ctx.status = 401
ctx.body = await Insun.ReturnUnit.returnErrorJson(401, 'No token detected in HTTP header [Authorization]!', {})
return
}
// 如果获取到了 token,则对 token 进行校验
try {
jwt.verify(token, config.SecurityInfo.secret)
await next()
} catch (err) {
console.log(err)
ctx.status = 401
ctx.body = await Insun.ReturnUnit.returnErrorJson(401, 'Token is expired!', {})
}
}
|
// build time:Thu Nov 29 2018 18:19:15 GMT+0800 (GMT+08:00)
(function(i,t,n,s){var e=function(s,e){this.elem=s;this.$elem=i(s);this.options=e;this.metadata=this.$elem.data("plugin-options");this.$win=i(t);this.sections={};this.didScroll=false;this.$doc=i(n);this.docHeight=this.$doc.height()};e.prototype={defaults:{navItems:"a",currentClass:"current",changeHash:false,easing:"swing",filter:"",scrollSpeed:750,scrollThreshold:.5,begin:false,end:false,scrollChange:false,padding:0},init:function(){this.config=i.extend({},this.defaults,this.options,this.metadata);this.$nav=this.$elem.find(this.config.navItems);if(this.config.filter!==""){this.$nav=this.$nav.filter(this.config.filter)}this.$nav.on("click.onePageNav",i.proxy(this.handleClick,this));this.getPositions();this.bindInterval();this.$win.on("resize.onePageNav",i.proxy(this.getPositions,this));return this},adjustNav:function(i,t){i.$elem.find("."+i.config.currentClass).removeClass(i.config.currentClass);t.addClass(i.config.currentClass)},bindInterval:function(){var i=this;var t;i.$win.on("scroll.onePageNav",function(){i.didScroll=true});i.t=setInterval(function(){t=i.$doc.height();if(i.didScroll){i.didScroll=false;i.scrollChange()}if(t!==i.docHeight){i.docHeight=t;i.getPositions()}},250)},getHash:function(i){return i.attr("href").split("#")[1]},getPositions:function(){var t=this;var n;var s;var e;t.$nav.each(function(){n=t.getHash(i(this));e=i("#"+n);if(e.length){s=e.offset().top;t.sections[n]=Math.round(s)}})},getSection:function(i){var t=null;var n=Math.round(this.$win.height()*this.config.scrollThreshold);for(var s in this.sections){if(this.sections[s]-n<i){t=s}}return t},handleClick:function(n){var s=this;var e=i(n.currentTarget);var o=e.parent();var a="#"+s.getHash(e);if(!o.hasClass(s.config.currentClass)){if(s.config.begin){s.config.begin()}s.adjustNav(s,o);s.unbindInterval();s.scrollTo(a,function(){if(s.config.changeHash){t.location.hash=a}s.bindInterval();if(s.config.end){s.config.end()}})}n.preventDefault()},scrollChange:function(){var i=this.$win.scrollTop();var t=this.getSection(i);var n;if(t!==null){n=this.$elem.find('a[href$="#'+t+'"]').parent();if(!n.hasClass(this.config.currentClass)){this.adjustNav(this,n);if(this.config.scrollChange){this.config.scrollChange(n)}}}},scrollTo:function(t,n){var s=i(t).offset().top-this.config.padding;i("html, body").animate({scrollTop:s},this.config.scrollSpeed,this.config.easing,n)},unbindInterval:function(){clearInterval(this.t);this.$win.unbind("scroll.onePageNav")}};e.defaults=e.prototype.defaults;i.fn.onePageNav=function(i){return this.each(function(){new e(this,i).init()})}})(jQuery,window,document);
//rebuild by neat
|
module.exports = api => ({
presets: [
[
'babel-preset-jason/esm',
{
modules: api.env() !== 'esm',
useBuiltIns: 'usage',
},
],
'@babel/typescript',
],
});
|
//crear objeto XMLHttpRequest
function creaObjetoAjax () {
var obj; //variable que recogerá el objeto
if (window.XMLHttpRequest) { //código para mayoría de navegadores
obj=new XMLHttpRequest();
}
else { //para IE 5 y IE 6
obj=new ActiveXObject(Microsoft.XMLHTTP);
}
return obj; //devolvemos objeto
}
//función constructora del objeto:
function ObjetoAjax () {
var nuevoajax=creaObjetoAjax()
this.objeto=nuevoajax;
this.pedirTexto=pedirTextoAjax;
this.cargaXML=cargarXML
}
//función para el método objeto.pedirTexto(url,id)
function pedirTextoAjax(url,id) {
var nuevoajax=this.objeto;
var idajax=id;
nuevoajax.open("GET",url,true);
nuevoajax.onreadystatechange=function () {
if (nuevoajax.readyState==4 && nuevoajax.status==200) {
var textoAjax=nuevoajax.responseText;
document.getElementById(idajax).innerHTML=textoAjax;
}
}
nuevoajax.send();
}
/*función del método cargaXML: devuelve el DOM del XML
como parámetro de la función que le pasamos*/
function cargarXML(url,funcion) {
var nuevoajax=this.objeto; //crear objeto XMLHttpRequest
var funcionXML=funcion //recoger función
nuevoajax.open("GET",url,true); //preparar el envio
nuevoajax.onreadystatechange=function() { //al cargarse el archivo...
if (nuevoajax.readyState==4) {
/* propiedad=nuevoajax.responseXML; //recoger el DOM */
var jsonarray = JSON.parse(nuevoajax.responseText);
funcionXML(jsonarray); //devolverlo como parámetro.
}
}
nuevoajax.send();
}
|
/*!
* jQuery JavaScript Library v1.12.4
* http://jquery.com/
*
* Includes Sizzle.js
* http://sizzlejs.com/
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2016-05-20T17:17Z
*/
(function( global, factory ) {
if ( typeof module === "object" && typeof module.exports === "object" ) {
// For CommonJS and CommonJS-like environments where a proper `window`
// is present, execute the factory and get jQuery.
// For environments that do not have a `window` with a `document`
// (such as Node.js), expose a factory as module.exports.
// This accentuates the need for the creation of a real `window`.
// e.g. var jQuery = require("jquery")(window);
// See ticket #14549 for more info.
module.exports = global.document ?
factory( global, true ) :
function( w ) {
if ( !w.document ) {
throw new Error( "jQuery requires a window with a document" );
}
return factory( w );
};
} else {
factory( global );
}
// Pass this if window is not defined yet
}(typeof window !== "undefined" ? window : this, function( window, noGlobal ) {
// Support: Firefox 18+
// Can't be in strict mode, several libs including ASP.NET trace
// the stack via arguments.caller.callee and Firefox dies if
// you try to trace through "use strict" call chains. (#13335)
//"use strict";
var deletedIds = [];
var document = window.document;
var slice = deletedIds.slice;
var concat = deletedIds.concat;
var push = deletedIds.push;
var indexOf = deletedIds.indexOf;
var class2type = {};
var toString = class2type.toString;
var hasOwn = class2type.hasOwnProperty;
var support = {};
var
version = "1.12.4",
// Define a local copy of jQuery
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
// Need init if jQuery is called (just allow error to be thrown if not included)
return new jQuery.fn.init( selector, context );
},
// Support: Android<4.1, IE<9
// Make sure we trim BOM and NBSP
rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
// Matches dashed string for camelizing
rmsPrefix = /^-ms-/,
rdashAlpha = /-([\da-z])/gi,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return letter.toUpperCase();
};
jQuery.fn = jQuery.prototype = {
// The current version of jQuery being used
jquery: version,
constructor: jQuery,
// Start with an empty selector
selector: "",
// The default length of a jQuery object is 0
length: 0,
toArray: function() {
return slice.call( this );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num != null ?
// Return just the one element from the set
( num < 0 ? this[ num + this.length ] : this[ num ] ) :
// Return all the elements in a clean array
slice.call( this );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems ) {
// Build a new jQuery matched element set
var ret = jQuery.merge( this.constructor(), elems );
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
each: function( callback ) {
return jQuery.each( this, callback );
},
map: function( callback ) {
return this.pushStack( jQuery.map( this, function( elem, i ) {
return callback.call( elem, i, elem );
} ) );
},
slice: function() {
return this.pushStack( slice.apply( this, arguments ) );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
eq: function( i ) {
var len = this.length,
j = +i + ( i < 0 ? len : 0 );
return this.pushStack( j >= 0 && j < len ? [ this[ j ] ] : [] );
},
end: function() {
return this.prevObject || this.constructor();
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: push,
sort: deletedIds.sort,
splice: deletedIds.splice
};
jQuery.extend = jQuery.fn.extend = function() {
var src, copyIsArray, copy, name, options, clone,
target = arguments[ 0 ] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
// skip the boolean and the target
target = arguments[ i ] || {};
i++;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction( target ) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( i === length ) {
target = this;
i--;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( ( options = arguments[ i ] ) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject( copy ) ||
( copyIsArray = jQuery.isArray( copy ) ) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray( src ) ? src : [];
} else {
clone = src && jQuery.isPlainObject( src ) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend( {
// Unique for each copy of jQuery on the page
expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ),
// Assume jQuery is ready without the ready module
isReady: true,
error: function( msg ) {
throw new Error( msg );
},
noop: function() {},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
return jQuery.type( obj ) === "function";
},
isArray: Array.isArray || function( obj ) {
return jQuery.type( obj ) === "array";
},
isWindow: function( obj ) {
/* jshint eqeqeq: false */
return obj != null && obj == obj.window;
},
isNumeric: function( obj ) {
// parseFloat NaNs numeric-cast false positives (null|true|false|"")
// ...but misinterprets leading-number strings, particularly hex literals ("0x...")
// subtraction forces infinities to NaN
// adding 1 corrects loss of precision from parseFloat (#15100)
var realStringObj = obj && obj.toString();
return !jQuery.isArray( obj ) && ( realStringObj - parseFloat( realStringObj ) + 1 ) >= 0;
},
isEmptyObject: function( obj ) {
var name;
for ( name in obj ) {
return false;
}
return true;
},
isPlainObject: function( obj ) {
var key;
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don't pass through, as well
if ( !obj || jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
try {
// Not own constructor property must be Object
if ( obj.constructor &&
!hasOwn.call( obj, "constructor" ) &&
!hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) {
return false;
}
} catch ( e ) {
// IE8,9 Will throw exceptions on certain host objects #9897
return false;
}
// Support: IE<9
// Handle iteration over inherited properties before own properties.
if ( !support.ownFirst ) {
for ( key in obj ) {
return hasOwn.call( obj, key );
}
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
for ( key in obj ) {}
return key === undefined || hasOwn.call( obj, key );
},
type: function( obj ) {
if ( obj == null ) {
return obj + "";
}
return typeof obj === "object" || typeof obj === "function" ?
class2type[ toString.call( obj ) ] || "object" :
typeof obj;
},
// Workarounds based on findings by Jim Driscoll
// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
globalEval: function( data ) {
if ( data && jQuery.trim( data ) ) {
// We use execScript on Internet Explorer
// We use an anonymous function so that context is window
// rather than jQuery in Firefox
( window.execScript || function( data ) {
window[ "eval" ].call( window, data ); // jscs:ignore requireDotNotation
} )( data );
}
},
// Convert dashed to camelCase; used by the css and data modules
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function( string ) {
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
},
each: function( obj, callback ) {
var length, i = 0;
if ( isArrayLike( obj ) ) {
length = obj.length;
for ( ; i < length; i++ ) {
if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) {
break;
}
}
} else {
for ( i in obj ) {
if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) {
break;
}
}
}
return obj;
},
// Support: Android<4.1, IE<9
trim: function( text ) {
return text == null ?
"" :
( text + "" ).replace( rtrim, "" );
},
// results is for internal usage only
makeArray: function( arr, results ) {
var ret = results || [];
if ( arr != null ) {
if ( isArrayLike( Object( arr ) ) ) {
jQuery.merge( ret,
typeof arr === "string" ?
[ arr ] : arr
);
} else {
push.call( ret, arr );
}
}
return ret;
},
inArray: function( elem, arr, i ) {
var len;
if ( arr ) {
if ( indexOf ) {
return indexOf.call( arr, elem, i );
}
len = arr.length;
i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;
for ( ; i < len; i++ ) {
// Skip accessing in sparse arrays
if ( i in arr && arr[ i ] === elem ) {
return i;
}
}
}
return -1;
},
merge: function( first, second ) {
var len = +second.length,
j = 0,
i = first.length;
while ( j < len ) {
first[ i++ ] = second[ j++ ];
}
// Support: IE<9
// Workaround casting of .length to NaN on otherwise arraylike objects (e.g., NodeLists)
if ( len !== len ) {
while ( second[ j ] !== undefined ) {
first[ i++ ] = second[ j++ ];
}
}
first.length = i;
return first;
},
grep: function( elems, callback, invert ) {
var callbackInverse,
matches = [],
i = 0,
length = elems.length,
callbackExpect = !invert;
// Go through the array, only saving the items
// that pass the validator function
for ( ; i < length; i++ ) {
callbackInverse = !callback( elems[ i ], i );
if ( callbackInverse !== callbackExpect ) {
matches.push( elems[ i ] );
}
}
return matches;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var length, value,
i = 0,
ret = [];
// Go through the array, translating each of the items to their new values
if ( isArrayLike( elems ) ) {
length = elems.length;
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret.push( value );
}
}
// Go through every key on the object,
} else {
for ( i in elems ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret.push( value );
}
}
}
// Flatten any nested arrays
return concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function( fn, context ) {
var args, proxy, tmp;
if ( typeof context === "string" ) {
tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
args = slice.call( arguments, 2 );
proxy = function() {
return fn.apply( context || this, args.concat( slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || jQuery.guid++;
return proxy;
},
now: function() {
return +( new Date() );
},
// jQuery.support is not used in Core but other projects attach their
// properties to it so it needs to exist.
support: support
} );
// JSHint would error on this code due to the Symbol not being defined in ES5.
// Defining this global in .jshintrc would create a danger of using the global
// unguarded in another place, it seems safer to just disable JSHint for these
// three lines.
/* jshint ignore: start */
if ( typeof Symbol === "function" ) {
jQuery.fn[ Symbol.iterator ] = deletedIds[ Symbol.iterator ];
}
/* jshint ignore: end */
// Populate the class2type map
jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ),
function( i, name ) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
} );
function isArrayLike( obj ) {
// Support: iOS 8.2 (not reproducible in simulator)
// `in` check used to prevent JIT error (gh-2145)
// hasOwn isn't used here due to false negatives
// regarding Nodelist length in IE
var length = !!obj && "length" in obj && obj.length,
type = jQuery.type( obj );
if ( type === "function" || jQuery.isWindow( obj ) ) {
return false;
}
return type === "array" || length === 0 ||
typeof length === "number" && length > 0 && ( length - 1 ) in obj;
}
var Sizzle =
/*!
* Sizzle CSS Selector Engine v2.2.1
* http://sizzlejs.com/
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2015-10-17
*/
(function( window ) {
var i,
support,
Expr,
getText,
isXML,
tokenize,
compile,
select,
outermostContext,
sortInput,
hasDuplicate,
// Local document vars
setDocument,
document,
docElem,
documentIsHTML,
rbuggyQSA,
rbuggyMatches,
matches,
contains,
// Instance-specific data
expando = "sizzle" + 1 * new Date(),
preferredDoc = window.document,
dirruns = 0,
done = 0,
classCache = createCache(),
tokenCache = createCache(),
compilerCache = createCache(),
sortOrder = function( a, b ) {
if ( a === b ) {
hasDuplicate = true;
}
return 0;
},
// General-purpose constants
MAX_NEGATIVE = 1 << 31,
// Instance methods
hasOwn = ({}).hasOwnProperty,
arr = [],
pop = arr.pop,
push_native = arr.push,
push = arr.push,
slice = arr.slice,
// Use a stripped-down indexOf as it's faster than native
// http://jsperf.com/thor-indexof-vs-for/5
indexOf = function( list, elem ) {
var i = 0,
len = list.length;
for ( ; i < len; i++ ) {
if ( list[i] === elem ) {
return i;
}
}
return -1;
},
booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",
// Regular expressions
// http://www.w3.org/TR/css3-selectors/#whitespace
whitespace = "[\\x20\\t\\r\\n\\f]",
// http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
identifier = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",
// Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors
attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace +
// Operator (capture 2)
"*([*^$|!~]?=)" + whitespace +
// "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]"
"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace +
"*\\]",
pseudos = ":(" + identifier + ")(?:\\((" +
// To reduce the number of selectors needing tokenize in the preFilter, prefer arguments:
// 1. quoted (capture 3; capture 4 or capture 5)
"('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" +
// 2. simple (capture 6)
"((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" +
// 3. anything else (capture 2)
".*" +
")\\)|)",
// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
rwhitespace = new RegExp( whitespace + "+", "g" ),
rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ),
rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ),
rpseudo = new RegExp( pseudos ),
ridentifier = new RegExp( "^" + identifier + "$" ),
matchExpr = {
"ID": new RegExp( "^#(" + identifier + ")" ),
"CLASS": new RegExp( "^\\.(" + identifier + ")" ),
"TAG": new RegExp( "^(" + identifier + "|[*])" ),
"ATTR": new RegExp( "^" + attributes ),
"PSEUDO": new RegExp( "^" + pseudos ),
"CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace +
"*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
"*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
"bool": new RegExp( "^(?:" + booleans + ")$", "i" ),
// For use in libraries implementing .is()
// We use this for POS matching in `select`
"needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" +
whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )
},
rinputs = /^(?:input|select|textarea|button)$/i,
rheader = /^h\d$/i,
rnative = /^[^{]+\{\s*\[native \w/,
// Easily-parseable/retrievable ID or TAG or CLASS selectors
rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
rsibling = /[+~]/,
rescape = /'|\\/g,
// CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ),
funescape = function( _, escaped, escapedWhitespace ) {
var high = "0x" + escaped - 0x10000;
// NaN means non-codepoint
// Support: Firefox<24
// Workaround erroneous numeric interpretation of +"0x"
return high !== high || escapedWhitespace ?
escaped :
high < 0 ?
// BMP codepoint
String.fromCharCode( high + 0x10000 ) :
// Supplemental Plane codepoint (surrogate pair)
String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
},
// Used for iframes
// See setDocument()
// Removing the function wrapper causes a "Permission Denied"
// error in IE
unloadHandler = function() {
setDocument();
};
// Optimize for push.apply( _, NodeList )
try {
push.apply(
(arr = slice.call( preferredDoc.childNodes )),
preferredDoc.childNodes
);
// Support: Android<4.0
// Detect silently failing push.apply
arr[ preferredDoc.childNodes.length ].nodeType;
} catch ( e ) {
push = { apply: arr.length ?
// Leverage slice if possible
function( target, els ) {
push_native.apply( target, slice.call(els) );
} :
// Support: IE<9
// Otherwise append directly
function( target, els ) {
var j = target.length,
i = 0;
// Can't trust NodeList.length
while ( (target[j++] = els[i++]) ) {}
target.length = j - 1;
}
};
}
function Sizzle( selector, context, results, seed ) {
var m, i, elem, nid, nidselect, match, groups, newSelector,
newContext = context && context.ownerDocument,
// nodeType defaults to 9, since context defaults to document
nodeType = context ? context.nodeType : 9;
results = results || [];
// Return early from calls with invalid selector or context
if ( typeof selector !== "string" || !selector ||
nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) {
return results;
}
// Try to shortcut find operations (as opposed to filters) in HTML documents
if ( !seed ) {
if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
setDocument( context );
}
context = context || document;
if ( documentIsHTML ) {
// If the selector is sufficiently simple, try using a "get*By*" DOM method
// (excepting DocumentFragment context, where the methods don't exist)
if ( nodeType !== 11 && (match = rquickExpr.exec( selector )) ) {
// ID selector
if ( (m = match[1]) ) {
// Document context
if ( nodeType === 9 ) {
if ( (elem = context.getElementById( m )) ) {
// Support: IE, Opera, Webkit
// TODO: identify versions
// getElementById can match elements by name instead of ID
if ( elem.id === m ) {
results.push( elem );
return results;
}
} else {
return results;
}
// Element context
} else {
// Support: IE, Opera, Webkit
// TODO: identify versions
// getElementById can match elements by name instead of ID
if ( newContext && (elem = newContext.getElementById( m )) &&
contains( context, elem ) &&
elem.id === m ) {
results.push( elem );
return results;
}
}
// Type selector
} else if ( match[2] ) {
push.apply( results, context.getElementsByTagName( selector ) );
return results;
// Class selector
} else if ( (m = match[3]) && support.getElementsByClassName &&
context.getElementsByClassName ) {
push.apply( results, context.getElementsByClassName( m ) );
return results;
}
}
// Take advantage of querySelectorAll
if ( support.qsa &&
!compilerCache[ selector + " " ] &&
(!rbuggyQSA || !rbuggyQSA.test( selector )) ) {
if ( nodeType !== 1 ) {
newContext = context;
newSelector = selector;
// qSA looks outside Element context, which is not what we want
// Thanks to Andrew Dupont for this workaround technique
// Support: IE <=8
// Exclude object elements
} else if ( context.nodeName.toLowerCase() !== "object" ) {
// Capture the context ID, setting it first if necessary
if ( (nid = context.getAttribute( "id" )) ) {
nid = nid.replace( rescape, "\\$&" );
} else {
context.setAttribute( "id", (nid = expando) );
}
// Prefix every selector in the list
groups = tokenize( selector );
i = groups.length;
nidselect = ridentifier.test( nid ) ? "#" + nid : "[id='" + nid + "']";
while ( i-- ) {
groups[i] = nidselect + " " + toSelector( groups[i] );
}
newSelector = groups.join( "," );
// Expand context for sibling selectors
newContext = rsibling.test( selector ) && testContext( context.parentNode ) ||
context;
}
if ( newSelector ) {
try {
push.apply( results,
newContext.querySelectorAll( newSelector )
);
return results;
} catch ( qsaError ) {
} finally {
if ( nid === expando ) {
context.removeAttribute( "id" );
}
}
}
}
}
}
// All others
return select( selector.replace( rtrim, "$1" ), context, results, seed );
}
/**
* Create key-value caches of limited size
* @returns {function(string, object)} Returns the Object data after storing it on itself with
* property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
* deleting the oldest entry
*/
function createCache() {
var keys = [];
function cache( key, value ) {
// Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
if ( keys.push( key + " " ) > Expr.cacheLength ) {
// Only keep the most recent entries
delete cache[ keys.shift() ];
}
return (cache[ key + " " ] = value);
}
return cache;
}
/**
* Mark a function for special use by Sizzle
* @param {Function} fn The function to mark
*/
function markFunction( fn ) {
fn[ expando ] = true;
return fn;
}
/**
* Support testing using an element
* @param {Function} fn Passed the created div and expects a boolean result
*/
function assert( fn ) {
var div = document.createElement("div");
try {
return !!fn( div );
} catch (e) {
return false;
} finally {
// Remove from its parent by default
if ( div.parentNode ) {
div.parentNode.removeChild( div );
}
// release memory in IE
div = null;
}
}
/**
* Adds the same handler for all of the specified attrs
* @param {String} attrs Pipe-separated list of attributes
* @param {Function} handler The method that will be applied
*/
function addHandle( attrs, handler ) {
var arr = attrs.split("|"),
i = arr.length;
while ( i-- ) {
Expr.attrHandle[ arr[i] ] = handler;
}
}
/**
* Checks document order of two siblings
* @param {Element} a
* @param {Element} b
* @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b
*/
function siblingCheck( a, b ) {
var cur = b && a,
diff = cur && a.nodeType === 1 && b.nodeType === 1 &&
( ~b.sourceIndex || MAX_NEGATIVE ) -
( ~a.sourceIndex || MAX_NEGATIVE );
// Use IE sourceIndex if available on both nodes
if ( diff ) {
return diff;
}
// Check if b follows a
if ( cur ) {
while ( (cur = cur.nextSibling) ) {
if ( cur === b ) {
return -1;
}
}
}
return a ? 1 : -1;
}
/**
* Returns a function to use in pseudos for input types
* @param {String} type
*/
function createInputPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === type;
};
}
/**
* Returns a function to use in pseudos for buttons
* @param {String} type
*/
function createButtonPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && elem.type === type;
};
}
/**
* Returns a function to use in pseudos for positionals
* @param {Function} fn
*/
function createPositionalPseudo( fn ) {
return markFunction(function( argument ) {
argument = +argument;
return markFunction(function( seed, matches ) {
var j,
matchIndexes = fn( [], seed.length, argument ),
i = matchIndexes.length;
// Match elements found at the specified indexes
while ( i-- ) {
if ( seed[ (j = matchIndexes[i]) ] ) {
seed[j] = !(matches[j] = seed[j]);
}
}
});
});
}
/**
* Checks a node for validity as a Sizzle context
* @param {Element|Object=} context
* @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value
*/
function testContext( context ) {
return context && typeof context.getElementsByTagName !== "undefined" && context;
}
// Expose support vars for convenience
support = Sizzle.support = {};
/**
* Detects XML nodes
* @param {Element|Object} elem An element or a document
* @returns {Boolean} True iff elem is a non-HTML XML node
*/
isXML = Sizzle.isXML = function( elem ) {
// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement = elem && (elem.ownerDocument || elem).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
/**
* Sets document-related variables once based on the current document
* @param {Element|Object} [doc] An element or document object to use to set the document
* @returns {Object} Returns the current document
*/
setDocument = Sizzle.setDocument = function( node ) {
var hasCompare, parent,
doc = node ? node.ownerDocument || node : preferredDoc;
// Return early if doc is invalid or already selected
if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
return document;
}
// Update global variables
document = doc;
docElem = document.documentElement;
documentIsHTML = !isXML( document );
// Support: IE 9-11, Edge
// Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936)
if ( (parent = document.defaultView) && parent.top !== parent ) {
// Support: IE 11
if ( parent.addEventListener ) {
parent.addEventListener( "unload", unloadHandler, false );
// Support: IE 9 - 10 only
} else if ( parent.attachEvent ) {
parent.attachEvent( "onunload", unloadHandler );
}
}
/* Attributes
---------------------------------------------------------------------- */
// Support: IE<8
// Verify that getAttribute really returns attributes and not properties
// (excepting IE8 booleans)
support.attributes = assert(function( div ) {
div.className = "i";
return !div.getAttribute("className");
});
/* getElement(s)By*
---------------------------------------------------------------------- */
// Check if getElementsByTagName("*") returns only elements
support.getElementsByTagName = assert(function( div ) {
div.appendChild( document.createComment("") );
return !div.getElementsByTagName("*").length;
});
// Support: IE<9
support.getElementsByClassName = rnative.test( document.getElementsByClassName );
// Support: IE<10
// Check if getElementById returns elements by name
// The broken getElementById methods don't pick up programatically-set names,
// so use a roundabout getElementsByName test
support.getById = assert(function( div ) {
docElem.appendChild( div ).id = expando;
return !document.getElementsByName || !document.getElementsByName( expando ).length;
});
// ID find and filter
if ( support.getById ) {
Expr.find["ID"] = function( id, context ) {
if ( typeof context.getElementById !== "undefined" && documentIsHTML ) {
var m = context.getElementById( id );
return m ? [ m ] : [];
}
};
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
return elem.getAttribute("id") === attrId;
};
};
} else {
// Support: IE6/7
// getElementById is not reliable as a find shortcut
delete Expr.find["ID"];
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
var node = typeof elem.getAttributeNode !== "undefined" &&
elem.getAttributeNode("id");
return node && node.value === attrId;
};
};
}
// Tag
Expr.find["TAG"] = support.getElementsByTagName ?
function( tag, context ) {
if ( typeof context.getElementsByTagName !== "undefined" ) {
return context.getElementsByTagName( tag );
// DocumentFragment nodes don't have gEBTN
} else if ( support.qsa ) {
return context.querySelectorAll( tag );
}
} :
function( tag, context ) {
var elem,
tmp = [],
i = 0,
// By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too
results = context.getElementsByTagName( tag );
// Filter out possible comments
if ( tag === "*" ) {
while ( (elem = results[i++]) ) {
if ( elem.nodeType === 1 ) {
tmp.push( elem );
}
}
return tmp;
}
return results;
};
// Class
Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) {
if ( typeof context.getElementsByClassName !== "undefined" && documentIsHTML ) {
return context.getElementsByClassName( className );
}
};
/* QSA/matchesSelector
---------------------------------------------------------------------- */
// QSA and matchesSelector support
// matchesSelector(:active) reports false when true (IE9/Opera 11.5)
rbuggyMatches = [];
// qSa(:focus) reports false when true (Chrome 21)
// We allow this because of a bug in IE8/9 that throws an error
// whenever `document.activeElement` is accessed on an iframe
// So, we allow :focus to pass through QSA all the time to avoid the IE error
// See http://bugs.jquery.com/ticket/13378
rbuggyQSA = [];
if ( (support.qsa = rnative.test( document.querySelectorAll )) ) {
// Build QSA regex
// Regex strategy adopted from Diego Perini
assert(function( div ) {
// Select is set to empty string on purpose
// This is to test IE's treatment of not explicitly
// setting a boolean content attribute,
// since its presence should be enough
// http://bugs.jquery.com/ticket/12359
docElem.appendChild( div ).innerHTML = "<a id='" + expando + "'></a>" +
"<select id='" + expando + "-\r\\' msallowcapture=''>" +
"<option selected=''></option></select>";
// Support: IE8, Opera 11-12.16
// Nothing should be selected when empty strings follow ^= or $= or *=
// The test attribute must be unknown in Opera but "safe" for WinRT
// http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section
if ( div.querySelectorAll("[msallowcapture^='']").length ) {
rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" );
}
// Support: IE8
// Boolean attributes and "value" are not treated correctly
if ( !div.querySelectorAll("[selected]").length ) {
rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" );
}
// Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+
if ( !div.querySelectorAll( "[id~=" + expando + "-]" ).length ) {
rbuggyQSA.push("~=");
}
// Webkit/Opera - :checked should return selected option elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
// IE8 throws error here and will not see later tests
if ( !div.querySelectorAll(":checked").length ) {
rbuggyQSA.push(":checked");
}
// Support: Safari 8+, iOS 8+
// https://bugs.webkit.org/show_bug.cgi?id=136851
// In-page `selector#id sibing-combinator selector` fails
if ( !div.querySelectorAll( "a#" + expando + "+*" ).length ) {
rbuggyQSA.push(".#.+[+~]");
}
});
assert(function( div ) {
// Support: Windows 8 Native Apps
// The type and name attributes are restricted during .innerHTML assignment
var input = document.createElement("input");
input.setAttribute( "type", "hidden" );
div.appendChild( input ).setAttribute( "name", "D" );
// Support: IE8
// Enforce case-sensitivity of name attribute
if ( div.querySelectorAll("[name=d]").length ) {
rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" );
}
// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
// IE8 throws error here and will not see later tests
if ( !div.querySelectorAll(":enabled").length ) {
rbuggyQSA.push( ":enabled", ":disabled" );
}
// Opera 10-11 does not throw on post-comma invalid pseudos
div.querySelectorAll("*,:x");
rbuggyQSA.push(",.*:");
});
}
if ( (support.matchesSelector = rnative.test( (matches = docElem.matches ||
docElem.webkitMatchesSelector ||
docElem.mozMatchesSelector ||
docElem.oMatchesSelector ||
docElem.msMatchesSelector) )) ) {
assert(function( div ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9)
support.disconnectedMatch = matches.call( div, "div" );
// This should fail with an exception
// Gecko does not error, returns false instead
matches.call( div, "[s!='']:x" );
rbuggyMatches.push( "!=", pseudos );
});
}
rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") );
rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") );
/* Contains
---------------------------------------------------------------------- */
hasCompare = rnative.test( docElem.compareDocumentPosition );
// Element contains another
// Purposefully self-exclusive
// As in, an element does not contain itself
contains = hasCompare || rnative.test( docElem.contains ) ?
function( a, b ) {
var adown = a.nodeType === 9 ? a.documentElement : a,
bup = b && b.parentNode;
return a === bup || !!( bup && bup.nodeType === 1 && (
adown.contains ?
adown.contains( bup ) :
a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
));
} :
function( a, b ) {
if ( b ) {
while ( (b = b.parentNode) ) {
if ( b === a ) {
return true;
}
}
}
return false;
};
/* Sorting
---------------------------------------------------------------------- */
// Document order sorting
sortOrder = hasCompare ?
function( a, b ) {
// Flag for duplicate removal
if ( a === b ) {
hasDuplicate = true;
return 0;
}
// Sort on method existence if only one input has compareDocumentPosition
var compare = !a.compareDocumentPosition - !b.compareDocumentPosition;
if ( compare ) {
return compare;
}
// Calculate position if both inputs belong to the same document
compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ?
a.compareDocumentPosition( b ) :
// Otherwise we know they are disconnected
1;
// Disconnected nodes
if ( compare & 1 ||
(!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) {
// Choose the first element that is related to our preferred document
if ( a === document || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) {
return -1;
}
if ( b === document || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) {
return 1;
}
// Maintain original order
return sortInput ?
( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) :
0;
}
return compare & 4 ? -1 : 1;
} :
function( a, b ) {
// Exit early if the nodes are identical
if ( a === b ) {
hasDuplicate = true;
return 0;
}
var cur,
i = 0,
aup = a.parentNode,
bup = b.parentNode,
ap = [ a ],
bp = [ b ];
// Parentless nodes are either documents or disconnected
if ( !aup || !bup ) {
return a === document ? -1 :
b === document ? 1 :
aup ? -1 :
bup ? 1 :
sortInput ?
( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) :
0;
// If the nodes are siblings, we can do a quick check
} else if ( aup === bup ) {
return siblingCheck( a, b );
}
// Otherwise we need full lists of their ancestors for comparison
cur = a;
while ( (cur = cur.parentNode) ) {
ap.unshift( cur );
}
cur = b;
while ( (cur = cur.parentNode) ) {
bp.unshift( cur );
}
// Walk down the tree looking for a discrepancy
while ( ap[i] === bp[i] ) {
i++;
}
return i ?
// Do a sibling check if the nodes have a common ancestor
siblingCheck( ap[i], bp[i] ) :
// Otherwise nodes in our document sort first
ap[i] === preferredDoc ? -1 :
bp[i] === preferredDoc ? 1 :
0;
};
return document;
};
Sizzle.matches = function( expr, elements ) {
return Sizzle( expr, null, null, elements );
};
Sizzle.matchesSelector = function( elem, expr ) {
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
// Make sure that attribute selectors are quoted
expr = expr.replace( rattributeQuotes, "='$1']" );
if ( support.matchesSelector && documentIsHTML &&
!compilerCache[ expr + " " ] &&
( !rbuggyMatches || !rbuggyMatches.test( expr ) ) &&
( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) {
try {
var ret = matches.call( elem, expr );
// IE 9's matchesSelector returns false on disconnected nodes
if ( ret || support.disconnectedMatch ||
// As well, disconnected nodes are said to be in a document
// fragment in IE 9
elem.document && elem.document.nodeType !== 11 ) {
return ret;
}
} catch (e) {}
}
return Sizzle( expr, document, null, [ elem ] ).length > 0;
};
Sizzle.contains = function( context, elem ) {
// Set document vars if needed
if ( ( context.ownerDocument || context ) !== document ) {
setDocument( context );
}
return contains( context, elem );
};
Sizzle.attr = function( elem, name ) {
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
var fn = Expr.attrHandle[ name.toLowerCase() ],
// Don't get fooled by Object.prototype properties (jQuery #13807)
val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ?
fn( elem, name, !documentIsHTML ) :
undefined;
return val !== undefined ?
val :
support.attributes || !documentIsHTML ?
elem.getAttribute( name ) :
(val = elem.getAttributeNode(name)) && val.specified ?
val.value :
null;
};
Sizzle.error = function( msg ) {
throw new Error( "Syntax error, unrecognized expression: " + msg );
};
/**
* Document sorting and removing duplicates
* @param {ArrayLike} results
*/
Sizzle.uniqueSort = function( results ) {
var elem,
duplicates = [],
j = 0,
i = 0;
// Unless we *know* we can detect duplicates, assume their presence
hasDuplicate = !support.detectDuplicates;
sortInput = !support.sortStable && results.slice( 0 );
results.sort( sortOrder );
if ( hasDuplicate ) {
while ( (elem = results[i++]) ) {
if ( elem === results[ i ] ) {
j = duplicates.push( i );
}
}
while ( j-- ) {
results.splice( duplicates[ j ], 1 );
}
}
// Clear input after sorting to release objects
// See https://github.com/jquery/sizzle/pull/225
sortInput = null;
return results;
};
/**
* Utility function for retrieving the text value of an array of DOM nodes
* @param {Array|Element} elem
*/
getText = Sizzle.getText = function( elem ) {
var node,
ret = "",
i = 0,
nodeType = elem.nodeType;
if ( !nodeType ) {
// If no nodeType, this is expected to be an array
while ( (node = elem[i++]) ) {
// Do not traverse comment nodes
ret += getText( node );
}
} else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
// Use textContent for elements
// innerText usage removed for consistency of new lines (jQuery #11153)
if ( typeof elem.textContent === "string" ) {
return elem.textContent;
} else {
// Traverse its children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
ret += getText( elem );
}
}
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
// Do not include comment or processing instruction nodes
return ret;
};
Expr = Sizzle.selectors = {
// Can be adjusted by the user
cacheLength: 50,
createPseudo: markFunction,
match: matchExpr,
attrHandle: {},
find: {},
relative: {
">": { dir: "parentNode", first: true },
" ": { dir: "parentNode" },
"+": { dir: "previousSibling", first: true },
"~": { dir: "previousSibling" }
},
preFilter: {
"ATTR": function( match ) {
match[1] = match[1].replace( runescape, funescape );
// Move the given value to match[3] whether quoted or unquoted
match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape );
if ( match[2] === "~=" ) {
match[3] = " " + match[3] + " ";
}
return match.slice( 0, 4 );
},
"CHILD": function( match ) {
/* matches from matchExpr["CHILD"]
1 type (only|nth|...)
2 what (child|of-type)
3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
4 xn-component of xn+y argument ([+-]?\d*n|)
5 sign of xn-component
6 x of xn-component
7 sign of y-component
8 y of y-component
*/
match[1] = match[1].toLowerCase();
if ( match[1].slice( 0, 3 ) === "nth" ) {
// nth-* requires argument
if ( !match[3] ) {
Sizzle.error( match[0] );
}
// numeric x and y parameters for Expr.filter.CHILD
// remember that false/true cast respectively to 0/1
match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) );
match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" );
// other types prohibit arguments
} else if ( match[3] ) {
Sizzle.error( match[0] );
}
return match;
},
"PSEUDO": function( match ) {
var excess,
unquoted = !match[6] && match[2];
if ( matchExpr["CHILD"].test( match[0] ) ) {
return null;
}
// Accept quoted arguments as-is
if ( match[3] ) {
match[2] = match[4] || match[5] || "";
// Strip excess characters from unquoted arguments
} else if ( unquoted && rpseudo.test( unquoted ) &&
// Get excess from tokenize (recursively)
(excess = tokenize( unquoted, true )) &&
// advance to the next closing parenthesis
(excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {
// excess is a negative index
match[0] = match[0].slice( 0, excess );
match[2] = unquoted.slice( 0, excess );
}
// Return only captures needed by the pseudo filter method (type and argument)
return match.slice( 0, 3 );
}
},
filter: {
"TAG": function( nodeNameSelector ) {
var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase();
return nodeNameSelector === "*" ?
function() { return true; } :
function( elem ) {
return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
};
},
"CLASS": function( className ) {
var pattern = classCache[ className + " " ];
return pattern ||
(pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
classCache( className, function( elem ) {
return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute("class") || "" );
});
},
"ATTR": function( name, operator, check ) {
return function( elem ) {
var result = Sizzle.attr( elem, name );
if ( result == null ) {
return operator === "!=";
}
if ( !operator ) {
return true;
}
result += "";
return operator === "=" ? result === check :
operator === "!=" ? result !== check :
operator === "^=" ? check && result.indexOf( check ) === 0 :
operator === "*=" ? check && result.indexOf( check ) > -1 :
operator === "$=" ? check && result.slice( -check.length ) === check :
operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 :
operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" :
false;
};
},
"CHILD": function( type, what, argument, first, last ) {
var simple = type.slice( 0, 3 ) !== "nth",
forward = type.slice( -4 ) !== "last",
ofType = what === "of-type";
return first === 1 && last === 0 ?
// Shortcut for :nth-*(n)
function( elem ) {
return !!elem.parentNode;
} :
function( elem, context, xml ) {
var cache, uniqueCache, outerCache, node, nodeIndex, start,
dir = simple !== forward ? "nextSibling" : "previousSibling",
parent = elem.parentNode,
name = ofType && elem.nodeName.toLowerCase(),
useCache = !xml && !ofType,
diff = false;
if ( parent ) {
// :(first|last|only)-(child|of-type)
if ( simple ) {
while ( dir ) {
node = elem;
while ( (node = node[ dir ]) ) {
if ( ofType ?
node.nodeName.toLowerCase() === name :
node.nodeType === 1 ) {
return false;
}
}
// Reverse direction for :only-* (if we haven't yet done so)
start = dir = type === "only" && !start && "nextSibling";
}
return true;
}
start = [ forward ? parent.firstChild : parent.lastChild ];
// non-xml :nth-child(...) stores cache data on `parent`
if ( forward && useCache ) {
// Seek `elem` from a previously-cached index
// ...in a gzip-friendly way
node = parent;
outerCache = node[ expando ] || (node[ expando ] = {});
// Support: IE <9 only
// Defend against cloned attroperties (jQuery gh-1709)
uniqueCache = outerCache[ node.uniqueID ] ||
(outerCache[ node.uniqueID ] = {});
cache = uniqueCache[ type ] || [];
nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ];
diff = nodeIndex && cache[ 2 ];
node = nodeIndex && parent.childNodes[ nodeIndex ];
while ( (node = ++nodeIndex && node && node[ dir ] ||
// Fallback to seeking `elem` from the start
(diff = nodeIndex = 0) || start.pop()) ) {
// When found, cache indexes on `parent` and break
if ( node.nodeType === 1 && ++diff && node === elem ) {
uniqueCache[ type ] = [ dirruns, nodeIndex, diff ];
break;
}
}
} else {
// Use previously-cached element index if available
if ( useCache ) {
// ...in a gzip-friendly way
node = elem;
outerCache = node[ expando ] || (node[ expando ] = {});
// Support: IE <9 only
// Defend against cloned attroperties (jQuery gh-1709)
uniqueCache = outerCache[ node.uniqueID ] ||
(outerCache[ node.uniqueID ] = {});
cache = uniqueCache[ type ] || [];
nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ];
diff = nodeIndex;
}
// xml :nth-child(...)
// or :nth-last-child(...) or :nth(-last)?-of-type(...)
if ( diff === false ) {
// Use the same loop as above to seek `elem` from the start
while ( (node = ++nodeIndex && node && node[ dir ] ||
(diff = nodeIndex = 0) || start.pop()) ) {
if ( ( ofType ?
node.nodeName.toLowerCase() === name :
node.nodeType === 1 ) &&
++diff ) {
// Cache the index of each encountered element
if ( useCache ) {
outerCache = node[ expando ] || (node[ expando ] = {});
// Support: IE <9 only
// Defend against cloned attroperties (jQuery gh-1709)
uniqueCache = outerCache[ node.uniqueID ] ||
(outerCache[ node.uniqueID ] = {});
uniqueCache[ type ] = [ dirruns, diff ];
}
if ( node === elem ) {
break;
}
}
}
}
}
// Incorporate the offset, then check against cycle size
diff -= last;
return diff === first || ( diff % first === 0 && diff / first >= 0 );
}
};
},
"PSEUDO": function( pseudo, argument ) {
// pseudo-class names are case-insensitive
// http://www.w3.org/TR/selectors/#pseudo-classes
// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
// Remember that setFilters inherits from pseudos
var args,
fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
Sizzle.error( "unsupported pseudo: " + pseudo );
// The user may use createPseudo to indicate that
// arguments are needed to create the filter function
// just as Sizzle does
if ( fn[ expando ] ) {
return fn( argument );
}
// But maintain support for old signatures
if ( fn.length > 1 ) {
args = [ pseudo, pseudo, "", argument ];
return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
markFunction(function( seed, matches ) {
var idx,
matched = fn( seed, argument ),
i = matched.length;
while ( i-- ) {
idx = indexOf( seed, matched[i] );
seed[ idx ] = !( matches[ idx ] = matched[i] );
}
}) :
function( elem ) {
return fn( elem, 0, args );
};
}
return fn;
}
},
pseudos: {
// Potentially complex pseudos
"not": markFunction(function( selector ) {
// Trim the selector passed to compile
// to avoid treating leading and trailing
// spaces as combinators
var input = [],
results = [],
matcher = compile( selector.replace( rtrim, "$1" ) );
return matcher[ expando ] ?
markFunction(function( seed, matches, context, xml ) {
var elem,
unmatched = matcher( seed, null, xml, [] ),
i = seed.length;
// Match elements unmatched by `matcher`
while ( i-- ) {
if ( (elem = unmatched[i]) ) {
seed[i] = !(matches[i] = elem);
}
}
}) :
function( elem, context, xml ) {
input[0] = elem;
matcher( input, null, xml, results );
// Don't keep the element (issue #299)
input[0] = null;
return !results.pop();
};
}),
"has": markFunction(function( selector ) {
return function( elem ) {
return Sizzle( selector, elem ).length > 0;
};
}),
"contains": markFunction(function( text ) {
text = text.replace( runescape, funescape );
return function( elem ) {
return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
};
}),
// "Whether an element is represented by a :lang() selector
// is based solely on the element's language value
// being equal to the identifier C,
// or beginning with the identifier C immediately followed by "-".
// The matching of C against the element's language value is performed case-insensitively.
// The identifier C does not have to be a valid language name."
// http://www.w3.org/TR/selectors/#lang-pseudo
"lang": markFunction( function( lang ) {
// lang value must be a valid identifier
if ( !ridentifier.test(lang || "") ) {
Sizzle.error( "unsupported lang: " + lang );
}
lang = lang.replace( runescape, funescape ).toLowerCase();
return function( elem ) {
var elemLang;
do {
if ( (elemLang = documentIsHTML ?
elem.lang :
elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) {
elemLang = elemLang.toLowerCase();
return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0;
}
} while ( (elem = elem.parentNode) && elem.nodeType === 1 );
return false;
};
}),
// Miscellaneous
"target": function( elem ) {
var hash = window.location && window.location.hash;
return hash && hash.slice( 1 ) === elem.id;
},
"root": function( elem ) {
return elem === docElem;
},
"focus": function( elem ) {
return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
},
// Boolean properties
"enabled": function( elem ) {
return elem.disabled === false;
},
"disabled": function( elem ) {
return elem.disabled === true;
},
"checked": function( elem ) {
// In CSS3, :checked should return both checked and selected elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
var nodeName = elem.nodeName.toLowerCase();
return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
},
"selected": function( elem ) {
// Accessing this property makes selected-by-default
// options in Safari work properly
if ( elem.parentNode ) {
elem.parentNode.selectedIndex;
}
return elem.selected === true;
},
// Contents
"empty": function( elem ) {
// http://www.w3.org/TR/selectors/#empty-pseudo
// :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5),
// but not by others (comment: 8; processing instruction: 7; etc.)
// nodeType < 6 works because attributes (2) do not appear as children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
if ( elem.nodeType < 6 ) {
return false;
}
}
return true;
},
"parent": function( elem ) {
return !Expr.pseudos["empty"]( elem );
},
// Element/input types
"header": function( elem ) {
return rheader.test( elem.nodeName );
},
"input": function( elem ) {
return rinputs.test( elem.nodeName );
},
"button": function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === "button" || name === "button";
},
"text": function( elem ) {
var attr;
return elem.nodeName.toLowerCase() === "input" &&
elem.type === "text" &&
// Support: IE<8
// New HTML5 attribute values (e.g., "search") appear with elem.type === "text"
( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" );
},
// Position-in-collection
"first": createPositionalPseudo(function() {
return [ 0 ];
}),
"last": createPositionalPseudo(function( matchIndexes, length ) {
return [ length - 1 ];
}),
"eq": createPositionalPseudo(function( matchIndexes, length, argument ) {
return [ argument < 0 ? argument + length : argument ];
}),
"even": createPositionalPseudo(function( matchIndexes, length ) {
var i = 0;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"odd": createPositionalPseudo(function( matchIndexes, length ) {
var i = 1;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"lt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; --i >= 0; ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"gt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; ++i < length; ) {
matchIndexes.push( i );
}
return matchIndexes;
})
}
};
Expr.pseudos["nth"] = Expr.pseudos["eq"];
// Add button/input type pseudos
for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) {
Expr.pseudos[ i ] = createInputPseudo( i );
}
for ( i in { submit: true, reset: true } ) {
Expr.pseudos[ i ] = createButtonPseudo( i );
}
// Easy API for creating new setFilters
function setFilters() {}
setFilters.prototype = Expr.filters = Expr.pseudos;
Expr.setFilters = new setFilters();
tokenize = Sizzle.tokenize = function( selector, parseOnly ) {
var matched, match, tokens, type,
soFar, groups, preFilters,
cached = tokenCache[ selector + " " ];
if ( cached ) {
return parseOnly ? 0 : cached.slice( 0 );
}
soFar = selector;
groups = [];
preFilters = Expr.preFilter;
while ( soFar ) {
// Comma and first run
if ( !matched || (match = rcomma.exec( soFar )) ) {
if ( match ) {
// Don't consume trailing commas as valid
soFar = soFar.slice( match[0].length ) || soFar;
}
groups.push( (tokens = []) );
}
matched = false;
// Combinators
if ( (match = rcombinators.exec( soFar )) ) {
matched = match.shift();
tokens.push({
value: matched,
// Cast descendant combinators to space
type: match[0].replace( rtrim, " " )
});
soFar = soFar.slice( matched.length );
}
// Filters
for ( type in Expr.filter ) {
if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
(match = preFilters[ type ]( match ))) ) {
matched = match.shift();
tokens.push({
value: matched,
type: type,
matches: match
});
soFar = soFar.slice( matched.length );
}
}
if ( !matched ) {
break;
}
}
// Return the length of the invalid excess
// if we're just parsing
// Otherwise, throw an error or return tokens
return parseOnly ?
soFar.length :
soFar ?
Sizzle.error( selector ) :
// Cache the tokens
tokenCache( selector, groups ).slice( 0 );
};
function toSelector( tokens ) {
var i = 0,
len = tokens.length,
selector = "";
for ( ; i < len; i++ ) {
selector += tokens[i].value;
}
return selector;
}
function addCombinator( matcher, combinator, base ) {
var dir = combinator.dir,
checkNonElements = base && dir === "parentNode",
doneName = done++;
return combinator.first ?
// Check against closest ancestor/preceding element
function( elem, context, xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
return matcher( elem, context, xml );
}
}
} :
// Check against all ancestor/preceding elements
function( elem, context, xml ) {
var oldCache, uniqueCache, outerCache,
newCache = [ dirruns, doneName ];
// We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching
if ( xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
if ( matcher( elem, context, xml ) ) {
return true;
}
}
}
} else {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
outerCache = elem[ expando ] || (elem[ expando ] = {});
// Support: IE <9 only
// Defend against cloned attroperties (jQuery gh-1709)
uniqueCache = outerCache[ elem.uniqueID ] || (outerCache[ elem.uniqueID ] = {});
if ( (oldCache = uniqueCache[ dir ]) &&
oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) {
// Assign to newCache so results back-propagate to previous elements
return (newCache[ 2 ] = oldCache[ 2 ]);
} else {
// Reuse newcache so results back-propagate to previous elements
uniqueCache[ dir ] = newCache;
// A match means we're done; a fail means we have to keep checking
if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) {
return true;
}
}
}
}
}
};
}
function elementMatcher( matchers ) {
return matchers.length > 1 ?
function( elem, context, xml ) {
var i = matchers.length;
while ( i-- ) {
if ( !matchers[i]( elem, context, xml ) ) {
return false;
}
}
return true;
} :
matchers[0];
}
function multipleContexts( selector, contexts, results ) {
var i = 0,
len = contexts.length;
for ( ; i < len; i++ ) {
Sizzle( selector, contexts[i], results );
}
return results;
}
function condense( unmatched, map, filter, context, xml ) {
var elem,
newUnmatched = [],
i = 0,
len = unmatched.length,
mapped = map != null;
for ( ; i < len; i++ ) {
if ( (elem = unmatched[i]) ) {
if ( !filter || filter( elem, context, xml ) ) {
newUnmatched.push( elem );
if ( mapped ) {
map.push( i );
}
}
}
}
return newUnmatched;
}
function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
if ( postFilter && !postFilter[ expando ] ) {
postFilter = setMatcher( postFilter );
}
if ( postFinder && !postFinder[ expando ] ) {
postFinder = setMatcher( postFinder, postSelector );
}
return markFunction(function( seed, results, context, xml ) {
var temp, i, elem,
preMap = [],
postMap = [],
preexisting = results.length,
// Get initial elements from seed or context
elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),
// Prefilter to get matcher input, preserving a map for seed-results synchronization
matcherIn = preFilter && ( seed || !selector ) ?
condense( elems, preMap, preFilter, context, xml ) :
elems,
matcherOut = matcher ?
// If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
// ...intermediate processing is necessary
[] :
// ...otherwise use results directly
results :
matcherIn;
// Find primary matches
if ( matcher ) {
matcher( matcherIn, matcherOut, context, xml );
}
// Apply postFilter
if ( postFilter ) {
temp = condense( matcherOut, postMap );
postFilter( temp, [], context, xml );
// Un-match failing elements by moving them back to matcherIn
i = temp.length;
while ( i-- ) {
if ( (elem = temp[i]) ) {
matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
}
}
}
if ( seed ) {
if ( postFinder || preFilter ) {
if ( postFinder ) {
// Get the final matcherOut by condensing this intermediate into postFinder contexts
temp = [];
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) ) {
// Restore matcherIn since elem is not yet a final match
temp.push( (matcherIn[i] = elem) );
}
}
postFinder( null, (matcherOut = []), temp, xml );
}
// Move matched elements from seed to results to keep them synchronized
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) &&
(temp = postFinder ? indexOf( seed, elem ) : preMap[i]) > -1 ) {
seed[temp] = !(results[temp] = elem);
}
}
}
// Add elements to results, through postFinder if defined
} else {
matcherOut = condense(
matcherOut === results ?
matcherOut.splice( preexisting, matcherOut.length ) :
matcherOut
);
if ( postFinder ) {
postFinder( null, results, matcherOut, xml );
} else {
push.apply( results, matcherOut );
}
}
});
}
function matcherFromTokens( tokens ) {
var checkContext, matcher, j,
len = tokens.length,
leadingRelative = Expr.relative[ tokens[0].type ],
implicitRelative = leadingRelative || Expr.relative[" "],
i = leadingRelative ? 1 : 0,
// The foundational matcher ensures that elements are reachable from top-level context(s)
matchContext = addCombinator( function( elem ) {
return elem === checkContext;
}, implicitRelative, true ),
matchAnyContext = addCombinator( function( elem ) {
return indexOf( checkContext, elem ) > -1;
}, implicitRelative, true ),
matchers = [ function( elem, context, xml ) {
var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
(checkContext = context).nodeType ?
matchContext( elem, context, xml ) :
matchAnyContext( elem, context, xml ) );
// Avoid hanging onto element (issue #299)
checkContext = null;
return ret;
} ];
for ( ; i < len; i++ ) {
if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
matchers = [ addCombinator(elementMatcher( matchers ), matcher) ];
} else {
matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );
// Return special upon seeing a positional matcher
if ( matcher[ expando ] ) {
// Find the next relative operator (if any) for proper handling
j = ++i;
for ( ; j < len; j++ ) {
if ( Expr.relative[ tokens[j].type ] ) {
break;
}
}
return setMatcher(
i > 1 && elementMatcher( matchers ),
i > 1 && toSelector(
// If the preceding token was a descendant combinator, insert an implicit any-element `*`
tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" })
).replace( rtrim, "$1" ),
matcher,
i < j && matcherFromTokens( tokens.slice( i, j ) ),
j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
j < len && toSelector( tokens )
);
}
matchers.push( matcher );
}
}
return elementMatcher( matchers );
}
function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
var bySet = setMatchers.length > 0,
byElement = elementMatchers.length > 0,
superMatcher = function( seed, context, xml, results, outermost ) {
var elem, j, matcher,
matchedCount = 0,
i = "0",
unmatched = seed && [],
setMatched = [],
contextBackup = outermostContext,
// We must always have either seed elements or outermost context
elems = seed || byElement && Expr.find["TAG"]( "*", outermost ),
// Use integer dirruns iff this is the outermost matcher
dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1),
len = elems.length;
if ( outermost ) {
outermostContext = context === document || context || outermost;
}
// Add elements passing elementMatchers directly to results
// Support: IE<9, Safari
// Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id
for ( ; i !== len && (elem = elems[i]) != null; i++ ) {
if ( byElement && elem ) {
j = 0;
if ( !context && elem.ownerDocument !== document ) {
setDocument( elem );
xml = !documentIsHTML;
}
while ( (matcher = elementMatchers[j++]) ) {
if ( matcher( elem, context || document, xml) ) {
results.push( elem );
break;
}
}
if ( outermost ) {
dirruns = dirrunsUnique;
}
}
// Track unmatched elements for set filters
if ( bySet ) {
// They will have gone through all possible matchers
if ( (elem = !matcher && elem) ) {
matchedCount--;
}
// Lengthen the array for every element, matched or not
if ( seed ) {
unmatched.push( elem );
}
}
}
// `i` is now the count of elements visited above, and adding it to `matchedCount`
// makes the latter nonnegative.
matchedCount += i;
// Apply set filters to unmatched elements
// NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount`
// equals `i`), unless we didn't visit _any_ elements in the above loop because we have
// no element matchers and no seed.
// Incrementing an initially-string "0" `i` allows `i` to remain a string only in that
// case, which will result in a "00" `matchedCount` that differs from `i` but is also
// numerically zero.
if ( bySet && i !== matchedCount ) {
j = 0;
while ( (matcher = setMatchers[j++]) ) {
matcher( unmatched, setMatched, context, xml );
}
if ( seed ) {
// Reintegrate element matches to eliminate the need for sorting
if ( matchedCount > 0 ) {
while ( i-- ) {
if ( !(unmatched[i] || setMatched[i]) ) {
setMatched[i] = pop.call( results );
}
}
}
// Discard index placeholder values to get only actual matches
setMatched = condense( setMatched );
}
// Add matches to results
push.apply( results, setMatched );
// Seedless set matches succeeding multiple successful matchers stipulate sorting
if ( outermost && !seed && setMatched.length > 0 &&
( matchedCount + setMatchers.length ) > 1 ) {
Sizzle.uniqueSort( results );
}
}
// Override manipulation of globals by nested matchers
if ( outermost ) {
dirruns = dirrunsUnique;
outermostContext = contextBackup;
}
return unmatched;
};
return bySet ?
markFunction( superMatcher ) :
superMatcher;
}
compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) {
var i,
setMatchers = [],
elementMatchers = [],
cached = compilerCache[ selector + " " ];
if ( !cached ) {
// Generate a function of recursive functions that can be used to check each element
if ( !match ) {
match = tokenize( selector );
}
i = match.length;
while ( i-- ) {
cached = matcherFromTokens( match[i] );
if ( cached[ expando ] ) {
setMatchers.push( cached );
} else {
elementMatchers.push( cached );
}
}
// Cache the compiled function
cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
// Save selector and tokenization
cached.selector = selector;
}
return cached;
};
/**
* A low-level selection function that works with Sizzle's compiled
* selector functions
* @param {String|Function} selector A selector or a pre-compiled
* selector function built with Sizzle.compile
* @param {Element} context
* @param {Array} [results]
* @param {Array} [seed] A set of elements to match against
*/
select = Sizzle.select = function( selector, context, results, seed ) {
var i, tokens, token, type, find,
compiled = typeof selector === "function" && selector,
match = !seed && tokenize( (selector = compiled.selector || selector) );
results = results || [];
// Try to minimize operations if there is only one selector in the list and no seed
// (the latter of which guarantees us context)
if ( match.length === 1 ) {
// Reduce context if the leading compound selector is an ID
tokens = match[0] = match[0].slice( 0 );
if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
support.getById && context.nodeType === 9 && documentIsHTML &&
Expr.relative[ tokens[1].type ] ) {
context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0];
if ( !context ) {
return results;
// Precompiled matchers will still verify ancestry, so step up a level
} else if ( compiled ) {
context = context.parentNode;
}
selector = selector.slice( tokens.shift().value.length );
}
// Fetch a seed set for right-to-left matching
i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length;
while ( i-- ) {
token = tokens[i];
// Abort if we hit a combinator
if ( Expr.relative[ (type = token.type) ] ) {
break;
}
if ( (find = Expr.find[ type ]) ) {
// Search, expanding context for leading sibling combinators
if ( (seed = find(
token.matches[0].replace( runescape, funescape ),
rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context
)) ) {
// If seed is empty or no tokens remain, we can return early
tokens.splice( i, 1 );
selector = seed.length && toSelector( tokens );
if ( !selector ) {
push.apply( results, seed );
return results;
}
break;
}
}
}
}
// Compile and execute a filtering function if one is not provided
// Provide `match` to avoid retokenization if we modified the selector above
( compiled || compile( selector, match ) )(
seed,
context,
!documentIsHTML,
results,
!context || rsibling.test( selector ) && testContext( context.parentNode ) || context
);
return results;
};
// One-time assignments
// Sort stability
support.sortStable = expando.split("").sort( sortOrder ).join("") === expando;
// Support: Chrome 14-35+
// Always assume duplicates if they aren't passed to the comparison function
support.detectDuplicates = !!hasDuplicate;
// Initialize against the default document
setDocument();
// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27)
// Detached nodes confoundingly follow *each other*
support.sortDetached = assert(function( div1 ) {
// Should return 1, but returns 4 (following)
return div1.compareDocumentPosition( document.createElement("div") ) & 1;
});
// Support: IE<8
// Prevent attribute/property "interpolation"
// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
if ( !assert(function( div ) {
div.innerHTML = "<a href='#'></a>";
return div.firstChild.getAttribute("href") === "#" ;
}) ) {
addHandle( "type|href|height|width", function( elem, name, isXML ) {
if ( !isXML ) {
return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 );
}
});
}
// Support: IE<9
// Use defaultValue in place of getAttribute("value")
if ( !support.attributes || !assert(function( div ) {
div.innerHTML = "<input/>";
div.firstChild.setAttribute( "value", "" );
return div.firstChild.getAttribute( "value" ) === "";
}) ) {
addHandle( "value", function( elem, name, isXML ) {
if ( !isXML && elem.nodeName.toLowerCase() === "input" ) {
return elem.defaultValue;
}
});
}
// Support: IE<9
// Use getAttributeNode to fetch booleans when getAttribute lies
if ( !assert(function( div ) {
return div.getAttribute("disabled") == null;
}) ) {
addHandle( booleans, function( elem, name, isXML ) {
var val;
if ( !isXML ) {
return elem[ name ] === true ? name.toLowerCase() :
(val = elem.getAttributeNode( name )) && val.specified ?
val.value :
null;
}
});
}
return Sizzle;
})( window );
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[ ":" ] = jQuery.expr.pseudos;
jQuery.uniqueSort = jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
var dir = function( elem, dir, until ) {
var matched = [],
truncate = until !== undefined;
while ( ( elem = elem[ dir ] ) && elem.nodeType !== 9 ) {
if ( elem.nodeType === 1 ) {
if ( truncate && jQuery( elem ).is( until ) ) {
break;
}
matched.push( elem );
}
}
return matched;
};
var siblings = function( n, elem ) {
var matched = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
matched.push( n );
}
}
return matched;
};
var rneedsContext = jQuery.expr.match.needsContext;
var rsingleTag = ( /^<([\w-]+)\s*\/?>(?:<\/\1>|)$/ );
var risSimple = /^.[^:#\[\.,]*$/;
// Implement the identical functionality for filter and not
function winnow( elements, qualifier, not ) {
if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep( elements, function( elem, i ) {
/* jshint -W018 */
return !!qualifier.call( elem, i, elem ) !== not;
} );
}
if ( qualifier.nodeType ) {
return jQuery.grep( elements, function( elem ) {
return ( elem === qualifier ) !== not;
} );
}
if ( typeof qualifier === "string" ) {
if ( risSimple.test( qualifier ) ) {
return jQuery.filter( qualifier, elements, not );
}
qualifier = jQuery.filter( qualifier, elements );
}
return jQuery.grep( elements, function( elem ) {
return ( jQuery.inArray( elem, qualifier ) > -1 ) !== not;
} );
}
jQuery.filter = function( expr, elems, not ) {
var elem = elems[ 0 ];
if ( not ) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 && elem.nodeType === 1 ?
jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] :
jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) {
return elem.nodeType === 1;
} ) );
};
jQuery.fn.extend( {
find: function( selector ) {
var i,
ret = [],
self = this,
len = self.length;
if ( typeof selector !== "string" ) {
return this.pushStack( jQuery( selector ).filter( function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( self[ i ], this ) ) {
return true;
}
}
} ) );
}
for ( i = 0; i < len; i++ ) {
jQuery.find( selector, self[ i ], ret );
}
// Needed because $( selector, context ) becomes $( context ).find( selector )
ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret );
ret.selector = this.selector ? this.selector + " " + selector : selector;
return ret;
},
filter: function( selector ) {
return this.pushStack( winnow( this, selector || [], false ) );
},
not: function( selector ) {
return this.pushStack( winnow( this, selector || [], true ) );
},
is: function( selector ) {
return !!winnow(
this,
// If this is a positional/relative selector, check membership in the returned set
// so $("p:first").is("p:last") won't return true for a doc with two "p".
typeof selector === "string" && rneedsContext.test( selector ) ?
jQuery( selector ) :
selector || [],
false
).length;
}
} );
// Initialize a jQuery object
// A central reference to the root jQuery(document)
var rootjQuery,
// A simple way to check for HTML strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
// Strict HTML recognition (#11290: must start with <)
rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,
init = jQuery.fn.init = function( selector, context, root ) {
var match, elem;
// HANDLE: $(""), $(null), $(undefined), $(false)
if ( !selector ) {
return this;
}
// init accepts an alternate rootjQuery
// so migrate can support jQuery.sub (gh-2101)
root = root || rootjQuery;
// Handle HTML strings
if ( typeof selector === "string" ) {
if ( selector.charAt( 0 ) === "<" &&
selector.charAt( selector.length - 1 ) === ">" &&
selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = rquickExpr.exec( selector );
}
// Match html or make sure no context is specified for #id
if ( match && ( match[ 1 ] || !context ) ) {
// HANDLE: $(html) -> $(array)
if ( match[ 1 ] ) {
context = context instanceof jQuery ? context[ 0 ] : context;
// scripts is true for back-compat
// Intentionally let the error be thrown if parseHTML is not present
jQuery.merge( this, jQuery.parseHTML(
match[ 1 ],
context && context.nodeType ? context.ownerDocument || context : document,
true
) );
// HANDLE: $(html, props)
if ( rsingleTag.test( match[ 1 ] ) && jQuery.isPlainObject( context ) ) {
for ( match in context ) {
// Properties of context are called as methods if possible
if ( jQuery.isFunction( this[ match ] ) ) {
this[ match ]( context[ match ] );
// ...and otherwise set as attributes
} else {
this.attr( match, context[ match ] );
}
}
}
return this;
// HANDLE: $(#id)
} else {
elem = document.getElementById( match[ 2 ] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id !== match[ 2 ] ) {
return rootjQuery.find( selector );
}
// Otherwise, we inject the element directly into the jQuery object
this.length = 1;
this[ 0 ] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return ( context || root ).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(DOMElement)
} else if ( selector.nodeType ) {
this.context = this[ 0 ] = selector;
this.length = 1;
return this;
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return typeof root.ready !== "undefined" ?
root.ready( selector ) :
// Execute immediately if ready is not present
selector( jQuery );
}
if ( selector.selector !== undefined ) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
};
// Give the init function the jQuery prototype for later instantiation
init.prototype = jQuery.fn;
// Initialize central reference
rootjQuery = jQuery( document );
var rparentsprev = /^(?:parents|prev(?:Until|All))/,
// methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.fn.extend( {
has: function( target ) {
var i,
targets = jQuery( target, this ),
len = targets.length;
return this.filter( function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( this, targets[ i ] ) ) {
return true;
}
}
} );
},
closest: function( selectors, context ) {
var cur,
i = 0,
l = this.length,
matched = [],
pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ?
jQuery( selectors, context || this.context ) :
0;
for ( ; i < l; i++ ) {
for ( cur = this[ i ]; cur && cur !== context; cur = cur.parentNode ) {
// Always skip document fragments
if ( cur.nodeType < 11 && ( pos ?
pos.index( cur ) > -1 :
// Don't pass non-elements to Sizzle
cur.nodeType === 1 &&
jQuery.find.matchesSelector( cur, selectors ) ) ) {
matched.push( cur );
break;
}
}
}
return this.pushStack( matched.length > 1 ? jQuery.uniqueSort( matched ) : matched );
},
// Determine the position of an element within
// the matched set of elements
index: function( elem ) {
// No argument, return index in parent
if ( !elem ) {
return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1;
}
// index in selector
if ( typeof elem === "string" ) {
return jQuery.inArray( this[ 0 ], jQuery( elem ) );
}
// Locate the position of the desired element
return jQuery.inArray(
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[ 0 ] : elem, this );
},
add: function( selector, context ) {
return this.pushStack(
jQuery.uniqueSort(
jQuery.merge( this.get(), jQuery( selector, context ) )
)
);
},
addBack: function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter( selector )
);
}
} );
function sibling( cur, dir ) {
do {
cur = cur[ dir ];
} while ( cur && cur.nodeType !== 1 );
return cur;
}
jQuery.each( {
parent: function( elem ) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function( elem ) {
return dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return dir( elem, "parentNode", until );
},
next: function( elem ) {
return sibling( elem, "nextSibling" );
},
prev: function( elem ) {
return sibling( elem, "previousSibling" );
},
nextAll: function( elem ) {
return dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return siblings( ( elem.parentNode || {} ).firstChild, elem );
},
children: function( elem ) {
return siblings( elem.firstChild );
},
contents: function( elem ) {
return jQuery.nodeName( elem, "iframe" ) ?
elem.contentDocument || elem.contentWindow.document :
jQuery.merge( [], elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
var ret = jQuery.map( this, fn, until );
if ( name.slice( -5 ) !== "Until" ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
ret = jQuery.filter( selector, ret );
}
if ( this.length > 1 ) {
// Remove duplicates
if ( !guaranteedUnique[ name ] ) {
ret = jQuery.uniqueSort( ret );
}
// Reverse order for parents* and prev-derivatives
if ( rparentsprev.test( name ) ) {
ret = ret.reverse();
}
}
return this.pushStack( ret );
};
} );
var rnotwhite = ( /\S+/g );
// Convert String-formatted options into Object-formatted ones
function createOptions( options ) {
var object = {};
jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) {
object[ flag ] = true;
} );
return object;
}
/*
* Create a callback list using the following parameters:
*
* options: an optional list of space-separated options that will change how
* the callback list behaves or a more traditional option object
*
* By default a callback list will act like an event callback list and can be
* "fired" multiple times.
*
* Possible options:
*
* once: will ensure the callback list can only be fired once (like a Deferred)
*
* memory: will keep track of previous values and will call any callback added
* after the list has been fired right away with the latest "memorized"
* values (like a Deferred)
*
* unique: will ensure a callback can only be added once (no duplicate in the list)
*
* stopOnFalse: interrupt callings when a callback returns false
*
*/
jQuery.Callbacks = function( options ) {
// Convert options from String-formatted to Object-formatted if needed
// (we check in cache first)
options = typeof options === "string" ?
createOptions( options ) :
jQuery.extend( {}, options );
var // Flag to know if list is currently firing
firing,
// Last fire value for non-forgettable lists
memory,
// Flag to know if list was already fired
fired,
// Flag to prevent firing
locked,
// Actual callback list
list = [],
// Queue of execution data for repeatable lists
queue = [],
// Index of currently firing callback (modified by add/remove as needed)
firingIndex = -1,
// Fire callbacks
fire = function() {
// Enforce single-firing
locked = options.once;
// Execute callbacks for all pending executions,
// respecting firingIndex overrides and runtime changes
fired = firing = true;
for ( ; queue.length; firingIndex = -1 ) {
memory = queue.shift();
while ( ++firingIndex < list.length ) {
// Run callback and check for early termination
if ( list[ firingIndex ].apply( memory[ 0 ], memory[ 1 ] ) === false &&
options.stopOnFalse ) {
// Jump to end and forget the data so .add doesn't re-fire
firingIndex = list.length;
memory = false;
}
}
}
// Forget the data if we're done with it
if ( !options.memory ) {
memory = false;
}
firing = false;
// Clean up if we're done firing for good
if ( locked ) {
// Keep an empty list if we have data for future add calls
if ( memory ) {
list = [];
// Otherwise, this object is spent
} else {
list = "";
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
// If we have memory from a past run, we should fire after adding
if ( memory && !firing ) {
firingIndex = list.length - 1;
queue.push( memory );
}
( function add( args ) {
jQuery.each( args, function( _, arg ) {
if ( jQuery.isFunction( arg ) ) {
if ( !options.unique || !self.has( arg ) ) {
list.push( arg );
}
} else if ( arg && arg.length && jQuery.type( arg ) !== "string" ) {
// Inspect recursively
add( arg );
}
} );
} )( arguments );
if ( memory && !firing ) {
fire();
}
}
return this;
},
// Remove a callback from the list
remove: function() {
jQuery.each( arguments, function( _, arg ) {
var index;
while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
list.splice( index, 1 );
// Handle firing indexes
if ( index <= firingIndex ) {
firingIndex--;
}
}
} );
return this;
},
// Check if a given callback is in the list.
// If no argument is given, return whether or not list has callbacks attached.
has: function( fn ) {
return fn ?
jQuery.inArray( fn, list ) > -1 :
list.length > 0;
},
// Remove all callbacks from the list
empty: function() {
if ( list ) {
list = [];
}
return this;
},
// Disable .fire and .add
// Abort any current/pending executions
// Clear all callbacks and values
disable: function() {
locked = queue = [];
list = memory = "";
return this;
},
disabled: function() {
return !list;
},
// Disable .fire
// Also disable .add unless we have memory (since it would have no effect)
// Abort any pending executions
lock: function() {
locked = true;
if ( !memory ) {
self.disable();
}
return this;
},
locked: function() {
return !!locked;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
if ( !locked ) {
args = args || [];
args = [ context, args.slice ? args.slice() : args ];
queue.push( args );
if ( !firing ) {
fire();
}
}
return this;
},
// Call all the callbacks with the given arguments
fire: function() {
self.fireWith( this, arguments );
return this;
},
// To know if the callbacks have already been called at least once
fired: function() {
return !!fired;
}
};
return self;
};
jQuery.extend( {
Deferred: function( func ) {
var tuples = [
// action, add listener, listener list, final state
[ "resolve", "done", jQuery.Callbacks( "once memory" ), "resolved" ],
[ "reject", "fail", jQuery.Callbacks( "once memory" ), "rejected" ],
[ "notify", "progress", jQuery.Callbacks( "memory" ) ]
],
state = "pending",
promise = {
state: function() {
return state;
},
always: function() {
deferred.done( arguments ).fail( arguments );
return this;
},
then: function( /* fnDone, fnFail, fnProgress */ ) {
var fns = arguments;
return jQuery.Deferred( function( newDefer ) {
jQuery.each( tuples, function( i, tuple ) {
var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ];
// deferred[ done | fail | progress ] for forwarding actions to newDefer
deferred[ tuple[ 1 ] ]( function() {
var returned = fn && fn.apply( this, arguments );
if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise()
.progress( newDefer.notify )
.done( newDefer.resolve )
.fail( newDefer.reject );
} else {
newDefer[ tuple[ 0 ] + "With" ](
this === promise ? newDefer.promise() : this,
fn ? [ returned ] : arguments
);
}
} );
} );
fns = null;
} ).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
return obj != null ? jQuery.extend( obj, promise ) : promise;
}
},
deferred = {};
// Keep pipe for back-compat
promise.pipe = promise.then;
// Add list-specific methods
jQuery.each( tuples, function( i, tuple ) {
var list = tuple[ 2 ],
stateString = tuple[ 3 ];
// promise[ done | fail | progress ] = list.add
promise[ tuple[ 1 ] ] = list.add;
// Handle state
if ( stateString ) {
list.add( function() {
// state = [ resolved | rejected ]
state = stateString;
// [ reject_list | resolve_list ].disable; progress_list.lock
}, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );
}
// deferred[ resolve | reject | notify ]
deferred[ tuple[ 0 ] ] = function() {
deferred[ tuple[ 0 ] + "With" ]( this === deferred ? promise : this, arguments );
return this;
};
deferred[ tuple[ 0 ] + "With" ] = list.fireWith;
} );
// Make the deferred a promise
promise.promise( deferred );
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
// All done!
return deferred;
},
// Deferred helper
when: function( subordinate /* , ..., subordinateN */ ) {
var i = 0,
resolveValues = slice.call( arguments ),
length = resolveValues.length,
// the count of uncompleted subordinates
remaining = length !== 1 ||
( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0,
// the master Deferred.
// If resolveValues consist of only a single Deferred, just use that.
deferred = remaining === 1 ? subordinate : jQuery.Deferred(),
// Update function for both resolve and progress values
updateFunc = function( i, contexts, values ) {
return function( value ) {
contexts[ i ] = this;
values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value;
if ( values === progressValues ) {
deferred.notifyWith( contexts, values );
} else if ( !( --remaining ) ) {
deferred.resolveWith( contexts, values );
}
};
},
progressValues, progressContexts, resolveContexts;
// add listeners to Deferred subordinates; treat others as resolved
if ( length > 1 ) {
progressValues = new Array( length );
progressContexts = new Array( length );
resolveContexts = new Array( length );
for ( ; i < length; i++ ) {
if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) {
resolveValues[ i ].promise()
.progress( updateFunc( i, progressContexts, progressValues ) )
.done( updateFunc( i, resolveContexts, resolveValues ) )
.fail( deferred.reject );
} else {
--remaining;
}
}
}
// if we're not waiting on anything, resolve the master
if ( !remaining ) {
deferred.resolveWith( resolveContexts, resolveValues );
}
return deferred.promise();
}
} );
// The deferred used on DOM ready
var readyList;
jQuery.fn.ready = function( fn ) {
// Add the callback
jQuery.ready.promise().done( fn );
return this;
};
jQuery.extend( {
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready
ready: function( wait ) {
// Abort if there are pending holds or we're already ready
if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
return;
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.triggerHandler ) {
jQuery( document ).triggerHandler( "ready" );
jQuery( document ).off( "ready" );
}
}
} );
/**
* Clean-up method for dom ready events
*/
function detach() {
if ( document.addEventListener ) {
document.removeEventListener( "DOMContentLoaded", completed );
window.removeEventListener( "load", completed );
} else {
document.detachEvent( "onreadystatechange", completed );
window.detachEvent( "onload", completed );
}
}
/**
* The ready event handler and self cleanup method
*/
function completed() {
// readyState === "complete" is good enough for us to call the dom ready in oldIE
if ( document.addEventListener ||
window.event.type === "load" ||
document.readyState === "complete" ) {
detach();
jQuery.ready();
}
}
jQuery.ready.promise = function( obj ) {
if ( !readyList ) {
readyList = jQuery.Deferred();
// Catch cases where $(document).ready() is called
// after the browser event has already occurred.
// Support: IE6-10
// Older IE sometimes signals "interactive" too soon
if ( document.readyState === "complete" ||
( document.readyState !== "loading" && !document.documentElement.doScroll ) ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
window.setTimeout( jQuery.ready );
// Standards-based browsers support DOMContentLoaded
} else if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", completed );
// A fallback to window.onload, that will always work
window.addEventListener( "load", completed );
// If IE event model is used
} else {
// Ensure firing before onload, maybe late but safe also for iframes
document.attachEvent( "onreadystatechange", completed );
// A fallback to window.onload, that will always work
window.attachEvent( "onload", completed );
// If IE and not a frame
// continually check to see if the document is ready
var top = false;
try {
top = window.frameElement == null && document.documentElement;
} catch ( e ) {}
if ( top && top.doScroll ) {
( function doScrollCheck() {
if ( !jQuery.isReady ) {
try {
// Use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
top.doScroll( "left" );
} catch ( e ) {
return window.setTimeout( doScrollCheck, 50 );
}
// detach all dom ready events
detach();
// and execute any waiting functions
jQuery.ready();
}
} )();
}
}
}
return readyList.promise( obj );
};
// Kick off the DOM ready check even if the user does not
jQuery.ready.promise();
// Support: IE<9
// Iteration over object's inherited properties before its own
var i;
for ( i in jQuery( support ) ) {
break;
}
support.ownFirst = i === "0";
// Note: most support tests are defined in their respective modules.
// false until the test is run
support.inlineBlockNeedsLayout = false;
// Execute ASAP in case we need to set body.style.zoom
jQuery( function() {
// Minified: var a,b,c,d
var val, div, body, container;
body = document.getElementsByTagName( "body" )[ 0 ];
if ( !body || !body.style ) {
// Return for frameset docs that don't have a body
return;
}
// Setup
div = document.createElement( "div" );
container = document.createElement( "div" );
container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px";
body.appendChild( container ).appendChild( div );
if ( typeof div.style.zoom !== "undefined" ) {
// Support: IE<8
// Check if natively block-level elements act like inline-block
// elements when setting their display to 'inline' and giving
// them layout
div.style.cssText = "display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1";
support.inlineBlockNeedsLayout = val = div.offsetWidth === 3;
if ( val ) {
// Prevent IE 6 from affecting layout for positioned elements #11048
// Prevent IE from shrinking the body in IE 7 mode #12869
// Support: IE<8
body.style.zoom = 1;
}
}
body.removeChild( container );
} );
( function() {
var div = document.createElement( "div" );
// Support: IE<9
support.deleteExpando = true;
try {
delete div.test;
} catch ( e ) {
support.deleteExpando = false;
}
// Null elements to avoid leaks in IE.
div = null;
} )();
var acceptData = function( elem ) {
var noData = jQuery.noData[ ( elem.nodeName + " " ).toLowerCase() ],
nodeType = +elem.nodeType || 1;
// Do not set data on non-element DOM nodes because it will not be cleared (#8335).
return nodeType !== 1 && nodeType !== 9 ?
false :
// Nodes accept data unless otherwise specified; rejection can be conditional
!noData || noData !== true && elem.getAttribute( "classid" ) === noData;
};
var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,
rmultiDash = /([A-Z])/g;
function dataAttr( elem, key, data ) {
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
// Only convert to a number if it doesn't change the string
+data + "" === data ? +data :
rbrace.test( data ) ? jQuery.parseJSON( data ) :
data;
} catch ( e ) {}
// Make sure we set the data so it isn't changed later
jQuery.data( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
// checks a cache object for emptiness
function isEmptyDataObject( obj ) {
var name;
for ( name in obj ) {
// if the public data object is empty, the private is still empty
if ( name === "data" && jQuery.isEmptyObject( obj[ name ] ) ) {
continue;
}
if ( name !== "toJSON" ) {
return false;
}
}
return true;
}
function internalData( elem, name, data, pvt /* Internal Use Only */ ) {
if ( !acceptData( elem ) ) {
return;
}
var ret, thisCache,
internalKey = jQuery.expando,
// We have to handle DOM nodes and JS objects differently because IE6-7
// can't GC object references properly across the DOM-JS boundary
isNode = elem.nodeType,
// Only DOM nodes need the global jQuery cache; JS object data is
// attached directly to the object so GC can occur automatically
cache = isNode ? jQuery.cache : elem,
// Only defining an ID for JS objects if its cache already exists allows
// the code to shortcut on the same path as a DOM node with no cache
id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey;
// Avoid doing any more work than we need to when trying to get data on an
// object that has no data at all
if ( ( !id || !cache[ id ] || ( !pvt && !cache[ id ].data ) ) &&
data === undefined && typeof name === "string" ) {
return;
}
if ( !id ) {
// Only DOM nodes need a new unique ID for each element since their data
// ends up in the global cache
if ( isNode ) {
id = elem[ internalKey ] = deletedIds.pop() || jQuery.guid++;
} else {
id = internalKey;
}
}
if ( !cache[ id ] ) {
// Avoid exposing jQuery metadata on plain JS objects when the object
// is serialized using JSON.stringify
cache[ id ] = isNode ? {} : { toJSON: jQuery.noop };
}
// An object can be passed to jQuery.data instead of a key/value pair; this gets
// shallow copied over onto the existing cache
if ( typeof name === "object" || typeof name === "function" ) {
if ( pvt ) {
cache[ id ] = jQuery.extend( cache[ id ], name );
} else {
cache[ id ].data = jQuery.extend( cache[ id ].data, name );
}
}
thisCache = cache[ id ];
// jQuery data() is stored in a separate object inside the object's internal data
// cache in order to avoid key collisions between internal data and user-defined
// data.
if ( !pvt ) {
if ( !thisCache.data ) {
thisCache.data = {};
}
thisCache = thisCache.data;
}
if ( data !== undefined ) {
thisCache[ jQuery.camelCase( name ) ] = data;
}
// Check for both converted-to-camel and non-converted data property names
// If a data property was specified
if ( typeof name === "string" ) {
// First Try to find as-is property data
ret = thisCache[ name ];
// Test for null|undefined property data
if ( ret == null ) {
// Try to find the camelCased property
ret = thisCache[ jQuery.camelCase( name ) ];
}
} else {
ret = thisCache;
}
return ret;
}
function internalRemoveData( elem, name, pvt ) {
if ( !acceptData( elem ) ) {
return;
}
var thisCache, i,
isNode = elem.nodeType,
// See jQuery.data for more information
cache = isNode ? jQuery.cache : elem,
id = isNode ? elem[ jQuery.expando ] : jQuery.expando;
// If there is already no cache entry for this object, there is no
// purpose in continuing
if ( !cache[ id ] ) {
return;
}
if ( name ) {
thisCache = pvt ? cache[ id ] : cache[ id ].data;
if ( thisCache ) {
// Support array or space separated string names for data keys
if ( !jQuery.isArray( name ) ) {
// try the string as a key before any manipulation
if ( name in thisCache ) {
name = [ name ];
} else {
// split the camel cased version by spaces unless a key with the spaces exists
name = jQuery.camelCase( name );
if ( name in thisCache ) {
name = [ name ];
} else {
name = name.split( " " );
}
}
} else {
// If "name" is an array of keys...
// When data is initially created, via ("key", "val") signature,
// keys will be converted to camelCase.
// Since there is no way to tell _how_ a key was added, remove
// both plain key and camelCase key. #12786
// This will only penalize the array argument path.
name = name.concat( jQuery.map( name, jQuery.camelCase ) );
}
i = name.length;
while ( i-- ) {
delete thisCache[ name[ i ] ];
}
// If there is no data left in the cache, we want to continue
// and let the cache object itself get destroyed
if ( pvt ? !isEmptyDataObject( thisCache ) : !jQuery.isEmptyObject( thisCache ) ) {
return;
}
}
}
// See jQuery.data for more information
if ( !pvt ) {
delete cache[ id ].data;
// Don't destroy the parent cache unless the internal data object
// had been the only thing left in it
if ( !isEmptyDataObject( cache[ id ] ) ) {
return;
}
}
// Destroy the cache
if ( isNode ) {
jQuery.cleanData( [ elem ], true );
// Use delete when supported for expandos or `cache` is not a window per isWindow (#10080)
/* jshint eqeqeq: false */
} else if ( support.deleteExpando || cache != cache.window ) {
/* jshint eqeqeq: true */
delete cache[ id ];
// When all else fails, undefined
} else {
cache[ id ] = undefined;
}
}
jQuery.extend( {
cache: {},
// The following elements (space-suffixed to avoid Object.prototype collisions)
// throw uncatchable exceptions if you attempt to set expando properties
noData: {
"applet ": true,
"embed ": true,
// ...but Flash objects (which have this classid) *can* handle expandos
"object ": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
},
hasData: function( elem ) {
elem = elem.nodeType ? jQuery.cache[ elem[ jQuery.expando ] ] : elem[ jQuery.expando ];
return !!elem && !isEmptyDataObject( elem );
},
data: function( elem, name, data ) {
return internalData( elem, name, data );
},
removeData: function( elem, name ) {
return internalRemoveData( elem, name );
},
// For internal use only.
_data: function( elem, name, data ) {
return internalData( elem, name, data, true );
},
_removeData: function( elem, name ) {
return internalRemoveData( elem, name, true );
}
} );
jQuery.fn.extend( {
data: function( key, value ) {
var i, name, data,
elem = this[ 0 ],
attrs = elem && elem.attributes;
// Special expections of .data basically thwart jQuery.access,
// so implement the relevant behavior ourselves
// Gets all values
if ( key === undefined ) {
if ( this.length ) {
data = jQuery.data( elem );
if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) {
i = attrs.length;
while ( i-- ) {
// Support: IE11+
// The attrs elements can be null (#14894)
if ( attrs[ i ] ) {
name = attrs[ i ].name;
if ( name.indexOf( "data-" ) === 0 ) {
name = jQuery.camelCase( name.slice( 5 ) );
dataAttr( elem, name, data[ name ] );
}
}
}
jQuery._data( elem, "parsedAttrs", true );
}
}
return data;
}
// Sets multiple values
if ( typeof key === "object" ) {
return this.each( function() {
jQuery.data( this, key );
} );
}
return arguments.length > 1 ?
// Sets one value
this.each( function() {
jQuery.data( this, key, value );
} ) :
// Gets one value
// Try to fetch any internally stored data first
elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : undefined;
},
removeData: function( key ) {
return this.each( function() {
jQuery.removeData( this, key );
} );
}
} );
jQuery.extend( {
queue: function( elem, type, data ) {
var queue;
if ( elem ) {
type = ( type || "fx" ) + "queue";
queue = jQuery._data( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !queue || jQuery.isArray( data ) ) {
queue = jQuery._data( elem, type, jQuery.makeArray( data ) );
} else {
queue.push( data );
}
}
return queue || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
startLength = queue.length,
fn = queue.shift(),
hooks = jQuery._queueHooks( elem, type ),
next = function() {
jQuery.dequeue( elem, type );
};
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
startLength--;
}
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift( "inprogress" );
}
// clear up the last queue stop function
delete hooks.stop;
fn.call( elem, next, hooks );
}
if ( !startLength && hooks ) {
hooks.empty.fire();
}
},
// not intended for public consumption - generates a queueHooks object,
// or returns the current one
_queueHooks: function( elem, type ) {
var key = type + "queueHooks";
return jQuery._data( elem, key ) || jQuery._data( elem, key, {
empty: jQuery.Callbacks( "once memory" ).add( function() {
jQuery._removeData( elem, type + "queue" );
jQuery._removeData( elem, key );
} )
} );
}
} );
jQuery.fn.extend( {
queue: function( type, data ) {
var setter = 2;
if ( typeof type !== "string" ) {
data = type;
type = "fx";
setter--;
}
if ( arguments.length < setter ) {
return jQuery.queue( this[ 0 ], type );
}
return data === undefined ?
this :
this.each( function() {
var queue = jQuery.queue( this, type, data );
// ensure a hooks for this queue
jQuery._queueHooks( this, type );
if ( type === "fx" && queue[ 0 ] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
} );
},
dequeue: function( type ) {
return this.each( function() {
jQuery.dequeue( this, type );
} );
},
clearQueue: function( type ) {
return this.queue( type || "fx", [] );
},
// Get a promise resolved when queues of a certain type
// are emptied (fx is the type by default)
promise: function( type, obj ) {
var tmp,
count = 1,
defer = jQuery.Deferred(),
elements = this,
i = this.length,
resolve = function() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
};
if ( typeof type !== "string" ) {
obj = type;
type = undefined;
}
type = type || "fx";
while ( i-- ) {
tmp = jQuery._data( elements[ i ], type + "queueHooks" );
if ( tmp && tmp.empty ) {
count++;
tmp.empty.add( resolve );
}
}
resolve();
return defer.promise( obj );
}
} );
( function() {
var shrinkWrapBlocksVal;
support.shrinkWrapBlocks = function() {
if ( shrinkWrapBlocksVal != null ) {
return shrinkWrapBlocksVal;
}
// Will be changed later if needed.
shrinkWrapBlocksVal = false;
// Minified: var b,c,d
var div, body, container;
body = document.getElementsByTagName( "body" )[ 0 ];
if ( !body || !body.style ) {
// Test fired too early or in an unsupported environment, exit.
return;
}
// Setup
div = document.createElement( "div" );
container = document.createElement( "div" );
container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px";
body.appendChild( container ).appendChild( div );
// Support: IE6
// Check if elements with layout shrink-wrap their children
if ( typeof div.style.zoom !== "undefined" ) {
// Reset CSS: box-sizing; display; margin; border
div.style.cssText =
// Support: Firefox<29, Android 2.3
// Vendor-prefix box-sizing
"-webkit-box-sizing:content-box;-moz-box-sizing:content-box;" +
"box-sizing:content-box;display:block;margin:0;border:0;" +
"padding:1px;width:1px;zoom:1";
div.appendChild( document.createElement( "div" ) ).style.width = "5px";
shrinkWrapBlocksVal = div.offsetWidth !== 3;
}
body.removeChild( container );
return shrinkWrapBlocksVal;
};
} )();
var pnum = ( /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/ ).source;
var rcssNum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" );
var cssExpand = [ "Top", "Right", "Bottom", "Left" ];
var isHidden = function( elem, el ) {
// isHidden might be called from jQuery#filter function;
// in that case, element will be second argument
elem = el || elem;
return jQuery.css( elem, "display" ) === "none" ||
!jQuery.contains( elem.ownerDocument, elem );
};
function adjustCSS( elem, prop, valueParts, tween ) {
var adjusted,
scale = 1,
maxIterations = 20,
currentValue = tween ?
function() { return tween.cur(); } :
function() { return jQuery.css( elem, prop, "" ); },
initial = currentValue(),
unit = valueParts && valueParts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ),
// Starting value computation is required for potential unit mismatches
initialInUnit = ( jQuery.cssNumber[ prop ] || unit !== "px" && +initial ) &&
rcssNum.exec( jQuery.css( elem, prop ) );
if ( initialInUnit && initialInUnit[ 3 ] !== unit ) {
// Trust units reported by jQuery.css
unit = unit || initialInUnit[ 3 ];
// Make sure we update the tween properties later on
valueParts = valueParts || [];
// Iteratively approximate from a nonzero starting point
initialInUnit = +initial || 1;
do {
// If previous iteration zeroed out, double until we get *something*.
// Use string for doubling so we don't accidentally see scale as unchanged below
scale = scale || ".5";
// Adjust and apply
initialInUnit = initialInUnit / scale;
jQuery.style( elem, prop, initialInUnit + unit );
// Update scale, tolerating zero or NaN from tween.cur()
// Break the loop if scale is unchanged or perfect, or if we've just had enough.
} while (
scale !== ( scale = currentValue() / initial ) && scale !== 1 && --maxIterations
);
}
if ( valueParts ) {
initialInUnit = +initialInUnit || +initial || 0;
// Apply relative offset (+=/-=) if specified
adjusted = valueParts[ 1 ] ?
initialInUnit + ( valueParts[ 1 ] + 1 ) * valueParts[ 2 ] :
+valueParts[ 2 ];
if ( tween ) {
tween.unit = unit;
tween.start = initialInUnit;
tween.end = adjusted;
}
}
return adjusted;
}
// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
var access = function( elems, fn, key, value, chainable, emptyGet, raw ) {
var i = 0,
length = elems.length,
bulk = key == null;
// Sets many values
if ( jQuery.type( key ) === "object" ) {
chainable = true;
for ( i in key ) {
access( elems, fn, i, key[ i ], true, emptyGet, raw );
}
// Sets one value
} else if ( value !== undefined ) {
chainable = true;
if ( !jQuery.isFunction( value ) ) {
raw = true;
}
if ( bulk ) {
// Bulk operations run against the entire set
if ( raw ) {
fn.call( elems, value );
fn = null;
// ...except when executing function values
} else {
bulk = fn;
fn = function( elem, key, value ) {
return bulk.call( jQuery( elem ), value );
};
}
}
if ( fn ) {
for ( ; i < length; i++ ) {
fn(
elems[ i ],
key,
raw ? value : value.call( elems[ i ], i, fn( elems[ i ], key ) )
);
}
}
}
return chainable ?
elems :
// Gets
bulk ?
fn.call( elems ) :
length ? fn( elems[ 0 ], key ) : emptyGet;
};
var rcheckableType = ( /^(?:checkbox|radio)$/i );
var rtagName = ( /<([\w:-]+)/ );
var rscriptType = ( /^$|\/(?:java|ecma)script/i );
var rleadingWhitespace = ( /^\s+/ );
var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|" +
"details|dialog|figcaption|figure|footer|header|hgroup|main|" +
"mark|meter|nav|output|picture|progress|section|summary|template|time|video";
function createSafeFragment( document ) {
var list = nodeNames.split( "|" ),
safeFrag = document.createDocumentFragment();
if ( safeFrag.createElement ) {
while ( list.length ) {
safeFrag.createElement(
list.pop()
);
}
}
return safeFrag;
}
( function() {
var div = document.createElement( "div" ),
fragment = document.createDocumentFragment(),
input = document.createElement( "input" );
// Setup
div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
// IE strips leading whitespace when .innerHTML is used
support.leadingWhitespace = div.firstChild.nodeType === 3;
// Make sure that tbody elements aren't automatically inserted
// IE will insert them into empty tables
support.tbody = !div.getElementsByTagName( "tbody" ).length;
// Make sure that link elements get serialized correctly by innerHTML
// This requires a wrapper element in IE
support.htmlSerialize = !!div.getElementsByTagName( "link" ).length;
// Makes sure cloning an html5 element does not cause problems
// Where outerHTML is undefined, this still works
support.html5Clone =
document.createElement( "nav" ).cloneNode( true ).outerHTML !== "<:nav></:nav>";
// Check if a disconnected checkbox will retain its checked
// value of true after appended to the DOM (IE6/7)
input.type = "checkbox";
input.checked = true;
fragment.appendChild( input );
support.appendChecked = input.checked;
// Make sure textarea (and checkbox) defaultValue is properly cloned
// Support: IE6-IE11+
div.innerHTML = "<textarea>x</textarea>";
support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue;
// #11217 - WebKit loses check when the name is after the checked attribute
fragment.appendChild( div );
// Support: Windows Web Apps (WWA)
// `name` and `type` must use .setAttribute for WWA (#14901)
input = document.createElement( "input" );
input.setAttribute( "type", "radio" );
input.setAttribute( "checked", "checked" );
input.setAttribute( "name", "t" );
div.appendChild( input );
// Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3
// old WebKit doesn't clone checked state correctly in fragments
support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Support: IE<9
// Cloned elements keep attachEvent handlers, we use addEventListener on IE9+
support.noCloneEvent = !!div.addEventListener;
// Support: IE<9
// Since attributes and properties are the same in IE,
// cleanData must set properties to undefined rather than use removeAttribute
div[ jQuery.expando ] = 1;
support.attributes = !div.getAttribute( jQuery.expando );
} )();
// We have to close these tags to support XHTML (#13200)
var wrapMap = {
option: [ 1, "<select multiple='multiple'>", "</select>" ],
legend: [ 1, "<fieldset>", "</fieldset>" ],
area: [ 1, "<map>", "</map>" ],
// Support: IE8
param: [ 1, "<object>", "</object>" ],
thead: [ 1, "<table>", "</table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
// IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags,
// unless wrapped in a div with non-breaking characters in front of it.
_default: support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X<div>", "</div>" ]
};
// Support: IE8-IE9
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
function getAll( context, tag ) {
var elems, elem,
i = 0,
found = typeof context.getElementsByTagName !== "undefined" ?
context.getElementsByTagName( tag || "*" ) :
typeof context.querySelectorAll !== "undefined" ?
context.querySelectorAll( tag || "*" ) :
undefined;
if ( !found ) {
for ( found = [], elems = context.childNodes || context;
( elem = elems[ i ] ) != null;
i++
) {
if ( !tag || jQuery.nodeName( elem, tag ) ) {
found.push( elem );
} else {
jQuery.merge( found, getAll( elem, tag ) );
}
}
}
return tag === undefined || tag && jQuery.nodeName( context, tag ) ?
jQuery.merge( [ context ], found ) :
found;
}
// Mark scripts as having already been evaluated
function setGlobalEval( elems, refElements ) {
var elem,
i = 0;
for ( ; ( elem = elems[ i ] ) != null; i++ ) {
jQuery._data(
elem,
"globalEval",
!refElements || jQuery._data( refElements[ i ], "globalEval" )
);
}
}
var rhtml = /<|&#?\w+;/,
rtbody = /<tbody/i;
function fixDefaultChecked( elem ) {
if ( rcheckableType.test( elem.type ) ) {
elem.defaultChecked = elem.checked;
}
}
function buildFragment( elems, context, scripts, selection, ignored ) {
var j, elem, contains,
tmp, tag, tbody, wrap,
l = elems.length,
// Ensure a safe fragment
safe = createSafeFragment( context ),
nodes = [],
i = 0;
for ( ; i < l; i++ ) {
elem = elems[ i ];
if ( elem || elem === 0 ) {
// Add nodes directly
if ( jQuery.type( elem ) === "object" ) {
jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem );
// Convert non-html into a text node
} else if ( !rhtml.test( elem ) ) {
nodes.push( context.createTextNode( elem ) );
// Convert html into DOM nodes
} else {
tmp = tmp || safe.appendChild( context.createElement( "div" ) );
// Deserialize a standard representation
tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase();
wrap = wrapMap[ tag ] || wrapMap._default;
tmp.innerHTML = wrap[ 1 ] + jQuery.htmlPrefilter( elem ) + wrap[ 2 ];
// Descend through wrappers to the right content
j = wrap[ 0 ];
while ( j-- ) {
tmp = tmp.lastChild;
}
// Manually add leading whitespace removed by IE
if ( !support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[ 0 ] ) );
}
// Remove IE's autoinserted <tbody> from table fragments
if ( !support.tbody ) {
// String was a <table>, *may* have spurious <tbody>
elem = tag === "table" && !rtbody.test( elem ) ?
tmp.firstChild :
// String was a bare <thead> or <tfoot>
wrap[ 1 ] === "<table>" && !rtbody.test( elem ) ?
tmp :
0;
j = elem && elem.childNodes.length;
while ( j-- ) {
if ( jQuery.nodeName( ( tbody = elem.childNodes[ j ] ), "tbody" ) &&
!tbody.childNodes.length ) {
elem.removeChild( tbody );
}
}
}
jQuery.merge( nodes, tmp.childNodes );
// Fix #12392 for WebKit and IE > 9
tmp.textContent = "";
// Fix #12392 for oldIE
while ( tmp.firstChild ) {
tmp.removeChild( tmp.firstChild );
}
// Remember the top-level container for proper cleanup
tmp = safe.lastChild;
}
}
}
// Fix #11356: Clear elements from fragment
if ( tmp ) {
safe.removeChild( tmp );
}
// Reset defaultChecked for any radios and checkboxes
// about to be appended to the DOM in IE 6/7 (#8060)
if ( !support.appendChecked ) {
jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked );
}
i = 0;
while ( ( elem = nodes[ i++ ] ) ) {
// Skip elements already in the context collection (trac-4087)
if ( selection && jQuery.inArray( elem, selection ) > -1 ) {
if ( ignored ) {
ignored.push( elem );
}
continue;
}
contains = jQuery.contains( elem.ownerDocument, elem );
// Append to fragment
tmp = getAll( safe.appendChild( elem ), "script" );
// Preserve script evaluation history
if ( contains ) {
setGlobalEval( tmp );
}
// Capture executables
if ( scripts ) {
j = 0;
while ( ( elem = tmp[ j++ ] ) ) {
if ( rscriptType.test( elem.type || "" ) ) {
scripts.push( elem );
}
}
}
}
tmp = null;
return safe;
}
( function() {
var i, eventName,
div = document.createElement( "div" );
// Support: IE<9 (lack submit/change bubble), Firefox (lack focus(in | out) events)
for ( i in { submit: true, change: true, focusin: true } ) {
eventName = "on" + i;
if ( !( support[ i ] = eventName in window ) ) {
// Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP)
div.setAttribute( eventName, "t" );
support[ i ] = div.attributes[ eventName ].expando === false;
}
}
// Null elements to avoid leaks in IE.
div = null;
} )();
var rformElems = /^(?:input|select|textarea)$/i,
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|pointer|contextmenu|drag|drop)|click/,
rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
rtypenamespace = /^([^.]*)(?:\.(.+)|)/;
function returnTrue() {
return true;
}
function returnFalse() {
return false;
}
// Support: IE9
// See #13393 for more info
function safeActiveElement() {
try {
return document.activeElement;
} catch ( err ) { }
}
function on( elem, types, selector, data, fn, one ) {
var origFn, type;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) {
// ( types-Object, data )
data = data || selector;
selector = undefined;
}
for ( type in types ) {
on( elem, type, selector, data, types[ type ], one );
}
return elem;
}
if ( data == null && fn == null ) {
// ( types, fn )
fn = selector;
data = selector = undefined;
} else if ( fn == null ) {
if ( typeof selector === "string" ) {
// ( types, selector, fn )
fn = data;
data = undefined;
} else {
// ( types, data, fn )
fn = data;
data = selector;
selector = undefined;
}
}
if ( fn === false ) {
fn = returnFalse;
} else if ( !fn ) {
return elem;
}
if ( one === 1 ) {
origFn = fn;
fn = function( event ) {
// Can use an empty set, since event contains the info
jQuery().off( event );
return origFn.apply( this, arguments );
};
// Use same guid so caller can remove using origFn
fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
}
return elem.each( function() {
jQuery.event.add( this, types, fn, data, selector );
} );
}
/*
* Helper functions for managing events -- not part of the public interface.
* Props to Dean Edwards' addEvent library for many of the ideas.
*/
jQuery.event = {
global: {},
add: function( elem, types, handler, data, selector ) {
var tmp, events, t, handleObjIn,
special, eventHandle, handleObj,
handlers, type, namespaces, origType,
elemData = jQuery._data( elem );
// Don't attach events to noData or text/comment nodes (but allow plain objects)
if ( !elemData ) {
return;
}
// Caller can pass in an object of custom data in lieu of the handler
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
selector = handleObjIn.selector;
}
// Make sure that the handler has a unique ID, used to find/remove it later
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure and main handler, if this is the first
if ( !( events = elemData.events ) ) {
events = elemData.events = {};
}
if ( !( eventHandle = elemData.handle ) ) {
eventHandle = elemData.handle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== "undefined" &&
( !e || jQuery.event.triggered !== e.type ) ?
jQuery.event.dispatch.apply( eventHandle.elem, arguments ) :
undefined;
};
// Add elem as a property of the handle fn to prevent a memory leak
// with IE non-native events
eventHandle.elem = elem;
}
// Handle multiple events separated by a space
types = ( types || "" ).match( rnotwhite ) || [ "" ];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[ t ] ) || [];
type = origType = tmp[ 1 ];
namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort();
// There *must* be a type, no attaching namespace-only handlers
if ( !type ) {
continue;
}
// If event changes its type, use the special event handlers for the changed type
special = jQuery.event.special[ type ] || {};
// If selector defined, determine special event api type, otherwise given type
type = ( selector ? special.delegateType : special.bindType ) || type;
// Update special based on newly reset type
special = jQuery.event.special[ type ] || {};
// handleObj is passed to all event handlers
handleObj = jQuery.extend( {
type: type,
origType: origType,
data: data,
handler: handler,
guid: handler.guid,
selector: selector,
needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
namespace: namespaces.join( "." )
}, handleObjIn );
// Init the event handler queue if we're the first
if ( !( handlers = events[ type ] ) ) {
handlers = events[ type ] = [];
handlers.delegateCount = 0;
// Only use addEventListener/attachEvent if the special events handler returns false
if ( !special.setup ||
special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
// Bind the global event handler to the element
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( "on" + type, eventHandle );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// Add to the element's handler list, delegates in front
if ( selector ) {
handlers.splice( handlers.delegateCount++, 0, handleObj );
} else {
handlers.push( handleObj );
}
// Keep track of which events have ever been used, for event optimization
jQuery.event.global[ type ] = true;
}
// Nullify elem to prevent memory leaks in IE
elem = null;
},
// Detach an event or set of events from an element
remove: function( elem, types, handler, selector, mappedTypes ) {
var j, handleObj, tmp,
origCount, t, events,
special, handlers, type,
namespaces, origType,
elemData = jQuery.hasData( elem ) && jQuery._data( elem );
if ( !elemData || !( events = elemData.events ) ) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = ( types || "" ).match( rnotwhite ) || [ "" ];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[ t ] ) || [];
type = origType = tmp[ 1 ];
namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort();
// Unbind all events (on this namespace, if provided) for the element
if ( !type ) {
for ( type in events ) {
jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
}
continue;
}
special = jQuery.event.special[ type ] || {};
type = ( selector ? special.delegateType : special.bindType ) || type;
handlers = events[ type ] || [];
tmp = tmp[ 2 ] &&
new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" );
// Remove matching events
origCount = j = handlers.length;
while ( j-- ) {
handleObj = handlers[ j ];
if ( ( mappedTypes || origType === handleObj.origType ) &&
( !handler || handler.guid === handleObj.guid ) &&
( !tmp || tmp.test( handleObj.namespace ) ) &&
( !selector || selector === handleObj.selector ||
selector === "**" && handleObj.selector ) ) {
handlers.splice( j, 1 );
if ( handleObj.selector ) {
handlers.delegateCount--;
}
if ( special.remove ) {
special.remove.call( elem, handleObj );
}
}
}
// Remove generic event handler if we removed something and no more handlers exist
// (avoids potential for endless recursion during removal of special event handlers)
if ( origCount && !handlers.length ) {
if ( !special.teardown ||
special.teardown.call( elem, namespaces, elemData.handle ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
delete events[ type ];
}
}
// Remove the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
delete elemData.handle;
// removeData also checks for emptiness and clears the expando if empty
// so use it instead of delete
jQuery._removeData( elem, "events" );
}
},
trigger: function( event, data, elem, onlyHandlers ) {
var handle, ontype, cur,
bubbleType, special, tmp, i,
eventPath = [ elem || document ],
type = hasOwn.call( event, "type" ) ? event.type : event,
namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split( "." ) : [];
cur = tmp = elem = elem || document;
// Don't do events on text and comment nodes
if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
}
// focus/blur morphs to focusin/out; ensure we're not firing them right now
if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
return;
}
if ( type.indexOf( "." ) > -1 ) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split( "." );
type = namespaces.shift();
namespaces.sort();
}
ontype = type.indexOf( ":" ) < 0 && "on" + type;
// Caller can pass in a jQuery.Event object, Object, or just an event type string
event = event[ jQuery.expando ] ?
event :
new jQuery.Event( type, typeof event === "object" && event );
// Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true)
event.isTrigger = onlyHandlers ? 2 : 3;
event.namespace = namespaces.join( "." );
event.rnamespace = event.namespace ?
new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ) :
null;
// Clean up the event in case it is being reused
event.result = undefined;
if ( !event.target ) {
event.target = elem;
}
// Clone any incoming data and prepend the event, creating the handler arg list
data = data == null ?
[ event ] :
jQuery.makeArray( data, [ event ] );
// Allow special events to draw outside the lines
special = jQuery.event.special[ type ] || {};
if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) {
return;
}
// Determine event propagation path in advance, per W3C events spec (#9951)
// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
bubbleType = special.delegateType || type;
if ( !rfocusMorph.test( bubbleType + type ) ) {
cur = cur.parentNode;
}
for ( ; cur; cur = cur.parentNode ) {
eventPath.push( cur );
tmp = cur;
}
// Only add window if we got to document (e.g., not plain obj or detached DOM)
if ( tmp === ( elem.ownerDocument || document ) ) {
eventPath.push( tmp.defaultView || tmp.parentWindow || window );
}
}
// Fire handlers on the event path
i = 0;
while ( ( cur = eventPath[ i++ ] ) && !event.isPropagationStopped() ) {
event.type = i > 1 ?
bubbleType :
special.bindType || type;
// jQuery handler
handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] &&
jQuery._data( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Native handler
handle = ontype && cur[ ontype ];
if ( handle && handle.apply && acceptData( cur ) ) {
event.result = handle.apply( cur, data );
if ( event.result === false ) {
event.preventDefault();
}
}
}
event.type = type;
// If nobody prevented the default action, do it now
if ( !onlyHandlers && !event.isDefaultPrevented() ) {
if (
( !special._default ||
special._default.apply( eventPath.pop(), data ) === false
) && acceptData( elem )
) {
// Call a native DOM method on the target with the same name name as the event.
// Can't use an .isFunction() check here because IE6/7 fails that test.
// Don't do default actions on window, that's where global variables be (#6170)
if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) {
// Don't re-trigger an onFOO event when we call its FOO() method
tmp = elem[ ontype ];
if ( tmp ) {
elem[ ontype ] = null;
}
// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type;
try {
elem[ type ]();
} catch ( e ) {
// IE<9 dies on focus/blur to hidden element (#1486,#12518)
// only reproducible on winXP IE8 native, not IE9 in IE8 mode
}
jQuery.event.triggered = undefined;
if ( tmp ) {
elem[ ontype ] = tmp;
}
}
}
}
return event.result;
},
dispatch: function( event ) {
// Make a writable jQuery.Event from the native event object
event = jQuery.event.fix( event );
var i, j, ret, matched, handleObj,
handlerQueue = [],
args = slice.call( arguments ),
handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [],
special = jQuery.event.special[ event.type ] || {};
// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[ 0 ] = event;
event.delegateTarget = this;
// Call the preDispatch hook for the mapped type, and let it bail if desired
if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
return;
}
// Determine handlers
handlerQueue = jQuery.event.handlers.call( this, event, handlers );
// Run delegates first; they may want to stop propagation beneath us
i = 0;
while ( ( matched = handlerQueue[ i++ ] ) && !event.isPropagationStopped() ) {
event.currentTarget = matched.elem;
j = 0;
while ( ( handleObj = matched.handlers[ j++ ] ) &&
!event.isImmediatePropagationStopped() ) {
// Triggered event must either 1) have no namespace, or 2) have namespace(s)
// a subset or equal to those in the bound event (both can have no namespace).
if ( !event.rnamespace || event.rnamespace.test( handleObj.namespace ) ) {
event.handleObj = handleObj;
event.data = handleObj.data;
ret = ( ( jQuery.event.special[ handleObj.origType ] || {} ).handle ||
handleObj.handler ).apply( matched.elem, args );
if ( ret !== undefined ) {
if ( ( event.result = ret ) === false ) {
event.preventDefault();
event.stopPropagation();
}
}
}
}
}
// Call the postDispatch hook for the mapped type
if ( special.postDispatch ) {
special.postDispatch.call( this, event );
}
return event.result;
},
handlers: function( event, handlers ) {
var i, matches, sel, handleObj,
handlerQueue = [],
delegateCount = handlers.delegateCount,
cur = event.target;
// Support (at least): Chrome, IE9
// Find delegate handlers
// Black-hole SVG <use> instance trees (#13180)
//
// Support: Firefox<=42+
// Avoid non-left-click in FF but don't block IE radio events (#3861, gh-2343)
if ( delegateCount && cur.nodeType &&
( event.type !== "click" || isNaN( event.button ) || event.button < 1 ) ) {
/* jshint eqeqeq: false */
for ( ; cur != this; cur = cur.parentNode || this ) {
/* jshint eqeqeq: true */
// Don't check non-elements (#13208)
// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
if ( cur.nodeType === 1 && ( cur.disabled !== true || event.type !== "click" ) ) {
matches = [];
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
// Don't conflict with Object.prototype properties (#13203)
sel = handleObj.selector + " ";
if ( matches[ sel ] === undefined ) {
matches[ sel ] = handleObj.needsContext ?
jQuery( sel, this ).index( cur ) > -1 :
jQuery.find( sel, this, null, [ cur ] ).length;
}
if ( matches[ sel ] ) {
matches.push( handleObj );
}
}
if ( matches.length ) {
handlerQueue.push( { elem: cur, handlers: matches } );
}
}
}
}
// Add the remaining (directly-bound) handlers
if ( delegateCount < handlers.length ) {
handlerQueue.push( { elem: this, handlers: handlers.slice( delegateCount ) } );
}
return handlerQueue;
},
fix: function( event ) {
if ( event[ jQuery.expando ] ) {
return event;
}
// Create a writable copy of the event object and normalize some properties
var i, prop, copy,
type = event.type,
originalEvent = event,
fixHook = this.fixHooks[ type ];
if ( !fixHook ) {
this.fixHooks[ type ] = fixHook =
rmouseEvent.test( type ) ? this.mouseHooks :
rkeyEvent.test( type ) ? this.keyHooks :
{};
}
copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;
event = new jQuery.Event( originalEvent );
i = copy.length;
while ( i-- ) {
prop = copy[ i ];
event[ prop ] = originalEvent[ prop ];
}
// Support: IE<9
// Fix target property (#1925)
if ( !event.target ) {
event.target = originalEvent.srcElement || document;
}
// Support: Safari 6-8+
// Target should not be a text node (#504, #13143)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
// Support: IE<9
// For mouse/key events, metaKey==false if it's undefined (#3368, #11328)
event.metaKey = !!event.metaKey;
return fixHook.filter ? fixHook.filter( event, originalEvent ) : event;
},
// Includes some event props shared by KeyEvent and MouseEvent
props: ( "altKey bubbles cancelable ctrlKey currentTarget detail eventPhase " +
"metaKey relatedTarget shiftKey target timeStamp view which" ).split( " " ),
fixHooks: {},
keyHooks: {
props: "char charCode key keyCode".split( " " ),
filter: function( event, original ) {
// Add which for key events
if ( event.which == null ) {
event.which = original.charCode != null ? original.charCode : original.keyCode;
}
return event;
}
},
mouseHooks: {
props: ( "button buttons clientX clientY fromElement offsetX offsetY " +
"pageX pageY screenX screenY toElement" ).split( " " ),
filter: function( event, original ) {
var body, eventDoc, doc,
button = original.button,
fromElement = original.fromElement;
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && original.clientX != null ) {
eventDoc = event.target.ownerDocument || document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = original.clientX +
( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) -
( doc && doc.clientLeft || body && body.clientLeft || 0 );
event.pageY = original.clientY +
( doc && doc.scrollTop || body && body.scrollTop || 0 ) -
( doc && doc.clientTop || body && body.clientTop || 0 );
}
// Add relatedTarget, if necessary
if ( !event.relatedTarget && fromElement ) {
event.relatedTarget = fromElement === event.target ?
original.toElement :
fromElement;
}
// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && button !== undefined ) {
event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
}
return event;
}
},
special: {
load: {
// Prevent triggered image.load events from bubbling to window.load
noBubble: true
},
focus: {
// Fire native event if possible so blur/focus sequence is correct
trigger: function() {
if ( this !== safeActiveElement() && this.focus ) {
try {
this.focus();
return false;
} catch ( e ) {
// Support: IE<9
// If we error on focus to hidden element (#1486, #12518),
// let .trigger() run the handlers
}
}
},
delegateType: "focusin"
},
blur: {
trigger: function() {
if ( this === safeActiveElement() && this.blur ) {
this.blur();
return false;
}
},
delegateType: "focusout"
},
click: {
// For checkbox, fire native event so checked state will be right
trigger: function() {
if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) {
this.click();
return false;
}
},
// For cross-browser consistency, don't fire native .click() on links
_default: function( event ) {
return jQuery.nodeName( event.target, "a" );
}
},
beforeunload: {
postDispatch: function( event ) {
// Support: Firefox 20+
// Firefox doesn't alert if the returnValue field is not set.
if ( event.result !== undefined && event.originalEvent ) {
event.originalEvent.returnValue = event.result;
}
}
}
},
// Piggyback on a donor event to simulate a different one
simulate: function( type, elem, event ) {
var e = jQuery.extend(
new jQuery.Event(),
event,
{
type: type,
isSimulated: true
// Previously, `originalEvent: {}` was set here, so stopPropagation call
// would not be triggered on donor event, since in our own
// jQuery.event.stopPropagation function we had a check for existence of
// originalEvent.stopPropagation method, so, consequently it would be a noop.
//
// Guard for simulated events was moved to jQuery.event.stopPropagation function
// since `originalEvent` should point to the original event for the
// constancy with other events and for more focused logic
}
);
jQuery.event.trigger( e, null, elem );
if ( e.isDefaultPrevented() ) {
event.preventDefault();
}
}
};
jQuery.removeEvent = document.removeEventListener ?
function( elem, type, handle ) {
// This "if" is needed for plain objects
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle );
}
} :
function( elem, type, handle ) {
var name = "on" + type;
if ( elem.detachEvent ) {
// #8545, #7054, preventing memory leaks for custom events in IE6-8
// detachEvent needed property on element, by name of that event,
// to properly expose it to GC
if ( typeof elem[ name ] === "undefined" ) {
elem[ name ] = null;
}
elem.detachEvent( name, handle );
}
};
jQuery.Event = function( src, props ) {
// Allow instantiation without the 'new' keyword
if ( !( this instanceof jQuery.Event ) ) {
return new jQuery.Event( src, props );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = src.defaultPrevented ||
src.defaultPrevented === undefined &&
// Support: IE < 9, Android < 4.0
src.returnValue === false ?
returnTrue :
returnFalse;
// Event type
} else {
this.type = src;
}
// Put explicitly provided properties onto the event object
if ( props ) {
jQuery.extend( this, props );
}
// Create a timestamp if incoming event doesn't have one
this.timeStamp = src && src.timeStamp || jQuery.now();
// Mark it as fixed
this[ jQuery.expando ] = true;
};
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
constructor: jQuery.Event,
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse,
preventDefault: function() {
var e = this.originalEvent;
this.isDefaultPrevented = returnTrue;
if ( !e ) {
return;
}
// If preventDefault exists, run it on the original event
if ( e.preventDefault ) {
e.preventDefault();
// Support: IE
// Otherwise set the returnValue property of the original event to false
} else {
e.returnValue = false;
}
},
stopPropagation: function() {
var e = this.originalEvent;
this.isPropagationStopped = returnTrue;
if ( !e || this.isSimulated ) {
return;
}
// If stopPropagation exists, run it on the original event
if ( e.stopPropagation ) {
e.stopPropagation();
}
// Support: IE
// Set the cancelBubble property of the original event to true
e.cancelBubble = true;
},
stopImmediatePropagation: function() {
var e = this.originalEvent;
this.isImmediatePropagationStopped = returnTrue;
if ( e && e.stopImmediatePropagation ) {
e.stopImmediatePropagation();
}
this.stopPropagation();
}
};
// Create mouseenter/leave events using mouseover/out and event-time checks
// so that event delegation works in jQuery.
// Do the same for pointerenter/pointerleave and pointerover/pointerout
//
// Support: Safari 7 only
// Safari sends mouseenter too often; see:
// https://code.google.com/p/chromium/issues/detail?id=470258
// for the description of the bug (it existed in older Chrome versions as well).
jQuery.each( {
mouseenter: "mouseover",
mouseleave: "mouseout",
pointerenter: "pointerover",
pointerleave: "pointerout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
delegateType: fix,
bindType: fix,
handle: function( event ) {
var ret,
target = this,
related = event.relatedTarget,
handleObj = event.handleObj;
// For mouseenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if ( !related || ( related !== target && !jQuery.contains( target, related ) ) ) {
event.type = handleObj.origType;
ret = handleObj.handler.apply( this, arguments );
event.type = fix;
}
return ret;
}
};
} );
// IE submit delegation
if ( !support.submit ) {
jQuery.event.special.submit = {
setup: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Lazy-add a submit handler when a descendant form may potentially be submitted
jQuery.event.add( this, "click._submit keypress._submit", function( e ) {
// Node name check avoids a VML-related crash in IE (#9807)
var elem = e.target,
form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ?
// Support: IE <=8
// We use jQuery.prop instead of elem.form
// to allow fixing the IE8 delegated submit issue (gh-2332)
// by 3rd party polyfills/workarounds.
jQuery.prop( elem, "form" ) :
undefined;
if ( form && !jQuery._data( form, "submit" ) ) {
jQuery.event.add( form, "submit._submit", function( event ) {
event._submitBubble = true;
} );
jQuery._data( form, "submit", true );
}
} );
// return undefined since we don't need an event listener
},
postDispatch: function( event ) {
// If form was submitted by the user, bubble the event up the tree
if ( event._submitBubble ) {
delete event._submitBubble;
if ( this.parentNode && !event.isTrigger ) {
jQuery.event.simulate( "submit", this.parentNode, event );
}
}
},
teardown: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Remove delegated handlers; cleanData eventually reaps submit handlers attached above
jQuery.event.remove( this, "._submit" );
}
};
}
// IE change delegation and checkbox/radio fix
if ( !support.change ) {
jQuery.event.special.change = {
setup: function() {
if ( rformElems.test( this.nodeName ) ) {
// IE doesn't fire change on a check/radio until blur; trigger it on click
// after a propertychange. Eat the blur-change in special.change.handle.
// This still fires onchange a second time for check/radio after blur.
if ( this.type === "checkbox" || this.type === "radio" ) {
jQuery.event.add( this, "propertychange._change", function( event ) {
if ( event.originalEvent.propertyName === "checked" ) {
this._justChanged = true;
}
} );
jQuery.event.add( this, "click._change", function( event ) {
if ( this._justChanged && !event.isTrigger ) {
this._justChanged = false;
}
// Allow triggered, simulated change events (#11500)
jQuery.event.simulate( "change", this, event );
} );
}
return false;
}
// Delegated event; lazy-add a change handler on descendant inputs
jQuery.event.add( this, "beforeactivate._change", function( e ) {
var elem = e.target;
if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "change" ) ) {
jQuery.event.add( elem, "change._change", function( event ) {
if ( this.parentNode && !event.isSimulated && !event.isTrigger ) {
jQuery.event.simulate( "change", this.parentNode, event );
}
} );
jQuery._data( elem, "change", true );
}
} );
},
handle: function( event ) {
var elem = event.target;
// Swallow native change events from checkbox/radio, we already triggered them above
if ( this !== elem || event.isSimulated || event.isTrigger ||
( elem.type !== "radio" && elem.type !== "checkbox" ) ) {
return event.handleObj.handler.apply( this, arguments );
}
},
teardown: function() {
jQuery.event.remove( this, "._change" );
return !rformElems.test( this.nodeName );
}
};
}
// Support: Firefox
// Firefox doesn't have focus(in | out) events
// Related ticket - https://bugzilla.mozilla.org/show_bug.cgi?id=687787
//
// Support: Chrome, Safari
// focus(in | out) events fire after focus & blur events,
// which is spec violation - http://www.w3.org/TR/DOM-Level-3-Events/#events-focusevent-event-order
// Related ticket - https://code.google.com/p/chromium/issues/detail?id=449857
if ( !support.focusin ) {
jQuery.each( { focus: "focusin", blur: "focusout" }, function( orig, fix ) {
// Attach a single capturing handler on the document while someone wants focusin/focusout
var handler = function( event ) {
jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ) );
};
jQuery.event.special[ fix ] = {
setup: function() {
var doc = this.ownerDocument || this,
attaches = jQuery._data( doc, fix );
if ( !attaches ) {
doc.addEventListener( orig, handler, true );
}
jQuery._data( doc, fix, ( attaches || 0 ) + 1 );
},
teardown: function() {
var doc = this.ownerDocument || this,
attaches = jQuery._data( doc, fix ) - 1;
if ( !attaches ) {
doc.removeEventListener( orig, handler, true );
jQuery._removeData( doc, fix );
} else {
jQuery._data( doc, fix, attaches );
}
}
};
} );
}
jQuery.fn.extend( {
on: function( types, selector, data, fn ) {
return on( this, types, selector, data, fn );
},
one: function( types, selector, data, fn ) {
return on( this, types, selector, data, fn, 1 );
},
off: function( types, selector, fn ) {
var handleObj, type;
if ( types && types.preventDefault && types.handleObj ) {
// ( event ) dispatched jQuery.Event
handleObj = types.handleObj;
jQuery( types.delegateTarget ).off(
handleObj.namespace ?
handleObj.origType + "." + handleObj.namespace :
handleObj.origType,
handleObj.selector,
handleObj.handler
);
return this;
}
if ( typeof types === "object" ) {
// ( types-object [, selector] )
for ( type in types ) {
this.off( type, selector, types[ type ] );
}
return this;
}
if ( selector === false || typeof selector === "function" ) {
// ( types [, fn] )
fn = selector;
selector = undefined;
}
if ( fn === false ) {
fn = returnFalse;
}
return this.each( function() {
jQuery.event.remove( this, types, fn, selector );
} );
},
trigger: function( type, data ) {
return this.each( function() {
jQuery.event.trigger( type, data, this );
} );
},
triggerHandler: function( type, data ) {
var elem = this[ 0 ];
if ( elem ) {
return jQuery.event.trigger( type, data, elem, true );
}
}
} );
var rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g,
rnoshimcache = new RegExp( "<(?:" + nodeNames + ")[\\s/>]", "i" ),
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi,
// Support: IE 10-11, Edge 10240+
// In IE/Edge using regex groups here causes severe slowdowns.
// See https://connect.microsoft.com/IE/feedback/details/1736512/
rnoInnerhtml = /<script|<style|<link/i,
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptTypeMasked = /^true\/(.*)/,
rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,
safeFragment = createSafeFragment( document ),
fragmentDiv = safeFragment.appendChild( document.createElement( "div" ) );
// Support: IE<8
// Manipulating tables requires a tbody
function manipulationTarget( elem, content ) {
return jQuery.nodeName( elem, "table" ) &&
jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ?
elem.getElementsByTagName( "tbody" )[ 0 ] ||
elem.appendChild( elem.ownerDocument.createElement( "tbody" ) ) :
elem;
}
// Replace/restore the type attribute of script elements for safe DOM manipulation
function disableScript( elem ) {
elem.type = ( jQuery.find.attr( elem, "type" ) !== null ) + "/" + elem.type;
return elem;
}
function restoreScript( elem ) {
var match = rscriptTypeMasked.exec( elem.type );
if ( match ) {
elem.type = match[ 1 ];
} else {
elem.removeAttribute( "type" );
}
return elem;
}
function cloneCopyEvent( src, dest ) {
if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
return;
}
var type, i, l,
oldData = jQuery._data( src ),
curData = jQuery._data( dest, oldData ),
events = oldData.events;
if ( events ) {
delete curData.handle;
curData.events = {};
for ( type in events ) {
for ( i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( dest, type, events[ type ][ i ] );
}
}
}
// make the cloned public data object a copy from the original
if ( curData.data ) {
curData.data = jQuery.extend( {}, curData.data );
}
}
function fixCloneNodeIssues( src, dest ) {
var nodeName, e, data;
// We do not need to do anything for non-Elements
if ( dest.nodeType !== 1 ) {
return;
}
nodeName = dest.nodeName.toLowerCase();
// IE6-8 copies events bound via attachEvent when using cloneNode.
if ( !support.noCloneEvent && dest[ jQuery.expando ] ) {
data = jQuery._data( dest );
for ( e in data.events ) {
jQuery.removeEvent( dest, e, data.handle );
}
// Event data gets referenced instead of copied if the expando gets copied too
dest.removeAttribute( jQuery.expando );
}
// IE blanks contents when cloning scripts, and tries to evaluate newly-set text
if ( nodeName === "script" && dest.text !== src.text ) {
disableScript( dest ).text = src.text;
restoreScript( dest );
// IE6-10 improperly clones children of object elements using classid.
// IE10 throws NoModificationAllowedError if parent is null, #12132.
} else if ( nodeName === "object" ) {
if ( dest.parentNode ) {
dest.outerHTML = src.outerHTML;
}
// This path appears unavoidable for IE9. When cloning an object
// element in IE9, the outerHTML strategy above is not sufficient.
// If the src has innerHTML and the destination does not,
// copy the src.innerHTML into the dest.innerHTML. #10324
if ( support.html5Clone && ( src.innerHTML && !jQuery.trim( dest.innerHTML ) ) ) {
dest.innerHTML = src.innerHTML;
}
} else if ( nodeName === "input" && rcheckableType.test( src.type ) ) {
// IE6-8 fails to persist the checked state of a cloned checkbox
// or radio button. Worse, IE6-7 fail to give the cloned element
// a checked appearance if the defaultChecked value isn't also set
dest.defaultChecked = dest.checked = src.checked;
// IE6-7 get confused and end up setting the value of a cloned
// checkbox/radio button to an empty string instead of "on"
if ( dest.value !== src.value ) {
dest.value = src.value;
}
// IE6-8 fails to return the selected option to the default selected
// state when cloning options
} else if ( nodeName === "option" ) {
dest.defaultSelected = dest.selected = src.defaultSelected;
// IE6-8 fails to set the defaultValue to the correct value when
// cloning other types of input fields
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
}
}
function domManip( collection, args, callback, ignored ) {
// Flatten any nested arrays
args = concat.apply( [], args );
var first, node, hasScripts,
scripts, doc, fragment,
i = 0,
l = collection.length,
iNoClone = l - 1,
value = args[ 0 ],
isFunction = jQuery.isFunction( value );
// We can't cloneNode fragments that contain checked, in WebKit
if ( isFunction ||
( l > 1 && typeof value === "string" &&
!support.checkClone && rchecked.test( value ) ) ) {
return collection.each( function( index ) {
var self = collection.eq( index );
if ( isFunction ) {
args[ 0 ] = value.call( this, index, self.html() );
}
domManip( self, args, callback, ignored );
} );
}
if ( l ) {
fragment = buildFragment( args, collection[ 0 ].ownerDocument, false, collection, ignored );
first = fragment.firstChild;
if ( fragment.childNodes.length === 1 ) {
fragment = first;
}
// Require either new content or an interest in ignored elements to invoke the callback
if ( first || ignored ) {
scripts = jQuery.map( getAll( fragment, "script" ), disableScript );
hasScripts = scripts.length;
// Use the original fragment for the last item
// instead of the first because it can end up
// being emptied incorrectly in certain situations (#8070).
for ( ; i < l; i++ ) {
node = fragment;
if ( i !== iNoClone ) {
node = jQuery.clone( node, true, true );
// Keep references to cloned scripts for later restoration
if ( hasScripts ) {
// Support: Android<4.1, PhantomJS<2
// push.apply(_, arraylike) throws on ancient WebKit
jQuery.merge( scripts, getAll( node, "script" ) );
}
}
callback.call( collection[ i ], node, i );
}
if ( hasScripts ) {
doc = scripts[ scripts.length - 1 ].ownerDocument;
// Reenable scripts
jQuery.map( scripts, restoreScript );
// Evaluate executable scripts on first document insertion
for ( i = 0; i < hasScripts; i++ ) {
node = scripts[ i ];
if ( rscriptType.test( node.type || "" ) &&
!jQuery._data( node, "globalEval" ) &&
jQuery.contains( doc, node ) ) {
if ( node.src ) {
// Optional AJAX dependency, but won't run scripts if not present
if ( jQuery._evalUrl ) {
jQuery._evalUrl( node.src );
}
} else {
jQuery.globalEval(
( node.text || node.textContent || node.innerHTML || "" )
.replace( rcleanScript, "" )
);
}
}
}
}
// Fix #11809: Avoid leaking memory
fragment = first = null;
}
}
return collection;
}
function remove( elem, selector, keepData ) {
var node,
elems = selector ? jQuery.filter( selector, elem ) : elem,
i = 0;
for ( ; ( node = elems[ i ] ) != null; i++ ) {
if ( !keepData && node.nodeType === 1 ) {
jQuery.cleanData( getAll( node ) );
}
if ( node.parentNode ) {
if ( keepData && jQuery.contains( node.ownerDocument, node ) ) {
setGlobalEval( getAll( node, "script" ) );
}
node.parentNode.removeChild( node );
}
}
return elem;
}
jQuery.extend( {
htmlPrefilter: function( html ) {
return html.replace( rxhtmlTag, "<$1></$2>" );
},
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var destElements, node, clone, i, srcElements,
inPage = jQuery.contains( elem.ownerDocument, elem );
if ( support.html5Clone || jQuery.isXMLDoc( elem ) ||
!rnoshimcache.test( "<" + elem.nodeName + ">" ) ) {
clone = elem.cloneNode( true );
// IE<=8 does not properly clone detached, unknown element nodes
} else {
fragmentDiv.innerHTML = elem.outerHTML;
fragmentDiv.removeChild( clone = fragmentDiv.firstChild );
}
if ( ( !support.noCloneEvent || !support.noCloneChecked ) &&
( elem.nodeType === 1 || elem.nodeType === 11 ) && !jQuery.isXMLDoc( elem ) ) {
// We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2
destElements = getAll( clone );
srcElements = getAll( elem );
// Fix all IE cloning issues
for ( i = 0; ( node = srcElements[ i ] ) != null; ++i ) {
// Ensure that the destination node is not null; Fixes #9587
if ( destElements[ i ] ) {
fixCloneNodeIssues( node, destElements[ i ] );
}
}
}
// Copy the events from the original to the clone
if ( dataAndEvents ) {
if ( deepDataAndEvents ) {
srcElements = srcElements || getAll( elem );
destElements = destElements || getAll( clone );
for ( i = 0; ( node = srcElements[ i ] ) != null; i++ ) {
cloneCopyEvent( node, destElements[ i ] );
}
} else {
cloneCopyEvent( elem, clone );
}
}
// Preserve script evaluation history
destElements = getAll( clone, "script" );
if ( destElements.length > 0 ) {
setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
}
destElements = srcElements = node = null;
// Return the cloned set
return clone;
},
cleanData: function( elems, /* internal */ forceAcceptData ) {
var elem, type, id, data,
i = 0,
internalKey = jQuery.expando,
cache = jQuery.cache,
attributes = support.attributes,
special = jQuery.event.special;
for ( ; ( elem = elems[ i ] ) != null; i++ ) {
if ( forceAcceptData || acceptData( elem ) ) {
id = elem[ internalKey ];
data = id && cache[ id ];
if ( data ) {
if ( data.events ) {
for ( type in data.events ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
// This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
}
// Remove cache only if it was not already removed by jQuery.event.remove
if ( cache[ id ] ) {
delete cache[ id ];
// Support: IE<9
// IE does not allow us to delete expando properties from nodes
// IE creates expando attributes along with the property
// IE does not have a removeAttribute function on Document nodes
if ( !attributes && typeof elem.removeAttribute !== "undefined" ) {
elem.removeAttribute( internalKey );
// Webkit & Blink performance suffers when deleting properties
// from DOM nodes, so set to undefined instead
// https://code.google.com/p/chromium/issues/detail?id=378607
} else {
elem[ internalKey ] = undefined;
}
deletedIds.push( id );
}
}
}
}
}
} );
jQuery.fn.extend( {
// Keep domManip exposed until 3.0 (gh-2225)
domManip: domManip,
detach: function( selector ) {
return remove( this, selector, true );
},
remove: function( selector ) {
return remove( this, selector );
},
text: function( value ) {
return access( this, function( value ) {
return value === undefined ?
jQuery.text( this ) :
this.empty().append(
( this[ 0 ] && this[ 0 ].ownerDocument || document ).createTextNode( value )
);
}, null, value, arguments.length );
},
append: function() {
return domManip( this, arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.appendChild( elem );
}
} );
},
prepend: function() {
return domManip( this, arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.insertBefore( elem, target.firstChild );
}
} );
},
before: function() {
return domManip( this, arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this );
}
} );
},
after: function() {
return domManip( this, arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this.nextSibling );
}
} );
},
empty: function() {
var elem,
i = 0;
for ( ; ( elem = this[ i ] ) != null; i++ ) {
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem, false ) );
}
// Remove any remaining nodes
while ( elem.firstChild ) {
elem.removeChild( elem.firstChild );
}
// If this is a select, ensure that it displays empty (#12336)
// Support: IE<9
if ( elem.options && jQuery.nodeName( elem, "select" ) ) {
elem.options.length = 0;
}
}
return this;
},
clone: function( dataAndEvents, deepDataAndEvents ) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map( function() {
return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
} );
},
html: function( value ) {
return access( this, function( value ) {
var elem = this[ 0 ] || {},
i = 0,
l = this.length;
if ( value === undefined ) {
return elem.nodeType === 1 ?
elem.innerHTML.replace( rinlinejQuery, "" ) :
undefined;
}
// See if we can take a shortcut and just use innerHTML
if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
( support.htmlSerialize || !rnoshimcache.test( value ) ) &&
( support.leadingWhitespace || !rleadingWhitespace.test( value ) ) &&
!wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) {
value = jQuery.htmlPrefilter( value );
try {
for ( ; i < l; i++ ) {
// Remove element nodes and prevent memory leaks
elem = this[ i ] || {};
if ( elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem, false ) );
elem.innerHTML = value;
}
}
elem = 0;
// If using innerHTML throws an exception, use the fallback method
} catch ( e ) {}
}
if ( elem ) {
this.empty().append( value );
}
}, null, value, arguments.length );
},
replaceWith: function() {
var ignored = [];
// Make the changes, replacing each non-ignored context element with the new content
return domManip( this, arguments, function( elem ) {
var parent = this.parentNode;
if ( jQuery.inArray( this, ignored ) < 0 ) {
jQuery.cleanData( getAll( this ) );
if ( parent ) {
parent.replaceChild( elem, this );
}
}
// Force callback invocation
}, ignored );
}
} );
jQuery.each( {
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var elems,
i = 0,
ret = [],
insert = jQuery( selector ),
last = insert.length - 1;
for ( ; i <= last; i++ ) {
elems = i === last ? this : this.clone( true );
jQuery( insert[ i ] )[ original ]( elems );
// Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get()
push.apply( ret, elems.get() );
}
return this.pushStack( ret );
};
} );
var iframe,
elemdisplay = {
// Support: Firefox
// We have to pre-define these values for FF (#10227)
HTML: "block",
BODY: "block"
};
/**
* Retrieve the actual display of a element
* @param {String} name nodeName of the element
* @param {Object} doc Document object
*/
// Called only from within defaultDisplay
function actualDisplay( name, doc ) {
var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ),
display = jQuery.css( elem[ 0 ], "display" );
// We don't have any data stored on the element,
// so use "detach" method as fast way to get rid of the element
elem.detach();
return display;
}
/**
* Try to determine the default display value of an element
* @param {String} nodeName
*/
function defaultDisplay( nodeName ) {
var doc = document,
display = elemdisplay[ nodeName ];
if ( !display ) {
display = actualDisplay( nodeName, doc );
// If the simple way fails, read from inside an iframe
if ( display === "none" || !display ) {
// Use the already-created iframe if possible
iframe = ( iframe || jQuery( "<iframe frameborder='0' width='0' height='0'/>" ) )
.appendTo( doc.documentElement );
// Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse
doc = ( iframe[ 0 ].contentWindow || iframe[ 0 ].contentDocument ).document;
// Support: IE
doc.write();
doc.close();
display = actualDisplay( nodeName, doc );
iframe.detach();
}
// Store the correct default display
elemdisplay[ nodeName ] = display;
}
return display;
}
var rmargin = ( /^margin/ );
var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" );
var swap = function( elem, options, callback, args ) {
var ret, name,
old = {};
// Remember the old values, and insert the new ones
for ( name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
ret = callback.apply( elem, args || [] );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
return ret;
};
var documentElement = document.documentElement;
( function() {
var pixelPositionVal, pixelMarginRightVal, boxSizingReliableVal,
reliableHiddenOffsetsVal, reliableMarginRightVal, reliableMarginLeftVal,
container = document.createElement( "div" ),
div = document.createElement( "div" );
// Finish early in limited (non-browser) environments
if ( !div.style ) {
return;
}
div.style.cssText = "float:left;opacity:.5";
// Support: IE<9
// Make sure that element opacity exists (as opposed to filter)
support.opacity = div.style.opacity === "0.5";
// Verify style float existence
// (IE uses styleFloat instead of cssFloat)
support.cssFloat = !!div.style.cssFloat;
div.style.backgroundClip = "content-box";
div.cloneNode( true ).style.backgroundClip = "";
support.clearCloneStyle = div.style.backgroundClip === "content-box";
container = document.createElement( "div" );
container.style.cssText = "border:0;width:8px;height:0;top:0;left:-9999px;" +
"padding:0;margin-top:1px;position:absolute";
div.innerHTML = "";
container.appendChild( div );
// Support: Firefox<29, Android 2.3
// Vendor-prefix box-sizing
support.boxSizing = div.style.boxSizing === "" || div.style.MozBoxSizing === "" ||
div.style.WebkitBoxSizing === "";
jQuery.extend( support, {
reliableHiddenOffsets: function() {
if ( pixelPositionVal == null ) {
computeStyleTests();
}
return reliableHiddenOffsetsVal;
},
boxSizingReliable: function() {
// We're checking for pixelPositionVal here instead of boxSizingReliableVal
// since that compresses better and they're computed together anyway.
if ( pixelPositionVal == null ) {
computeStyleTests();
}
return boxSizingReliableVal;
},
pixelMarginRight: function() {
// Support: Android 4.0-4.3
if ( pixelPositionVal == null ) {
computeStyleTests();
}
return pixelMarginRightVal;
},
pixelPosition: function() {
if ( pixelPositionVal == null ) {
computeStyleTests();
}
return pixelPositionVal;
},
reliableMarginRight: function() {
// Support: Android 2.3
if ( pixelPositionVal == null ) {
computeStyleTests();
}
return reliableMarginRightVal;
},
reliableMarginLeft: function() {
// Support: IE <=8 only, Android 4.0 - 4.3 only, Firefox <=3 - 37
if ( pixelPositionVal == null ) {
computeStyleTests();
}
return reliableMarginLeftVal;
}
} );
function computeStyleTests() {
var contents, divStyle,
documentElement = document.documentElement;
// Setup
documentElement.appendChild( container );
div.style.cssText =
// Support: Android 2.3
// Vendor-prefix box-sizing
"-webkit-box-sizing:border-box;box-sizing:border-box;" +
"position:relative;display:block;" +
"margin:auto;border:1px;padding:1px;" +
"top:1%;width:50%";
// Support: IE<9
// Assume reasonable values in the absence of getComputedStyle
pixelPositionVal = boxSizingReliableVal = reliableMarginLeftVal = false;
pixelMarginRightVal = reliableMarginRightVal = true;
// Check for getComputedStyle so that this code is not run in IE<9.
if ( window.getComputedStyle ) {
divStyle = window.getComputedStyle( div );
pixelPositionVal = ( divStyle || {} ).top !== "1%";
reliableMarginLeftVal = ( divStyle || {} ).marginLeft === "2px";
boxSizingReliableVal = ( divStyle || { width: "4px" } ).width === "4px";
// Support: Android 4.0 - 4.3 only
// Some styles come back with percentage values, even though they shouldn't
div.style.marginRight = "50%";
pixelMarginRightVal = ( divStyle || { marginRight: "4px" } ).marginRight === "4px";
// Support: Android 2.3 only
// Div with explicit width and no margin-right incorrectly
// gets computed margin-right based on width of container (#3333)
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
contents = div.appendChild( document.createElement( "div" ) );
// Reset CSS: box-sizing; display; margin; border; padding
contents.style.cssText = div.style.cssText =
// Support: Android 2.3
// Vendor-prefix box-sizing
"-webkit-box-sizing:content-box;-moz-box-sizing:content-box;" +
"box-sizing:content-box;display:block;margin:0;border:0;padding:0";
contents.style.marginRight = contents.style.width = "0";
div.style.width = "1px";
reliableMarginRightVal =
!parseFloat( ( window.getComputedStyle( contents ) || {} ).marginRight );
div.removeChild( contents );
}
// Support: IE6-8
// First check that getClientRects works as expected
// Check if table cells still have offsetWidth/Height when they are set
// to display:none and there are still other visible table cells in a
// table row; if so, offsetWidth/Height are not reliable for use when
// determining if an element has been hidden directly using
// display:none (it is still safe to use offsets if a parent element is
// hidden; don safety goggles and see bug #4512 for more information).
div.style.display = "none";
reliableHiddenOffsetsVal = div.getClientRects().length === 0;
if ( reliableHiddenOffsetsVal ) {
div.style.display = "";
div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>";
div.childNodes[ 0 ].style.borderCollapse = "separate";
contents = div.getElementsByTagName( "td" );
contents[ 0 ].style.cssText = "margin:0;border:0;padding:0;display:none";
reliableHiddenOffsetsVal = contents[ 0 ].offsetHeight === 0;
if ( reliableHiddenOffsetsVal ) {
contents[ 0 ].style.display = "";
contents[ 1 ].style.display = "none";
reliableHiddenOffsetsVal = contents[ 0 ].offsetHeight === 0;
}
}
// Teardown
documentElement.removeChild( container );
}
} )();
var getStyles, curCSS,
rposition = /^(top|right|bottom|left)$/;
if ( window.getComputedStyle ) {
getStyles = function( elem ) {
// Support: IE<=11+, Firefox<=30+ (#15098, #14150)
// IE throws on elements created in popups
// FF meanwhile throws on frame elements through "defaultView.getComputedStyle"
var view = elem.ownerDocument.defaultView;
if ( !view || !view.opener ) {
view = window;
}
return view.getComputedStyle( elem );
};
curCSS = function( elem, name, computed ) {
var width, minWidth, maxWidth, ret,
style = elem.style;
computed = computed || getStyles( elem );
// getPropertyValue is only needed for .css('filter') in IE9, see #12537
ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined;
// Support: Opera 12.1x only
// Fall back to style even without computed
// computed is undefined for elems on document fragments
if ( ( ret === "" || ret === undefined ) && !jQuery.contains( elem.ownerDocument, elem ) ) {
ret = jQuery.style( elem, name );
}
if ( computed ) {
// A tribute to the "awesome hack by Dean Edwards"
// Chrome < 17 and Safari 5.0 uses "computed value"
// instead of "used value" for margin-right
// Safari 5.1.7 (at least) returns percentage for a larger set of values,
// but width seems to be reliably pixels
// this is against the CSSOM draft spec:
// http://dev.w3.org/csswg/cssom/#resolved-values
if ( !support.pixelMarginRight() && rnumnonpx.test( ret ) && rmargin.test( name ) ) {
// Remember the original values
width = style.width;
minWidth = style.minWidth;
maxWidth = style.maxWidth;
// Put in the new values to get a computed value out
style.minWidth = style.maxWidth = style.width = ret;
ret = computed.width;
// Revert the changed values
style.width = width;
style.minWidth = minWidth;
style.maxWidth = maxWidth;
}
}
// Support: IE
// IE returns zIndex value as an integer.
return ret === undefined ?
ret :
ret + "";
};
} else if ( documentElement.currentStyle ) {
getStyles = function( elem ) {
return elem.currentStyle;
};
curCSS = function( elem, name, computed ) {
var left, rs, rsLeft, ret,
style = elem.style;
computed = computed || getStyles( elem );
ret = computed ? computed[ name ] : undefined;
// Avoid setting ret to empty string here
// so we don't default to auto
if ( ret == null && style && style[ name ] ) {
ret = style[ name ];
}
// From the awesome hack by Dean Edwards
// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
// If we're not dealing with a regular pixel number
// but a number that has a weird ending, we need to convert it to pixels
// but not position css attributes, as those are
// proportional to the parent element instead
// and we can't measure the parent instead because it
// might trigger a "stacking dolls" problem
if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) {
// Remember the original values
left = style.left;
rs = elem.runtimeStyle;
rsLeft = rs && rs.left;
// Put in the new values to get a computed value out
if ( rsLeft ) {
rs.left = elem.currentStyle.left;
}
style.left = name === "fontSize" ? "1em" : ret;
ret = style.pixelLeft + "px";
// Revert the changed values
style.left = left;
if ( rsLeft ) {
rs.left = rsLeft;
}
}
// Support: IE
// IE returns zIndex value as an integer.
return ret === undefined ?
ret :
ret + "" || "auto";
};
}
function addGetHookIf( conditionFn, hookFn ) {
// Define the hook, we'll check on the first run if it's really needed.
return {
get: function() {
if ( conditionFn() ) {
// Hook not needed (or it's not possible to use it due
// to missing dependency), remove it.
delete this.get;
return;
}
// Hook needed; redefine it so that the support test is not executed again.
return ( this.get = hookFn ).apply( this, arguments );
}
};
}
var
ralpha = /alpha\([^)]*\)/i,
ropacity = /opacity\s*=\s*([^)]*)/i,
// swappable if display is none or starts with table except
// "table", "table-cell", or "table-caption"
// see here for display values:
// https://developer.mozilla.org/en-US/docs/CSS/display
rdisplayswap = /^(none|table(?!-c[ea]).+)/,
rnumsplit = new RegExp( "^(" + pnum + ")(.*)$", "i" ),
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssNormalTransform = {
letterSpacing: "0",
fontWeight: "400"
},
cssPrefixes = [ "Webkit", "O", "Moz", "ms" ],
emptyStyle = document.createElement( "div" ).style;
// return a css property mapped to a potentially vendor prefixed property
function vendorPropName( name ) {
// shortcut for names that are not vendor prefixed
if ( name in emptyStyle ) {
return name;
}
// check for vendor prefixed names
var capName = name.charAt( 0 ).toUpperCase() + name.slice( 1 ),
i = cssPrefixes.length;
while ( i-- ) {
name = cssPrefixes[ i ] + capName;
if ( name in emptyStyle ) {
return name;
}
}
}
function showHide( elements, show ) {
var display, elem, hidden,
values = [],
index = 0,
length = elements.length;
for ( ; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
values[ index ] = jQuery._data( elem, "olddisplay" );
display = elem.style.display;
if ( show ) {
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if ( !values[ index ] && display === "none" ) {
elem.style.display = "";
}
// Set elements which have been overridden with display: none
// in a stylesheet to whatever the default browser style is
// for such an element
if ( elem.style.display === "" && isHidden( elem ) ) {
values[ index ] =
jQuery._data( elem, "olddisplay", defaultDisplay( elem.nodeName ) );
}
} else {
hidden = isHidden( elem );
if ( display && display !== "none" || !hidden ) {
jQuery._data(
elem,
"olddisplay",
hidden ? display : jQuery.css( elem, "display" )
);
}
}
}
// Set the display of most of the elements in a second loop
// to avoid the constant reflow
for ( index = 0; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
if ( !show || elem.style.display === "none" || elem.style.display === "" ) {
elem.style.display = show ? values[ index ] || "" : "none";
}
}
return elements;
}
function setPositiveNumber( elem, value, subtract ) {
var matches = rnumsplit.exec( value );
return matches ?
// Guard against undefined "subtract", e.g., when used as in cssHooks
Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) :
value;
}
function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) {
var i = extra === ( isBorderBox ? "border" : "content" ) ?
// If we already have the right measurement, avoid augmentation
4 :
// Otherwise initialize for horizontal or vertical properties
name === "width" ? 1 : 0,
val = 0;
for ( ; i < 4; i += 2 ) {
// both box models exclude margin, so add it if we want it
if ( extra === "margin" ) {
val += jQuery.css( elem, extra + cssExpand[ i ], true, styles );
}
if ( isBorderBox ) {
// border-box includes padding, so remove it if we want content
if ( extra === "content" ) {
val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
}
// at this point, extra isn't border nor margin, so remove border
if ( extra !== "margin" ) {
val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
} else {
// at this point, extra isn't content, so add padding
val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
// at this point, extra isn't content nor padding, so add border
if ( extra !== "padding" ) {
val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
}
}
return val;
}
function getWidthOrHeight( elem, name, extra ) {
// Start with offset property, which is equivalent to the border-box value
var valueIsBorderBox = true,
val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
styles = getStyles( elem ),
isBorderBox = support.boxSizing &&
jQuery.css( elem, "boxSizing", false, styles ) === "border-box";
// some non-html elements return undefined for offsetWidth, so check for null/undefined
// svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285
// MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668
if ( val <= 0 || val == null ) {
// Fall back to computed then uncomputed css if necessary
val = curCSS( elem, name, styles );
if ( val < 0 || val == null ) {
val = elem.style[ name ];
}
// Computed unit is not pixels. Stop here and return.
if ( rnumnonpx.test( val ) ) {
return val;
}
// we need the check for style in case a browser which returns unreliable values
// for getComputedStyle silently falls back to the reliable elem.style
valueIsBorderBox = isBorderBox &&
( support.boxSizingReliable() || val === elem.style[ name ] );
// Normalize "", auto, and prepare for extra
val = parseFloat( val ) || 0;
}
// use the active box-sizing model to add/subtract irrelevant styles
return ( val +
augmentWidthOrHeight(
elem,
name,
extra || ( isBorderBox ? "border" : "content" ),
valueIsBorderBox,
styles
)
) + "px";
}
jQuery.extend( {
// Add in style property hooks for overriding the default
// behavior of getting and setting a style property
cssHooks: {
opacity: {
get: function( elem, computed ) {
if ( computed ) {
// We should always get a number back from opacity
var ret = curCSS( elem, "opacity" );
return ret === "" ? "1" : ret;
}
}
}
},
// Don't automatically add "px" to these possibly-unitless properties
cssNumber: {
"animationIterationCount": true,
"columnCount": true,
"fillOpacity": true,
"flexGrow": true,
"flexShrink": true,
"fontWeight": true,
"lineHeight": true,
"opacity": true,
"order": true,
"orphans": true,
"widows": true,
"zIndex": true,
"zoom": true
},
// Add in properties whose names you wish to fix before
// setting or getting the value
cssProps: {
// normalize float css property
"float": support.cssFloat ? "cssFloat" : "styleFloat"
},
// Get and set the style property on a DOM Node
style: function( elem, name, value, extra ) {
// Don't set styles on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
return;
}
// Make sure that we're working with the right name
var ret, type, hooks,
origName = jQuery.camelCase( name ),
style = elem.style;
name = jQuery.cssProps[ origName ] ||
( jQuery.cssProps[ origName ] = vendorPropName( origName ) || origName );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// Check if we're setting a value
if ( value !== undefined ) {
type = typeof value;
// Convert "+=" or "-=" to relative numbers (#7345)
if ( type === "string" && ( ret = rcssNum.exec( value ) ) && ret[ 1 ] ) {
value = adjustCSS( elem, name, ret );
// Fixes bug #9237
type = "number";
}
// Make sure that null and NaN values aren't set. See: #7116
if ( value == null || value !== value ) {
return;
}
// If a number was passed in, add the unit (except for certain CSS properties)
if ( type === "number" ) {
value += ret && ret[ 3 ] || ( jQuery.cssNumber[ origName ] ? "" : "px" );
}
// Fixes #8908, it can be done more correctly by specifing setters in cssHooks,
// but it would mean to define eight
// (for every problematic property) identical functions
if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) {
style[ name ] = "inherit";
}
// If a hook was provided, use that value, otherwise just set the specified value
if ( !hooks || !( "set" in hooks ) ||
( value = hooks.set( elem, value, extra ) ) !== undefined ) {
// Support: IE
// Swallow errors from 'invalid' CSS values (#5509)
try {
style[ name ] = value;
} catch ( e ) {}
}
} else {
// If a hook was provided get the non-computed value from there
if ( hooks && "get" in hooks &&
( ret = hooks.get( elem, false, extra ) ) !== undefined ) {
return ret;
}
// Otherwise just get the value from the style object
return style[ name ];
}
},
css: function( elem, name, extra, styles ) {
var num, val, hooks,
origName = jQuery.camelCase( name );
// Make sure that we're working with the right name
name = jQuery.cssProps[ origName ] ||
( jQuery.cssProps[ origName ] = vendorPropName( origName ) || origName );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// If a hook was provided get the computed value from there
if ( hooks && "get" in hooks ) {
val = hooks.get( elem, true, extra );
}
// Otherwise, if a way to get the computed value exists, use that
if ( val === undefined ) {
val = curCSS( elem, name, styles );
}
//convert "normal" to computed value
if ( val === "normal" && name in cssNormalTransform ) {
val = cssNormalTransform[ name ];
}
// Return, converting to number if forced or a qualifier was provided and val looks numeric
if ( extra === "" || extra ) {
num = parseFloat( val );
return extra === true || isFinite( num ) ? num || 0 : val;
}
return val;
}
} );
jQuery.each( [ "height", "width" ], function( i, name ) {
jQuery.cssHooks[ name ] = {
get: function( elem, computed, extra ) {
if ( computed ) {
// certain elements can have dimension info if we invisibly show them
// however, it must have a current display style that would benefit from this
return rdisplayswap.test( jQuery.css( elem, "display" ) ) &&
elem.offsetWidth === 0 ?
swap( elem, cssShow, function() {
return getWidthOrHeight( elem, name, extra );
} ) :
getWidthOrHeight( elem, name, extra );
}
},
set: function( elem, value, extra ) {
var styles = extra && getStyles( elem );
return setPositiveNumber( elem, value, extra ?
augmentWidthOrHeight(
elem,
name,
extra,
support.boxSizing &&
jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
styles
) : 0
);
}
};
} );
if ( !support.opacity ) {
jQuery.cssHooks.opacity = {
get: function( elem, computed ) {
// IE uses filters for opacity
return ropacity.test( ( computed && elem.currentStyle ?
elem.currentStyle.filter :
elem.style.filter ) || "" ) ?
( 0.01 * parseFloat( RegExp.$1 ) ) + "" :
computed ? "1" : "";
},
set: function( elem, value ) {
var style = elem.style,
currentStyle = elem.currentStyle,
opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "",
filter = currentStyle && currentStyle.filter || style.filter || "";
// IE has trouble with opacity if it does not have layout
// Force it by setting the zoom level
style.zoom = 1;
// if setting opacity to 1, and no other filters exist -
// attempt to remove filter attribute #6652
// if value === "", then remove inline opacity #12685
if ( ( value >= 1 || value === "" ) &&
jQuery.trim( filter.replace( ralpha, "" ) ) === "" &&
style.removeAttribute ) {
// Setting style.filter to null, "" & " " still leave "filter:" in the cssText
// if "filter:" is present at all, clearType is disabled, we want to avoid this
// style.removeAttribute is IE Only, but so apparently is this code path...
style.removeAttribute( "filter" );
// if there is no filter style applied in a css rule
// or unset inline opacity, we are done
if ( value === "" || currentStyle && !currentStyle.filter ) {
return;
}
}
// otherwise, set new filter values
style.filter = ralpha.test( filter ) ?
filter.replace( ralpha, opacity ) :
filter + " " + opacity;
}
};
}
jQuery.cssHooks.marginRight = addGetHookIf( support.reliableMarginRight,
function( elem, computed ) {
if ( computed ) {
return swap( elem, { "display": "inline-block" },
curCSS, [ elem, "marginRight" ] );
}
}
);
jQuery.cssHooks.marginLeft = addGetHookIf( support.reliableMarginLeft,
function( elem, computed ) {
if ( computed ) {
return (
parseFloat( curCSS( elem, "marginLeft" ) ) ||
// Support: IE<=11+
// Running getBoundingClientRect on a disconnected node in IE throws an error
// Support: IE8 only
// getClientRects() errors on disconnected elems
( jQuery.contains( elem.ownerDocument, elem ) ?
elem.getBoundingClientRect().left -
swap( elem, { marginLeft: 0 }, function() {
return elem.getBoundingClientRect().left;
} ) :
0
)
) + "px";
}
}
);
// These hooks are used by animate to expand properties
jQuery.each( {
margin: "",
padding: "",
border: "Width"
}, function( prefix, suffix ) {
jQuery.cssHooks[ prefix + suffix ] = {
expand: function( value ) {
var i = 0,
expanded = {},
// assumes a single number if not a string
parts = typeof value === "string" ? value.split( " " ) : [ value ];
for ( ; i < 4; i++ ) {
expanded[ prefix + cssExpand[ i ] + suffix ] =
parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
}
return expanded;
}
};
if ( !rmargin.test( prefix ) ) {
jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
}
} );
jQuery.fn.extend( {
css: function( name, value ) {
return access( this, function( elem, name, value ) {
var styles, len,
map = {},
i = 0;
if ( jQuery.isArray( name ) ) {
styles = getStyles( elem );
len = name.length;
for ( ; i < len; i++ ) {
map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles );
}
return map;
}
return value !== undefined ?
jQuery.style( elem, name, value ) :
jQuery.css( elem, name );
}, name, value, arguments.length > 1 );
},
show: function() {
return showHide( this, true );
},
hide: function() {
return showHide( this );
},
toggle: function( state ) {
if ( typeof state === "boolean" ) {
return state ? this.show() : this.hide();
}
return this.each( function() {
if ( isHidden( this ) ) {
jQuery( this ).show();
} else {
jQuery( this ).hide();
}
} );
}
} );
function Tween( elem, options, prop, end, easing ) {
return new Tween.prototype.init( elem, options, prop, end, easing );
}
jQuery.Tween = Tween;
Tween.prototype = {
constructor: Tween,
init: function( elem, options, prop, end, easing, unit ) {
this.elem = elem;
this.prop = prop;
this.easing = easing || jQuery.easing._default;
this.options = options;
this.start = this.now = this.cur();
this.end = end;
this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" );
},
cur: function() {
var hooks = Tween.propHooks[ this.prop ];
return hooks && hooks.get ?
hooks.get( this ) :
Tween.propHooks._default.get( this );
},
run: function( percent ) {
var eased,
hooks = Tween.propHooks[ this.prop ];
if ( this.options.duration ) {
this.pos = eased = jQuery.easing[ this.easing ](
percent, this.options.duration * percent, 0, 1, this.options.duration
);
} else {
this.pos = eased = percent;
}
this.now = ( this.end - this.start ) * eased + this.start;
if ( this.options.step ) {
this.options.step.call( this.elem, this.now, this );
}
if ( hooks && hooks.set ) {
hooks.set( this );
} else {
Tween.propHooks._default.set( this );
}
return this;
}
};
Tween.prototype.init.prototype = Tween.prototype;
Tween.propHooks = {
_default: {
get: function( tween ) {
var result;
// Use a property on the element directly when it is not a DOM element,
// or when there is no matching style property that exists.
if ( tween.elem.nodeType !== 1 ||
tween.elem[ tween.prop ] != null && tween.elem.style[ tween.prop ] == null ) {
return tween.elem[ tween.prop ];
}
// passing an empty string as a 3rd parameter to .css will automatically
// attempt a parseFloat and fallback to a string if the parse fails
// so, simple values such as "10px" are parsed to Float.
// complex values such as "rotate(1rad)" are returned as is.
result = jQuery.css( tween.elem, tween.prop, "" );
// Empty strings, null, undefined and "auto" are converted to 0.
return !result || result === "auto" ? 0 : result;
},
set: function( tween ) {
// use step hook for back compat - use cssHook if its there - use .style if its
// available and use plain properties where available
if ( jQuery.fx.step[ tween.prop ] ) {
jQuery.fx.step[ tween.prop ]( tween );
} else if ( tween.elem.nodeType === 1 &&
( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null ||
jQuery.cssHooks[ tween.prop ] ) ) {
jQuery.style( tween.elem, tween.prop, tween.now + tween.unit );
} else {
tween.elem[ tween.prop ] = tween.now;
}
}
}
};
// Support: IE <=9
// Panic based approach to setting things on disconnected nodes
Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
set: function( tween ) {
if ( tween.elem.nodeType && tween.elem.parentNode ) {
tween.elem[ tween.prop ] = tween.now;
}
}
};
jQuery.easing = {
linear: function( p ) {
return p;
},
swing: function( p ) {
return 0.5 - Math.cos( p * Math.PI ) / 2;
},
_default: "swing"
};
jQuery.fx = Tween.prototype.init;
// Back Compat <1.8 extension point
jQuery.fx.step = {};
var
fxNow, timerId,
rfxtypes = /^(?:toggle|show|hide)$/,
rrun = /queueHooks$/;
// Animations created synchronously will run synchronously
function createFxNow() {
window.setTimeout( function() {
fxNow = undefined;
} );
return ( fxNow = jQuery.now() );
}
// Generate parameters to create a standard animation
function genFx( type, includeWidth ) {
var which,
attrs = { height: type },
i = 0;
// if we include width, step value is 1 to do all cssExpand values,
// if we don't include width, step value is 2 to skip over Left and Right
includeWidth = includeWidth ? 1 : 0;
for ( ; i < 4 ; i += 2 - includeWidth ) {
which = cssExpand[ i ];
attrs[ "margin" + which ] = attrs[ "padding" + which ] = type;
}
if ( includeWidth ) {
attrs.opacity = attrs.width = type;
}
return attrs;
}
function createTween( value, prop, animation ) {
var tween,
collection = ( Animation.tweeners[ prop ] || [] ).concat( Animation.tweeners[ "*" ] ),
index = 0,
length = collection.length;
for ( ; index < length; index++ ) {
if ( ( tween = collection[ index ].call( animation, prop, value ) ) ) {
// we're done with this property
return tween;
}
}
}
function defaultPrefilter( elem, props, opts ) {
/* jshint validthis: true */
var prop, value, toggle, tween, hooks, oldfire, display, checkDisplay,
anim = this,
orig = {},
style = elem.style,
hidden = elem.nodeType && isHidden( elem ),
dataShow = jQuery._data( elem, "fxshow" );
// handle queue: false promises
if ( !opts.queue ) {
hooks = jQuery._queueHooks( elem, "fx" );
if ( hooks.unqueued == null ) {
hooks.unqueued = 0;
oldfire = hooks.empty.fire;
hooks.empty.fire = function() {
if ( !hooks.unqueued ) {
oldfire();
}
};
}
hooks.unqueued++;
anim.always( function() {
// doing this makes sure that the complete handler will be called
// before this completes
anim.always( function() {
hooks.unqueued--;
if ( !jQuery.queue( elem, "fx" ).length ) {
hooks.empty.fire();
}
} );
} );
}
// height/width overflow pass
if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) {
// Make sure that nothing sneaks out
// Record all 3 overflow attributes because IE does not
// change the overflow attribute when overflowX and
// overflowY are set to the same value
opts.overflow = [ style.overflow, style.overflowX, style.overflowY ];
// Set display property to inline-block for height/width
// animations on inline elements that are having width/height animated
display = jQuery.css( elem, "display" );
// Test default display if display is currently "none"
checkDisplay = display === "none" ?
jQuery._data( elem, "olddisplay" ) || defaultDisplay( elem.nodeName ) : display;
if ( checkDisplay === "inline" && jQuery.css( elem, "float" ) === "none" ) {
// inline-level elements accept inline-block;
// block-level elements need to be inline with layout
if ( !support.inlineBlockNeedsLayout || defaultDisplay( elem.nodeName ) === "inline" ) {
style.display = "inline-block";
} else {
style.zoom = 1;
}
}
}
if ( opts.overflow ) {
style.overflow = "hidden";
if ( !support.shrinkWrapBlocks() ) {
anim.always( function() {
style.overflow = opts.overflow[ 0 ];
style.overflowX = opts.overflow[ 1 ];
style.overflowY = opts.overflow[ 2 ];
} );
}
}
// show/hide pass
for ( prop in props ) {
value = props[ prop ];
if ( rfxtypes.exec( value ) ) {
delete props[ prop ];
toggle = toggle || value === "toggle";
if ( value === ( hidden ? "hide" : "show" ) ) {
// If there is dataShow left over from a stopped hide or show
// and we are going to proceed with show, we should pretend to be hidden
if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) {
hidden = true;
} else {
continue;
}
}
orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop );
// Any non-fx value stops us from restoring the original display value
} else {
display = undefined;
}
}
if ( !jQuery.isEmptyObject( orig ) ) {
if ( dataShow ) {
if ( "hidden" in dataShow ) {
hidden = dataShow.hidden;
}
} else {
dataShow = jQuery._data( elem, "fxshow", {} );
}
// store state if its toggle - enables .stop().toggle() to "reverse"
if ( toggle ) {
dataShow.hidden = !hidden;
}
if ( hidden ) {
jQuery( elem ).show();
} else {
anim.done( function() {
jQuery( elem ).hide();
} );
}
anim.done( function() {
var prop;
jQuery._removeData( elem, "fxshow" );
for ( prop in orig ) {
jQuery.style( elem, prop, orig[ prop ] );
}
} );
for ( prop in orig ) {
tween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim );
if ( !( prop in dataShow ) ) {
dataShow[ prop ] = tween.start;
if ( hidden ) {
tween.end = tween.start;
tween.start = prop === "width" || prop === "height" ? 1 : 0;
}
}
}
// If this is a noop like .hide().hide(), restore an overwritten display value
} else if ( ( display === "none" ? defaultDisplay( elem.nodeName ) : display ) === "inline" ) {
style.display = display;
}
}
function propFilter( props, specialEasing ) {
var index, name, easing, value, hooks;
// camelCase, specialEasing and expand cssHook pass
for ( index in props ) {
name = jQuery.camelCase( index );
easing = specialEasing[ name ];
value = props[ index ];
if ( jQuery.isArray( value ) ) {
easing = value[ 1 ];
value = props[ index ] = value[ 0 ];
}
if ( index !== name ) {
props[ name ] = value;
delete props[ index ];
}
hooks = jQuery.cssHooks[ name ];
if ( hooks && "expand" in hooks ) {
value = hooks.expand( value );
delete props[ name ];
// not quite $.extend, this wont overwrite keys already present.
// also - reusing 'index' from above because we have the correct "name"
for ( index in value ) {
if ( !( index in props ) ) {
props[ index ] = value[ index ];
specialEasing[ index ] = easing;
}
}
} else {
specialEasing[ name ] = easing;
}
}
}
function Animation( elem, properties, options ) {
var result,
stopped,
index = 0,
length = Animation.prefilters.length,
deferred = jQuery.Deferred().always( function() {
// don't match elem in the :animated selector
delete tick.elem;
} ),
tick = function() {
if ( stopped ) {
return false;
}
var currentTime = fxNow || createFxNow(),
remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ),
// Support: Android 2.3
// Archaic crash bug won't allow us to use `1 - ( 0.5 || 0 )` (#12497)
temp = remaining / animation.duration || 0,
percent = 1 - temp,
index = 0,
length = animation.tweens.length;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( percent );
}
deferred.notifyWith( elem, [ animation, percent, remaining ] );
if ( percent < 1 && length ) {
return remaining;
} else {
deferred.resolveWith( elem, [ animation ] );
return false;
}
},
animation = deferred.promise( {
elem: elem,
props: jQuery.extend( {}, properties ),
opts: jQuery.extend( true, {
specialEasing: {},
easing: jQuery.easing._default
}, options ),
originalProperties: properties,
originalOptions: options,
startTime: fxNow || createFxNow(),
duration: options.duration,
tweens: [],
createTween: function( prop, end ) {
var tween = jQuery.Tween( elem, animation.opts, prop, end,
animation.opts.specialEasing[ prop ] || animation.opts.easing );
animation.tweens.push( tween );
return tween;
},
stop: function( gotoEnd ) {
var index = 0,
// if we are going to the end, we want to run all the tweens
// otherwise we skip this part
length = gotoEnd ? animation.tweens.length : 0;
if ( stopped ) {
return this;
}
stopped = true;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( 1 );
}
// resolve when we played the last frame
// otherwise, reject
if ( gotoEnd ) {
deferred.notifyWith( elem, [ animation, 1, 0 ] );
deferred.resolveWith( elem, [ animation, gotoEnd ] );
} else {
deferred.rejectWith( elem, [ animation, gotoEnd ] );
}
return this;
}
} ),
props = animation.props;
propFilter( props, animation.opts.specialEasing );
for ( ; index < length ; index++ ) {
result = Animation.prefilters[ index ].call( animation, elem, props, animation.opts );
if ( result ) {
if ( jQuery.isFunction( result.stop ) ) {
jQuery._queueHooks( animation.elem, animation.opts.queue ).stop =
jQuery.proxy( result.stop, result );
}
return result;
}
}
jQuery.map( props, createTween, animation );
if ( jQuery.isFunction( animation.opts.start ) ) {
animation.opts.start.call( elem, animation );
}
jQuery.fx.timer(
jQuery.extend( tick, {
elem: elem,
anim: animation,
queue: animation.opts.queue
} )
);
// attach callbacks from options
return animation.progress( animation.opts.progress )
.done( animation.opts.done, animation.opts.complete )
.fail( animation.opts.fail )
.always( animation.opts.always );
}
jQuery.Animation = jQuery.extend( Animation, {
tweeners: {
"*": [ function( prop, value ) {
var tween = this.createTween( prop, value );
adjustCSS( tween.elem, prop, rcssNum.exec( value ), tween );
return tween;
} ]
},
tweener: function( props, callback ) {
if ( jQuery.isFunction( props ) ) {
callback = props;
props = [ "*" ];
} else {
props = props.match( rnotwhite );
}
var prop,
index = 0,
length = props.length;
for ( ; index < length ; index++ ) {
prop = props[ index ];
Animation.tweeners[ prop ] = Animation.tweeners[ prop ] || [];
Animation.tweeners[ prop ].unshift( callback );
}
},
prefilters: [ defaultPrefilter ],
prefilter: function( callback, prepend ) {
if ( prepend ) {
Animation.prefilters.unshift( callback );
} else {
Animation.prefilters.push( callback );
}
}
} );
jQuery.speed = function( speed, easing, fn ) {
var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
complete: fn || !fn && easing ||
jQuery.isFunction( speed ) && speed,
duration: speed,
easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing
};
opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
opt.duration in jQuery.fx.speeds ?
jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default;
// normalize opt.queue - true/undefined/null -> "fx"
if ( opt.queue == null || opt.queue === true ) {
opt.queue = "fx";
}
// Queueing
opt.old = opt.complete;
opt.complete = function() {
if ( jQuery.isFunction( opt.old ) ) {
opt.old.call( this );
}
if ( opt.queue ) {
jQuery.dequeue( this, opt.queue );
}
};
return opt;
};
jQuery.fn.extend( {
fadeTo: function( speed, to, easing, callback ) {
// show any hidden elements after setting opacity to 0
return this.filter( isHidden ).css( "opacity", 0 ).show()
// animate to the value specified
.end().animate( { opacity: to }, speed, easing, callback );
},
animate: function( prop, speed, easing, callback ) {
var empty = jQuery.isEmptyObject( prop ),
optall = jQuery.speed( speed, easing, callback ),
doAnimation = function() {
// Operate on a copy of prop so per-property easing won't be lost
var anim = Animation( this, jQuery.extend( {}, prop ), optall );
// Empty animations, or finishing resolves immediately
if ( empty || jQuery._data( this, "finish" ) ) {
anim.stop( true );
}
};
doAnimation.finish = doAnimation;
return empty || optall.queue === false ?
this.each( doAnimation ) :
this.queue( optall.queue, doAnimation );
},
stop: function( type, clearQueue, gotoEnd ) {
var stopQueue = function( hooks ) {
var stop = hooks.stop;
delete hooks.stop;
stop( gotoEnd );
};
if ( typeof type !== "string" ) {
gotoEnd = clearQueue;
clearQueue = type;
type = undefined;
}
if ( clearQueue && type !== false ) {
this.queue( type || "fx", [] );
}
return this.each( function() {
var dequeue = true,
index = type != null && type + "queueHooks",
timers = jQuery.timers,
data = jQuery._data( this );
if ( index ) {
if ( data[ index ] && data[ index ].stop ) {
stopQueue( data[ index ] );
}
} else {
for ( index in data ) {
if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) {
stopQueue( data[ index ] );
}
}
}
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this &&
( type == null || timers[ index ].queue === type ) ) {
timers[ index ].anim.stop( gotoEnd );
dequeue = false;
timers.splice( index, 1 );
}
}
// start the next in the queue if the last step wasn't forced
// timers currently will call their complete callbacks, which will dequeue
// but only if they were gotoEnd
if ( dequeue || !gotoEnd ) {
jQuery.dequeue( this, type );
}
} );
},
finish: function( type ) {
if ( type !== false ) {
type = type || "fx";
}
return this.each( function() {
var index,
data = jQuery._data( this ),
queue = data[ type + "queue" ],
hooks = data[ type + "queueHooks" ],
timers = jQuery.timers,
length = queue ? queue.length : 0;
// enable finishing flag on private data
data.finish = true;
// empty the queue first
jQuery.queue( this, type, [] );
if ( hooks && hooks.stop ) {
hooks.stop.call( this, true );
}
// look for any active animations, and finish them
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && timers[ index ].queue === type ) {
timers[ index ].anim.stop( true );
timers.splice( index, 1 );
}
}
// look for any animations in the old queue and finish them
for ( index = 0; index < length; index++ ) {
if ( queue[ index ] && queue[ index ].finish ) {
queue[ index ].finish.call( this );
}
}
// turn off finishing flag
delete data.finish;
} );
}
} );
jQuery.each( [ "toggle", "show", "hide" ], function( i, name ) {
var cssFn = jQuery.fn[ name ];
jQuery.fn[ name ] = function( speed, easing, callback ) {
return speed == null || typeof speed === "boolean" ?
cssFn.apply( this, arguments ) :
this.animate( genFx( name, true ), speed, easing, callback );
};
} );
// Generate shortcuts for custom animations
jQuery.each( {
slideDown: genFx( "show" ),
slideUp: genFx( "hide" ),
slideToggle: genFx( "toggle" ),
fadeIn: { opacity: "show" },
fadeOut: { opacity: "hide" },
fadeToggle: { opacity: "toggle" }
}, function( name, props ) {
jQuery.fn[ name ] = function( speed, easing, callback ) {
return this.animate( props, speed, easing, callback );
};
} );
jQuery.timers = [];
jQuery.fx.tick = function() {
var timer,
timers = jQuery.timers,
i = 0;
fxNow = jQuery.now();
for ( ; i < timers.length; i++ ) {
timer = timers[ i ];
// Checks the timer has not already been removed
if ( !timer() && timers[ i ] === timer ) {
timers.splice( i--, 1 );
}
}
if ( !timers.length ) {
jQuery.fx.stop();
}
fxNow = undefined;
};
jQuery.fx.timer = function( timer ) {
jQuery.timers.push( timer );
if ( timer() ) {
jQuery.fx.start();
} else {
jQuery.timers.pop();
}
};
jQuery.fx.interval = 13;
jQuery.fx.start = function() {
if ( !timerId ) {
timerId = window.setInterval( jQuery.fx.tick, jQuery.fx.interval );
}
};
jQuery.fx.stop = function() {
window.clearInterval( timerId );
timerId = null;
};
jQuery.fx.speeds = {
slow: 600,
fast: 200,
// Default speed
_default: 400
};
// Based off of the plugin by Clint Helfers, with permission.
// http://web.archive.org/web/20100324014747/http://blindsignals.com/index.php/2009/07/jquery-delay/
jQuery.fn.delay = function( time, type ) {
time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
type = type || "fx";
return this.queue( type, function( next, hooks ) {
var timeout = window.setTimeout( next, time );
hooks.stop = function() {
window.clearTimeout( timeout );
};
} );
};
( function() {
var a,
input = document.createElement( "input" ),
div = document.createElement( "div" ),
select = document.createElement( "select" ),
opt = select.appendChild( document.createElement( "option" ) );
// Setup
div = document.createElement( "div" );
div.setAttribute( "className", "t" );
div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
a = div.getElementsByTagName( "a" )[ 0 ];
// Support: Windows Web Apps (WWA)
// `type` must use .setAttribute for WWA (#14901)
input.setAttribute( "type", "checkbox" );
div.appendChild( input );
a = div.getElementsByTagName( "a" )[ 0 ];
// First batch of tests.
a.style.cssText = "top:1px";
// Test setAttribute on camelCase class.
// If it works, we need attrFixes when doing get/setAttribute (ie6/7)
support.getSetAttribute = div.className !== "t";
// Get the style information from getAttribute
// (IE uses .cssText instead)
support.style = /top/.test( a.getAttribute( "style" ) );
// Make sure that URLs aren't manipulated
// (IE normalizes it by default)
support.hrefNormalized = a.getAttribute( "href" ) === "/a";
// Check the default checkbox/radio value ("" on WebKit; "on" elsewhere)
support.checkOn = !!input.value;
// Make sure that a selected-by-default option has a working selected property.
// (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
support.optSelected = opt.selected;
// Tests for enctype support on a form (#6743)
support.enctype = !!document.createElement( "form" ).enctype;
// Make sure that the options inside disabled selects aren't marked as disabled
// (WebKit marks them as disabled)
select.disabled = true;
support.optDisabled = !opt.disabled;
// Support: IE8 only
// Check if we can trust getAttribute("value")
input = document.createElement( "input" );
input.setAttribute( "value", "" );
support.input = input.getAttribute( "value" ) === "";
// Check if an input maintains its value after becoming a radio
input.value = "t";
input.setAttribute( "type", "radio" );
support.radioValue = input.value === "t";
} )();
var rreturn = /\r/g,
rspaces = /[\x20\t\r\n\f]+/g;
jQuery.fn.extend( {
val: function( value ) {
var hooks, ret, isFunction,
elem = this[ 0 ];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.type ] ||
jQuery.valHooks[ elem.nodeName.toLowerCase() ];
if (
hooks &&
"get" in hooks &&
( ret = hooks.get( elem, "value" ) ) !== undefined
) {
return ret;
}
ret = elem.value;
return typeof ret === "string" ?
// handle most common string cases
ret.replace( rreturn, "" ) :
// handle cases where value is null/undef or number
ret == null ? "" : ret;
}
return;
}
isFunction = jQuery.isFunction( value );
return this.each( function( i ) {
var val;
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call( this, i, jQuery( this ).val() );
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( jQuery.isArray( val ) ) {
val = jQuery.map( val, function( value ) {
return value == null ? "" : value + "";
} );
}
hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
// If set returns undefined, fall back to normal setting
if ( !hooks || !( "set" in hooks ) || hooks.set( this, val, "value" ) === undefined ) {
this.value = val;
}
} );
}
} );
jQuery.extend( {
valHooks: {
option: {
get: function( elem ) {
var val = jQuery.find.attr( elem, "value" );
return val != null ?
val :
// Support: IE10-11+
// option.text throws exceptions (#14686, #14858)
// Strip and collapse whitespace
// https://html.spec.whatwg.org/#strip-and-collapse-whitespace
jQuery.trim( jQuery.text( elem ) ).replace( rspaces, " " );
}
},
select: {
get: function( elem ) {
var value, option,
options = elem.options,
index = elem.selectedIndex,
one = elem.type === "select-one" || index < 0,
values = one ? null : [],
max = one ? index + 1 : options.length,
i = index < 0 ?
max :
one ? index : 0;
// Loop through all the selected options
for ( ; i < max; i++ ) {
option = options[ i ];
// oldIE doesn't update selected after form reset (#2551)
if ( ( option.selected || i === index ) &&
// Don't return options that are disabled or in a disabled optgroup
( support.optDisabled ?
!option.disabled :
option.getAttribute( "disabled" ) === null ) &&
( !option.parentNode.disabled ||
!jQuery.nodeName( option.parentNode, "optgroup" ) ) ) {
// Get the specific value for the option
value = jQuery( option ).val();
// We don't need an array for one selects
if ( one ) {
return value;
}
// Multi-Selects return an array
values.push( value );
}
}
return values;
},
set: function( elem, value ) {
var optionSet, option,
options = elem.options,
values = jQuery.makeArray( value ),
i = options.length;
while ( i-- ) {
option = options[ i ];
if ( jQuery.inArray( jQuery.valHooks.option.get( option ), values ) > -1 ) {
// Support: IE6
// When new option element is added to select box we need to
// force reflow of newly added node in order to workaround delay
// of initialization properties
try {
option.selected = optionSet = true;
} catch ( _ ) {
// Will be executed only in IE6
option.scrollHeight;
}
} else {
option.selected = false;
}
}
// Force browsers to behave consistently when non-matching value is set
if ( !optionSet ) {
elem.selectedIndex = -1;
}
return options;
}
}
}
} );
// Radios and checkboxes getter/setter
jQuery.each( [ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = {
set: function( elem, value ) {
if ( jQuery.isArray( value ) ) {
return ( elem.checked = jQuery.inArray( jQuery( elem ).val(), value ) > -1 );
}
}
};
if ( !support.checkOn ) {
jQuery.valHooks[ this ].get = function( elem ) {
return elem.getAttribute( "value" ) === null ? "on" : elem.value;
};
}
} );
var nodeHook, boolHook,
attrHandle = jQuery.expr.attrHandle,
ruseDefault = /^(?:checked|selected)$/i,
getSetAttribute = support.getSetAttribute,
getSetInput = support.input;
jQuery.fn.extend( {
attr: function( name, value ) {
return access( this, jQuery.attr, name, value, arguments.length > 1 );
},
removeAttr: function( name ) {
return this.each( function() {
jQuery.removeAttr( this, name );
} );
}
} );
jQuery.extend( {
attr: function( elem, name, value ) {
var ret, hooks,
nType = elem.nodeType;
// Don't get/set attributes on text, comment and attribute nodes
if ( nType === 3 || nType === 8 || nType === 2 ) {
return;
}
// Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === "undefined" ) {
return jQuery.prop( elem, name, value );
}
// All attributes are lowercase
// Grab necessary hook if one is defined
if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
name = name.toLowerCase();
hooks = jQuery.attrHooks[ name ] ||
( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook );
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
return;
}
if ( hooks && "set" in hooks &&
( ret = hooks.set( elem, value, name ) ) !== undefined ) {
return ret;
}
elem.setAttribute( name, value + "" );
return value;
}
if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) {
return ret;
}
ret = jQuery.find.attr( elem, name );
// Non-existent attributes return null, we normalize to undefined
return ret == null ? undefined : ret;
},
attrHooks: {
type: {
set: function( elem, value ) {
if ( !support.radioValue && value === "radio" &&
jQuery.nodeName( elem, "input" ) ) {
// Setting the type on a radio button after the value resets the value in IE8-9
// Reset value to default in case type is set after value during creation
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
}
},
removeAttr: function( elem, value ) {
var name, propName,
i = 0,
attrNames = value && value.match( rnotwhite );
if ( attrNames && elem.nodeType === 1 ) {
while ( ( name = attrNames[ i++ ] ) ) {
propName = jQuery.propFix[ name ] || name;
// Boolean attributes get special treatment (#10870)
if ( jQuery.expr.match.bool.test( name ) ) {
// Set corresponding property to false
if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {
elem[ propName ] = false;
// Support: IE<9
// Also clear defaultChecked/defaultSelected (if appropriate)
} else {
elem[ jQuery.camelCase( "default-" + name ) ] =
elem[ propName ] = false;
}
// See #9699 for explanation of this approach (setting first, then removal)
} else {
jQuery.attr( elem, name, "" );
}
elem.removeAttribute( getSetAttribute ? name : propName );
}
}
}
} );
// Hooks for boolean attributes
boolHook = {
set: function( elem, value, name ) {
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {
// IE<8 needs the *property* name
elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name );
} else {
// Support: IE<9
// Use defaultChecked and defaultSelected for oldIE
elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true;
}
return name;
}
};
jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) {
var getter = attrHandle[ name ] || jQuery.find.attr;
if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {
attrHandle[ name ] = function( elem, name, isXML ) {
var ret, handle;
if ( !isXML ) {
// Avoid an infinite loop by temporarily removing this function from the getter
handle = attrHandle[ name ];
attrHandle[ name ] = ret;
ret = getter( elem, name, isXML ) != null ?
name.toLowerCase() :
null;
attrHandle[ name ] = handle;
}
return ret;
};
} else {
attrHandle[ name ] = function( elem, name, isXML ) {
if ( !isXML ) {
return elem[ jQuery.camelCase( "default-" + name ) ] ?
name.toLowerCase() :
null;
}
};
}
} );
// fix oldIE attroperties
if ( !getSetInput || !getSetAttribute ) {
jQuery.attrHooks.value = {
set: function( elem, value, name ) {
if ( jQuery.nodeName( elem, "input" ) ) {
// Does not return so that setAttribute is also used
elem.defaultValue = value;
} else {
// Use nodeHook if defined (#1954); otherwise setAttribute is fine
return nodeHook && nodeHook.set( elem, value, name );
}
}
};
}
// IE6/7 do not support getting/setting some attributes with get/setAttribute
if ( !getSetAttribute ) {
// Use this for any attribute in IE6/7
// This fixes almost every IE6/7 issue
nodeHook = {
set: function( elem, value, name ) {
// Set the existing or create a new attribute node
var ret = elem.getAttributeNode( name );
if ( !ret ) {
elem.setAttributeNode(
( ret = elem.ownerDocument.createAttribute( name ) )
);
}
ret.value = value += "";
// Break association with cloned elements by also using setAttribute (#9646)
if ( name === "value" || value === elem.getAttribute( name ) ) {
return value;
}
}
};
// Some attributes are constructed with empty-string values when not defined
attrHandle.id = attrHandle.name = attrHandle.coords =
function( elem, name, isXML ) {
var ret;
if ( !isXML ) {
return ( ret = elem.getAttributeNode( name ) ) && ret.value !== "" ?
ret.value :
null;
}
};
// Fixing value retrieval on a button requires this module
jQuery.valHooks.button = {
get: function( elem, name ) {
var ret = elem.getAttributeNode( name );
if ( ret && ret.specified ) {
return ret.value;
}
},
set: nodeHook.set
};
// Set contenteditable to false on removals(#10429)
// Setting to empty string throws an error as an invalid value
jQuery.attrHooks.contenteditable = {
set: function( elem, value, name ) {
nodeHook.set( elem, value === "" ? false : value, name );
}
};
// Set width and height to auto instead of 0 on empty string( Bug #8150 )
// This is for removals
jQuery.each( [ "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = {
set: function( elem, value ) {
if ( value === "" ) {
elem.setAttribute( name, "auto" );
return value;
}
}
};
} );
}
if ( !support.style ) {
jQuery.attrHooks.style = {
get: function( elem ) {
// Return undefined in the case of empty string
// Note: IE uppercases css property names, but if we were to .toLowerCase()
// .cssText, that would destroy case sensitivity in URL's, like in "background"
return elem.style.cssText || undefined;
},
set: function( elem, value ) {
return ( elem.style.cssText = value + "" );
}
};
}
var rfocusable = /^(?:input|select|textarea|button|object)$/i,
rclickable = /^(?:a|area)$/i;
jQuery.fn.extend( {
prop: function( name, value ) {
return access( this, jQuery.prop, name, value, arguments.length > 1 );
},
removeProp: function( name ) {
name = jQuery.propFix[ name ] || name;
return this.each( function() {
// try/catch handles cases where IE balks (such as removing a property on window)
try {
this[ name ] = undefined;
delete this[ name ];
} catch ( e ) {}
} );
}
} );
jQuery.extend( {
prop: function( elem, name, value ) {
var ret, hooks,
nType = elem.nodeType;
// Don't get/set properties on text, comment and attribute nodes
if ( nType === 3 || nType === 8 || nType === 2 ) {
return;
}
if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
// Fix name and attach hooks
name = jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
}
if ( value !== undefined ) {
if ( hooks && "set" in hooks &&
( ret = hooks.set( elem, value, name ) ) !== undefined ) {
return ret;
}
return ( elem[ name ] = value );
}
if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) {
return ret;
}
return elem[ name ];
},
propHooks: {
tabIndex: {
get: function( elem ) {
// elem.tabIndex doesn't always return the
// correct value when it hasn't been explicitly set
// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
// Use proper attribute retrieval(#12072)
var tabindex = jQuery.find.attr( elem, "tabindex" );
return tabindex ?
parseInt( tabindex, 10 ) :
rfocusable.test( elem.nodeName ) ||
rclickable.test( elem.nodeName ) && elem.href ?
0 :
-1;
}
}
},
propFix: {
"for": "htmlFor",
"class": "className"
}
} );
// Some attributes require a special call on IE
// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
if ( !support.hrefNormalized ) {
// href/src property should get the full normalized URL (#10299/#12915)
jQuery.each( [ "href", "src" ], function( i, name ) {
jQuery.propHooks[ name ] = {
get: function( elem ) {
return elem.getAttribute( name, 4 );
}
};
} );
}
// Support: Safari, IE9+
// Accessing the selectedIndex property
// forces the browser to respect setting selected
// on the option
// The getter ensures a default option is selected
// when in an optgroup
if ( !support.optSelected ) {
jQuery.propHooks.selected = {
get: function( elem ) {
var parent = elem.parentNode;
if ( parent ) {
parent.selectedIndex;
// Make sure that it also works with optgroups, see #5701
if ( parent.parentNode ) {
parent.parentNode.selectedIndex;
}
}
return null;
},
set: function( elem ) {
var parent = elem.parentNode;
if ( parent ) {
parent.selectedIndex;
if ( parent.parentNode ) {
parent.parentNode.selectedIndex;
}
}
}
};
}
jQuery.each( [
"tabIndex",
"readOnly",
"maxLength",
"cellSpacing",
"cellPadding",
"rowSpan",
"colSpan",
"useMap",
"frameBorder",
"contentEditable"
], function() {
jQuery.propFix[ this.toLowerCase() ] = this;
} );
// IE6/7 call enctype encoding
if ( !support.enctype ) {
jQuery.propFix.enctype = "encoding";
}
var rclass = /[\t\r\n\f]/g;
function getClass( elem ) {
return jQuery.attr( elem, "class" ) || "";
}
jQuery.fn.extend( {
addClass: function( value ) {
var classes, elem, cur, curValue, clazz, j, finalValue,
i = 0;
if ( jQuery.isFunction( value ) ) {
return this.each( function( j ) {
jQuery( this ).addClass( value.call( this, j, getClass( this ) ) );
} );
}
if ( typeof value === "string" && value ) {
classes = value.match( rnotwhite ) || [];
while ( ( elem = this[ i++ ] ) ) {
curValue = getClass( elem );
cur = elem.nodeType === 1 &&
( " " + curValue + " " ).replace( rclass, " " );
if ( cur ) {
j = 0;
while ( ( clazz = classes[ j++ ] ) ) {
if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
cur += clazz + " ";
}
}
// only assign if different to avoid unneeded rendering.
finalValue = jQuery.trim( cur );
if ( curValue !== finalValue ) {
jQuery.attr( elem, "class", finalValue );
}
}
}
}
return this;
},
removeClass: function( value ) {
var classes, elem, cur, curValue, clazz, j, finalValue,
i = 0;
if ( jQuery.isFunction( value ) ) {
return this.each( function( j ) {
jQuery( this ).removeClass( value.call( this, j, getClass( this ) ) );
} );
}
if ( !arguments.length ) {
return this.attr( "class", "" );
}
if ( typeof value === "string" && value ) {
classes = value.match( rnotwhite ) || [];
while ( ( elem = this[ i++ ] ) ) {
curValue = getClass( elem );
// This expression is here for better compressibility (see addClass)
cur = elem.nodeType === 1 &&
( " " + curValue + " " ).replace( rclass, " " );
if ( cur ) {
j = 0;
while ( ( clazz = classes[ j++ ] ) ) {
// Remove *all* instances
while ( cur.indexOf( " " + clazz + " " ) > -1 ) {
cur = cur.replace( " " + clazz + " ", " " );
}
}
// Only assign if different to avoid unneeded rendering.
finalValue = jQuery.trim( cur );
if ( curValue !== finalValue ) {
jQuery.attr( elem, "class", finalValue );
}
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
var type = typeof value;
if ( typeof stateVal === "boolean" && type === "string" ) {
return stateVal ? this.addClass( value ) : this.removeClass( value );
}
if ( jQuery.isFunction( value ) ) {
return this.each( function( i ) {
jQuery( this ).toggleClass(
value.call( this, i, getClass( this ), stateVal ),
stateVal
);
} );
}
return this.each( function() {
var className, i, self, classNames;
if ( type === "string" ) {
// Toggle individual class names
i = 0;
self = jQuery( this );
classNames = value.match( rnotwhite ) || [];
while ( ( className = classNames[ i++ ] ) ) {
// Check each className given, space separated list
if ( self.hasClass( className ) ) {
self.removeClass( className );
} else {
self.addClass( className );
}
}
// Toggle whole class name
} else if ( value === undefined || type === "boolean" ) {
className = getClass( this );
if ( className ) {
// store className if set
jQuery._data( this, "__className__", className );
}
// If the element has a class name or if we're passed "false",
// then remove the whole classname (if there was one, the above saved it).
// Otherwise bring back whatever was previously saved (if anything),
// falling back to the empty string if nothing was stored.
jQuery.attr( this, "class",
className || value === false ?
"" :
jQuery._data( this, "__className__" ) || ""
);
}
} );
},
hasClass: function( selector ) {
var className, elem,
i = 0;
className = " " + selector + " ";
while ( ( elem = this[ i++ ] ) ) {
if ( elem.nodeType === 1 &&
( " " + getClass( elem ) + " " ).replace( rclass, " " )
.indexOf( className ) > -1
) {
return true;
}
}
return false;
}
} );
// Return jQuery for attributes-only inclusion
jQuery.each( ( "blur focus focusin focusout load resize scroll unload click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup error contextmenu" ).split( " " ),
function( i, name ) {
// Handle event binding
jQuery.fn[ name ] = function( data, fn ) {
return arguments.length > 0 ?
this.on( name, null, data, fn ) :
this.trigger( name );
};
} );
jQuery.fn.extend( {
hover: function( fnOver, fnOut ) {
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
}
} );
var location = window.location;
var nonce = jQuery.now();
var rquery = ( /\?/ );
var rvalidtokens = /(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;
jQuery.parseJSON = function( data ) {
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
// Support: Android 2.3
// Workaround failure to string-cast null input
return window.JSON.parse( data + "" );
}
var requireNonComma,
depth = null,
str = jQuery.trim( data + "" );
// Guard against invalid (and possibly dangerous) input by ensuring that nothing remains
// after removing valid tokens
return str && !jQuery.trim( str.replace( rvalidtokens, function( token, comma, open, close ) {
// Force termination if we see a misplaced comma
if ( requireNonComma && comma ) {
depth = 0;
}
// Perform no more replacements after returning to outermost depth
if ( depth === 0 ) {
return token;
}
// Commas must not follow "[", "{", or ","
requireNonComma = open || comma;
// Determine new depth
// array/object open ("[" or "{"): depth += true - false (increment)
// array/object close ("]" or "}"): depth += false - true (decrement)
// other cases ("," or primitive): depth += true - true (numeric cast)
depth += !close - !open;
// Remove this token
return "";
} ) ) ?
( Function( "return " + str ) )() :
jQuery.error( "Invalid JSON: " + data );
};
// Cross-browser xml parsing
jQuery.parseXML = function( data ) {
var xml, tmp;
if ( !data || typeof data !== "string" ) {
return null;
}
try {
if ( window.DOMParser ) { // Standard
tmp = new window.DOMParser();
xml = tmp.parseFromString( data, "text/xml" );
} else { // IE
xml = new window.ActiveXObject( "Microsoft.XMLDOM" );
xml.async = "false";
xml.loadXML( data );
}
} catch ( e ) {
xml = undefined;
}
if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
};
var
rhash = /#.*$/,
rts = /([?&])_=[^&]*/,
// IE leaves an \r character at EOL
rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg,
// #7653, #8125, #8152: local protocol detection
rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
rnoContent = /^(?:GET|HEAD)$/,
rprotocol = /^\/\//,
rurl = /^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,
/* Prefilters
* 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
* 2) These are called:
* - BEFORE asking for a transport
* - AFTER param serialization (s.data is a string if s.processData is true)
* 3) key is the dataType
* 4) the catchall symbol "*" can be used
* 5) execution will start with transport dataType and THEN continue down to "*" if needed
*/
prefilters = {},
/* Transports bindings
* 1) key is the dataType
* 2) the catchall symbol "*" can be used
* 3) selection will start with transport dataType and THEN go to "*" if needed
*/
transports = {},
// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
allTypes = "*/".concat( "*" ),
// Document location
ajaxLocation = location.href,
// Segment location into parts
ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];
// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports( structure ) {
// dataTypeExpression is optional and defaults to "*"
return function( dataTypeExpression, func ) {
if ( typeof dataTypeExpression !== "string" ) {
func = dataTypeExpression;
dataTypeExpression = "*";
}
var dataType,
i = 0,
dataTypes = dataTypeExpression.toLowerCase().match( rnotwhite ) || [];
if ( jQuery.isFunction( func ) ) {
// For each dataType in the dataTypeExpression
while ( ( dataType = dataTypes[ i++ ] ) ) {
// Prepend if requested
if ( dataType.charAt( 0 ) === "+" ) {
dataType = dataType.slice( 1 ) || "*";
( structure[ dataType ] = structure[ dataType ] || [] ).unshift( func );
// Otherwise append
} else {
( structure[ dataType ] = structure[ dataType ] || [] ).push( func );
}
}
}
};
}
// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) {
var inspected = {},
seekingTransport = ( structure === transports );
function inspect( dataType ) {
var selected;
inspected[ dataType ] = true;
jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) {
var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR );
if ( typeof dataTypeOrTransport === "string" &&
!seekingTransport && !inspected[ dataTypeOrTransport ] ) {
options.dataTypes.unshift( dataTypeOrTransport );
inspect( dataTypeOrTransport );
return false;
} else if ( seekingTransport ) {
return !( selected = dataTypeOrTransport );
}
} );
return selected;
}
return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" );
}
// A special extend for ajax options
// that takes "flat" options (not to be deep extended)
// Fixes #9887
function ajaxExtend( target, src ) {
var deep, key,
flatOptions = jQuery.ajaxSettings.flatOptions || {};
for ( key in src ) {
if ( src[ key ] !== undefined ) {
( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ];
}
}
if ( deep ) {
jQuery.extend( true, target, deep );
}
return target;
}
/* Handles responses to an ajax request:
* - finds the right dataType (mediates between content-type and expected dataType)
* - returns the corresponding response
*/
function ajaxHandleResponses( s, jqXHR, responses ) {
var firstDataType, ct, finalDataType, type,
contents = s.contents,
dataTypes = s.dataTypes;
// Remove auto dataType and get content-type in the process
while ( dataTypes[ 0 ] === "*" ) {
dataTypes.shift();
if ( ct === undefined ) {
ct = s.mimeType || jqXHR.getResponseHeader( "Content-Type" );
}
}
// Check if we're dealing with a known content-type
if ( ct ) {
for ( type in contents ) {
if ( contents[ type ] && contents[ type ].test( ct ) ) {
dataTypes.unshift( type );
break;
}
}
}
// Check to see if we have a response for the expected dataType
if ( dataTypes[ 0 ] in responses ) {
finalDataType = dataTypes[ 0 ];
} else {
// Try convertible dataTypes
for ( type in responses ) {
if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[ 0 ] ] ) {
finalDataType = type;
break;
}
if ( !firstDataType ) {
firstDataType = type;
}
}
// Or just use first one
finalDataType = finalDataType || firstDataType;
}
// If we found a dataType
// We add the dataType to the list if needed
// and return the corresponding response
if ( finalDataType ) {
if ( finalDataType !== dataTypes[ 0 ] ) {
dataTypes.unshift( finalDataType );
}
return responses[ finalDataType ];
}
}
/* Chain conversions given the request and the original response
* Also sets the responseXXX fields on the jqXHR instance
*/
function ajaxConvert( s, response, jqXHR, isSuccess ) {
var conv2, current, conv, tmp, prev,
converters = {},
// Work with a copy of dataTypes in case we need to modify it for conversion
dataTypes = s.dataTypes.slice();
// Create converters map with lowercased keys
if ( dataTypes[ 1 ] ) {
for ( conv in s.converters ) {
converters[ conv.toLowerCase() ] = s.converters[ conv ];
}
}
current = dataTypes.shift();
// Convert to each sequential dataType
while ( current ) {
if ( s.responseFields[ current ] ) {
jqXHR[ s.responseFields[ current ] ] = response;
}
// Apply the dataFilter if provided
if ( !prev && isSuccess && s.dataFilter ) {
response = s.dataFilter( response, s.dataType );
}
prev = current;
current = dataTypes.shift();
if ( current ) {
// There's only work to do if current dataType is non-auto
if ( current === "*" ) {
current = prev;
// Convert response if prev dataType is non-auto and differs from current
} else if ( prev !== "*" && prev !== current ) {
// Seek a direct converter
conv = converters[ prev + " " + current ] || converters[ "* " + current ];
// If none found, seek a pair
if ( !conv ) {
for ( conv2 in converters ) {
// If conv2 outputs current
tmp = conv2.split( " " );
if ( tmp[ 1 ] === current ) {
// If prev can be converted to accepted input
conv = converters[ prev + " " + tmp[ 0 ] ] ||
converters[ "* " + tmp[ 0 ] ];
if ( conv ) {
// Condense equivalence converters
if ( conv === true ) {
conv = converters[ conv2 ];
// Otherwise, insert the intermediate dataType
} else if ( converters[ conv2 ] !== true ) {
current = tmp[ 0 ];
dataTypes.unshift( tmp[ 1 ] );
}
break;
}
}
}
}
// Apply converter (if not an equivalence)
if ( conv !== true ) {
// Unless errors are allowed to bubble, catch and return them
if ( conv && s[ "throws" ] ) { // jscs:ignore requireDotNotation
response = conv( response );
} else {
try {
response = conv( response );
} catch ( e ) {
return {
state: "parsererror",
error: conv ? e : "No conversion from " + prev + " to " + current
};
}
}
}
}
}
}
return { state: "success", data: response };
}
jQuery.extend( {
// Counter for holding the number of active queries
active: 0,
// Last-Modified header cache for next request
lastModified: {},
etag: {},
ajaxSettings: {
url: ajaxLocation,
type: "GET",
isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
global: true,
processData: true,
async: true,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
/*
timeout: 0,
data: null,
dataType: null,
username: null,
password: null,
cache: null,
throws: false,
traditional: false,
headers: {},
*/
accepts: {
"*": allTypes,
text: "text/plain",
html: "text/html",
xml: "application/xml, text/xml",
json: "application/json, text/javascript"
},
contents: {
xml: /\bxml\b/,
html: /\bhtml/,
json: /\bjson\b/
},
responseFields: {
xml: "responseXML",
text: "responseText",
json: "responseJSON"
},
// Data converters
// Keys separate source (or catchall "*") and destination types with a single space
converters: {
// Convert anything to text
"* text": String,
// Text to html (true = no transformation)
"text html": true,
// Evaluate text as a json expression
"text json": jQuery.parseJSON,
// Parse text as xml
"text xml": jQuery.parseXML
},
// For options that shouldn't be deep extended:
// you can add your own custom options here if
// and when you create one that shouldn't be
// deep extended (see ajaxExtend)
flatOptions: {
url: true,
context: true
}
},
// Creates a full fledged settings object into target
// with both ajaxSettings and settings fields.
// If target is omitted, writes into ajaxSettings.
ajaxSetup: function( target, settings ) {
return settings ?
// Building a settings object
ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) :
// Extending ajaxSettings
ajaxExtend( jQuery.ajaxSettings, target );
},
ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
ajaxTransport: addToPrefiltersOrTransports( transports ),
// Main method
ajax: function( url, options ) {
// If url is an object, simulate pre-1.5 signature
if ( typeof url === "object" ) {
options = url;
url = undefined;
}
// Force options to be an object
options = options || {};
var
// Cross-domain detection vars
parts,
// Loop variable
i,
// URL without anti-cache param
cacheURL,
// Response headers as string
responseHeadersString,
// timeout handle
timeoutTimer,
// To know if global events are to be dispatched
fireGlobals,
transport,
// Response headers
responseHeaders,
// Create the final options object
s = jQuery.ajaxSetup( {}, options ),
// Callbacks context
callbackContext = s.context || s,
// Context for global events is callbackContext if it is a DOM node or jQuery collection
globalEventContext = s.context &&
( callbackContext.nodeType || callbackContext.jquery ) ?
jQuery( callbackContext ) :
jQuery.event,
// Deferreds
deferred = jQuery.Deferred(),
completeDeferred = jQuery.Callbacks( "once memory" ),
// Status-dependent callbacks
statusCode = s.statusCode || {},
// Headers (they are sent all at once)
requestHeaders = {},
requestHeadersNames = {},
// The jqXHR state
state = 0,
// Default abort message
strAbort = "canceled",
// Fake xhr
jqXHR = {
readyState: 0,
// Builds headers hashtable if needed
getResponseHeader: function( key ) {
var match;
if ( state === 2 ) {
if ( !responseHeaders ) {
responseHeaders = {};
while ( ( match = rheaders.exec( responseHeadersString ) ) ) {
responseHeaders[ match[ 1 ].toLowerCase() ] = match[ 2 ];
}
}
match = responseHeaders[ key.toLowerCase() ];
}
return match == null ? null : match;
},
// Raw string
getAllResponseHeaders: function() {
return state === 2 ? responseHeadersString : null;
},
// Caches the header
setRequestHeader: function( name, value ) {
var lname = name.toLowerCase();
if ( !state ) {
name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
requestHeaders[ name ] = value;
}
return this;
},
// Overrides response content-type header
overrideMimeType: function( type ) {
if ( !state ) {
s.mimeType = type;
}
return this;
},
// Status-dependent callbacks
statusCode: function( map ) {
var code;
if ( map ) {
if ( state < 2 ) {
for ( code in map ) {
// Lazy-add the new callback in a way that preserves old ones
statusCode[ code ] = [ statusCode[ code ], map[ code ] ];
}
} else {
// Execute the appropriate callbacks
jqXHR.always( map[ jqXHR.status ] );
}
}
return this;
},
// Cancel the request
abort: function( statusText ) {
var finalText = statusText || strAbort;
if ( transport ) {
transport.abort( finalText );
}
done( 0, finalText );
return this;
}
};
// Attach deferreds
deferred.promise( jqXHR ).complete = completeDeferred.add;
jqXHR.success = jqXHR.done;
jqXHR.error = jqXHR.fail;
// Remove hash character (#7531: and string promotion)
// Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
// Handle falsy url in the settings object (#10093: consistency with old signature)
// We also use the url parameter if available
s.url = ( ( url || s.url || ajaxLocation ) + "" )
.replace( rhash, "" )
.replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
// Alias method option to type as per ticket #12004
s.type = options.method || options.type || s.method || s.type;
// Extract dataTypes list
s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( rnotwhite ) || [ "" ];
// A cross-domain request is in order when we have a protocol:host:port mismatch
if ( s.crossDomain == null ) {
parts = rurl.exec( s.url.toLowerCase() );
s.crossDomain = !!( parts &&
( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] ||
( parts[ 3 ] || ( parts[ 1 ] === "http:" ? "80" : "443" ) ) !==
( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? "80" : "443" ) ) )
);
}
// Convert data if not already a string
if ( s.data && s.processData && typeof s.data !== "string" ) {
s.data = jQuery.param( s.data, s.traditional );
}
// Apply prefilters
inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
// If request was aborted inside a prefilter, stop there
if ( state === 2 ) {
return jqXHR;
}
// We can fire global events as of now if asked to
// Don't fire events if jQuery.event is undefined in an AMD-usage scenario (#15118)
fireGlobals = jQuery.event && s.global;
// Watch for a new set of requests
if ( fireGlobals && jQuery.active++ === 0 ) {
jQuery.event.trigger( "ajaxStart" );
}
// Uppercase the type
s.type = s.type.toUpperCase();
// Determine if request has content
s.hasContent = !rnoContent.test( s.type );
// Save the URL in case we're toying with the If-Modified-Since
// and/or If-None-Match header later on
cacheURL = s.url;
// More options handling for requests with no content
if ( !s.hasContent ) {
// If data is available, append data to url
if ( s.data ) {
cacheURL = ( s.url += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data );
// #9682: remove data so that it's not used in an eventual retry
delete s.data;
}
// Add anti-cache in url if needed
if ( s.cache === false ) {
s.url = rts.test( cacheURL ) ?
// If there is already a '_' parameter, set its value
cacheURL.replace( rts, "$1_=" + nonce++ ) :
// Otherwise add one to the end
cacheURL + ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + nonce++;
}
}
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
if ( jQuery.lastModified[ cacheURL ] ) {
jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] );
}
if ( jQuery.etag[ cacheURL ] ) {
jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] );
}
}
// Set the correct header, if data is being sent
if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
jqXHR.setRequestHeader( "Content-Type", s.contentType );
}
// Set the Accepts header for the server, depending on the dataType
jqXHR.setRequestHeader(
"Accept",
s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[ 0 ] ] ?
s.accepts[ s.dataTypes[ 0 ] ] +
( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
s.accepts[ "*" ]
);
// Check for headers option
for ( i in s.headers ) {
jqXHR.setRequestHeader( i, s.headers[ i ] );
}
// Allow custom headers/mimetypes and early abort
if ( s.beforeSend &&
( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
// Abort if not done already and return
return jqXHR.abort();
}
// aborting is no longer a cancellation
strAbort = "abort";
// Install callbacks on deferreds
for ( i in { success: 1, error: 1, complete: 1 } ) {
jqXHR[ i ]( s[ i ] );
}
// Get transport
transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
// If no transport, we auto-abort
if ( !transport ) {
done( -1, "No Transport" );
} else {
jqXHR.readyState = 1;
// Send global event
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
}
// If request was aborted inside ajaxSend, stop there
if ( state === 2 ) {
return jqXHR;
}
// Timeout
if ( s.async && s.timeout > 0 ) {
timeoutTimer = window.setTimeout( function() {
jqXHR.abort( "timeout" );
}, s.timeout );
}
try {
state = 1;
transport.send( requestHeaders, done );
} catch ( e ) {
// Propagate exception as error if not done
if ( state < 2 ) {
done( -1, e );
// Simply rethrow otherwise
} else {
throw e;
}
}
}
// Callback for when everything is done
function done( status, nativeStatusText, responses, headers ) {
var isSuccess, success, error, response, modified,
statusText = nativeStatusText;
// Called once
if ( state === 2 ) {
return;
}
// State is "done" now
state = 2;
// Clear timeout if it exists
if ( timeoutTimer ) {
window.clearTimeout( timeoutTimer );
}
// Dereference transport for early garbage collection
// (no matter how long the jqXHR object will be used)
transport = undefined;
// Cache response headers
responseHeadersString = headers || "";
// Set readyState
jqXHR.readyState = status > 0 ? 4 : 0;
// Determine if successful
isSuccess = status >= 200 && status < 300 || status === 304;
// Get response data
if ( responses ) {
response = ajaxHandleResponses( s, jqXHR, responses );
}
// Convert no matter what (that way responseXXX fields are always set)
response = ajaxConvert( s, response, jqXHR, isSuccess );
// If successful, handle type chaining
if ( isSuccess ) {
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
modified = jqXHR.getResponseHeader( "Last-Modified" );
if ( modified ) {
jQuery.lastModified[ cacheURL ] = modified;
}
modified = jqXHR.getResponseHeader( "etag" );
if ( modified ) {
jQuery.etag[ cacheURL ] = modified;
}
}
// if no content
if ( status === 204 || s.type === "HEAD" ) {
statusText = "nocontent";
// if not modified
} else if ( status === 304 ) {
statusText = "notmodified";
// If we have data, let's convert it
} else {
statusText = response.state;
success = response.data;
error = response.error;
isSuccess = !error;
}
} else {
// We extract error from statusText
// then normalize statusText and status for non-aborts
error = statusText;
if ( status || !statusText ) {
statusText = "error";
if ( status < 0 ) {
status = 0;
}
}
}
// Set data for the fake xhr object
jqXHR.status = status;
jqXHR.statusText = ( nativeStatusText || statusText ) + "";
// Success/Error
if ( isSuccess ) {
deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
} else {
deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
}
// Status-dependent callbacks
jqXHR.statusCode( statusCode );
statusCode = undefined;
if ( fireGlobals ) {
globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError",
[ jqXHR, s, isSuccess ? success : error ] );
}
// Complete
completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
// Handle the global AJAX counter
if ( !( --jQuery.active ) ) {
jQuery.event.trigger( "ajaxStop" );
}
}
}
return jqXHR;
},
getJSON: function( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
},
getScript: function( url, callback ) {
return jQuery.get( url, undefined, callback, "script" );
}
} );
jQuery.each( [ "get", "post" ], function( i, method ) {
jQuery[ method ] = function( url, data, callback, type ) {
// shift arguments if data argument was omitted
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = undefined;
}
// The url can be an options object (which then must have .url)
return jQuery.ajax( jQuery.extend( {
url: url,
type: method,
dataType: type,
data: data,
success: callback
}, jQuery.isPlainObject( url ) && url ) );
};
} );
jQuery._evalUrl = function( url ) {
return jQuery.ajax( {
url: url,
// Make this explicit, since user can override this through ajaxSetup (#11264)
type: "GET",
dataType: "script",
cache: true,
async: false,
global: false,
"throws": true
} );
};
jQuery.fn.extend( {
wrapAll: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each( function( i ) {
jQuery( this ).wrapAll( html.call( this, i ) );
} );
}
if ( this[ 0 ] ) {
// The elements to wrap the target around
var wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true );
if ( this[ 0 ].parentNode ) {
wrap.insertBefore( this[ 0 ] );
}
wrap.map( function() {
var elem = this;
while ( elem.firstChild && elem.firstChild.nodeType === 1 ) {
elem = elem.firstChild;
}
return elem;
} ).append( this );
}
return this;
},
wrapInner: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each( function( i ) {
jQuery( this ).wrapInner( html.call( this, i ) );
} );
}
return this.each( function() {
var self = jQuery( this ),
contents = self.contents();
if ( contents.length ) {
contents.wrapAll( html );
} else {
self.append( html );
}
} );
},
wrap: function( html ) {
var isFunction = jQuery.isFunction( html );
return this.each( function( i ) {
jQuery( this ).wrapAll( isFunction ? html.call( this, i ) : html );
} );
},
unwrap: function() {
return this.parent().each( function() {
if ( !jQuery.nodeName( this, "body" ) ) {
jQuery( this ).replaceWith( this.childNodes );
}
} ).end();
}
} );
function getDisplay( elem ) {
return elem.style && elem.style.display || jQuery.css( elem, "display" );
}
function filterHidden( elem ) {
// Disconnected elements are considered hidden
if ( !jQuery.contains( elem.ownerDocument || document, elem ) ) {
return true;
}
while ( elem && elem.nodeType === 1 ) {
if ( getDisplay( elem ) === "none" || elem.type === "hidden" ) {
return true;
}
elem = elem.parentNode;
}
return false;
}
jQuery.expr.filters.hidden = function( elem ) {
// Support: Opera <= 12.12
// Opera reports offsetWidths and offsetHeights less than zero on some elements
return support.reliableHiddenOffsets() ?
( elem.offsetWidth <= 0 && elem.offsetHeight <= 0 &&
!elem.getClientRects().length ) :
filterHidden( elem );
};
jQuery.expr.filters.visible = function( elem ) {
return !jQuery.expr.filters.hidden( elem );
};
var r20 = /%20/g,
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
rsubmittable = /^(?:input|select|textarea|keygen)/i;
function buildParams( prefix, obj, traditional, add ) {
var name;
if ( jQuery.isArray( obj ) ) {
// Serialize array item.
jQuery.each( obj, function( i, v ) {
if ( traditional || rbracket.test( prefix ) ) {
// Treat each array item as a scalar.
add( prefix, v );
} else {
// Item is non-scalar (array or object), encode its numeric index.
buildParams(
prefix + "[" + ( typeof v === "object" && v != null ? i : "" ) + "]",
v,
traditional,
add
);
}
} );
} else if ( !traditional && jQuery.type( obj ) === "object" ) {
// Serialize object item.
for ( name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
// Serialize an array of form elements or a set of
// key/values into a query string
jQuery.param = function( a, traditional ) {
var prefix,
s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
} );
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
return s.join( "&" ).replace( r20, "+" );
};
jQuery.fn.extend( {
serialize: function() {
return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
return this.map( function() {
// Can add propHook for "elements" to filter or add form elements
var elements = jQuery.prop( this, "elements" );
return elements ? jQuery.makeArray( elements ) : this;
} )
.filter( function() {
var type = this.type;
// Use .is(":disabled") so that fieldset[disabled] works
return this.name && !jQuery( this ).is( ":disabled" ) &&
rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) &&
( this.checked || !rcheckableType.test( type ) );
} )
.map( function( i, elem ) {
var val = jQuery( this ).val();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val ) {
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
} ) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
} ).get();
}
} );
// Create the request object
// (This is still attached to ajaxSettings for backward compatibility)
jQuery.ajaxSettings.xhr = window.ActiveXObject !== undefined ?
// Support: IE6-IE8
function() {
// XHR cannot access local files, always use ActiveX for that case
if ( this.isLocal ) {
return createActiveXHR();
}
// Support: IE 9-11
// IE seems to error on cross-domain PATCH requests when ActiveX XHR
// is used. In IE 9+ always use the native XHR.
// Note: this condition won't catch Edge as it doesn't define
// document.documentMode but it also doesn't support ActiveX so it won't
// reach this code.
if ( document.documentMode > 8 ) {
return createStandardXHR();
}
// Support: IE<9
// oldIE XHR does not support non-RFC2616 methods (#13240)
// See http://msdn.microsoft.com/en-us/library/ie/ms536648(v=vs.85).aspx
// and http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9
// Although this check for six methods instead of eight
// since IE also does not support "trace" and "connect"
return /^(get|post|head|put|delete|options)$/i.test( this.type ) &&
createStandardXHR() || createActiveXHR();
} :
// For all other browsers, use the standard XMLHttpRequest object
createStandardXHR;
var xhrId = 0,
xhrCallbacks = {},
xhrSupported = jQuery.ajaxSettings.xhr();
// Support: IE<10
// Open requests must be manually aborted on unload (#5280)
// See https://support.microsoft.com/kb/2856746 for more info
if ( window.attachEvent ) {
window.attachEvent( "onunload", function() {
for ( var key in xhrCallbacks ) {
xhrCallbacks[ key ]( undefined, true );
}
} );
}
// Determine support properties
support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
xhrSupported = support.ajax = !!xhrSupported;
// Create transport if the browser can provide an xhr
if ( xhrSupported ) {
jQuery.ajaxTransport( function( options ) {
// Cross domain only allowed if supported through XMLHttpRequest
if ( !options.crossDomain || support.cors ) {
var callback;
return {
send: function( headers, complete ) {
var i,
xhr = options.xhr(),
id = ++xhrId;
// Open the socket
xhr.open(
options.type,
options.url,
options.async,
options.username,
options.password
);
// Apply custom fields if provided
if ( options.xhrFields ) {
for ( i in options.xhrFields ) {
xhr[ i ] = options.xhrFields[ i ];
}
}
// Override mime type if needed
if ( options.mimeType && xhr.overrideMimeType ) {
xhr.overrideMimeType( options.mimeType );
}
// X-Requested-With header
// For cross-domain requests, seeing as conditions for a preflight are
// akin to a jigsaw puzzle, we simply never set it to be sure.
// (it can always be set on a per-request basis or even using ajaxSetup)
// For same-domain requests, won't change header if already provided.
if ( !options.crossDomain && !headers[ "X-Requested-With" ] ) {
headers[ "X-Requested-With" ] = "XMLHttpRequest";
}
// Set headers
for ( i in headers ) {
// Support: IE<9
// IE's ActiveXObject throws a 'Type Mismatch' exception when setting
// request header to a null-value.
//
// To keep consistent with other XHR implementations, cast the value
// to string and ignore `undefined`.
if ( headers[ i ] !== undefined ) {
xhr.setRequestHeader( i, headers[ i ] + "" );
}
}
// Do send the request
// This may raise an exception which is actually
// handled in jQuery.ajax (so no try/catch here)
xhr.send( ( options.hasContent && options.data ) || null );
// Listener
callback = function( _, isAbort ) {
var status, statusText, responses;
// Was never called and is aborted or complete
if ( callback && ( isAbort || xhr.readyState === 4 ) ) {
// Clean up
delete xhrCallbacks[ id ];
callback = undefined;
xhr.onreadystatechange = jQuery.noop;
// Abort manually if needed
if ( isAbort ) {
if ( xhr.readyState !== 4 ) {
xhr.abort();
}
} else {
responses = {};
status = xhr.status;
// Support: IE<10
// Accessing binary-data responseText throws an exception
// (#11426)
if ( typeof xhr.responseText === "string" ) {
responses.text = xhr.responseText;
}
// Firefox throws an exception when accessing
// statusText for faulty cross-domain requests
try {
statusText = xhr.statusText;
} catch ( e ) {
// We normalize with Webkit giving an empty statusText
statusText = "";
}
// Filter status for non standard behaviors
// If the request is local and we have data: assume a success
// (success with no data won't get notified, that's the best we
// can do given current implementations)
if ( !status && options.isLocal && !options.crossDomain ) {
status = responses.text ? 200 : 404;
// IE - #1450: sometimes returns 1223 when it should be 204
} else if ( status === 1223 ) {
status = 204;
}
}
}
// Call complete if needed
if ( responses ) {
complete( status, statusText, responses, xhr.getAllResponseHeaders() );
}
};
// Do send the request
// `xhr.send` may raise an exception, but it will be
// handled in jQuery.ajax (so no try/catch here)
if ( !options.async ) {
// If we're in sync mode we fire the callback
callback();
} else if ( xhr.readyState === 4 ) {
// (IE6 & IE7) if it's in cache and has been
// retrieved directly we need to fire the callback
window.setTimeout( callback );
} else {
// Register the callback, but delay it in case `xhr.send` throws
// Add to the list of active xhr callbacks
xhr.onreadystatechange = xhrCallbacks[ id ] = callback;
}
},
abort: function() {
if ( callback ) {
callback( undefined, true );
}
}
};
}
} );
}
// Functions to create xhrs
function createStandardXHR() {
try {
return new window.XMLHttpRequest();
} catch ( e ) {}
}
function createActiveXHR() {
try {
return new window.ActiveXObject( "Microsoft.XMLHTTP" );
} catch ( e ) {}
}
// Install script dataType
jQuery.ajaxSetup( {
accepts: {
script: "text/javascript, application/javascript, " +
"application/ecmascript, application/x-ecmascript"
},
contents: {
script: /\b(?:java|ecma)script\b/
},
converters: {
"text script": function( text ) {
jQuery.globalEval( text );
return text;
}
}
} );
// Handle cache's special case and global
jQuery.ajaxPrefilter( "script", function( s ) {
if ( s.cache === undefined ) {
s.cache = false;
}
if ( s.crossDomain ) {
s.type = "GET";
s.global = false;
}
} );
// Bind script tag hack transport
jQuery.ajaxTransport( "script", function( s ) {
// This transport only deals with cross domain requests
if ( s.crossDomain ) {
var script,
head = document.head || jQuery( "head" )[ 0 ] || document.documentElement;
return {
send: function( _, callback ) {
script = document.createElement( "script" );
script.async = true;
if ( s.scriptCharset ) {
script.charset = s.scriptCharset;
}
script.src = s.url;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function( _, isAbort ) {
if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
// Remove the script
if ( script.parentNode ) {
script.parentNode.removeChild( script );
}
// Dereference the script
script = null;
// Callback if not abort
if ( !isAbort ) {
callback( 200, "success" );
}
}
};
// Circumvent IE6 bugs with base elements (#2709 and #4378) by prepending
// Use native DOM manipulation to avoid our domManip AJAX trickery
head.insertBefore( script, head.firstChild );
},
abort: function() {
if ( script ) {
script.onload( undefined, true );
}
}
};
}
} );
var oldCallbacks = [],
rjsonp = /(=)\?(?=&|$)|\?\?/;
// Default jsonp settings
jQuery.ajaxSetup( {
jsonp: "callback",
jsonpCallback: function() {
var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) );
this[ callback ] = true;
return callback;
}
} );
// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
var callbackName, overwritten, responseContainer,
jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ?
"url" :
typeof s.data === "string" &&
( s.contentType || "" )
.indexOf( "application/x-www-form-urlencoded" ) === 0 &&
rjsonp.test( s.data ) && "data"
);
// Handle iff the expected data type is "jsonp" or we have a parameter to set
if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) {
// Get callback name, remembering preexisting value associated with it
callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ?
s.jsonpCallback() :
s.jsonpCallback;
// Insert callback into url or form data
if ( jsonProp ) {
s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName );
} else if ( s.jsonp !== false ) {
s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;
}
// Use data converter to retrieve json after script execution
s.converters[ "script json" ] = function() {
if ( !responseContainer ) {
jQuery.error( callbackName + " was not called" );
}
return responseContainer[ 0 ];
};
// force json dataType
s.dataTypes[ 0 ] = "json";
// Install callback
overwritten = window[ callbackName ];
window[ callbackName ] = function() {
responseContainer = arguments;
};
// Clean-up function (fires after converters)
jqXHR.always( function() {
// If previous value didn't exist - remove it
if ( overwritten === undefined ) {
jQuery( window ).removeProp( callbackName );
// Otherwise restore preexisting value
} else {
window[ callbackName ] = overwritten;
}
// Save back as free
if ( s[ callbackName ] ) {
// make sure that re-using the options doesn't screw things around
s.jsonpCallback = originalSettings.jsonpCallback;
// save the callback name for future use
oldCallbacks.push( callbackName );
}
// Call if it was a function and we have a response
if ( responseContainer && jQuery.isFunction( overwritten ) ) {
overwritten( responseContainer[ 0 ] );
}
responseContainer = overwritten = undefined;
} );
// Delegate to script
return "script";
}
} );
// data: string of html
// context (optional): If specified, the fragment will be created in this context,
// defaults to document
// keepScripts (optional): If true, will include scripts passed in the html string
jQuery.parseHTML = function( data, context, keepScripts ) {
if ( !data || typeof data !== "string" ) {
return null;
}
if ( typeof context === "boolean" ) {
keepScripts = context;
context = false;
}
context = context || document;
var parsed = rsingleTag.exec( data ),
scripts = !keepScripts && [];
// Single tag
if ( parsed ) {
return [ context.createElement( parsed[ 1 ] ) ];
}
parsed = buildFragment( [ data ], context, scripts );
if ( scripts && scripts.length ) {
jQuery( scripts ).remove();
}
return jQuery.merge( [], parsed.childNodes );
};
// Keep a copy of the old load method
var _load = jQuery.fn.load;
/**
* Load a url into a page
*/
jQuery.fn.load = function( url, params, callback ) {
if ( typeof url !== "string" && _load ) {
return _load.apply( this, arguments );
}
var selector, type, response,
self = this,
off = url.indexOf( " " );
if ( off > -1 ) {
selector = jQuery.trim( url.slice( off, url.length ) );
url = url.slice( 0, off );
}
// If it's a function
if ( jQuery.isFunction( params ) ) {
// We assume that it's the callback
callback = params;
params = undefined;
// Otherwise, build a param string
} else if ( params && typeof params === "object" ) {
type = "POST";
}
// If we have elements to modify, make the request
if ( self.length > 0 ) {
jQuery.ajax( {
url: url,
// If "type" variable is undefined, then "GET" method will be used.
// Make value of this field explicit since
// user can override it through ajaxSetup method
type: type || "GET",
dataType: "html",
data: params
} ).done( function( responseText ) {
// Save response for use in complete callback
response = arguments;
self.html( selector ?
// If a selector was specified, locate the right elements in a dummy div
// Exclude scripts to avoid IE 'Permission Denied' errors
jQuery( "<div>" ).append( jQuery.parseHTML( responseText ) ).find( selector ) :
// Otherwise use the full result
responseText );
// If the request succeeds, this function gets "data", "status", "jqXHR"
// but they are ignored because response was set above.
// If it fails, this function gets "jqXHR", "status", "error"
} ).always( callback && function( jqXHR, status ) {
self.each( function() {
callback.apply( this, response || [ jqXHR.responseText, status, jqXHR ] );
} );
} );
}
return this;
};
// Attach a bunch of functions for handling common AJAX events
jQuery.each( [
"ajaxStart",
"ajaxStop",
"ajaxComplete",
"ajaxError",
"ajaxSuccess",
"ajaxSend"
], function( i, type ) {
jQuery.fn[ type ] = function( fn ) {
return this.on( type, fn );
};
} );
jQuery.expr.filters.animated = function( elem ) {
return jQuery.grep( jQuery.timers, function( fn ) {
return elem === fn.elem;
} ).length;
};
/**
* Gets a window from an element
*/
function getWindow( elem ) {
return jQuery.isWindow( elem ) ?
elem :
elem.nodeType === 9 ?
elem.defaultView || elem.parentWindow :
false;
}
jQuery.offset = {
setOffset: function( elem, options, i ) {
var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition,
position = jQuery.css( elem, "position" ),
curElem = jQuery( elem ),
props = {};
// set position first, in-case top/left are set even on static elem
if ( position === "static" ) {
elem.style.position = "relative";
}
curOffset = curElem.offset();
curCSSTop = jQuery.css( elem, "top" );
curCSSLeft = jQuery.css( elem, "left" );
calculatePosition = ( position === "absolute" || position === "fixed" ) &&
jQuery.inArray( "auto", [ curCSSTop, curCSSLeft ] ) > -1;
// need to be able to calculate position if either top or left
// is auto and position is either absolute or fixed
if ( calculatePosition ) {
curPosition = curElem.position();
curTop = curPosition.top;
curLeft = curPosition.left;
} else {
curTop = parseFloat( curCSSTop ) || 0;
curLeft = parseFloat( curCSSLeft ) || 0;
}
if ( jQuery.isFunction( options ) ) {
// Use jQuery.extend here to allow modification of coordinates argument (gh-1848)
options = options.call( elem, i, jQuery.extend( {}, curOffset ) );
}
if ( options.top != null ) {
props.top = ( options.top - curOffset.top ) + curTop;
}
if ( options.left != null ) {
props.left = ( options.left - curOffset.left ) + curLeft;
}
if ( "using" in options ) {
options.using.call( elem, props );
} else {
curElem.css( props );
}
}
};
jQuery.fn.extend( {
offset: function( options ) {
if ( arguments.length ) {
return options === undefined ?
this :
this.each( function( i ) {
jQuery.offset.setOffset( this, options, i );
} );
}
var docElem, win,
box = { top: 0, left: 0 },
elem = this[ 0 ],
doc = elem && elem.ownerDocument;
if ( !doc ) {
return;
}
docElem = doc.documentElement;
// Make sure it's not a disconnected DOM node
if ( !jQuery.contains( docElem, elem ) ) {
return box;
}
// If we don't have gBCR, just use 0,0 rather than error
// BlackBerry 5, iOS 3 (original iPhone)
if ( typeof elem.getBoundingClientRect !== "undefined" ) {
box = elem.getBoundingClientRect();
}
win = getWindow( doc );
return {
top: box.top + ( win.pageYOffset || docElem.scrollTop ) - ( docElem.clientTop || 0 ),
left: box.left + ( win.pageXOffset || docElem.scrollLeft ) - ( docElem.clientLeft || 0 )
};
},
position: function() {
if ( !this[ 0 ] ) {
return;
}
var offsetParent, offset,
parentOffset = { top: 0, left: 0 },
elem = this[ 0 ];
// Fixed elements are offset from window (parentOffset = {top:0, left: 0},
// because it is its only offset parent
if ( jQuery.css( elem, "position" ) === "fixed" ) {
// we assume that getBoundingClientRect is available when computed position is fixed
offset = elem.getBoundingClientRect();
} else {
// Get *real* offsetParent
offsetParent = this.offsetParent();
// Get correct offsets
offset = this.offset();
if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) {
parentOffset = offsetParent.offset();
}
// Add offsetParent borders
parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true );
parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true );
}
// Subtract parent offsets and element margins
// note: when an element has margin: auto the offsetLeft and marginLeft
// are the same in Safari causing offset.left to incorrectly be 0
return {
top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ),
left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true )
};
},
offsetParent: function() {
return this.map( function() {
var offsetParent = this.offsetParent;
while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) &&
jQuery.css( offsetParent, "position" ) === "static" ) ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || documentElement;
} );
}
} );
// Create scrollLeft and scrollTop methods
jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) {
var top = /Y/.test( prop );
jQuery.fn[ method ] = function( val ) {
return access( this, function( elem, method, val ) {
var win = getWindow( elem );
if ( val === undefined ) {
return win ? ( prop in win ) ? win[ prop ] :
win.document.documentElement[ method ] :
elem[ method ];
}
if ( win ) {
win.scrollTo(
!top ? val : jQuery( win ).scrollLeft(),
top ? val : jQuery( win ).scrollTop()
);
} else {
elem[ method ] = val;
}
}, method, val, arguments.length, null );
};
} );
// Support: Safari<7-8+, Chrome<37-44+
// Add the top/left cssHooks using jQuery.fn.position
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// getComputedStyle returns percent when specified for top/left/bottom/right
// rather than make the css module depend on the offset module, we just check for it here
jQuery.each( [ "top", "left" ], function( i, prop ) {
jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition,
function( elem, computed ) {
if ( computed ) {
computed = curCSS( elem, prop );
// if curCSS returns percentage, fallback to offset
return rnumnonpx.test( computed ) ?
jQuery( elem ).position()[ prop ] + "px" :
computed;
}
}
);
} );
// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name },
function( defaultExtra, funcName ) {
// margin is only for outerHeight, outerWidth
jQuery.fn[ funcName ] = function( margin, value ) {
var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),
extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );
return access( this, function( elem, type, value ) {
var doc;
if ( jQuery.isWindow( elem ) ) {
// As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there
// isn't a whole lot we can do. See pull request at this URL for discussion:
// https://github.com/jquery/jquery/pull/764
return elem.document.documentElement[ "client" + name ];
}
// Get document width or height
if ( elem.nodeType === 9 ) {
doc = elem.documentElement;
// Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height],
// whichever is greatest
// unfortunately, this causes bug #3838 in IE6/8 only,
// but there is currently no good, small way to fix it.
return Math.max(
elem.body[ "scroll" + name ], doc[ "scroll" + name ],
elem.body[ "offset" + name ], doc[ "offset" + name ],
doc[ "client" + name ]
);
}
return value === undefined ?
// Get width or height on the element, requesting but not forcing parseFloat
jQuery.css( elem, type, extra ) :
// Set width or height on the element
jQuery.style( elem, type, value, extra );
}, type, chainable ? margin : undefined, chainable, null );
};
} );
} );
jQuery.fn.extend( {
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
unbind: function( types, fn ) {
return this.off( types, null, fn );
},
delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
},
undelegate: function( selector, types, fn ) {
// ( namespace ) or ( selector, types [, fn] )
return arguments.length === 1 ?
this.off( selector, "**" ) :
this.off( types, selector || "**", fn );
}
} );
// The number of elements contained in the matched element set
jQuery.fn.size = function() {
return this.length;
};
jQuery.fn.andSelf = jQuery.fn.addBack;
// Register as a named AMD module, since jQuery can be concatenated with other
// files that may use define, but not via a proper concatenation script that
// understands anonymous AMD modules. A named AMD is safest and most robust
// way to register. Lowercase jquery is used because AMD module names are
// derived from file names, and jQuery is normally delivered in a lowercase
// file name. Do this after creating the global so that if an AMD module wants
// to call noConflict to hide this version of jQuery, it will work.
// Note that for maximum portability, libraries that are not jQuery should
// declare themselves as anonymous modules, and avoid setting a global if an
// AMD loader is present. jQuery is a special case. For more information, see
// https://github.com/jrburke/requirejs/wiki/Updating-existing-libraries#wiki-anon
if ( typeof define === "function" && define.amd ) {
define( "jquery", [], function() {
return jQuery;
} );
}
var
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$;
jQuery.noConflict = function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
};
// Expose jQuery and $ identifiers, even in
// AMD (#7102#comment:10, https://github.com/jquery/jquery/pull/557)
// and CommonJS for browser emulators (#13566)
if ( !noGlobal ) {
window.jQuery = window.$ = jQuery;
}
return jQuery;
}));
/**!
* @fileOverview Kickass library to create and place poppers near their reference elements.
* @version 1.12.9
* @license
* Copyright (c) 2016 Federico Zivolo and contributors
*
* 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.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.Popper = factory());
}(this, (function () { 'use strict';
var isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined';
var longerTimeoutBrowsers = ['Edge', 'Trident', 'Firefox'];
var timeoutDuration = 0;
for (var i = 0; i < longerTimeoutBrowsers.length; i += 1) {
if (isBrowser && navigator.userAgent.indexOf(longerTimeoutBrowsers[i]) >= 0) {
timeoutDuration = 1;
break;
}
}
function microtaskDebounce(fn) {
var called = false;
return function () {
if (called) {
return;
}
called = true;
window.Promise.resolve().then(function () {
called = false;
fn();
});
};
}
function taskDebounce(fn) {
var scheduled = false;
return function () {
if (!scheduled) {
scheduled = true;
setTimeout(function () {
scheduled = false;
fn();
}, timeoutDuration);
}
};
}
var supportsMicroTasks = isBrowser && window.Promise;
/**
* Create a debounced version of a method, that's asynchronously deferred
* but called in the minimum time possible.
*
* @method
* @memberof Popper.Utils
* @argument {Function} fn
* @returns {Function}
*/
var debounce = supportsMicroTasks ? microtaskDebounce : taskDebounce;
/**
* Check if the given variable is a function
* @method
* @memberof Popper.Utils
* @argument {Any} functionToCheck - variable to check
* @returns {Boolean} answer to: is a function?
*/
function isFunction(functionToCheck) {
var getType = {};
return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
}
/**
* Get CSS computed property of the given element
* @method
* @memberof Popper.Utils
* @argument {Eement} element
* @argument {String} property
*/
function getStyleComputedProperty(element, property) {
if (element.nodeType !== 1) {
return [];
}
// NOTE: 1 DOM access here
var css = getComputedStyle(element, null);
return property ? css[property] : css;
}
/**
* Returns the parentNode or the host of the element
* @method
* @memberof Popper.Utils
* @argument {Element} element
* @returns {Element} parent
*/
function getParentNode(element) {
if (element.nodeName === 'HTML') {
return element;
}
return element.parentNode || element.host;
}
/**
* Returns the scrolling parent of the given element
* @method
* @memberof Popper.Utils
* @argument {Element} element
* @returns {Element} scroll parent
*/
function getScrollParent(element) {
// Return body, `getScroll` will take care to get the correct `scrollTop` from it
if (!element) {
return document.body;
}
switch (element.nodeName) {
case 'HTML':
case 'BODY':
return element.ownerDocument.body;
case '#document':
return element.body;
}
// Firefox want us to check `-x` and `-y` variations as well
var _getStyleComputedProp = getStyleComputedProperty(element),
overflow = _getStyleComputedProp.overflow,
overflowX = _getStyleComputedProp.overflowX,
overflowY = _getStyleComputedProp.overflowY;
if (/(auto|scroll)/.test(overflow + overflowY + overflowX)) {
return element;
}
return getScrollParent(getParentNode(element));
}
/**
* Returns the offset parent of the given element
* @method
* @memberof Popper.Utils
* @argument {Element} element
* @returns {Element} offset parent
*/
function getOffsetParent(element) {
// NOTE: 1 DOM access here
var offsetParent = element && element.offsetParent;
var nodeName = offsetParent && offsetParent.nodeName;
if (!nodeName || nodeName === 'BODY' || nodeName === 'HTML') {
if (element) {
return element.ownerDocument.documentElement;
}
return document.documentElement;
}
// .offsetParent will return the closest TD or TABLE in case
// no offsetParent is present, I hate this job...
if (['TD', 'TABLE'].indexOf(offsetParent.nodeName) !== -1 && getStyleComputedProperty(offsetParent, 'position') === 'static') {
return getOffsetParent(offsetParent);
}
return offsetParent;
}
function isOffsetContainer(element) {
var nodeName = element.nodeName;
if (nodeName === 'BODY') {
return false;
}
return nodeName === 'HTML' || getOffsetParent(element.firstElementChild) === element;
}
/**
* Finds the root node (document, shadowDOM root) of the given element
* @method
* @memberof Popper.Utils
* @argument {Element} node
* @returns {Element} root node
*/
function getRoot(node) {
if (node.parentNode !== null) {
return getRoot(node.parentNode);
}
return node;
}
/**
* Finds the offset parent common to the two provided nodes
* @method
* @memberof Popper.Utils
* @argument {Element} element1
* @argument {Element} element2
* @returns {Element} common offset parent
*/
function findCommonOffsetParent(element1, element2) {
// This check is needed to avoid errors in case one of the elements isn't defined for any reason
if (!element1 || !element1.nodeType || !element2 || !element2.nodeType) {
return document.documentElement;
}
// Here we make sure to give as "start" the element that comes first in the DOM
var order = element1.compareDocumentPosition(element2) & Node.DOCUMENT_POSITION_FOLLOWING;
var start = order ? element1 : element2;
var end = order ? element2 : element1;
// Get common ancestor container
var range = document.createRange();
range.setStart(start, 0);
range.setEnd(end, 0);
var commonAncestorContainer = range.commonAncestorContainer;
// Both nodes are inside #document
if (element1 !== commonAncestorContainer && element2 !== commonAncestorContainer || start.contains(end)) {
if (isOffsetContainer(commonAncestorContainer)) {
return commonAncestorContainer;
}
return getOffsetParent(commonAncestorContainer);
}
// one of the nodes is inside shadowDOM, find which one
var element1root = getRoot(element1);
if (element1root.host) {
return findCommonOffsetParent(element1root.host, element2);
} else {
return findCommonOffsetParent(element1, getRoot(element2).host);
}
}
/**
* Gets the scroll value of the given element in the given side (top and left)
* @method
* @memberof Popper.Utils
* @argument {Element} element
* @argument {String} side `top` or `left`
* @returns {number} amount of scrolled pixels
*/
function getScroll(element) {
var side = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'top';
var upperSide = side === 'top' ? 'scrollTop' : 'scrollLeft';
var nodeName = element.nodeName;
if (nodeName === 'BODY' || nodeName === 'HTML') {
var html = element.ownerDocument.documentElement;
var scrollingElement = element.ownerDocument.scrollingElement || html;
return scrollingElement[upperSide];
}
return element[upperSide];
}
/*
* Sum or subtract the element scroll values (left and top) from a given rect object
* @method
* @memberof Popper.Utils
* @param {Object} rect - Rect object you want to change
* @param {HTMLElement} element - The element from the function reads the scroll values
* @param {Boolean} subtract - set to true if you want to subtract the scroll values
* @return {Object} rect - The modifier rect object
*/
function includeScroll(rect, element) {
var subtract = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var scrollTop = getScroll(element, 'top');
var scrollLeft = getScroll(element, 'left');
var modifier = subtract ? -1 : 1;
rect.top += scrollTop * modifier;
rect.bottom += scrollTop * modifier;
rect.left += scrollLeft * modifier;
rect.right += scrollLeft * modifier;
return rect;
}
/*
* Helper to detect borders of a given element
* @method
* @memberof Popper.Utils
* @param {CSSStyleDeclaration} styles
* Result of `getStyleComputedProperty` on the given element
* @param {String} axis - `x` or `y`
* @return {number} borders - The borders size of the given axis
*/
function getBordersSize(styles, axis) {
var sideA = axis === 'x' ? 'Left' : 'Top';
var sideB = sideA === 'Left' ? 'Right' : 'Bottom';
return parseFloat(styles['border' + sideA + 'Width'], 10) + parseFloat(styles['border' + sideB + 'Width'], 10);
}
/**
* Tells if you are running Internet Explorer 10
* @method
* @memberof Popper.Utils
* @returns {Boolean} isIE10
*/
var isIE10 = undefined;
var isIE10$1 = function () {
if (isIE10 === undefined) {
isIE10 = navigator.appVersion.indexOf('MSIE 10') !== -1;
}
return isIE10;
};
function getSize(axis, body, html, computedStyle) {
return Math.max(body['offset' + axis], body['scroll' + axis], html['client' + axis], html['offset' + axis], html['scroll' + axis], isIE10$1() ? html['offset' + axis] + computedStyle['margin' + (axis === 'Height' ? 'Top' : 'Left')] + computedStyle['margin' + (axis === 'Height' ? 'Bottom' : 'Right')] : 0);
}
function getWindowSizes() {
var body = document.body;
var html = document.documentElement;
var computedStyle = isIE10$1() && getComputedStyle(html);
return {
height: getSize('Height', body, html, computedStyle),
width: getSize('Width', body, html, computedStyle)
};
}
var classCallCheck = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
var createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
var defineProperty = function (obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
};
var _extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
/**
* Given element offsets, generate an output similar to getBoundingClientRect
* @method
* @memberof Popper.Utils
* @argument {Object} offsets
* @returns {Object} ClientRect like output
*/
function getClientRect(offsets) {
return _extends({}, offsets, {
right: offsets.left + offsets.width,
bottom: offsets.top + offsets.height
});
}
/**
* Get bounding client rect of given element
* @method
* @memberof Popper.Utils
* @param {HTMLElement} element
* @return {Object} client rect
*/
function getBoundingClientRect(element) {
var rect = {};
// IE10 10 FIX: Please, don't ask, the element isn't
// considered in DOM in some circumstances...
// This isn't reproducible in IE10 compatibility mode of IE11
if (isIE10$1()) {
try {
rect = element.getBoundingClientRect();
var scrollTop = getScroll(element, 'top');
var scrollLeft = getScroll(element, 'left');
rect.top += scrollTop;
rect.left += scrollLeft;
rect.bottom += scrollTop;
rect.right += scrollLeft;
} catch (err) {}
} else {
rect = element.getBoundingClientRect();
}
var result = {
left: rect.left,
top: rect.top,
width: rect.right - rect.left,
height: rect.bottom - rect.top
};
// subtract scrollbar size from sizes
var sizes = element.nodeName === 'HTML' ? getWindowSizes() : {};
var width = sizes.width || element.clientWidth || result.right - result.left;
var height = sizes.height || element.clientHeight || result.bottom - result.top;
var horizScrollbar = element.offsetWidth - width;
var vertScrollbar = element.offsetHeight - height;
// if an hypothetical scrollbar is detected, we must be sure it's not a `border`
// we make this check conditional for performance reasons
if (horizScrollbar || vertScrollbar) {
var styles = getStyleComputedProperty(element);
horizScrollbar -= getBordersSize(styles, 'x');
vertScrollbar -= getBordersSize(styles, 'y');
result.width -= horizScrollbar;
result.height -= vertScrollbar;
}
return getClientRect(result);
}
function getOffsetRectRelativeToArbitraryNode(children, parent) {
var isIE10 = isIE10$1();
var isHTML = parent.nodeName === 'HTML';
var childrenRect = getBoundingClientRect(children);
var parentRect = getBoundingClientRect(parent);
var scrollParent = getScrollParent(children);
var styles = getStyleComputedProperty(parent);
var borderTopWidth = parseFloat(styles.borderTopWidth, 10);
var borderLeftWidth = parseFloat(styles.borderLeftWidth, 10);
var offsets = getClientRect({
top: childrenRect.top - parentRect.top - borderTopWidth,
left: childrenRect.left - parentRect.left - borderLeftWidth,
width: childrenRect.width,
height: childrenRect.height
});
offsets.marginTop = 0;
offsets.marginLeft = 0;
// Subtract margins of documentElement in case it's being used as parent
// we do this only on HTML because it's the only element that behaves
// differently when margins are applied to it. The margins are included in
// the box of the documentElement, in the other cases not.
if (!isIE10 && isHTML) {
var marginTop = parseFloat(styles.marginTop, 10);
var marginLeft = parseFloat(styles.marginLeft, 10);
offsets.top -= borderTopWidth - marginTop;
offsets.bottom -= borderTopWidth - marginTop;
offsets.left -= borderLeftWidth - marginLeft;
offsets.right -= borderLeftWidth - marginLeft;
// Attach marginTop and marginLeft because in some circumstances we may need them
offsets.marginTop = marginTop;
offsets.marginLeft = marginLeft;
}
if (isIE10 ? parent.contains(scrollParent) : parent === scrollParent && scrollParent.nodeName !== 'BODY') {
offsets = includeScroll(offsets, parent);
}
return offsets;
}
function getViewportOffsetRectRelativeToArtbitraryNode(element) {
var html = element.ownerDocument.documentElement;
var relativeOffset = getOffsetRectRelativeToArbitraryNode(element, html);
var width = Math.max(html.clientWidth, window.innerWidth || 0);
var height = Math.max(html.clientHeight, window.innerHeight || 0);
var scrollTop = getScroll(html);
var scrollLeft = getScroll(html, 'left');
var offset = {
top: scrollTop - relativeOffset.top + relativeOffset.marginTop,
left: scrollLeft - relativeOffset.left + relativeOffset.marginLeft,
width: width,
height: height
};
return getClientRect(offset);
}
/**
* Check if the given element is fixed or is inside a fixed parent
* @method
* @memberof Popper.Utils
* @argument {Element} element
* @argument {Element} customContainer
* @returns {Boolean} answer to "isFixed?"
*/
function isFixed(element) {
var nodeName = element.nodeName;
if (nodeName === 'BODY' || nodeName === 'HTML') {
return false;
}
if (getStyleComputedProperty(element, 'position') === 'fixed') {
return true;
}
return isFixed(getParentNode(element));
}
/**
* Computed the boundaries limits and return them
* @method
* @memberof Popper.Utils
* @param {HTMLElement} popper
* @param {HTMLElement} reference
* @param {number} padding
* @param {HTMLElement} boundariesElement - Element used to define the boundaries
* @returns {Object} Coordinates of the boundaries
*/
function getBoundaries(popper, reference, padding, boundariesElement) {
// NOTE: 1 DOM access here
var boundaries = { top: 0, left: 0 };
var offsetParent = findCommonOffsetParent(popper, reference);
// Handle viewport case
if (boundariesElement === 'viewport') {
boundaries = getViewportOffsetRectRelativeToArtbitraryNode(offsetParent);
} else {
// Handle other cases based on DOM element used as boundaries
var boundariesNode = void 0;
if (boundariesElement === 'scrollParent') {
boundariesNode = getScrollParent(getParentNode(reference));
if (boundariesNode.nodeName === 'BODY') {
boundariesNode = popper.ownerDocument.documentElement;
}
} else if (boundariesElement === 'window') {
boundariesNode = popper.ownerDocument.documentElement;
} else {
boundariesNode = boundariesElement;
}
var offsets = getOffsetRectRelativeToArbitraryNode(boundariesNode, offsetParent);
// In case of HTML, we need a different computation
if (boundariesNode.nodeName === 'HTML' && !isFixed(offsetParent)) {
var _getWindowSizes = getWindowSizes(),
height = _getWindowSizes.height,
width = _getWindowSizes.width;
boundaries.top += offsets.top - offsets.marginTop;
boundaries.bottom = height + offsets.top;
boundaries.left += offsets.left - offsets.marginLeft;
boundaries.right = width + offsets.left;
} else {
// for all the other DOM elements, this one is good
boundaries = offsets;
}
}
// Add paddings
boundaries.left += padding;
boundaries.top += padding;
boundaries.right -= padding;
boundaries.bottom -= padding;
return boundaries;
}
function getArea(_ref) {
var width = _ref.width,
height = _ref.height;
return width * height;
}
/**
* Utility used to transform the `auto` placement to the placement with more
* available space.
* @method
* @memberof Popper.Utils
* @argument {Object} data - The data object generated by update method
* @argument {Object} options - Modifiers configuration and options
* @returns {Object} The data object, properly modified
*/
function computeAutoPlacement(placement, refRect, popper, reference, boundariesElement) {
var padding = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 0;
if (placement.indexOf('auto') === -1) {
return placement;
}
var boundaries = getBoundaries(popper, reference, padding, boundariesElement);
var rects = {
top: {
width: boundaries.width,
height: refRect.top - boundaries.top
},
right: {
width: boundaries.right - refRect.right,
height: boundaries.height
},
bottom: {
width: boundaries.width,
height: boundaries.bottom - refRect.bottom
},
left: {
width: refRect.left - boundaries.left,
height: boundaries.height
}
};
var sortedAreas = Object.keys(rects).map(function (key) {
return _extends({
key: key
}, rects[key], {
area: getArea(rects[key])
});
}).sort(function (a, b) {
return b.area - a.area;
});
var filteredAreas = sortedAreas.filter(function (_ref2) {
var width = _ref2.width,
height = _ref2.height;
return width >= popper.clientWidth && height >= popper.clientHeight;
});
var computedPlacement = filteredAreas.length > 0 ? filteredAreas[0].key : sortedAreas[0].key;
var variation = placement.split('-')[1];
return computedPlacement + (variation ? '-' + variation : '');
}
/**
* Get offsets to the reference element
* @method
* @memberof Popper.Utils
* @param {Object} state
* @param {Element} popper - the popper element
* @param {Element} reference - the reference element (the popper will be relative to this)
* @returns {Object} An object containing the offsets which will be applied to the popper
*/
function getReferenceOffsets(state, popper, reference) {
var commonOffsetParent = findCommonOffsetParent(popper, reference);
return getOffsetRectRelativeToArbitraryNode(reference, commonOffsetParent);
}
/**
* Get the outer sizes of the given element (offset size + margins)
* @method
* @memberof Popper.Utils
* @argument {Element} element
* @returns {Object} object containing width and height properties
*/
function getOuterSizes(element) {
var styles = getComputedStyle(element);
var x = parseFloat(styles.marginTop) + parseFloat(styles.marginBottom);
var y = parseFloat(styles.marginLeft) + parseFloat(styles.marginRight);
var result = {
width: element.offsetWidth + y,
height: element.offsetHeight + x
};
return result;
}
/**
* Get the opposite placement of the given one
* @method
* @memberof Popper.Utils
* @argument {String} placement
* @returns {String} flipped placement
*/
function getOppositePlacement(placement) {
var hash = { left: 'right', right: 'left', bottom: 'top', top: 'bottom' };
return placement.replace(/left|right|bottom|top/g, function (matched) {
return hash[matched];
});
}
/**
* Get offsets to the popper
* @method
* @memberof Popper.Utils
* @param {Object} position - CSS position the Popper will get applied
* @param {HTMLElement} popper - the popper element
* @param {Object} referenceOffsets - the reference offsets (the popper will be relative to this)
* @param {String} placement - one of the valid placement options
* @returns {Object} popperOffsets - An object containing the offsets which will be applied to the popper
*/
function getPopperOffsets(popper, referenceOffsets, placement) {
placement = placement.split('-')[0];
// Get popper node sizes
var popperRect = getOuterSizes(popper);
// Add position, width and height to our offsets object
var popperOffsets = {
width: popperRect.width,
height: popperRect.height
};
// depending by the popper placement we have to compute its offsets slightly differently
var isHoriz = ['right', 'left'].indexOf(placement) !== -1;
var mainSide = isHoriz ? 'top' : 'left';
var secondarySide = isHoriz ? 'left' : 'top';
var measurement = isHoriz ? 'height' : 'width';
var secondaryMeasurement = !isHoriz ? 'height' : 'width';
popperOffsets[mainSide] = referenceOffsets[mainSide] + referenceOffsets[measurement] / 2 - popperRect[measurement] / 2;
if (placement === secondarySide) {
popperOffsets[secondarySide] = referenceOffsets[secondarySide] - popperRect[secondaryMeasurement];
} else {
popperOffsets[secondarySide] = referenceOffsets[getOppositePlacement(secondarySide)];
}
return popperOffsets;
}
/**
* Mimics the `find` method of Array
* @method
* @memberof Popper.Utils
* @argument {Array} arr
* @argument prop
* @argument value
* @returns index or -1
*/
function find(arr, check) {
// use native find if supported
if (Array.prototype.find) {
return arr.find(check);
}
// use `filter` to obtain the same behavior of `find`
return arr.filter(check)[0];
}
/**
* Return the index of the matching object
* @method
* @memberof Popper.Utils
* @argument {Array} arr
* @argument prop
* @argument value
* @returns index or -1
*/
function findIndex(arr, prop, value) {
// use native findIndex if supported
if (Array.prototype.findIndex) {
return arr.findIndex(function (cur) {
return cur[prop] === value;
});
}
// use `find` + `indexOf` if `findIndex` isn't supported
var match = find(arr, function (obj) {
return obj[prop] === value;
});
return arr.indexOf(match);
}
/**
* Loop trough the list of modifiers and run them in order,
* each of them will then edit the data object.
* @method
* @memberof Popper.Utils
* @param {dataObject} data
* @param {Array} modifiers
* @param {String} ends - Optional modifier name used as stopper
* @returns {dataObject}
*/
function runModifiers(modifiers, data, ends) {
var modifiersToRun = ends === undefined ? modifiers : modifiers.slice(0, findIndex(modifiers, 'name', ends));
modifiersToRun.forEach(function (modifier) {
if (modifier['function']) {
// eslint-disable-line dot-notation
console.warn('`modifier.function` is deprecated, use `modifier.fn`!');
}
var fn = modifier['function'] || modifier.fn; // eslint-disable-line dot-notation
if (modifier.enabled && isFunction(fn)) {
// Add properties to offsets to make them a complete clientRect object
// we do this before each modifier to make sure the previous one doesn't
// mess with these values
data.offsets.popper = getClientRect(data.offsets.popper);
data.offsets.reference = getClientRect(data.offsets.reference);
data = fn(data, modifier);
}
});
return data;
}
/**
* Updates the position of the popper, computing the new offsets and applying
* the new style.<br />
* Prefer `scheduleUpdate` over `update` because of performance reasons.
* @method
* @memberof Popper
*/
function update() {
// if popper is destroyed, don't perform any further update
if (this.state.isDestroyed) {
return;
}
var data = {
instance: this,
styles: {},
arrowStyles: {},
attributes: {},
flipped: false,
offsets: {}
};
// compute reference element offsets
data.offsets.reference = getReferenceOffsets(this.state, this.popper, this.reference);
// compute auto placement, store placement inside the data object,
// modifiers will be able to edit `placement` if needed
// and refer to originalPlacement to know the original value
data.placement = computeAutoPlacement(this.options.placement, data.offsets.reference, this.popper, this.reference, this.options.modifiers.flip.boundariesElement, this.options.modifiers.flip.padding);
// store the computed placement inside `originalPlacement`
data.originalPlacement = data.placement;
// compute the popper offsets
data.offsets.popper = getPopperOffsets(this.popper, data.offsets.reference, data.placement);
data.offsets.popper.position = 'absolute';
// run the modifiers
data = runModifiers(this.modifiers, data);
// the first `update` will call `onCreate` callback
// the other ones will call `onUpdate` callback
if (!this.state.isCreated) {
this.state.isCreated = true;
this.options.onCreate(data);
} else {
this.options.onUpdate(data);
}
}
/**
* Helper used to know if the given modifier is enabled.
* @method
* @memberof Popper.Utils
* @returns {Boolean}
*/
function isModifierEnabled(modifiers, modifierName) {
return modifiers.some(function (_ref) {
var name = _ref.name,
enabled = _ref.enabled;
return enabled && name === modifierName;
});
}
/**
* Get the prefixed supported property name
* @method
* @memberof Popper.Utils
* @argument {String} property (camelCase)
* @returns {String} prefixed property (camelCase or PascalCase, depending on the vendor prefix)
*/
function getSupportedPropertyName(property) {
var prefixes = [false, 'ms', 'Webkit', 'Moz', 'O'];
var upperProp = property.charAt(0).toUpperCase() + property.slice(1);
for (var i = 0; i < prefixes.length - 1; i++) {
var prefix = prefixes[i];
var toCheck = prefix ? '' + prefix + upperProp : property;
if (typeof document.body.style[toCheck] !== 'undefined') {
return toCheck;
}
}
return null;
}
/**
* Destroy the popper
* @method
* @memberof Popper
*/
function destroy() {
this.state.isDestroyed = true;
// touch DOM only if `applyStyle` modifier is enabled
if (isModifierEnabled(this.modifiers, 'applyStyle')) {
this.popper.removeAttribute('x-placement');
this.popper.style.left = '';
this.popper.style.position = '';
this.popper.style.top = '';
this.popper.style[getSupportedPropertyName('transform')] = '';
}
this.disableEventListeners();
// remove the popper if user explicity asked for the deletion on destroy
// do not use `remove` because IE11 doesn't support it
if (this.options.removeOnDestroy) {
this.popper.parentNode.removeChild(this.popper);
}
return this;
}
/**
* Get the window associated with the element
* @argument {Element} element
* @returns {Window}
*/
function getWindow(element) {
var ownerDocument = element.ownerDocument;
return ownerDocument ? ownerDocument.defaultView : window;
}
function attachToScrollParents(scrollParent, event, callback, scrollParents) {
var isBody = scrollParent.nodeName === 'BODY';
var target = isBody ? scrollParent.ownerDocument.defaultView : scrollParent;
target.addEventListener(event, callback, { passive: true });
if (!isBody) {
attachToScrollParents(getScrollParent(target.parentNode), event, callback, scrollParents);
}
scrollParents.push(target);
}
/**
* Setup needed event listeners used to update the popper position
* @method
* @memberof Popper.Utils
* @private
*/
function setupEventListeners(reference, options, state, updateBound) {
// Resize event listener on window
state.updateBound = updateBound;
getWindow(reference).addEventListener('resize', state.updateBound, { passive: true });
// Scroll event listener on scroll parents
var scrollElement = getScrollParent(reference);
attachToScrollParents(scrollElement, 'scroll', state.updateBound, state.scrollParents);
state.scrollElement = scrollElement;
state.eventsEnabled = true;
return state;
}
/**
* It will add resize/scroll events and start recalculating
* position of the popper element when they are triggered.
* @method
* @memberof Popper
*/
function enableEventListeners() {
if (!this.state.eventsEnabled) {
this.state = setupEventListeners(this.reference, this.options, this.state, this.scheduleUpdate);
}
}
/**
* Remove event listeners used to update the popper position
* @method
* @memberof Popper.Utils
* @private
*/
function removeEventListeners(reference, state) {
// Remove resize event listener on window
getWindow(reference).removeEventListener('resize', state.updateBound);
// Remove scroll event listener on scroll parents
state.scrollParents.forEach(function (target) {
target.removeEventListener('scroll', state.updateBound);
});
// Reset state
state.updateBound = null;
state.scrollParents = [];
state.scrollElement = null;
state.eventsEnabled = false;
return state;
}
/**
* It will remove resize/scroll events and won't recalculate popper position
* when they are triggered. It also won't trigger onUpdate callback anymore,
* unless you call `update` method manually.
* @method
* @memberof Popper
*/
function disableEventListeners() {
if (this.state.eventsEnabled) {
cancelAnimationFrame(this.scheduleUpdate);
this.state = removeEventListeners(this.reference, this.state);
}
}
/**
* Tells if a given input is a number
* @method
* @memberof Popper.Utils
* @param {*} input to check
* @return {Boolean}
*/
function isNumeric(n) {
return n !== '' && !isNaN(parseFloat(n)) && isFinite(n);
}
/**
* Set the style to the given popper
* @method
* @memberof Popper.Utils
* @argument {Element} element - Element to apply the style to
* @argument {Object} styles
* Object with a list of properties and values which will be applied to the element
*/
function setStyles(element, styles) {
Object.keys(styles).forEach(function (prop) {
var unit = '';
// add unit if the value is numeric and is one of the following
if (['width', 'height', 'top', 'right', 'bottom', 'left'].indexOf(prop) !== -1 && isNumeric(styles[prop])) {
unit = 'px';
}
element.style[prop] = styles[prop] + unit;
});
}
/**
* Set the attributes to the given popper
* @method
* @memberof Popper.Utils
* @argument {Element} element - Element to apply the attributes to
* @argument {Object} styles
* Object with a list of properties and values which will be applied to the element
*/
function setAttributes(element, attributes) {
Object.keys(attributes).forEach(function (prop) {
var value = attributes[prop];
if (value !== false) {
element.setAttribute(prop, attributes[prop]);
} else {
element.removeAttribute(prop);
}
});
}
/**
* @function
* @memberof Modifiers
* @argument {Object} data - The data object generated by `update` method
* @argument {Object} data.styles - List of style properties - values to apply to popper element
* @argument {Object} data.attributes - List of attribute properties - values to apply to popper element
* @argument {Object} options - Modifiers configuration and options
* @returns {Object} The same data object
*/
function applyStyle(data) {
// any property present in `data.styles` will be applied to the popper,
// in this way we can make the 3rd party modifiers add custom styles to it
// Be aware, modifiers could override the properties defined in the previous
// lines of this modifier!
setStyles(data.instance.popper, data.styles);
// any property present in `data.attributes` will be applied to the popper,
// they will be set as HTML attributes of the element
setAttributes(data.instance.popper, data.attributes);
// if arrowElement is defined and arrowStyles has some properties
if (data.arrowElement && Object.keys(data.arrowStyles).length) {
setStyles(data.arrowElement, data.arrowStyles);
}
return data;
}
/**
* Set the x-placement attribute before everything else because it could be used
* to add margins to the popper margins needs to be calculated to get the
* correct popper offsets.
* @method
* @memberof Popper.modifiers
* @param {HTMLElement} reference - The reference element used to position the popper
* @param {HTMLElement} popper - The HTML element used as popper.
* @param {Object} options - Popper.js options
*/
function applyStyleOnLoad(reference, popper, options, modifierOptions, state) {
// compute reference element offsets
var referenceOffsets = getReferenceOffsets(state, popper, reference);
// compute auto placement, store placement inside the data object,
// modifiers will be able to edit `placement` if needed
// and refer to originalPlacement to know the original value
var placement = computeAutoPlacement(options.placement, referenceOffsets, popper, reference, options.modifiers.flip.boundariesElement, options.modifiers.flip.padding);
popper.setAttribute('x-placement', placement);
// Apply `position` to popper before anything else because
// without the position applied we can't guarantee correct computations
setStyles(popper, { position: 'absolute' });
return options;
}
/**
* @function
* @memberof Modifiers
* @argument {Object} data - The data object generated by `update` method
* @argument {Object} options - Modifiers configuration and options
* @returns {Object} The data object, properly modified
*/
function computeStyle(data, options) {
var x = options.x,
y = options.y;
var popper = data.offsets.popper;
// Remove this legacy support in Popper.js v2
var legacyGpuAccelerationOption = find(data.instance.modifiers, function (modifier) {
return modifier.name === 'applyStyle';
}).gpuAcceleration;
if (legacyGpuAccelerationOption !== undefined) {
console.warn('WARNING: `gpuAcceleration` option moved to `computeStyle` modifier and will not be supported in future versions of Popper.js!');
}
var gpuAcceleration = legacyGpuAccelerationOption !== undefined ? legacyGpuAccelerationOption : options.gpuAcceleration;
var offsetParent = getOffsetParent(data.instance.popper);
var offsetParentRect = getBoundingClientRect(offsetParent);
// Styles
var styles = {
position: popper.position
};
// floor sides to avoid blurry text
var offsets = {
left: Math.floor(popper.left),
top: Math.floor(popper.top),
bottom: Math.floor(popper.bottom),
right: Math.floor(popper.right)
};
var sideA = x === 'bottom' ? 'top' : 'bottom';
var sideB = y === 'right' ? 'left' : 'right';
// if gpuAcceleration is set to `true` and transform is supported,
// we use `translate3d` to apply the position to the popper we
// automatically use the supported prefixed version if needed
var prefixedProperty = getSupportedPropertyName('transform');
// now, let's make a step back and look at this code closely (wtf?)
// If the content of the popper grows once it's been positioned, it
// may happen that the popper gets misplaced because of the new content
// overflowing its reference element
// To avoid this problem, we provide two options (x and y), which allow
// the consumer to define the offset origin.
// If we position a popper on top of a reference element, we can set
// `x` to `top` to make the popper grow towards its top instead of
// its bottom.
var left = void 0,
top = void 0;
if (sideA === 'bottom') {
top = -offsetParentRect.height + offsets.bottom;
} else {
top = offsets.top;
}
if (sideB === 'right') {
left = -offsetParentRect.width + offsets.right;
} else {
left = offsets.left;
}
if (gpuAcceleration && prefixedProperty) {
styles[prefixedProperty] = 'translate3d(' + left + 'px, ' + top + 'px, 0)';
styles[sideA] = 0;
styles[sideB] = 0;
styles.willChange = 'transform';
} else {
// othwerise, we use the standard `top`, `left`, `bottom` and `right` properties
var invertTop = sideA === 'bottom' ? -1 : 1;
var invertLeft = sideB === 'right' ? -1 : 1;
styles[sideA] = top * invertTop;
styles[sideB] = left * invertLeft;
styles.willChange = sideA + ', ' + sideB;
}
// Attributes
var attributes = {
'x-placement': data.placement
};
// Update `data` attributes, styles and arrowStyles
data.attributes = _extends({}, attributes, data.attributes);
data.styles = _extends({}, styles, data.styles);
data.arrowStyles = _extends({}, data.offsets.arrow, data.arrowStyles);
return data;
}
/**
* Helper used to know if the given modifier depends from another one.<br />
* It checks if the needed modifier is listed and enabled.
* @method
* @memberof Popper.Utils
* @param {Array} modifiers - list of modifiers
* @param {String} requestingName - name of requesting modifier
* @param {String} requestedName - name of requested modifier
* @returns {Boolean}
*/
function isModifierRequired(modifiers, requestingName, requestedName) {
var requesting = find(modifiers, function (_ref) {
var name = _ref.name;
return name === requestingName;
});
var isRequired = !!requesting && modifiers.some(function (modifier) {
return modifier.name === requestedName && modifier.enabled && modifier.order < requesting.order;
});
if (!isRequired) {
var _requesting = '`' + requestingName + '`';
var requested = '`' + requestedName + '`';
console.warn(requested + ' modifier is required by ' + _requesting + ' modifier in order to work, be sure to include it before ' + _requesting + '!');
}
return isRequired;
}
/**
* @function
* @memberof Modifiers
* @argument {Object} data - The data object generated by update method
* @argument {Object} options - Modifiers configuration and options
* @returns {Object} The data object, properly modified
*/
function arrow(data, options) {
var _data$offsets$arrow;
// arrow depends on keepTogether in order to work
if (!isModifierRequired(data.instance.modifiers, 'arrow', 'keepTogether')) {
return data;
}
var arrowElement = options.element;
// if arrowElement is a string, suppose it's a CSS selector
if (typeof arrowElement === 'string') {
arrowElement = data.instance.popper.querySelector(arrowElement);
// if arrowElement is not found, don't run the modifier
if (!arrowElement) {
return data;
}
} else {
// if the arrowElement isn't a query selector we must check that the
// provided DOM node is child of its popper node
if (!data.instance.popper.contains(arrowElement)) {
console.warn('WARNING: `arrow.element` must be child of its popper element!');
return data;
}
}
var placement = data.placement.split('-')[0];
var _data$offsets = data.offsets,
popper = _data$offsets.popper,
reference = _data$offsets.reference;
var isVertical = ['left', 'right'].indexOf(placement) !== -1;
var len = isVertical ? 'height' : 'width';
var sideCapitalized = isVertical ? 'Top' : 'Left';
var side = sideCapitalized.toLowerCase();
var altSide = isVertical ? 'left' : 'top';
var opSide = isVertical ? 'bottom' : 'right';
var arrowElementSize = getOuterSizes(arrowElement)[len];
//
// extends keepTogether behavior making sure the popper and its
// reference have enough pixels in conjuction
//
// top/left side
if (reference[opSide] - arrowElementSize < popper[side]) {
data.offsets.popper[side] -= popper[side] - (reference[opSide] - arrowElementSize);
}
// bottom/right side
if (reference[side] + arrowElementSize > popper[opSide]) {
data.offsets.popper[side] += reference[side] + arrowElementSize - popper[opSide];
}
data.offsets.popper = getClientRect(data.offsets.popper);
// compute center of the popper
var center = reference[side] + reference[len] / 2 - arrowElementSize / 2;
// Compute the sideValue using the updated popper offsets
// take popper margin in account because we don't have this info available
var css = getStyleComputedProperty(data.instance.popper);
var popperMarginSide = parseFloat(css['margin' + sideCapitalized], 10);
var popperBorderSide = parseFloat(css['border' + sideCapitalized + 'Width'], 10);
var sideValue = center - data.offsets.popper[side] - popperMarginSide - popperBorderSide;
// prevent arrowElement from being placed not contiguously to its popper
sideValue = Math.max(Math.min(popper[len] - arrowElementSize, sideValue), 0);
data.arrowElement = arrowElement;
data.offsets.arrow = (_data$offsets$arrow = {}, defineProperty(_data$offsets$arrow, side, Math.round(sideValue)), defineProperty(_data$offsets$arrow, altSide, ''), _data$offsets$arrow);
return data;
}
/**
* Get the opposite placement variation of the given one
* @method
* @memberof Popper.Utils
* @argument {String} placement variation
* @returns {String} flipped placement variation
*/
function getOppositeVariation(variation) {
if (variation === 'end') {
return 'start';
} else if (variation === 'start') {
return 'end';
}
return variation;
}
/**
* List of accepted placements to use as values of the `placement` option.<br />
* Valid placements are:
* - `auto`
* - `top`
* - `right`
* - `bottom`
* - `left`
*
* Each placement can have a variation from this list:
* - `-start`
* - `-end`
*
* Variations are interpreted easily if you think of them as the left to right
* written languages. Horizontally (`top` and `bottom`), `start` is left and `end`
* is right.<br />
* Vertically (`left` and `right`), `start` is top and `end` is bottom.
*
* Some valid examples are:
* - `top-end` (on top of reference, right aligned)
* - `right-start` (on right of reference, top aligned)
* - `bottom` (on bottom, centered)
* - `auto-right` (on the side with more space available, alignment depends by placement)
*
* @static
* @type {Array}
* @enum {String}
* @readonly
* @method placements
* @memberof Popper
*/
var placements = ['auto-start', 'auto', 'auto-end', 'top-start', 'top', 'top-end', 'right-start', 'right', 'right-end', 'bottom-end', 'bottom', 'bottom-start', 'left-end', 'left', 'left-start'];
// Get rid of `auto` `auto-start` and `auto-end`
var validPlacements = placements.slice(3);
/**
* Given an initial placement, returns all the subsequent placements
* clockwise (or counter-clockwise).
*
* @method
* @memberof Popper.Utils
* @argument {String} placement - A valid placement (it accepts variations)
* @argument {Boolean} counter - Set to true to walk the placements counterclockwise
* @returns {Array} placements including their variations
*/
function clockwise(placement) {
var counter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
var index = validPlacements.indexOf(placement);
var arr = validPlacements.slice(index + 1).concat(validPlacements.slice(0, index));
return counter ? arr.reverse() : arr;
}
var BEHAVIORS = {
FLIP: 'flip',
CLOCKWISE: 'clockwise',
COUNTERCLOCKWISE: 'counterclockwise'
};
/**
* @function
* @memberof Modifiers
* @argument {Object} data - The data object generated by update method
* @argument {Object} options - Modifiers configuration and options
* @returns {Object} The data object, properly modified
*/
function flip(data, options) {
// if `inner` modifier is enabled, we can't use the `flip` modifier
if (isModifierEnabled(data.instance.modifiers, 'inner')) {
return data;
}
if (data.flipped && data.placement === data.originalPlacement) {
// seems like flip is trying to loop, probably there's not enough space on any of the flippable sides
return data;
}
var boundaries = getBoundaries(data.instance.popper, data.instance.reference, options.padding, options.boundariesElement);
var placement = data.placement.split('-')[0];
var placementOpposite = getOppositePlacement(placement);
var variation = data.placement.split('-')[1] || '';
var flipOrder = [];
switch (options.behavior) {
case BEHAVIORS.FLIP:
flipOrder = [placement, placementOpposite];
break;
case BEHAVIORS.CLOCKWISE:
flipOrder = clockwise(placement);
break;
case BEHAVIORS.COUNTERCLOCKWISE:
flipOrder = clockwise(placement, true);
break;
default:
flipOrder = options.behavior;
}
flipOrder.forEach(function (step, index) {
if (placement !== step || flipOrder.length === index + 1) {
return data;
}
placement = data.placement.split('-')[0];
placementOpposite = getOppositePlacement(placement);
var popperOffsets = data.offsets.popper;
var refOffsets = data.offsets.reference;
// using floor because the reference offsets may contain decimals we are not going to consider here
var floor = Math.floor;
var overlapsRef = placement === 'left' && floor(popperOffsets.right) > floor(refOffsets.left) || placement === 'right' && floor(popperOffsets.left) < floor(refOffsets.right) || placement === 'top' && floor(popperOffsets.bottom) > floor(refOffsets.top) || placement === 'bottom' && floor(popperOffsets.top) < floor(refOffsets.bottom);
var overflowsLeft = floor(popperOffsets.left) < floor(boundaries.left);
var overflowsRight = floor(popperOffsets.right) > floor(boundaries.right);
var overflowsTop = floor(popperOffsets.top) < floor(boundaries.top);
var overflowsBottom = floor(popperOffsets.bottom) > floor(boundaries.bottom);
var overflowsBoundaries = placement === 'left' && overflowsLeft || placement === 'right' && overflowsRight || placement === 'top' && overflowsTop || placement === 'bottom' && overflowsBottom;
// flip the variation if required
var isVertical = ['top', 'bottom'].indexOf(placement) !== -1;
var flippedVariation = !!options.flipVariations && (isVertical && variation === 'start' && overflowsLeft || isVertical && variation === 'end' && overflowsRight || !isVertical && variation === 'start' && overflowsTop || !isVertical && variation === 'end' && overflowsBottom);
if (overlapsRef || overflowsBoundaries || flippedVariation) {
// this boolean to detect any flip loop
data.flipped = true;
if (overlapsRef || overflowsBoundaries) {
placement = flipOrder[index + 1];
}
if (flippedVariation) {
variation = getOppositeVariation(variation);
}
data.placement = placement + (variation ? '-' + variation : '');
// this object contains `position`, we want to preserve it along with
// any additional property we may add in the future
data.offsets.popper = _extends({}, data.offsets.popper, getPopperOffsets(data.instance.popper, data.offsets.reference, data.placement));
data = runModifiers(data.instance.modifiers, data, 'flip');
}
});
return data;
}
/**
* @function
* @memberof Modifiers
* @argument {Object} data - The data object generated by update method
* @argument {Object} options - Modifiers configuration and options
* @returns {Object} The data object, properly modified
*/
function keepTogether(data) {
var _data$offsets = data.offsets,
popper = _data$offsets.popper,
reference = _data$offsets.reference;
var placement = data.placement.split('-')[0];
var floor = Math.floor;
var isVertical = ['top', 'bottom'].indexOf(placement) !== -1;
var side = isVertical ? 'right' : 'bottom';
var opSide = isVertical ? 'left' : 'top';
var measurement = isVertical ? 'width' : 'height';
if (popper[side] < floor(reference[opSide])) {
data.offsets.popper[opSide] = floor(reference[opSide]) - popper[measurement];
}
if (popper[opSide] > floor(reference[side])) {
data.offsets.popper[opSide] = floor(reference[side]);
}
return data;
}
/**
* Converts a string containing value + unit into a px value number
* @function
* @memberof {modifiers~offset}
* @private
* @argument {String} str - Value + unit string
* @argument {String} measurement - `height` or `width`
* @argument {Object} popperOffsets
* @argument {Object} referenceOffsets
* @returns {Number|String}
* Value in pixels, or original string if no values were extracted
*/
function toValue(str, measurement, popperOffsets, referenceOffsets) {
// separate value from unit
var split = str.match(/((?:\-|\+)?\d*\.?\d*)(.*)/);
var value = +split[1];
var unit = split[2];
// If it's not a number it's an operator, I guess
if (!value) {
return str;
}
if (unit.indexOf('%') === 0) {
var element = void 0;
switch (unit) {
case '%p':
element = popperOffsets;
break;
case '%':
case '%r':
default:
element = referenceOffsets;
}
var rect = getClientRect(element);
return rect[measurement] / 100 * value;
} else if (unit === 'vh' || unit === 'vw') {
// if is a vh or vw, we calculate the size based on the viewport
var size = void 0;
if (unit === 'vh') {
size = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
} else {
size = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
}
return size / 100 * value;
} else {
// if is an explicit pixel unit, we get rid of the unit and keep the value
// if is an implicit unit, it's px, and we return just the value
return value;
}
}
/**
* Parse an `offset` string to extrapolate `x` and `y` numeric offsets.
* @function
* @memberof {modifiers~offset}
* @private
* @argument {String} offset
* @argument {Object} popperOffsets
* @argument {Object} referenceOffsets
* @argument {String} basePlacement
* @returns {Array} a two cells array with x and y offsets in numbers
*/
function parseOffset(offset, popperOffsets, referenceOffsets, basePlacement) {
var offsets = [0, 0];
// Use height if placement is left or right and index is 0 otherwise use width
// in this way the first offset will use an axis and the second one
// will use the other one
var useHeight = ['right', 'left'].indexOf(basePlacement) !== -1;
// Split the offset string to obtain a list of values and operands
// The regex addresses values with the plus or minus sign in front (+10, -20, etc)
var fragments = offset.split(/(\+|\-)/).map(function (frag) {
return frag.trim();
});
// Detect if the offset string contains a pair of values or a single one
// they could be separated by comma or space
var divider = fragments.indexOf(find(fragments, function (frag) {
return frag.search(/,|\s/) !== -1;
}));
if (fragments[divider] && fragments[divider].indexOf(',') === -1) {
console.warn('Offsets separated by white space(s) are deprecated, use a comma (,) instead.');
}
// If divider is found, we divide the list of values and operands to divide
// them by ofset X and Y.
var splitRegex = /\s*,\s*|\s+/;
var ops = divider !== -1 ? [fragments.slice(0, divider).concat([fragments[divider].split(splitRegex)[0]]), [fragments[divider].split(splitRegex)[1]].concat(fragments.slice(divider + 1))] : [fragments];
// Convert the values with units to absolute pixels to allow our computations
ops = ops.map(function (op, index) {
// Most of the units rely on the orientation of the popper
var measurement = (index === 1 ? !useHeight : useHeight) ? 'height' : 'width';
var mergeWithPrevious = false;
return op
// This aggregates any `+` or `-` sign that aren't considered operators
// e.g.: 10 + +5 => [10, +, +5]
.reduce(function (a, b) {
if (a[a.length - 1] === '' && ['+', '-'].indexOf(b) !== -1) {
a[a.length - 1] = b;
mergeWithPrevious = true;
return a;
} else if (mergeWithPrevious) {
a[a.length - 1] += b;
mergeWithPrevious = false;
return a;
} else {
return a.concat(b);
}
}, [])
// Here we convert the string values into number values (in px)
.map(function (str) {
return toValue(str, measurement, popperOffsets, referenceOffsets);
});
});
// Loop trough the offsets arrays and execute the operations
ops.forEach(function (op, index) {
op.forEach(function (frag, index2) {
if (isNumeric(frag)) {
offsets[index] += frag * (op[index2 - 1] === '-' ? -1 : 1);
}
});
});
return offsets;
}
/**
* @function
* @memberof Modifiers
* @argument {Object} data - The data object generated by update method
* @argument {Object} options - Modifiers configuration and options
* @argument {Number|String} options.offset=0
* The offset value as described in the modifier description
* @returns {Object} The data object, properly modified
*/
function offset(data, _ref) {
var offset = _ref.offset;
var placement = data.placement,
_data$offsets = data.offsets,
popper = _data$offsets.popper,
reference = _data$offsets.reference;
var basePlacement = placement.split('-')[0];
var offsets = void 0;
if (isNumeric(+offset)) {
offsets = [+offset, 0];
} else {
offsets = parseOffset(offset, popper, reference, basePlacement);
}
if (basePlacement === 'left') {
popper.top += offsets[0];
popper.left -= offsets[1];
} else if (basePlacement === 'right') {
popper.top += offsets[0];
popper.left += offsets[1];
} else if (basePlacement === 'top') {
popper.left += offsets[0];
popper.top -= offsets[1];
} else if (basePlacement === 'bottom') {
popper.left += offsets[0];
popper.top += offsets[1];
}
data.popper = popper;
return data;
}
/**
* @function
* @memberof Modifiers
* @argument {Object} data - The data object generated by `update` method
* @argument {Object} options - Modifiers configuration and options
* @returns {Object} The data object, properly modified
*/
function preventOverflow(data, options) {
var boundariesElement = options.boundariesElement || getOffsetParent(data.instance.popper);
// If offsetParent is the reference element, we really want to
// go one step up and use the next offsetParent as reference to
// avoid to make this modifier completely useless and look like broken
if (data.instance.reference === boundariesElement) {
boundariesElement = getOffsetParent(boundariesElement);
}
var boundaries = getBoundaries(data.instance.popper, data.instance.reference, options.padding, boundariesElement);
options.boundaries = boundaries;
var order = options.priority;
var popper = data.offsets.popper;
var check = {
primary: function primary(placement) {
var value = popper[placement];
if (popper[placement] < boundaries[placement] && !options.escapeWithReference) {
value = Math.max(popper[placement], boundaries[placement]);
}
return defineProperty({}, placement, value);
},
secondary: function secondary(placement) {
var mainSide = placement === 'right' ? 'left' : 'top';
var value = popper[mainSide];
if (popper[placement] > boundaries[placement] && !options.escapeWithReference) {
value = Math.min(popper[mainSide], boundaries[placement] - (placement === 'right' ? popper.width : popper.height));
}
return defineProperty({}, mainSide, value);
}
};
order.forEach(function (placement) {
var side = ['left', 'top'].indexOf(placement) !== -1 ? 'primary' : 'secondary';
popper = _extends({}, popper, check[side](placement));
});
data.offsets.popper = popper;
return data;
}
/**
* @function
* @memberof Modifiers
* @argument {Object} data - The data object generated by `update` method
* @argument {Object} options - Modifiers configuration and options
* @returns {Object} The data object, properly modified
*/
function shift(data) {
var placement = data.placement;
var basePlacement = placement.split('-')[0];
var shiftvariation = placement.split('-')[1];
// if shift shiftvariation is specified, run the modifier
if (shiftvariation) {
var _data$offsets = data.offsets,
reference = _data$offsets.reference,
popper = _data$offsets.popper;
var isVertical = ['bottom', 'top'].indexOf(basePlacement) !== -1;
var side = isVertical ? 'left' : 'top';
var measurement = isVertical ? 'width' : 'height';
var shiftOffsets = {
start: defineProperty({}, side, reference[side]),
end: defineProperty({}, side, reference[side] + reference[measurement] - popper[measurement])
};
data.offsets.popper = _extends({}, popper, shiftOffsets[shiftvariation]);
}
return data;
}
/**
* @function
* @memberof Modifiers
* @argument {Object} data - The data object generated by update method
* @argument {Object} options - Modifiers configuration and options
* @returns {Object} The data object, properly modified
*/
function hide(data) {
if (!isModifierRequired(data.instance.modifiers, 'hide', 'preventOverflow')) {
return data;
}
var refRect = data.offsets.reference;
var bound = find(data.instance.modifiers, function (modifier) {
return modifier.name === 'preventOverflow';
}).boundaries;
if (refRect.bottom < bound.top || refRect.left > bound.right || refRect.top > bound.bottom || refRect.right < bound.left) {
// Avoid unnecessary DOM access if visibility hasn't changed
if (data.hide === true) {
return data;
}
data.hide = true;
data.attributes['x-out-of-boundaries'] = '';
} else {
// Avoid unnecessary DOM access if visibility hasn't changed
if (data.hide === false) {
return data;
}
data.hide = false;
data.attributes['x-out-of-boundaries'] = false;
}
return data;
}
/**
* @function
* @memberof Modifiers
* @argument {Object} data - The data object generated by `update` method
* @argument {Object} options - Modifiers configuration and options
* @returns {Object} The data object, properly modified
*/
function inner(data) {
var placement = data.placement;
var basePlacement = placement.split('-')[0];
var _data$offsets = data.offsets,
popper = _data$offsets.popper,
reference = _data$offsets.reference;
var isHoriz = ['left', 'right'].indexOf(basePlacement) !== -1;
var subtractLength = ['top', 'left'].indexOf(basePlacement) === -1;
popper[isHoriz ? 'left' : 'top'] = reference[basePlacement] - (subtractLength ? popper[isHoriz ? 'width' : 'height'] : 0);
data.placement = getOppositePlacement(placement);
data.offsets.popper = getClientRect(popper);
return data;
}
/**
* Modifier function, each modifier can have a function of this type assigned
* to its `fn` property.<br />
* These functions will be called on each update, this means that you must
* make sure they are performant enough to avoid performance bottlenecks.
*
* @function ModifierFn
* @argument {dataObject} data - The data object generated by `update` method
* @argument {Object} options - Modifiers configuration and options
* @returns {dataObject} The data object, properly modified
*/
/**
* Modifiers are plugins used to alter the behavior of your poppers.<br />
* Popper.js uses a set of 9 modifiers to provide all the basic functionalities
* needed by the library.
*
* Usually you don't want to override the `order`, `fn` and `onLoad` props.
* All the other properties are configurations that could be tweaked.
* @namespace modifiers
*/
var modifiers = {
/**
* Modifier used to shift the popper on the start or end of its reference
* element.<br />
* It will read the variation of the `placement` property.<br />
* It can be one either `-end` or `-start`.
* @memberof modifiers
* @inner
*/
shift: {
/** @prop {number} order=100 - Index used to define the order of execution */
order: 100,
/** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
enabled: true,
/** @prop {ModifierFn} */
fn: shift
},
/**
* The `offset` modifier can shift your popper on both its axis.
*
* It accepts the following units:
* - `px` or unitless, interpreted as pixels
* - `%` or `%r`, percentage relative to the length of the reference element
* - `%p`, percentage relative to the length of the popper element
* - `vw`, CSS viewport width unit
* - `vh`, CSS viewport height unit
*
* For length is intended the main axis relative to the placement of the popper.<br />
* This means that if the placement is `top` or `bottom`, the length will be the
* `width`. In case of `left` or `right`, it will be the height.
*
* You can provide a single value (as `Number` or `String`), or a pair of values
* as `String` divided by a comma or one (or more) white spaces.<br />
* The latter is a deprecated method because it leads to confusion and will be
* removed in v2.<br />
* Additionally, it accepts additions and subtractions between different units.
* Note that multiplications and divisions aren't supported.
*
* Valid examples are:
* ```
* 10
* '10%'
* '10, 10'
* '10%, 10'
* '10 + 10%'
* '10 - 5vh + 3%'
* '-10px + 5vh, 5px - 6%'
* ```
* > **NB**: If you desire to apply offsets to your poppers in a way that may make them overlap
* > with their reference element, unfortunately, you will have to disable the `flip` modifier.
* > More on this [reading this issue](https://github.com/FezVrasta/popper.js/issues/373)
*
* @memberof modifiers
* @inner
*/
offset: {
/** @prop {number} order=200 - Index used to define the order of execution */
order: 200,
/** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
enabled: true,
/** @prop {ModifierFn} */
fn: offset,
/** @prop {Number|String} offset=0
* The offset value as described in the modifier description
*/
offset: 0
},
/**
* Modifier used to prevent the popper from being positioned outside the boundary.
*
* An scenario exists where the reference itself is not within the boundaries.<br />
* We can say it has "escaped the boundaries" — or just "escaped".<br />
* In this case we need to decide whether the popper should either:
*
* - detach from the reference and remain "trapped" in the boundaries, or
* - if it should ignore the boundary and "escape with its reference"
*
* When `escapeWithReference` is set to`true` and reference is completely
* outside its boundaries, the popper will overflow (or completely leave)
* the boundaries in order to remain attached to the edge of the reference.
*
* @memberof modifiers
* @inner
*/
preventOverflow: {
/** @prop {number} order=300 - Index used to define the order of execution */
order: 300,
/** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
enabled: true,
/** @prop {ModifierFn} */
fn: preventOverflow,
/**
* @prop {Array} [priority=['left','right','top','bottom']]
* Popper will try to prevent overflow following these priorities by default,
* then, it could overflow on the left and on top of the `boundariesElement`
*/
priority: ['left', 'right', 'top', 'bottom'],
/**
* @prop {number} padding=5
* Amount of pixel used to define a minimum distance between the boundaries
* and the popper this makes sure the popper has always a little padding
* between the edges of its container
*/
padding: 5,
/**
* @prop {String|HTMLElement} boundariesElement='scrollParent'
* Boundaries used by the modifier, can be `scrollParent`, `window`,
* `viewport` or any DOM element.
*/
boundariesElement: 'scrollParent'
},
/**
* Modifier used to make sure the reference and its popper stay near eachothers
* without leaving any gap between the two. Expecially useful when the arrow is
* enabled and you want to assure it to point to its reference element.
* It cares only about the first axis, you can still have poppers with margin
* between the popper and its reference element.
* @memberof modifiers
* @inner
*/
keepTogether: {
/** @prop {number} order=400 - Index used to define the order of execution */
order: 400,
/** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
enabled: true,
/** @prop {ModifierFn} */
fn: keepTogether
},
/**
* This modifier is used to move the `arrowElement` of the popper to make
* sure it is positioned between the reference element and its popper element.
* It will read the outer size of the `arrowElement` node to detect how many
* pixels of conjuction are needed.
*
* It has no effect if no `arrowElement` is provided.
* @memberof modifiers
* @inner
*/
arrow: {
/** @prop {number} order=500 - Index used to define the order of execution */
order: 500,
/** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
enabled: true,
/** @prop {ModifierFn} */
fn: arrow,
/** @prop {String|HTMLElement} element='[x-arrow]' - Selector or node used as arrow */
element: '[x-arrow]'
},
/**
* Modifier used to flip the popper's placement when it starts to overlap its
* reference element.
*
* Requires the `preventOverflow` modifier before it in order to work.
*
* **NOTE:** this modifier will interrupt the current update cycle and will
* restart it if it detects the need to flip the placement.
* @memberof modifiers
* @inner
*/
flip: {
/** @prop {number} order=600 - Index used to define the order of execution */
order: 600,
/** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
enabled: true,
/** @prop {ModifierFn} */
fn: flip,
/**
* @prop {String|Array} behavior='flip'
* The behavior used to change the popper's placement. It can be one of
* `flip`, `clockwise`, `counterclockwise` or an array with a list of valid
* placements (with optional variations).
*/
behavior: 'flip',
/**
* @prop {number} padding=5
* The popper will flip if it hits the edges of the `boundariesElement`
*/
padding: 5,
/**
* @prop {String|HTMLElement} boundariesElement='viewport'
* The element which will define the boundaries of the popper position,
* the popper will never be placed outside of the defined boundaries
* (except if keepTogether is enabled)
*/
boundariesElement: 'viewport'
},
/**
* Modifier used to make the popper flow toward the inner of the reference element.
* By default, when this modifier is disabled, the popper will be placed outside
* the reference element.
* @memberof modifiers
* @inner
*/
inner: {
/** @prop {number} order=700 - Index used to define the order of execution */
order: 700,
/** @prop {Boolean} enabled=false - Whether the modifier is enabled or not */
enabled: false,
/** @prop {ModifierFn} */
fn: inner
},
/**
* Modifier used to hide the popper when its reference element is outside of the
* popper boundaries. It will set a `x-out-of-boundaries` attribute which can
* be used to hide with a CSS selector the popper when its reference is
* out of boundaries.
*
* Requires the `preventOverflow` modifier before it in order to work.
* @memberof modifiers
* @inner
*/
hide: {
/** @prop {number} order=800 - Index used to define the order of execution */
order: 800,
/** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
enabled: true,
/** @prop {ModifierFn} */
fn: hide
},
/**
* Computes the style that will be applied to the popper element to gets
* properly positioned.
*
* Note that this modifier will not touch the DOM, it just prepares the styles
* so that `applyStyle` modifier can apply it. This separation is useful
* in case you need to replace `applyStyle` with a custom implementation.
*
* This modifier has `850` as `order` value to maintain backward compatibility
* with previous versions of Popper.js. Expect the modifiers ordering method
* to change in future major versions of the library.
*
* @memberof modifiers
* @inner
*/
computeStyle: {
/** @prop {number} order=850 - Index used to define the order of execution */
order: 850,
/** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
enabled: true,
/** @prop {ModifierFn} */
fn: computeStyle,
/**
* @prop {Boolean} gpuAcceleration=true
* If true, it uses the CSS 3d transformation to position the popper.
* Otherwise, it will use the `top` and `left` properties.
*/
gpuAcceleration: true,
/**
* @prop {string} [x='bottom']
* Where to anchor the X axis (`bottom` or `top`). AKA X offset origin.
* Change this if your popper should grow in a direction different from `bottom`
*/
x: 'bottom',
/**
* @prop {string} [x='left']
* Where to anchor the Y axis (`left` or `right`). AKA Y offset origin.
* Change this if your popper should grow in a direction different from `right`
*/
y: 'right'
},
/**
* Applies the computed styles to the popper element.
*
* All the DOM manipulations are limited to this modifier. This is useful in case
* you want to integrate Popper.js inside a framework or view library and you
* want to delegate all the DOM manipulations to it.
*
* Note that if you disable this modifier, you must make sure the popper element
* has its position set to `absolute` before Popper.js can do its work!
*
* Just disable this modifier and define you own to achieve the desired effect.
*
* @memberof modifiers
* @inner
*/
applyStyle: {
/** @prop {number} order=900 - Index used to define the order of execution */
order: 900,
/** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
enabled: true,
/** @prop {ModifierFn} */
fn: applyStyle,
/** @prop {Function} */
onLoad: applyStyleOnLoad,
/**
* @deprecated since version 1.10.0, the property moved to `computeStyle` modifier
* @prop {Boolean} gpuAcceleration=true
* If true, it uses the CSS 3d transformation to position the popper.
* Otherwise, it will use the `top` and `left` properties.
*/
gpuAcceleration: undefined
}
};
/**
* The `dataObject` is an object containing all the informations used by Popper.js
* this object get passed to modifiers and to the `onCreate` and `onUpdate` callbacks.
* @name dataObject
* @property {Object} data.instance The Popper.js instance
* @property {String} data.placement Placement applied to popper
* @property {String} data.originalPlacement Placement originally defined on init
* @property {Boolean} data.flipped True if popper has been flipped by flip modifier
* @property {Boolean} data.hide True if the reference element is out of boundaries, useful to know when to hide the popper.
* @property {HTMLElement} data.arrowElement Node used as arrow by arrow modifier
* @property {Object} data.styles Any CSS property defined here will be applied to the popper, it expects the JavaScript nomenclature (eg. `marginBottom`)
* @property {Object} data.arrowStyles Any CSS property defined here will be applied to the popper arrow, it expects the JavaScript nomenclature (eg. `marginBottom`)
* @property {Object} data.boundaries Offsets of the popper boundaries
* @property {Object} data.offsets The measurements of popper, reference and arrow elements.
* @property {Object} data.offsets.popper `top`, `left`, `width`, `height` values
* @property {Object} data.offsets.reference `top`, `left`, `width`, `height` values
* @property {Object} data.offsets.arrow] `top` and `left` offsets, only one of them will be different from 0
*/
/**
* Default options provided to Popper.js constructor.<br />
* These can be overriden using the `options` argument of Popper.js.<br />
* To override an option, simply pass as 3rd argument an object with the same
* structure of this object, example:
* ```
* new Popper(ref, pop, {
* modifiers: {
* preventOverflow: { enabled: false }
* }
* })
* ```
* @type {Object}
* @static
* @memberof Popper
*/
var Defaults = {
/**
* Popper's placement
* @prop {Popper.placements} placement='bottom'
*/
placement: 'bottom',
/**
* Whether events (resize, scroll) are initially enabled
* @prop {Boolean} eventsEnabled=true
*/
eventsEnabled: true,
/**
* Set to true if you want to automatically remove the popper when
* you call the `destroy` method.
* @prop {Boolean} removeOnDestroy=false
*/
removeOnDestroy: false,
/**
* Callback called when the popper is created.<br />
* By default, is set to no-op.<br />
* Access Popper.js instance with `data.instance`.
* @prop {onCreate}
*/
onCreate: function onCreate() {},
/**
* Callback called when the popper is updated, this callback is not called
* on the initialization/creation of the popper, but only on subsequent
* updates.<br />
* By default, is set to no-op.<br />
* Access Popper.js instance with `data.instance`.
* @prop {onUpdate}
*/
onUpdate: function onUpdate() {},
/**
* List of modifiers used to modify the offsets before they are applied to the popper.
* They provide most of the functionalities of Popper.js
* @prop {modifiers}
*/
modifiers: modifiers
};
/**
* @callback onCreate
* @param {dataObject} data
*/
/**
* @callback onUpdate
* @param {dataObject} data
*/
// Utils
// Methods
var Popper = function () {
/**
* Create a new Popper.js instance
* @class Popper
* @param {HTMLElement|referenceObject} reference - The reference element used to position the popper
* @param {HTMLElement} popper - The HTML element used as popper.
* @param {Object} options - Your custom options to override the ones defined in [Defaults](#defaults)
* @return {Object} instance - The generated Popper.js instance
*/
function Popper(reference, popper) {
var _this = this;
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
classCallCheck(this, Popper);
this.scheduleUpdate = function () {
return requestAnimationFrame(_this.update);
};
// make update() debounced, so that it only runs at most once-per-tick
this.update = debounce(this.update.bind(this));
// with {} we create a new object with the options inside it
this.options = _extends({}, Popper.Defaults, options);
// init state
this.state = {
isDestroyed: false,
isCreated: false,
scrollParents: []
};
// get reference and popper elements (allow jQuery wrappers)
this.reference = reference && reference.jquery ? reference[0] : reference;
this.popper = popper && popper.jquery ? popper[0] : popper;
// Deep merge modifiers options
this.options.modifiers = {};
Object.keys(_extends({}, Popper.Defaults.modifiers, options.modifiers)).forEach(function (name) {
_this.options.modifiers[name] = _extends({}, Popper.Defaults.modifiers[name] || {}, options.modifiers ? options.modifiers[name] : {});
});
// Refactoring modifiers' list (Object => Array)
this.modifiers = Object.keys(this.options.modifiers).map(function (name) {
return _extends({
name: name
}, _this.options.modifiers[name]);
})
// sort the modifiers by order
.sort(function (a, b) {
return a.order - b.order;
});
// modifiers have the ability to execute arbitrary code when Popper.js get inited
// such code is executed in the same order of its modifier
// they could add new properties to their options configuration
// BE AWARE: don't add options to `options.modifiers.name` but to `modifierOptions`!
this.modifiers.forEach(function (modifierOptions) {
if (modifierOptions.enabled && isFunction(modifierOptions.onLoad)) {
modifierOptions.onLoad(_this.reference, _this.popper, _this.options, modifierOptions, _this.state);
}
});
// fire the first update to position the popper in the right place
this.update();
var eventsEnabled = this.options.eventsEnabled;
if (eventsEnabled) {
// setup event listeners, they will take care of update the position in specific situations
this.enableEventListeners();
}
this.state.eventsEnabled = eventsEnabled;
}
// We can't use class properties because they don't get listed in the
// class prototype and break stuff like Sinon stubs
createClass(Popper, [{
key: 'update',
value: function update$$1() {
return update.call(this);
}
}, {
key: 'destroy',
value: function destroy$$1() {
return destroy.call(this);
}
}, {
key: 'enableEventListeners',
value: function enableEventListeners$$1() {
return enableEventListeners.call(this);
}
}, {
key: 'disableEventListeners',
value: function disableEventListeners$$1() {
return disableEventListeners.call(this);
}
/**
* Schedule an update, it will run on the next UI update available
* @method scheduleUpdate
* @memberof Popper
*/
/**
* Collection of utilities useful when writing custom modifiers.
* Starting from version 1.7, this method is available only if you
* include `popper-utils.js` before `popper.js`.
*
* **DEPRECATION**: This way to access PopperUtils is deprecated
* and will be removed in v2! Use the PopperUtils module directly instead.
* Due to the high instability of the methods contained in Utils, we can't
* guarantee them to follow semver. Use them at your own risk!
* @static
* @private
* @type {Object}
* @deprecated since version 1.8
* @member Utils
* @memberof Popper
*/
}]);
return Popper;
}();
/**
* The `referenceObject` is an object that provides an interface compatible with Popper.js
* and lets you use it as replacement of a real DOM node.<br />
* You can use this method to position a popper relatively to a set of coordinates
* in case you don't have a DOM node to use as reference.
*
* ```
* new Popper(referenceObject, popperNode);
* ```
*
* NB: This feature isn't supported in Internet Explorer 10
* @name referenceObject
* @property {Function} data.getBoundingClientRect
* A function that returns a set of coordinates compatible with the native `getBoundingClientRect` method.
* @property {number} data.clientWidth
* An ES6 getter that will return the width of the virtual reference element.
* @property {number} data.clientHeight
* An ES6 getter that will return the height of the virtual reference element.
*/
Popper.Utils = (typeof window !== 'undefined' ? window : global).PopperUtils;
Popper.placements = placements;
Popper.Defaults = Defaults;
return Popper;
})));
/*!
* Bootstrap v4.0.0-beta.2 (https://getbootstrap.com)
* Copyright 2011-2017 The Bootstrap Authors (https://github.com/twbs/bootstrap/graphs/contributors)
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
*/
var bootstrap = (function (exports,$,Popper) {
'use strict';
$ = $ && $.hasOwnProperty('default') ? $['default'] : $;
Popper = Popper && Popper.hasOwnProperty('default') ? Popper['default'] : Popper;
/**
* --------------------------------------------------------------------------
* Bootstrap (v4.0.0-beta.2): util.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
var Util = function () {
/**
* ------------------------------------------------------------------------
* Private TransitionEnd Helpers
* ------------------------------------------------------------------------
*/
var transition = false;
var MAX_UID = 1000000;
var TransitionEndEvent = {
WebkitTransition: 'webkitTransitionEnd',
MozTransition: 'transitionend',
OTransition: 'oTransitionEnd otransitionend',
transition: 'transitionend' // shoutout AngusCroll (https://goo.gl/pxwQGp)
};
function toType(obj) {
return {}.toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase();
}
function getSpecialTransitionEndEvent() {
return {
bindType: transition.end,
delegateType: transition.end,
handle: function handle(event) {
if ($(event.target).is(this)) {
return event.handleObj.handler.apply(this, arguments); // eslint-disable-line prefer-rest-params
}
return undefined; // eslint-disable-line no-undefined
}
};
}
function transitionEndTest() {
if (window.QUnit) {
return false;
}
var el = document.createElement('bootstrap');
for (var name in TransitionEndEvent) {
if (typeof el.style[name] !== 'undefined') {
return {
end: TransitionEndEvent[name]
};
}
}
return false;
}
function transitionEndEmulator(duration) {
var _this = this;
var called = false;
$(this).one(Util.TRANSITION_END, function () {
called = true;
});
setTimeout(function () {
if (!called) {
Util.triggerTransitionEnd(_this);
}
}, duration);
return this;
}
function setTransitionEndSupport() {
transition = transitionEndTest();
$.fn.emulateTransitionEnd = transitionEndEmulator;
if (Util.supportsTransitionEnd()) {
$.event.special[Util.TRANSITION_END] = getSpecialTransitionEndEvent();
}
}
/**
* --------------------------------------------------------------------------
* Public Util Api
* --------------------------------------------------------------------------
*/
var Util = {
TRANSITION_END: 'bsTransitionEnd',
getUID: function getUID(prefix) {
do {
// eslint-disable-next-line no-bitwise
prefix += ~~(Math.random() * MAX_UID); // "~~" acts like a faster Math.floor() here
} while (document.getElementById(prefix));
return prefix;
},
getSelectorFromElement: function getSelectorFromElement(element) {
var selector = element.getAttribute('data-target');
if (!selector || selector === '#') {
selector = element.getAttribute('href') || '';
}
try {
var $selector = $(document).find(selector);
return $selector.length > 0 ? selector : null;
} catch (error) {
return null;
}
},
reflow: function reflow(element) {
return element.offsetHeight;
},
triggerTransitionEnd: function triggerTransitionEnd(element) {
$(element).trigger(transition.end);
},
supportsTransitionEnd: function supportsTransitionEnd() {
return Boolean(transition);
},
isElement: function isElement(obj) {
return (obj[0] || obj).nodeType;
},
typeCheckConfig: function typeCheckConfig(componentName, config, configTypes) {
for (var property in configTypes) {
if (Object.prototype.hasOwnProperty.call(configTypes, property)) {
var expectedTypes = configTypes[property];
var value = config[property];
var valueType = value && Util.isElement(value) ? 'element' : toType(value);
if (!new RegExp(expectedTypes).test(valueType)) {
throw new Error(componentName.toUpperCase() + ": " + ("Option \"" + property + "\" provided type \"" + valueType + "\" ") + ("but expected type \"" + expectedTypes + "\"."));
}
}
}
}
};
setTransitionEndSupport();
return Util;
}($);
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
var createClass = _createClass;
function _inheritsLoose(subClass, superClass) {
subClass.prototype = Object.create(superClass.prototype);
subClass.prototype.constructor = subClass;
subClass.__proto__ = superClass;
}
var inheritsLoose = _inheritsLoose;
/**
* --------------------------------------------------------------------------
* Bootstrap (v4.0.0-beta.2): alert.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
var Alert = function () {
/**
* ------------------------------------------------------------------------
* Constants
* ------------------------------------------------------------------------
*/
var NAME = 'alert';
var VERSION = '4.0.0-beta.2';
var DATA_KEY = 'bs.alert';
var EVENT_KEY = "." + DATA_KEY;
var DATA_API_KEY = '.data-api';
var JQUERY_NO_CONFLICT = $.fn[NAME];
var TRANSITION_DURATION = 150;
var Selector = {
DISMISS: '[data-dismiss="alert"]'
};
var Event = {
CLOSE: "close" + EVENT_KEY,
CLOSED: "closed" + EVENT_KEY,
CLICK_DATA_API: "click" + EVENT_KEY + DATA_API_KEY
};
var ClassName = {
ALERT: 'alert',
FADE: 'fade',
SHOW: 'show'
/**
* ------------------------------------------------------------------------
* Class Definition
* ------------------------------------------------------------------------
*/
};
var Alert =
/*#__PURE__*/
function () {
function Alert(element) {
this._element = element;
} // getters
var _proto = Alert.prototype;
// public
_proto.close = function close(element) {
element = element || this._element;
var rootElement = this._getRootElement(element);
var customEvent = this._triggerCloseEvent(rootElement);
if (customEvent.isDefaultPrevented()) {
return;
}
this._removeElement(rootElement);
};
_proto.dispose = function dispose() {
$.removeData(this._element, DATA_KEY);
this._element = null;
}; // private
_proto._getRootElement = function _getRootElement(element) {
var selector = Util.getSelectorFromElement(element);
var parent = false;
if (selector) {
parent = $(selector)[0];
}
if (!parent) {
parent = $(element).closest("." + ClassName.ALERT)[0];
}
return parent;
};
_proto._triggerCloseEvent = function _triggerCloseEvent(element) {
var closeEvent = $.Event(Event.CLOSE);
$(element).trigger(closeEvent);
return closeEvent;
};
_proto._removeElement = function _removeElement(element) {
var _this = this;
$(element).removeClass(ClassName.SHOW);
if (!Util.supportsTransitionEnd() || !$(element).hasClass(ClassName.FADE)) {
this._destroyElement(element);
return;
}
$(element).one(Util.TRANSITION_END, function (event) {
return _this._destroyElement(element, event);
}).emulateTransitionEnd(TRANSITION_DURATION);
};
_proto._destroyElement = function _destroyElement(element) {
$(element).detach().trigger(Event.CLOSED).remove();
}; // static
Alert._jQueryInterface = function _jQueryInterface(config) {
return this.each(function () {
var $element = $(this);
var data = $element.data(DATA_KEY);
if (!data) {
data = new Alert(this);
$element.data(DATA_KEY, data);
}
if (config === 'close') {
data[config](this);
}
});
};
Alert._handleDismiss = function _handleDismiss(alertInstance) {
return function (event) {
if (event) {
event.preventDefault();
}
alertInstance.close(this);
};
};
createClass(Alert, null, [{
key: "VERSION",
get: function get() {
return VERSION;
}
}]);
return Alert;
}();
/**
* ------------------------------------------------------------------------
* Data Api implementation
* ------------------------------------------------------------------------
*/
$(document).on(Event.CLICK_DATA_API, Selector.DISMISS, Alert._handleDismiss(new Alert()));
/**
* ------------------------------------------------------------------------
* jQuery
* ------------------------------------------------------------------------
*/
$.fn[NAME] = Alert._jQueryInterface;
$.fn[NAME].Constructor = Alert;
$.fn[NAME].noConflict = function () {
$.fn[NAME] = JQUERY_NO_CONFLICT;
return Alert._jQueryInterface;
};
return Alert;
}($);
/**
* --------------------------------------------------------------------------
* Bootstrap (v4.0.0-beta.2): button.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
var Button = function () {
/**
* ------------------------------------------------------------------------
* Constants
* ------------------------------------------------------------------------
*/
var NAME = 'button';
var VERSION = '4.0.0-beta.2';
var DATA_KEY = 'bs.button';
var EVENT_KEY = "." + DATA_KEY;
var DATA_API_KEY = '.data-api';
var JQUERY_NO_CONFLICT = $.fn[NAME];
var ClassName = {
ACTIVE: 'active',
BUTTON: 'btn',
FOCUS: 'focus'
};
var Selector = {
DATA_TOGGLE_CARROT: '[data-toggle^="button"]',
DATA_TOGGLE: '[data-toggle="buttons"]',
INPUT: 'input',
ACTIVE: '.active',
BUTTON: '.btn'
};
var Event = {
CLICK_DATA_API: "click" + EVENT_KEY + DATA_API_KEY,
FOCUS_BLUR_DATA_API: "focus" + EVENT_KEY + DATA_API_KEY + " " + ("blur" + EVENT_KEY + DATA_API_KEY)
/**
* ------------------------------------------------------------------------
* Class Definition
* ------------------------------------------------------------------------
*/
};
var Button =
/*#__PURE__*/
function () {
function Button(element) {
this._element = element;
} // getters
var _proto = Button.prototype;
// public
_proto.toggle = function toggle() {
var triggerChangeEvent = true;
var addAriaPressed = true;
var rootElement = $(this._element).closest(Selector.DATA_TOGGLE)[0];
if (rootElement) {
var input = $(this._element).find(Selector.INPUT)[0];
if (input) {
if (input.type === 'radio') {
if (input.checked && $(this._element).hasClass(ClassName.ACTIVE)) {
triggerChangeEvent = false;
} else {
var activeElement = $(rootElement).find(Selector.ACTIVE)[0];
if (activeElement) {
$(activeElement).removeClass(ClassName.ACTIVE);
}
}
}
if (triggerChangeEvent) {
if (input.hasAttribute('disabled') || rootElement.hasAttribute('disabled') || input.classList.contains('disabled') || rootElement.classList.contains('disabled')) {
return;
}
input.checked = !$(this._element).hasClass(ClassName.ACTIVE);
$(input).trigger('change');
}
input.focus();
addAriaPressed = false;
}
}
if (addAriaPressed) {
this._element.setAttribute('aria-pressed', !$(this._element).hasClass(ClassName.ACTIVE));
}
if (triggerChangeEvent) {
$(this._element).toggleClass(ClassName.ACTIVE);
}
};
_proto.dispose = function dispose() {
$.removeData(this._element, DATA_KEY);
this._element = null;
}; // static
Button._jQueryInterface = function _jQueryInterface(config) {
return this.each(function () {
var data = $(this).data(DATA_KEY);
if (!data) {
data = new Button(this);
$(this).data(DATA_KEY, data);
}
if (config === 'toggle') {
data[config]();
}
});
};
createClass(Button, null, [{
key: "VERSION",
get: function get() {
return VERSION;
}
}]);
return Button;
}();
/**
* ------------------------------------------------------------------------
* Data Api implementation
* ------------------------------------------------------------------------
*/
$(document).on(Event.CLICK_DATA_API, Selector.DATA_TOGGLE_CARROT, function (event) {
event.preventDefault();
var button = event.target;
if (!$(button).hasClass(ClassName.BUTTON)) {
button = $(button).closest(Selector.BUTTON);
}
Button._jQueryInterface.call($(button), 'toggle');
}).on(Event.FOCUS_BLUR_DATA_API, Selector.DATA_TOGGLE_CARROT, function (event) {
var button = $(event.target).closest(Selector.BUTTON)[0];
$(button).toggleClass(ClassName.FOCUS, /^focus(in)?$/.test(event.type));
});
/**
* ------------------------------------------------------------------------
* jQuery
* ------------------------------------------------------------------------
*/
$.fn[NAME] = Button._jQueryInterface;
$.fn[NAME].Constructor = Button;
$.fn[NAME].noConflict = function () {
$.fn[NAME] = JQUERY_NO_CONFLICT;
return Button._jQueryInterface;
};
return Button;
}($);
/**
* --------------------------------------------------------------------------
* Bootstrap (v4.0.0-beta.2): carousel.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
var Carousel = function () {
/**
* ------------------------------------------------------------------------
* Constants
* ------------------------------------------------------------------------
*/
var NAME = 'carousel';
var VERSION = '4.0.0-beta.2';
var DATA_KEY = 'bs.carousel';
var EVENT_KEY = "." + DATA_KEY;
var DATA_API_KEY = '.data-api';
var JQUERY_NO_CONFLICT = $.fn[NAME];
var TRANSITION_DURATION = 600;
var ARROW_LEFT_KEYCODE = 37; // KeyboardEvent.which value for left arrow key
var ARROW_RIGHT_KEYCODE = 39; // KeyboardEvent.which value for right arrow key
var TOUCHEVENT_COMPAT_WAIT = 500; // Time for mouse compat events to fire after touch
var Default = {
interval: 5000,
keyboard: true,
slide: false,
pause: 'hover',
wrap: true
};
var DefaultType = {
interval: '(number|boolean)',
keyboard: 'boolean',
slide: '(boolean|string)',
pause: '(string|boolean)',
wrap: 'boolean'
};
var Direction = {
NEXT: 'next',
PREV: 'prev',
LEFT: 'left',
RIGHT: 'right'
};
var Event = {
SLIDE: "slide" + EVENT_KEY,
SLID: "slid" + EVENT_KEY,
KEYDOWN: "keydown" + EVENT_KEY,
MOUSEENTER: "mouseenter" + EVENT_KEY,
MOUSELEAVE: "mouseleave" + EVENT_KEY,
TOUCHEND: "touchend" + EVENT_KEY,
LOAD_DATA_API: "load" + EVENT_KEY + DATA_API_KEY,
CLICK_DATA_API: "click" + EVENT_KEY + DATA_API_KEY
};
var ClassName = {
CAROUSEL: 'carousel',
ACTIVE: 'active',
SLIDE: 'slide',
RIGHT: 'carousel-item-right',
LEFT: 'carousel-item-left',
NEXT: 'carousel-item-next',
PREV: 'carousel-item-prev',
ITEM: 'carousel-item'
};
var Selector = {
ACTIVE: '.active',
ACTIVE_ITEM: '.active.carousel-item',
ITEM: '.carousel-item',
NEXT_PREV: '.carousel-item-next, .carousel-item-prev',
INDICATORS: '.carousel-indicators',
DATA_SLIDE: '[data-slide], [data-slide-to]',
DATA_RIDE: '[data-ride="carousel"]'
/**
* ------------------------------------------------------------------------
* Class Definition
* ------------------------------------------------------------------------
*/
};
var Carousel =
/*#__PURE__*/
function () {
function Carousel(element, config) {
this._items = null;
this._interval = null;
this._activeElement = null;
this._isPaused = false;
this._isSliding = false;
this.touchTimeout = null;
this._config = this._getConfig(config);
this._element = $(element)[0];
this._indicatorsElement = $(this._element).find(Selector.INDICATORS)[0];
this._addEventListeners();
} // getters
var _proto = Carousel.prototype;
// public
_proto.next = function next() {
if (!this._isSliding) {
this._slide(Direction.NEXT);
}
};
_proto.nextWhenVisible = function nextWhenVisible() {
// Don't call next when the page isn't visible
// or the carousel or its parent isn't visible
if (!document.hidden && $(this._element).is(':visible') && $(this._element).css('visibility') !== 'hidden') {
this.next();
}
};
_proto.prev = function prev() {
if (!this._isSliding) {
this._slide(Direction.PREV);
}
};
_proto.pause = function pause(event) {
if (!event) {
this._isPaused = true;
}
if ($(this._element).find(Selector.NEXT_PREV)[0] && Util.supportsTransitionEnd()) {
Util.triggerTransitionEnd(this._element);
this.cycle(true);
}
clearInterval(this._interval);
this._interval = null;
};
_proto.cycle = function cycle(event) {
if (!event) {
this._isPaused = false;
}
if (this._interval) {
clearInterval(this._interval);
this._interval = null;
}
if (this._config.interval && !this._isPaused) {
this._interval = setInterval((document.visibilityState ? this.nextWhenVisible : this.next).bind(this), this._config.interval);
}
};
_proto.to = function to(index) {
var _this = this;
this._activeElement = $(this._element).find(Selector.ACTIVE_ITEM)[0];
var activeIndex = this._getItemIndex(this._activeElement);
if (index > this._items.length - 1 || index < 0) {
return;
}
if (this._isSliding) {
$(this._element).one(Event.SLID, function () {
return _this.to(index);
});
return;
}
if (activeIndex === index) {
this.pause();
this.cycle();
return;
}
var direction = index > activeIndex ? Direction.NEXT : Direction.PREV;
this._slide(direction, this._items[index]);
};
_proto.dispose = function dispose() {
$(this._element).off(EVENT_KEY);
$.removeData(this._element, DATA_KEY);
this._items = null;
this._config = null;
this._element = null;
this._interval = null;
this._isPaused = null;
this._isSliding = null;
this._activeElement = null;
this._indicatorsElement = null;
}; // private
_proto._getConfig = function _getConfig(config) {
config = $.extend({}, Default, config);
Util.typeCheckConfig(NAME, config, DefaultType);
return config;
};
_proto._addEventListeners = function _addEventListeners() {
var _this2 = this;
if (this._config.keyboard) {
$(this._element).on(Event.KEYDOWN, function (event) {
return _this2._keydown(event);
});
}
if (this._config.pause === 'hover') {
$(this._element).on(Event.MOUSEENTER, function (event) {
return _this2.pause(event);
}).on(Event.MOUSELEAVE, function (event) {
return _this2.cycle(event);
});
if ('ontouchstart' in document.documentElement) {
// if it's a touch-enabled device, mouseenter/leave are fired as
// part of the mouse compatibility events on first tap - the carousel
// would stop cycling until user tapped out of it;
// here, we listen for touchend, explicitly pause the carousel
// (as if it's the second time we tap on it, mouseenter compat event
// is NOT fired) and after a timeout (to allow for mouse compatibility
// events to fire) we explicitly restart cycling
$(this._element).on(Event.TOUCHEND, function () {
_this2.pause();
if (_this2.touchTimeout) {
clearTimeout(_this2.touchTimeout);
}
_this2.touchTimeout = setTimeout(function (event) {
return _this2.cycle(event);
}, TOUCHEVENT_COMPAT_WAIT + _this2._config.interval);
});
}
}
};
_proto._keydown = function _keydown(event) {
if (/input|textarea/i.test(event.target.tagName)) {
return;
}
switch (event.which) {
case ARROW_LEFT_KEYCODE:
event.preventDefault();
this.prev();
break;
case ARROW_RIGHT_KEYCODE:
event.preventDefault();
this.next();
break;
default:
return;
}
};
_proto._getItemIndex = function _getItemIndex(element) {
this._items = $.makeArray($(element).parent().find(Selector.ITEM));
return this._items.indexOf(element);
};
_proto._getItemByDirection = function _getItemByDirection(direction, activeElement) {
var isNextDirection = direction === Direction.NEXT;
var isPrevDirection = direction === Direction.PREV;
var activeIndex = this._getItemIndex(activeElement);
var lastItemIndex = this._items.length - 1;
var isGoingToWrap = isPrevDirection && activeIndex === 0 || isNextDirection && activeIndex === lastItemIndex;
if (isGoingToWrap && !this._config.wrap) {
return activeElement;
}
var delta = direction === Direction.PREV ? -1 : 1;
var itemIndex = (activeIndex + delta) % this._items.length;
return itemIndex === -1 ? this._items[this._items.length - 1] : this._items[itemIndex];
};
_proto._triggerSlideEvent = function _triggerSlideEvent(relatedTarget, eventDirectionName) {
var targetIndex = this._getItemIndex(relatedTarget);
var fromIndex = this._getItemIndex($(this._element).find(Selector.ACTIVE_ITEM)[0]);
var slideEvent = $.Event(Event.SLIDE, {
relatedTarget: relatedTarget,
direction: eventDirectionName,
from: fromIndex,
to: targetIndex
});
$(this._element).trigger(slideEvent);
return slideEvent;
};
_proto._setActiveIndicatorElement = function _setActiveIndicatorElement(element) {
if (this._indicatorsElement) {
$(this._indicatorsElement).find(Selector.ACTIVE).removeClass(ClassName.ACTIVE);
var nextIndicator = this._indicatorsElement.children[this._getItemIndex(element)];
if (nextIndicator) {
$(nextIndicator).addClass(ClassName.ACTIVE);
}
}
};
_proto._slide = function _slide(direction, element) {
var _this3 = this;
var activeElement = $(this._element).find(Selector.ACTIVE_ITEM)[0];
var activeElementIndex = this._getItemIndex(activeElement);
var nextElement = element || activeElement && this._getItemByDirection(direction, activeElement);
var nextElementIndex = this._getItemIndex(nextElement);
var isCycling = Boolean(this._interval);
var directionalClassName;
var orderClassName;
var eventDirectionName;
if (direction === Direction.NEXT) {
directionalClassName = ClassName.LEFT;
orderClassName = ClassName.NEXT;
eventDirectionName = Direction.LEFT;
} else {
directionalClassName = ClassName.RIGHT;
orderClassName = ClassName.PREV;
eventDirectionName = Direction.RIGHT;
}
if (nextElement && $(nextElement).hasClass(ClassName.ACTIVE)) {
this._isSliding = false;
return;
}
var slideEvent = this._triggerSlideEvent(nextElement, eventDirectionName);
if (slideEvent.isDefaultPrevented()) {
return;
}
if (!activeElement || !nextElement) {
// some weirdness is happening, so we bail
return;
}
this._isSliding = true;
if (isCycling) {
this.pause();
}
this._setActiveIndicatorElement(nextElement);
var slidEvent = $.Event(Event.SLID, {
relatedTarget: nextElement,
direction: eventDirectionName,
from: activeElementIndex,
to: nextElementIndex
});
if (Util.supportsTransitionEnd() && $(this._element).hasClass(ClassName.SLIDE)) {
$(nextElement).addClass(orderClassName);
Util.reflow(nextElement);
$(activeElement).addClass(directionalClassName);
$(nextElement).addClass(directionalClassName);
$(activeElement).one(Util.TRANSITION_END, function () {
$(nextElement).removeClass(directionalClassName + " " + orderClassName).addClass(ClassName.ACTIVE);
$(activeElement).removeClass(ClassName.ACTIVE + " " + orderClassName + " " + directionalClassName);
_this3._isSliding = false;
setTimeout(function () {
return $(_this3._element).trigger(slidEvent);
}, 0);
}).emulateTransitionEnd(TRANSITION_DURATION);
} else {
$(activeElement).removeClass(ClassName.ACTIVE);
$(nextElement).addClass(ClassName.ACTIVE);
this._isSliding = false;
$(this._element).trigger(slidEvent);
}
if (isCycling) {
this.cycle();
}
}; // static
Carousel._jQueryInterface = function _jQueryInterface(config) {
return this.each(function () {
var data = $(this).data(DATA_KEY);
var _config = $.extend({}, Default, $(this).data());
if (typeof config === 'object') {
$.extend(_config, config);
}
var action = typeof config === 'string' ? config : _config.slide;
if (!data) {
data = new Carousel(this, _config);
$(this).data(DATA_KEY, data);
}
if (typeof config === 'number') {
data.to(config);
} else if (typeof action === 'string') {
if (typeof data[action] === 'undefined') {
throw new Error("No method named \"" + action + "\"");
}
data[action]();
} else if (_config.interval) {
data.pause();
data.cycle();
}
});
};
Carousel._dataApiClickHandler = function _dataApiClickHandler(event) {
var selector = Util.getSelectorFromElement(this);
if (!selector) {
return;
}
var target = $(selector)[0];
if (!target || !$(target).hasClass(ClassName.CAROUSEL)) {
return;
}
var config = $.extend({}, $(target).data(), $(this).data());
var slideIndex = this.getAttribute('data-slide-to');
if (slideIndex) {
config.interval = false;
}
Carousel._jQueryInterface.call($(target), config);
if (slideIndex) {
$(target).data(DATA_KEY).to(slideIndex);
}
event.preventDefault();
};
createClass(Carousel, null, [{
key: "VERSION",
get: function get() {
return VERSION;
}
}, {
key: "Default",
get: function get() {
return Default;
}
}]);
return Carousel;
}();
/**
* ------------------------------------------------------------------------
* Data Api implementation
* ------------------------------------------------------------------------
*/
$(document).on(Event.CLICK_DATA_API, Selector.DATA_SLIDE, Carousel._dataApiClickHandler);
$(window).on(Event.LOAD_DATA_API, function () {
$(Selector.DATA_RIDE).each(function () {
var $carousel = $(this);
Carousel._jQueryInterface.call($carousel, $carousel.data());
});
});
/**
* ------------------------------------------------------------------------
* jQuery
* ------------------------------------------------------------------------
*/
$.fn[NAME] = Carousel._jQueryInterface;
$.fn[NAME].Constructor = Carousel;
$.fn[NAME].noConflict = function () {
$.fn[NAME] = JQUERY_NO_CONFLICT;
return Carousel._jQueryInterface;
};
return Carousel;
}($);
/**
* --------------------------------------------------------------------------
* Bootstrap (v4.0.0-beta.2): collapse.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
var Collapse = function () {
/**
* ------------------------------------------------------------------------
* Constants
* ------------------------------------------------------------------------
*/
var NAME = 'collapse';
var VERSION = '4.0.0-beta.2';
var DATA_KEY = 'bs.collapse';
var EVENT_KEY = "." + DATA_KEY;
var DATA_API_KEY = '.data-api';
var JQUERY_NO_CONFLICT = $.fn[NAME];
var TRANSITION_DURATION = 600;
var Default = {
toggle: true,
parent: ''
};
var DefaultType = {
toggle: 'boolean',
parent: '(string|element)'
};
var Event = {
SHOW: "show" + EVENT_KEY,
SHOWN: "shown" + EVENT_KEY,
HIDE: "hide" + EVENT_KEY,
HIDDEN: "hidden" + EVENT_KEY,
CLICK_DATA_API: "click" + EVENT_KEY + DATA_API_KEY
};
var ClassName = {
SHOW: 'show',
COLLAPSE: 'collapse',
COLLAPSING: 'collapsing',
COLLAPSED: 'collapsed'
};
var Dimension = {
WIDTH: 'width',
HEIGHT: 'height'
};
var Selector = {
ACTIVES: '.show, .collapsing',
DATA_TOGGLE: '[data-toggle="collapse"]'
/**
* ------------------------------------------------------------------------
* Class Definition
* ------------------------------------------------------------------------
*/
};
var Collapse =
/*#__PURE__*/
function () {
function Collapse(element, config) {
this._isTransitioning = false;
this._element = element;
this._config = this._getConfig(config);
this._triggerArray = $.makeArray($("[data-toggle=\"collapse\"][href=\"#" + element.id + "\"]," + ("[data-toggle=\"collapse\"][data-target=\"#" + element.id + "\"]")));
var tabToggles = $(Selector.DATA_TOGGLE);
for (var i = 0; i < tabToggles.length; i++) {
var elem = tabToggles[i];
var selector = Util.getSelectorFromElement(elem);
if (selector !== null && $(selector).filter(element).length > 0) {
this._triggerArray.push(elem);
}
}
this._parent = this._config.parent ? this._getParent() : null;
if (!this._config.parent) {
this._addAriaAndCollapsedClass(this._element, this._triggerArray);
}
if (this._config.toggle) {
this.toggle();
}
} // getters
var _proto = Collapse.prototype;
// public
_proto.toggle = function toggle() {
if ($(this._element).hasClass(ClassName.SHOW)) {
this.hide();
} else {
this.show();
}
};
_proto.show = function show() {
var _this = this;
if (this._isTransitioning || $(this._element).hasClass(ClassName.SHOW)) {
return;
}
var actives;
var activesData;
if (this._parent) {
actives = $.makeArray($(this._parent).children().children(Selector.ACTIVES));
if (!actives.length) {
actives = null;
}
}
if (actives) {
activesData = $(actives).data(DATA_KEY);
if (activesData && activesData._isTransitioning) {
return;
}
}
var startEvent = $.Event(Event.SHOW);
$(this._element).trigger(startEvent);
if (startEvent.isDefaultPrevented()) {
return;
}
if (actives) {
Collapse._jQueryInterface.call($(actives), 'hide');
if (!activesData) {
$(actives).data(DATA_KEY, null);
}
}
var dimension = this._getDimension();
$(this._element).removeClass(ClassName.COLLAPSE).addClass(ClassName.COLLAPSING);
this._element.style[dimension] = 0;
if (this._triggerArray.length) {
$(this._triggerArray).removeClass(ClassName.COLLAPSED).attr('aria-expanded', true);
}
this.setTransitioning(true);
var complete = function complete() {
$(_this._element).removeClass(ClassName.COLLAPSING).addClass(ClassName.COLLAPSE).addClass(ClassName.SHOW);
_this._element.style[dimension] = '';
_this.setTransitioning(false);
$(_this._element).trigger(Event.SHOWN);
};
if (!Util.supportsTransitionEnd()) {
complete();
return;
}
var capitalizedDimension = dimension[0].toUpperCase() + dimension.slice(1);
var scrollSize = "scroll" + capitalizedDimension;
$(this._element).one(Util.TRANSITION_END, complete).emulateTransitionEnd(TRANSITION_DURATION);
this._element.style[dimension] = this._element[scrollSize] + "px";
};
_proto.hide = function hide() {
var _this2 = this;
if (this._isTransitioning || !$(this._element).hasClass(ClassName.SHOW)) {
return;
}
var startEvent = $.Event(Event.HIDE);
$(this._element).trigger(startEvent);
if (startEvent.isDefaultPrevented()) {
return;
}
var dimension = this._getDimension();
this._element.style[dimension] = this._element.getBoundingClientRect()[dimension] + "px";
Util.reflow(this._element);
$(this._element).addClass(ClassName.COLLAPSING).removeClass(ClassName.COLLAPSE).removeClass(ClassName.SHOW);
if (this._triggerArray.length) {
for (var i = 0; i < this._triggerArray.length; i++) {
var trigger = this._triggerArray[i];
var selector = Util.getSelectorFromElement(trigger);
if (selector !== null) {
var $elem = $(selector);
if (!$elem.hasClass(ClassName.SHOW)) {
$(trigger).addClass(ClassName.COLLAPSED).attr('aria-expanded', false);
}
}
}
}
this.setTransitioning(true);
var complete = function complete() {
_this2.setTransitioning(false);
$(_this2._element).removeClass(ClassName.COLLAPSING).addClass(ClassName.COLLAPSE).trigger(Event.HIDDEN);
};
this._element.style[dimension] = '';
if (!Util.supportsTransitionEnd()) {
complete();
return;
}
$(this._element).one(Util.TRANSITION_END, complete).emulateTransitionEnd(TRANSITION_DURATION);
};
_proto.setTransitioning = function setTransitioning(isTransitioning) {
this._isTransitioning = isTransitioning;
};
_proto.dispose = function dispose() {
$.removeData(this._element, DATA_KEY);
this._config = null;
this._parent = null;
this._element = null;
this._triggerArray = null;
this._isTransitioning = null;
}; // private
_proto._getConfig = function _getConfig(config) {
config = $.extend({}, Default, config);
config.toggle = Boolean(config.toggle); // coerce string values
Util.typeCheckConfig(NAME, config, DefaultType);
return config;
};
_proto._getDimension = function _getDimension() {
var hasWidth = $(this._element).hasClass(Dimension.WIDTH);
return hasWidth ? Dimension.WIDTH : Dimension.HEIGHT;
};
_proto._getParent = function _getParent() {
var _this3 = this;
var parent = null;
if (Util.isElement(this._config.parent)) {
parent = this._config.parent; // it's a jQuery object
if (typeof this._config.parent.jquery !== 'undefined') {
parent = this._config.parent[0];
}
} else {
parent = $(this._config.parent)[0];
}
var selector = "[data-toggle=\"collapse\"][data-parent=\"" + this._config.parent + "\"]";
$(parent).find(selector).each(function (i, element) {
_this3._addAriaAndCollapsedClass(Collapse._getTargetFromElement(element), [element]);
});
return parent;
};
_proto._addAriaAndCollapsedClass = function _addAriaAndCollapsedClass(element, triggerArray) {
if (element) {
var isOpen = $(element).hasClass(ClassName.SHOW);
if (triggerArray.length) {
$(triggerArray).toggleClass(ClassName.COLLAPSED, !isOpen).attr('aria-expanded', isOpen);
}
}
}; // static
Collapse._getTargetFromElement = function _getTargetFromElement(element) {
var selector = Util.getSelectorFromElement(element);
return selector ? $(selector)[0] : null;
};
Collapse._jQueryInterface = function _jQueryInterface(config) {
return this.each(function () {
var $this = $(this);
var data = $this.data(DATA_KEY);
var _config = $.extend({}, Default, $this.data(), typeof config === 'object' && config);
if (!data && _config.toggle && /show|hide/.test(config)) {
_config.toggle = false;
}
if (!data) {
data = new Collapse(this, _config);
$this.data(DATA_KEY, data);
}
if (typeof config === 'string') {
if (typeof data[config] === 'undefined') {
throw new Error("No method named \"" + config + "\"");
}
data[config]();
}
});
};
createClass(Collapse, null, [{
key: "VERSION",
get: function get() {
return VERSION;
}
}, {
key: "Default",
get: function get() {
return Default;
}
}]);
return Collapse;
}();
/**
* ------------------------------------------------------------------------
* Data Api implementation
* ------------------------------------------------------------------------
*/
$(document).on(Event.CLICK_DATA_API, Selector.DATA_TOGGLE, function (event) {
// preventDefault only for <a> elements (which change the URL) not inside the collapsible element
if (event.currentTarget.tagName === 'A') {
event.preventDefault();
}
var $trigger = $(this);
var selector = Util.getSelectorFromElement(this);
$(selector).each(function () {
var $target = $(this);
var data = $target.data(DATA_KEY);
var config = data ? 'toggle' : $trigger.data();
Collapse._jQueryInterface.call($target, config);
});
});
/**
* ------------------------------------------------------------------------
* jQuery
* ------------------------------------------------------------------------
*/
$.fn[NAME] = Collapse._jQueryInterface;
$.fn[NAME].Constructor = Collapse;
$.fn[NAME].noConflict = function () {
$.fn[NAME] = JQUERY_NO_CONFLICT;
return Collapse._jQueryInterface;
};
return Collapse;
}($);
/**
* --------------------------------------------------------------------------
* Bootstrap (v4.0.0-beta.2): dropdown.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
var Dropdown = function () {
/**
* Check for Popper dependency
* Popper - https://popper.js.org
*/
if (typeof Popper === 'undefined') {
throw new Error('Bootstrap dropdown require Popper.js (https://popper.js.org)');
}
/**
* ------------------------------------------------------------------------
* Constants
* ------------------------------------------------------------------------
*/
var NAME = 'dropdown';
var VERSION = '4.0.0-beta.2';
var DATA_KEY = 'bs.dropdown';
var EVENT_KEY = "." + DATA_KEY;
var DATA_API_KEY = '.data-api';
var JQUERY_NO_CONFLICT = $.fn[NAME];
var ESCAPE_KEYCODE = 27; // KeyboardEvent.which value for Escape (Esc) key
var SPACE_KEYCODE = 32; // KeyboardEvent.which value for space key
var TAB_KEYCODE = 9; // KeyboardEvent.which value for tab key
var ARROW_UP_KEYCODE = 38; // KeyboardEvent.which value for up arrow key
var ARROW_DOWN_KEYCODE = 40; // KeyboardEvent.which value for down arrow key
var RIGHT_MOUSE_BUTTON_WHICH = 3; // MouseEvent.which value for the right button (assuming a right-handed mouse)
var REGEXP_KEYDOWN = new RegExp(ARROW_UP_KEYCODE + "|" + ARROW_DOWN_KEYCODE + "|" + ESCAPE_KEYCODE);
var Event = {
HIDE: "hide" + EVENT_KEY,
HIDDEN: "hidden" + EVENT_KEY,
SHOW: "show" + EVENT_KEY,
SHOWN: "shown" + EVENT_KEY,
CLICK: "click" + EVENT_KEY,
CLICK_DATA_API: "click" + EVENT_KEY + DATA_API_KEY,
KEYDOWN_DATA_API: "keydown" + EVENT_KEY + DATA_API_KEY,
KEYUP_DATA_API: "keyup" + EVENT_KEY + DATA_API_KEY
};
var ClassName = {
DISABLED: 'disabled',
SHOW: 'show',
DROPUP: 'dropup',
MENURIGHT: 'dropdown-menu-right',
MENULEFT: 'dropdown-menu-left'
};
var Selector = {
DATA_TOGGLE: '[data-toggle="dropdown"]',
FORM_CHILD: '.dropdown form',
MENU: '.dropdown-menu',
NAVBAR_NAV: '.navbar-nav',
VISIBLE_ITEMS: '.dropdown-menu .dropdown-item:not(.disabled)'
};
var AttachmentMap = {
TOP: 'top-start',
TOPEND: 'top-end',
BOTTOM: 'bottom-start',
BOTTOMEND: 'bottom-end'
};
var Default = {
offset: 0,
flip: true
};
var DefaultType = {
offset: '(number|string|function)',
flip: 'boolean'
/**
* ------------------------------------------------------------------------
* Class Definition
* ------------------------------------------------------------------------
*/
};
var Dropdown =
/*#__PURE__*/
function () {
function Dropdown(element, config) {
this._element = element;
this._popper = null;
this._config = this._getConfig(config);
this._menu = this._getMenuElement();
this._inNavbar = this._detectNavbar();
this._addEventListeners();
} // getters
var _proto = Dropdown.prototype;
// public
_proto.toggle = function toggle() {
if (this._element.disabled || $(this._element).hasClass(ClassName.DISABLED)) {
return;
}
var parent = Dropdown._getParentFromElement(this._element);
var isActive = $(this._menu).hasClass(ClassName.SHOW);
Dropdown._clearMenus();
if (isActive) {
return;
}
var relatedTarget = {
relatedTarget: this._element
};
var showEvent = $.Event(Event.SHOW, relatedTarget);
$(parent).trigger(showEvent);
if (showEvent.isDefaultPrevented()) {
return;
}
var element = this._element; // for dropup with alignment we use the parent as popper container
if ($(parent).hasClass(ClassName.DROPUP)) {
if ($(this._menu).hasClass(ClassName.MENULEFT) || $(this._menu).hasClass(ClassName.MENURIGHT)) {
element = parent;
}
}
this._popper = new Popper(element, this._menu, this._getPopperConfig()); // if this is a touch-enabled device we add extra
// empty mouseover listeners to the body's immediate children;
// only needed because of broken event delegation on iOS
// https://www.quirksmode.org/blog/archives/2014/02/mouse_event_bub.html
if ('ontouchstart' in document.documentElement && !$(parent).closest(Selector.NAVBAR_NAV).length) {
$('body').children().on('mouseover', null, $.noop);
}
this._element.focus();
this._element.setAttribute('aria-expanded', true);
$(this._menu).toggleClass(ClassName.SHOW);
$(parent).toggleClass(ClassName.SHOW).trigger($.Event(Event.SHOWN, relatedTarget));
};
_proto.dispose = function dispose() {
$.removeData(this._element, DATA_KEY);
$(this._element).off(EVENT_KEY);
this._element = null;
this._menu = null;
if (this._popper !== null) {
this._popper.destroy();
}
this._popper = null;
};
_proto.update = function update() {
this._inNavbar = this._detectNavbar();
if (this._popper !== null) {
this._popper.scheduleUpdate();
}
}; // private
_proto._addEventListeners = function _addEventListeners() {
var _this = this;
$(this._element).on(Event.CLICK, function (event) {
event.preventDefault();
event.stopPropagation();
_this.toggle();
});
};
_proto._getConfig = function _getConfig(config) {
config = $.extend({}, this.constructor.Default, $(this._element).data(), config);
Util.typeCheckConfig(NAME, config, this.constructor.DefaultType);
return config;
};
_proto._getMenuElement = function _getMenuElement() {
if (!this._menu) {
var parent = Dropdown._getParentFromElement(this._element);
this._menu = $(parent).find(Selector.MENU)[0];
}
return this._menu;
};
_proto._getPlacement = function _getPlacement() {
var $parentDropdown = $(this._element).parent();
var placement = AttachmentMap.BOTTOM; // Handle dropup
if ($parentDropdown.hasClass(ClassName.DROPUP)) {
placement = AttachmentMap.TOP;
if ($(this._menu).hasClass(ClassName.MENURIGHT)) {
placement = AttachmentMap.TOPEND;
}
} else if ($(this._menu).hasClass(ClassName.MENURIGHT)) {
placement = AttachmentMap.BOTTOMEND;
}
return placement;
};
_proto._detectNavbar = function _detectNavbar() {
return $(this._element).closest('.navbar').length > 0;
};
_proto._getPopperConfig = function _getPopperConfig() {
var _this2 = this;
var offsetConf = {};
if (typeof this._config.offset === 'function') {
offsetConf.fn = function (data) {
data.offsets = $.extend({}, data.offsets, _this2._config.offset(data.offsets) || {});
return data;
};
} else {
offsetConf.offset = this._config.offset;
}
var popperConfig = {
placement: this._getPlacement(),
modifiers: {
offset: offsetConf,
flip: {
enabled: this._config.flip
}
} // Disable Popper.js for Dropdown in Navbar
};
if (this._inNavbar) {
popperConfig.modifiers.applyStyle = {
enabled: !this._inNavbar
};
}
return popperConfig;
}; // static
Dropdown._jQueryInterface = function _jQueryInterface(config) {
return this.each(function () {
var data = $(this).data(DATA_KEY);
var _config = typeof config === 'object' ? config : null;
if (!data) {
data = new Dropdown(this, _config);
$(this).data(DATA_KEY, data);
}
if (typeof config === 'string') {
if (typeof data[config] === 'undefined') {
throw new Error("No method named \"" + config + "\"");
}
data[config]();
}
});
};
Dropdown._clearMenus = function _clearMenus(event) {
if (event && (event.which === RIGHT_MOUSE_BUTTON_WHICH || event.type === 'keyup' && event.which !== TAB_KEYCODE)) {
return;
}
var toggles = $.makeArray($(Selector.DATA_TOGGLE));
for (var i = 0; i < toggles.length; i++) {
var parent = Dropdown._getParentFromElement(toggles[i]);
var context = $(toggles[i]).data(DATA_KEY);
var relatedTarget = {
relatedTarget: toggles[i]
};
if (!context) {
continue;
}
var dropdownMenu = context._menu;
if (!$(parent).hasClass(ClassName.SHOW)) {
continue;
}
if (event && (event.type === 'click' && /input|textarea/i.test(event.target.tagName) || event.type === 'keyup' && event.which === TAB_KEYCODE) && $.contains(parent, event.target)) {
continue;
}
var hideEvent = $.Event(Event.HIDE, relatedTarget);
$(parent).trigger(hideEvent);
if (hideEvent.isDefaultPrevented()) {
continue;
} // if this is a touch-enabled device we remove the extra
// empty mouseover listeners we added for iOS support
if ('ontouchstart' in document.documentElement) {
$('body').children().off('mouseover', null, $.noop);
}
toggles[i].setAttribute('aria-expanded', 'false');
$(dropdownMenu).removeClass(ClassName.SHOW);
$(parent).removeClass(ClassName.SHOW).trigger($.Event(Event.HIDDEN, relatedTarget));
}
};
Dropdown._getParentFromElement = function _getParentFromElement(element) {
var parent;
var selector = Util.getSelectorFromElement(element);
if (selector) {
parent = $(selector)[0];
}
return parent || element.parentNode;
};
Dropdown._dataApiKeydownHandler = function _dataApiKeydownHandler(event) {
if (!REGEXP_KEYDOWN.test(event.which) || /button/i.test(event.target.tagName) && event.which === SPACE_KEYCODE || /input|textarea/i.test(event.target.tagName)) {
return;
}
event.preventDefault();
event.stopPropagation();
if (this.disabled || $(this).hasClass(ClassName.DISABLED)) {
return;
}
var parent = Dropdown._getParentFromElement(this);
var isActive = $(parent).hasClass(ClassName.SHOW);
if (!isActive && (event.which !== ESCAPE_KEYCODE || event.which !== SPACE_KEYCODE) || isActive && (event.which === ESCAPE_KEYCODE || event.which === SPACE_KEYCODE)) {
if (event.which === ESCAPE_KEYCODE) {
var toggle = $(parent).find(Selector.DATA_TOGGLE)[0];
$(toggle).trigger('focus');
}
$(this).trigger('click');
return;
}
var items = $(parent).find(Selector.VISIBLE_ITEMS).get();
if (!items.length) {
return;
}
var index = items.indexOf(event.target);
if (event.which === ARROW_UP_KEYCODE && index > 0) {
// up
index--;
}
if (event.which === ARROW_DOWN_KEYCODE && index < items.length - 1) {
// down
index++;
}
if (index < 0) {
index = 0;
}
items[index].focus();
};
createClass(Dropdown, null, [{
key: "VERSION",
get: function get() {
return VERSION;
}
}, {
key: "Default",
get: function get() {
return Default;
}
}, {
key: "DefaultType",
get: function get() {
return DefaultType;
}
}]);
return Dropdown;
}();
/**
* ------------------------------------------------------------------------
* Data Api implementation
* ------------------------------------------------------------------------
*/
$(document).on(Event.KEYDOWN_DATA_API, Selector.DATA_TOGGLE, Dropdown._dataApiKeydownHandler).on(Event.KEYDOWN_DATA_API, Selector.MENU, Dropdown._dataApiKeydownHandler).on(Event.CLICK_DATA_API + " " + Event.KEYUP_DATA_API, Dropdown._clearMenus).on(Event.CLICK_DATA_API, Selector.DATA_TOGGLE, function (event) {
event.preventDefault();
event.stopPropagation();
Dropdown._jQueryInterface.call($(this), 'toggle');
}).on(Event.CLICK_DATA_API, Selector.FORM_CHILD, function (e) {
e.stopPropagation();
});
/**
* ------------------------------------------------------------------------
* jQuery
* ------------------------------------------------------------------------
*/
$.fn[NAME] = Dropdown._jQueryInterface;
$.fn[NAME].Constructor = Dropdown;
$.fn[NAME].noConflict = function () {
$.fn[NAME] = JQUERY_NO_CONFLICT;
return Dropdown._jQueryInterface;
};
return Dropdown;
}($, Popper);
/**
* --------------------------------------------------------------------------
* Bootstrap (v4.0.0-beta.2): modal.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
var Modal = function () {
/**
* ------------------------------------------------------------------------
* Constants
* ------------------------------------------------------------------------
*/
var NAME = 'modal';
var VERSION = '4.0.0-beta.2';
var DATA_KEY = 'bs.modal';
var EVENT_KEY = "." + DATA_KEY;
var DATA_API_KEY = '.data-api';
var JQUERY_NO_CONFLICT = $.fn[NAME];
var TRANSITION_DURATION = 300;
var BACKDROP_TRANSITION_DURATION = 150;
var ESCAPE_KEYCODE = 27; // KeyboardEvent.which value for Escape (Esc) key
var Default = {
backdrop: true,
keyboard: true,
focus: true,
show: true
};
var DefaultType = {
backdrop: '(boolean|string)',
keyboard: 'boolean',
focus: 'boolean',
show: 'boolean'
};
var Event = {
HIDE: "hide" + EVENT_KEY,
HIDDEN: "hidden" + EVENT_KEY,
SHOW: "show" + EVENT_KEY,
SHOWN: "shown" + EVENT_KEY,
FOCUSIN: "focusin" + EVENT_KEY,
RESIZE: "resize" + EVENT_KEY,
CLICK_DISMISS: "click.dismiss" + EVENT_KEY,
KEYDOWN_DISMISS: "keydown.dismiss" + EVENT_KEY,
MOUSEUP_DISMISS: "mouseup.dismiss" + EVENT_KEY,
MOUSEDOWN_DISMISS: "mousedown.dismiss" + EVENT_KEY,
CLICK_DATA_API: "click" + EVENT_KEY + DATA_API_KEY
};
var ClassName = {
SCROLLBAR_MEASURER: 'modal-scrollbar-measure',
BACKDROP: 'modal-backdrop',
OPEN: 'modal-open',
FADE: 'fade',
SHOW: 'show'
};
var Selector = {
DIALOG: '.modal-dialog',
DATA_TOGGLE: '[data-toggle="modal"]',
DATA_DISMISS: '[data-dismiss="modal"]',
FIXED_CONTENT: '.fixed-top, .fixed-bottom, .is-fixed, .sticky-top',
STICKY_CONTENT: '.sticky-top',
NAVBAR_TOGGLER: '.navbar-toggler'
/**
* ------------------------------------------------------------------------
* Class Definition
* ------------------------------------------------------------------------
*/
};
var Modal =
/*#__PURE__*/
function () {
function Modal(element, config) {
this._config = this._getConfig(config);
this._element = element;
this._dialog = $(element).find(Selector.DIALOG)[0];
this._backdrop = null;
this._isShown = false;
this._isBodyOverflowing = false;
this._ignoreBackdropClick = false;
this._originalBodyPadding = 0;
this._scrollbarWidth = 0;
} // getters
var _proto = Modal.prototype;
// public
_proto.toggle = function toggle(relatedTarget) {
return this._isShown ? this.hide() : this.show(relatedTarget);
};
_proto.show = function show(relatedTarget) {
var _this = this;
if (this._isTransitioning || this._isShown) {
return;
}
if (Util.supportsTransitionEnd() && $(this._element).hasClass(ClassName.FADE)) {
this._isTransitioning = true;
}
var showEvent = $.Event(Event.SHOW, {
relatedTarget: relatedTarget
});
$(this._element).trigger(showEvent);
if (this._isShown || showEvent.isDefaultPrevented()) {
return;
}
this._isShown = true;
this._checkScrollbar();
this._setScrollbar();
this._adjustDialog();
$(document.body).addClass(ClassName.OPEN);
this._setEscapeEvent();
this._setResizeEvent();
$(this._element).on(Event.CLICK_DISMISS, Selector.DATA_DISMISS, function (event) {
return _this.hide(event);
});
$(this._dialog).on(Event.MOUSEDOWN_DISMISS, function () {
$(_this._element).one(Event.MOUSEUP_DISMISS, function (event) {
if ($(event.target).is(_this._element)) {
_this._ignoreBackdropClick = true;
}
});
});
this._showBackdrop(function () {
return _this._showElement(relatedTarget);
});
};
_proto.hide = function hide(event) {
var _this2 = this;
if (event) {
event.preventDefault();
}
if (this._isTransitioning || !this._isShown) {
return;
}
var hideEvent = $.Event(Event.HIDE);
$(this._element).trigger(hideEvent);
if (!this._isShown || hideEvent.isDefaultPrevented()) {
return;
}
this._isShown = false;
var transition = Util.supportsTransitionEnd() && $(this._element).hasClass(ClassName.FADE);
if (transition) {
this._isTransitioning = true;
}
this._setEscapeEvent();
this._setResizeEvent();
$(document).off(Event.FOCUSIN);
$(this._element).removeClass(ClassName.SHOW);
$(this._element).off(Event.CLICK_DISMISS);
$(this._dialog).off(Event.MOUSEDOWN_DISMISS);
if (transition) {
$(this._element).one(Util.TRANSITION_END, function (event) {
return _this2._hideModal(event);
}).emulateTransitionEnd(TRANSITION_DURATION);
} else {
this._hideModal();
}
};
_proto.dispose = function dispose() {
$.removeData(this._element, DATA_KEY);
$(window, document, this._element, this._backdrop).off(EVENT_KEY);
this._config = null;
this._element = null;
this._dialog = null;
this._backdrop = null;
this._isShown = null;
this._isBodyOverflowing = null;
this._ignoreBackdropClick = null;
this._scrollbarWidth = null;
};
_proto.handleUpdate = function handleUpdate() {
this._adjustDialog();
}; // private
_proto._getConfig = function _getConfig(config) {
config = $.extend({}, Default, config);
Util.typeCheckConfig(NAME, config, DefaultType);
return config;
};
_proto._showElement = function _showElement(relatedTarget) {
var _this3 = this;
var transition = Util.supportsTransitionEnd() && $(this._element).hasClass(ClassName.FADE);
if (!this._element.parentNode || this._element.parentNode.nodeType !== Node.ELEMENT_NODE) {
// don't move modals dom position
document.body.appendChild(this._element);
}
this._element.style.display = 'block';
this._element.removeAttribute('aria-hidden');
this._element.scrollTop = 0;
if (transition) {
Util.reflow(this._element);
}
$(this._element).addClass(ClassName.SHOW);
if (this._config.focus) {
this._enforceFocus();
}
var shownEvent = $.Event(Event.SHOWN, {
relatedTarget: relatedTarget
});
var transitionComplete = function transitionComplete() {
if (_this3._config.focus) {
_this3._element.focus();
}
_this3._isTransitioning = false;
$(_this3._element).trigger(shownEvent);
};
if (transition) {
$(this._dialog).one(Util.TRANSITION_END, transitionComplete).emulateTransitionEnd(TRANSITION_DURATION);
} else {
transitionComplete();
}
};
_proto._enforceFocus = function _enforceFocus() {
var _this4 = this;
$(document).off(Event.FOCUSIN) // guard against infinite focus loop
.on(Event.FOCUSIN, function (event) {
if (document !== event.target && _this4._element !== event.target && !$(_this4._element).has(event.target).length) {
_this4._element.focus();
}
});
};
_proto._setEscapeEvent = function _setEscapeEvent() {
var _this5 = this;
if (this._isShown && this._config.keyboard) {
$(this._element).on(Event.KEYDOWN_DISMISS, function (event) {
if (event.which === ESCAPE_KEYCODE) {
event.preventDefault();
_this5.hide();
}
});
} else if (!this._isShown) {
$(this._element).off(Event.KEYDOWN_DISMISS);
}
};
_proto._setResizeEvent = function _setResizeEvent() {
var _this6 = this;
if (this._isShown) {
$(window).on(Event.RESIZE, function (event) {
return _this6.handleUpdate(event);
});
} else {
$(window).off(Event.RESIZE);
}
};
_proto._hideModal = function _hideModal() {
var _this7 = this;
this._element.style.display = 'none';
this._element.setAttribute('aria-hidden', true);
this._isTransitioning = false;
this._showBackdrop(function () {
$(document.body).removeClass(ClassName.OPEN);
_this7._resetAdjustments();
_this7._resetScrollbar();
$(_this7._element).trigger(Event.HIDDEN);
});
};
_proto._removeBackdrop = function _removeBackdrop() {
if (this._backdrop) {
$(this._backdrop).remove();
this._backdrop = null;
}
};
_proto._showBackdrop = function _showBackdrop(callback) {
var _this8 = this;
var animate = $(this._element).hasClass(ClassName.FADE) ? ClassName.FADE : '';
if (this._isShown && this._config.backdrop) {
var doAnimate = Util.supportsTransitionEnd() && animate;
this._backdrop = document.createElement('div');
this._backdrop.className = ClassName.BACKDROP;
if (animate) {
$(this._backdrop).addClass(animate);
}
$(this._backdrop).appendTo(document.body);
$(this._element).on(Event.CLICK_DISMISS, function (event) {
if (_this8._ignoreBackdropClick) {
_this8._ignoreBackdropClick = false;
return;
}
if (event.target !== event.currentTarget) {
return;
}
if (_this8._config.backdrop === 'static') {
_this8._element.focus();
} else {
_this8.hide();
}
});
if (doAnimate) {
Util.reflow(this._backdrop);
}
$(this._backdrop).addClass(ClassName.SHOW);
if (!callback) {
return;
}
if (!doAnimate) {
callback();
return;
}
$(this._backdrop).one(Util.TRANSITION_END, callback).emulateTransitionEnd(BACKDROP_TRANSITION_DURATION);
} else if (!this._isShown && this._backdrop) {
$(this._backdrop).removeClass(ClassName.SHOW);
var callbackRemove = function callbackRemove() {
_this8._removeBackdrop();
if (callback) {
callback();
}
};
if (Util.supportsTransitionEnd() && $(this._element).hasClass(ClassName.FADE)) {
$(this._backdrop).one(Util.TRANSITION_END, callbackRemove).emulateTransitionEnd(BACKDROP_TRANSITION_DURATION);
} else {
callbackRemove();
}
} else if (callback) {
callback();
}
}; // ----------------------------------------------------------------------
// the following methods are used to handle overflowing modals
// todo (fat): these should probably be refactored out of modal.js
// ----------------------------------------------------------------------
_proto._adjustDialog = function _adjustDialog() {
var isModalOverflowing = this._element.scrollHeight > document.documentElement.clientHeight;
if (!this._isBodyOverflowing && isModalOverflowing) {
this._element.style.paddingLeft = this._scrollbarWidth + "px";
}
if (this._isBodyOverflowing && !isModalOverflowing) {
this._element.style.paddingRight = this._scrollbarWidth + "px";
}
};
_proto._resetAdjustments = function _resetAdjustments() {
this._element.style.paddingLeft = '';
this._element.style.paddingRight = '';
};
_proto._checkScrollbar = function _checkScrollbar() {
var rect = document.body.getBoundingClientRect();
this._isBodyOverflowing = rect.left + rect.right < window.innerWidth;
this._scrollbarWidth = this._getScrollbarWidth();
};
_proto._setScrollbar = function _setScrollbar() {
var _this9 = this;
if (this._isBodyOverflowing) {
// Note: DOMNode.style.paddingRight returns the actual value or '' if not set
// while $(DOMNode).css('padding-right') returns the calculated value or 0 if not set
// Adjust fixed content padding
$(Selector.FIXED_CONTENT).each(function (index, element) {
var actualPadding = $(element)[0].style.paddingRight;
var calculatedPadding = $(element).css('padding-right');
$(element).data('padding-right', actualPadding).css('padding-right', parseFloat(calculatedPadding) + _this9._scrollbarWidth + "px");
}); // Adjust sticky content margin
$(Selector.STICKY_CONTENT).each(function (index, element) {
var actualMargin = $(element)[0].style.marginRight;
var calculatedMargin = $(element).css('margin-right');
$(element).data('margin-right', actualMargin).css('margin-right', parseFloat(calculatedMargin) - _this9._scrollbarWidth + "px");
}); // Adjust navbar-toggler margin
$(Selector.NAVBAR_TOGGLER).each(function (index, element) {
var actualMargin = $(element)[0].style.marginRight;
var calculatedMargin = $(element).css('margin-right');
$(element).data('margin-right', actualMargin).css('margin-right', parseFloat(calculatedMargin) + _this9._scrollbarWidth + "px");
}); // Adjust body padding
var actualPadding = document.body.style.paddingRight;
var calculatedPadding = $('body').css('padding-right');
$('body').data('padding-right', actualPadding).css('padding-right', parseFloat(calculatedPadding) + this._scrollbarWidth + "px");
}
};
_proto._resetScrollbar = function _resetScrollbar() {
// Restore fixed content padding
$(Selector.FIXED_CONTENT).each(function (index, element) {
var padding = $(element).data('padding-right');
if (typeof padding !== 'undefined') {
$(element).css('padding-right', padding).removeData('padding-right');
}
}); // Restore sticky content and navbar-toggler margin
$(Selector.STICKY_CONTENT + ", " + Selector.NAVBAR_TOGGLER).each(function (index, element) {
var margin = $(element).data('margin-right');
if (typeof margin !== 'undefined') {
$(element).css('margin-right', margin).removeData('margin-right');
}
}); // Restore body padding
var padding = $('body').data('padding-right');
if (typeof padding !== 'undefined') {
$('body').css('padding-right', padding).removeData('padding-right');
}
};
_proto._getScrollbarWidth = function _getScrollbarWidth() {
// thx d.walsh
var scrollDiv = document.createElement('div');
scrollDiv.className = ClassName.SCROLLBAR_MEASURER;
document.body.appendChild(scrollDiv);
var scrollbarWidth = scrollDiv.getBoundingClientRect().width - scrollDiv.clientWidth;
document.body.removeChild(scrollDiv);
return scrollbarWidth;
}; // static
Modal._jQueryInterface = function _jQueryInterface(config, relatedTarget) {
return this.each(function () {
var data = $(this).data(DATA_KEY);
var _config = $.extend({}, Modal.Default, $(this).data(), typeof config === 'object' && config);
if (!data) {
data = new Modal(this, _config);
$(this).data(DATA_KEY, data);
}
if (typeof config === 'string') {
if (typeof data[config] === 'undefined') {
throw new Error("No method named \"" + config + "\"");
}
data[config](relatedTarget);
} else if (_config.show) {
data.show(relatedTarget);
}
});
};
createClass(Modal, null, [{
key: "VERSION",
get: function get() {
return VERSION;
}
}, {
key: "Default",
get: function get() {
return Default;
}
}]);
return Modal;
}();
/**
* ------------------------------------------------------------------------
* Data Api implementation
* ------------------------------------------------------------------------
*/
$(document).on(Event.CLICK_DATA_API, Selector.DATA_TOGGLE, function (event) {
var _this10 = this;
var target;
var selector = Util.getSelectorFromElement(this);
if (selector) {
target = $(selector)[0];
}
var config = $(target).data(DATA_KEY) ? 'toggle' : $.extend({}, $(target).data(), $(this).data());
if (this.tagName === 'A' || this.tagName === 'AREA') {
event.preventDefault();
}
var $target = $(target).one(Event.SHOW, function (showEvent) {
if (showEvent.isDefaultPrevented()) {
// only register focus restorer if modal will actually get shown
return;
}
$target.one(Event.HIDDEN, function () {
if ($(_this10).is(':visible')) {
_this10.focus();
}
});
});
Modal._jQueryInterface.call($(target), config, this);
});
/**
* ------------------------------------------------------------------------
* jQuery
* ------------------------------------------------------------------------
*/
$.fn[NAME] = Modal._jQueryInterface;
$.fn[NAME].Constructor = Modal;
$.fn[NAME].noConflict = function () {
$.fn[NAME] = JQUERY_NO_CONFLICT;
return Modal._jQueryInterface;
};
return Modal;
}($);
/**
* --------------------------------------------------------------------------
* Bootstrap (v4.0.0-beta.2): tooltip.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
var Tooltip = function () {
/**
* Check for Popper dependency
* Popper - https://popper.js.org
*/
if (typeof Popper === 'undefined') {
throw new Error('Bootstrap tooltips require Popper.js (https://popper.js.org)');
}
/**
* ------------------------------------------------------------------------
* Constants
* ------------------------------------------------------------------------
*/
var NAME = 'tooltip';
var VERSION = '4.0.0-beta.2';
var DATA_KEY = 'bs.tooltip';
var EVENT_KEY = "." + DATA_KEY;
var JQUERY_NO_CONFLICT = $.fn[NAME];
var TRANSITION_DURATION = 150;
var CLASS_PREFIX = 'bs-tooltip';
var BSCLS_PREFIX_REGEX = new RegExp("(^|\\s)" + CLASS_PREFIX + "\\S+", 'g');
var DefaultType = {
animation: 'boolean',
template: 'string',
title: '(string|element|function)',
trigger: 'string',
delay: '(number|object)',
html: 'boolean',
selector: '(string|boolean)',
placement: '(string|function)',
offset: '(number|string)',
container: '(string|element|boolean)',
fallbackPlacement: '(string|array)'
};
var AttachmentMap = {
AUTO: 'auto',
TOP: 'top',
RIGHT: 'right',
BOTTOM: 'bottom',
LEFT: 'left'
};
var Default = {
animation: true,
template: '<div class="tooltip" role="tooltip">' + '<div class="arrow"></div>' + '<div class="tooltip-inner"></div></div>',
trigger: 'hover focus',
title: '',
delay: 0,
html: false,
selector: false,
placement: 'top',
offset: 0,
container: false,
fallbackPlacement: 'flip'
};
var HoverState = {
SHOW: 'show',
OUT: 'out'
};
var Event = {
HIDE: "hide" + EVENT_KEY,
HIDDEN: "hidden" + EVENT_KEY,
SHOW: "show" + EVENT_KEY,
SHOWN: "shown" + EVENT_KEY,
INSERTED: "inserted" + EVENT_KEY,
CLICK: "click" + EVENT_KEY,
FOCUSIN: "focusin" + EVENT_KEY,
FOCUSOUT: "focusout" + EVENT_KEY,
MOUSEENTER: "mouseenter" + EVENT_KEY,
MOUSELEAVE: "mouseleave" + EVENT_KEY
};
var ClassName = {
FADE: 'fade',
SHOW: 'show'
};
var Selector = {
TOOLTIP: '.tooltip',
TOOLTIP_INNER: '.tooltip-inner',
ARROW: '.arrow'
};
var Trigger = {
HOVER: 'hover',
FOCUS: 'focus',
CLICK: 'click',
MANUAL: 'manual'
/**
* ------------------------------------------------------------------------
* Class Definition
* ------------------------------------------------------------------------
*/
};
var Tooltip =
/*#__PURE__*/
function () {
function Tooltip(element, config) {
// private
this._isEnabled = true;
this._timeout = 0;
this._hoverState = '';
this._activeTrigger = {};
this._popper = null; // protected
this.element = element;
this.config = this._getConfig(config);
this.tip = null;
this._setListeners();
} // getters
var _proto = Tooltip.prototype;
// public
_proto.enable = function enable() {
this._isEnabled = true;
};
_proto.disable = function disable() {
this._isEnabled = false;
};
_proto.toggleEnabled = function toggleEnabled() {
this._isEnabled = !this._isEnabled;
};
_proto.toggle = function toggle(event) {
if (!this._isEnabled) {
return;
}
if (event) {
var dataKey = this.constructor.DATA_KEY;
var context = $(event.currentTarget).data(dataKey);
if (!context) {
context = new this.constructor(event.currentTarget, this._getDelegateConfig());
$(event.currentTarget).data(dataKey, context);
}
context._activeTrigger.click = !context._activeTrigger.click;
if (context._isWithActiveTrigger()) {
context._enter(null, context);
} else {
context._leave(null, context);
}
} else {
if ($(this.getTipElement()).hasClass(ClassName.SHOW)) {
this._leave(null, this);
return;
}
this._enter(null, this);
}
};
_proto.dispose = function dispose() {
clearTimeout(this._timeout);
$.removeData(this.element, this.constructor.DATA_KEY);
$(this.element).off(this.constructor.EVENT_KEY);
$(this.element).closest('.modal').off('hide.bs.modal');
if (this.tip) {
$(this.tip).remove();
}
this._isEnabled = null;
this._timeout = null;
this._hoverState = null;
this._activeTrigger = null;
if (this._popper !== null) {
this._popper.destroy();
}
this._popper = null;
this.element = null;
this.config = null;
this.tip = null;
};
_proto.show = function show() {
var _this = this;
if ($(this.element).css('display') === 'none') {
throw new Error('Please use show on visible elements');
}
var showEvent = $.Event(this.constructor.Event.SHOW);
if (this.isWithContent() && this._isEnabled) {
$(this.element).trigger(showEvent);
var isInTheDom = $.contains(this.element.ownerDocument.documentElement, this.element);
if (showEvent.isDefaultPrevented() || !isInTheDom) {
return;
}
var tip = this.getTipElement();
var tipId = Util.getUID(this.constructor.NAME);
tip.setAttribute('id', tipId);
this.element.setAttribute('aria-describedby', tipId);
this.setContent();
if (this.config.animation) {
$(tip).addClass(ClassName.FADE);
}
var placement = typeof this.config.placement === 'function' ? this.config.placement.call(this, tip, this.element) : this.config.placement;
var attachment = this._getAttachment(placement);
this.addAttachmentClass(attachment);
var container = this.config.container === false ? document.body : $(this.config.container);
$(tip).data(this.constructor.DATA_KEY, this);
if (!$.contains(this.element.ownerDocument.documentElement, this.tip)) {
$(tip).appendTo(container);
}
$(this.element).trigger(this.constructor.Event.INSERTED);
this._popper = new Popper(this.element, tip, {
placement: attachment,
modifiers: {
offset: {
offset: this.config.offset
},
flip: {
behavior: this.config.fallbackPlacement
},
arrow: {
element: Selector.ARROW
}
},
onCreate: function onCreate(data) {
if (data.originalPlacement !== data.placement) {
_this._handlePopperPlacementChange(data);
}
},
onUpdate: function onUpdate(data) {
_this._handlePopperPlacementChange(data);
}
});
$(tip).addClass(ClassName.SHOW); // if this is a touch-enabled device we add extra
// empty mouseover listeners to the body's immediate children;
// only needed because of broken event delegation on iOS
// https://www.quirksmode.org/blog/archives/2014/02/mouse_event_bub.html
if ('ontouchstart' in document.documentElement) {
$('body').children().on('mouseover', null, $.noop);
}
var complete = function complete() {
if (_this.config.animation) {
_this._fixTransition();
}
var prevHoverState = _this._hoverState;
_this._hoverState = null;
$(_this.element).trigger(_this.constructor.Event.SHOWN);
if (prevHoverState === HoverState.OUT) {
_this._leave(null, _this);
}
};
if (Util.supportsTransitionEnd() && $(this.tip).hasClass(ClassName.FADE)) {
$(this.tip).one(Util.TRANSITION_END, complete).emulateTransitionEnd(Tooltip._TRANSITION_DURATION);
} else {
complete();
}
}
};
_proto.hide = function hide(callback) {
var _this2 = this;
var tip = this.getTipElement();
var hideEvent = $.Event(this.constructor.Event.HIDE);
var complete = function complete() {
if (_this2._hoverState !== HoverState.SHOW && tip.parentNode) {
tip.parentNode.removeChild(tip);
}
_this2._cleanTipClass();
_this2.element.removeAttribute('aria-describedby');
$(_this2.element).trigger(_this2.constructor.Event.HIDDEN);
if (_this2._popper !== null) {
_this2._popper.destroy();
}
if (callback) {
callback();
}
};
$(this.element).trigger(hideEvent);
if (hideEvent.isDefaultPrevented()) {
return;
}
$(tip).removeClass(ClassName.SHOW); // if this is a touch-enabled device we remove the extra
// empty mouseover listeners we added for iOS support
if ('ontouchstart' in document.documentElement) {
$('body').children().off('mouseover', null, $.noop);
}
this._activeTrigger[Trigger.CLICK] = false;
this._activeTrigger[Trigger.FOCUS] = false;
this._activeTrigger[Trigger.HOVER] = false;
if (Util.supportsTransitionEnd() && $(this.tip).hasClass(ClassName.FADE)) {
$(tip).one(Util.TRANSITION_END, complete).emulateTransitionEnd(TRANSITION_DURATION);
} else {
complete();
}
this._hoverState = '';
};
_proto.update = function update() {
if (this._popper !== null) {
this._popper.scheduleUpdate();
}
}; // protected
_proto.isWithContent = function isWithContent() {
return Boolean(this.getTitle());
};
_proto.addAttachmentClass = function addAttachmentClass(attachment) {
$(this.getTipElement()).addClass(CLASS_PREFIX + "-" + attachment);
};
_proto.getTipElement = function getTipElement() {
this.tip = this.tip || $(this.config.template)[0];
return this.tip;
};
_proto.setContent = function setContent() {
var $tip = $(this.getTipElement());
this.setElementContent($tip.find(Selector.TOOLTIP_INNER), this.getTitle());
$tip.removeClass(ClassName.FADE + " " + ClassName.SHOW);
};
_proto.setElementContent = function setElementContent($element, content) {
var html = this.config.html;
if (typeof content === 'object' && (content.nodeType || content.jquery)) {
// content is a DOM node or a jQuery
if (html) {
if (!$(content).parent().is($element)) {
$element.empty().append(content);
}
} else {
$element.text($(content).text());
}
} else {
$element[html ? 'html' : 'text'](content);
}
};
_proto.getTitle = function getTitle() {
var title = this.element.getAttribute('data-original-title');
if (!title) {
title = typeof this.config.title === 'function' ? this.config.title.call(this.element) : this.config.title;
}
return title;
}; // private
_proto._getAttachment = function _getAttachment(placement) {
return AttachmentMap[placement.toUpperCase()];
};
_proto._setListeners = function _setListeners() {
var _this3 = this;
var triggers = this.config.trigger.split(' ');
triggers.forEach(function (trigger) {
if (trigger === 'click') {
$(_this3.element).on(_this3.constructor.Event.CLICK, _this3.config.selector, function (event) {
return _this3.toggle(event);
});
} else if (trigger !== Trigger.MANUAL) {
var eventIn = trigger === Trigger.HOVER ? _this3.constructor.Event.MOUSEENTER : _this3.constructor.Event.FOCUSIN;
var eventOut = trigger === Trigger.HOVER ? _this3.constructor.Event.MOUSELEAVE : _this3.constructor.Event.FOCUSOUT;
$(_this3.element).on(eventIn, _this3.config.selector, function (event) {
return _this3._enter(event);
}).on(eventOut, _this3.config.selector, function (event) {
return _this3._leave(event);
});
}
$(_this3.element).closest('.modal').on('hide.bs.modal', function () {
return _this3.hide();
});
});
if (this.config.selector) {
this.config = $.extend({}, this.config, {
trigger: 'manual',
selector: ''
});
} else {
this._fixTitle();
}
};
_proto._fixTitle = function _fixTitle() {
var titleType = typeof this.element.getAttribute('data-original-title');
if (this.element.getAttribute('title') || titleType !== 'string') {
this.element.setAttribute('data-original-title', this.element.getAttribute('title') || '');
this.element.setAttribute('title', '');
}
};
_proto._enter = function _enter(event, context) {
var dataKey = this.constructor.DATA_KEY;
context = context || $(event.currentTarget).data(dataKey);
if (!context) {
context = new this.constructor(event.currentTarget, this._getDelegateConfig());
$(event.currentTarget).data(dataKey, context);
}
if (event) {
context._activeTrigger[event.type === 'focusin' ? Trigger.FOCUS : Trigger.HOVER] = true;
}
if ($(context.getTipElement()).hasClass(ClassName.SHOW) || context._hoverState === HoverState.SHOW) {
context._hoverState = HoverState.SHOW;
return;
}
clearTimeout(context._timeout);
context._hoverState = HoverState.SHOW;
if (!context.config.delay || !context.config.delay.show) {
context.show();
return;
}
context._timeout = setTimeout(function () {
if (context._hoverState === HoverState.SHOW) {
context.show();
}
}, context.config.delay.show);
};
_proto._leave = function _leave(event, context) {
var dataKey = this.constructor.DATA_KEY;
context = context || $(event.currentTarget).data(dataKey);
if (!context) {
context = new this.constructor(event.currentTarget, this._getDelegateConfig());
$(event.currentTarget).data(dataKey, context);
}
if (event) {
context._activeTrigger[event.type === 'focusout' ? Trigger.FOCUS : Trigger.HOVER] = false;
}
if (context._isWithActiveTrigger()) {
return;
}
clearTimeout(context._timeout);
context._hoverState = HoverState.OUT;
if (!context.config.delay || !context.config.delay.hide) {
context.hide();
return;
}
context._timeout = setTimeout(function () {
if (context._hoverState === HoverState.OUT) {
context.hide();
}
}, context.config.delay.hide);
};
_proto._isWithActiveTrigger = function _isWithActiveTrigger() {
for (var trigger in this._activeTrigger) {
if (this._activeTrigger[trigger]) {
return true;
}
}
return false;
};
_proto._getConfig = function _getConfig(config) {
config = $.extend({}, this.constructor.Default, $(this.element).data(), config);
if (typeof config.delay === 'number') {
config.delay = {
show: config.delay,
hide: config.delay
};
}
if (typeof config.title === 'number') {
config.title = config.title.toString();
}
if (typeof config.content === 'number') {
config.content = config.content.toString();
}
Util.typeCheckConfig(NAME, config, this.constructor.DefaultType);
return config;
};
_proto._getDelegateConfig = function _getDelegateConfig() {
var config = {};
if (this.config) {
for (var key in this.config) {
if (this.constructor.Default[key] !== this.config[key]) {
config[key] = this.config[key];
}
}
}
return config;
};
_proto._cleanTipClass = function _cleanTipClass() {
var $tip = $(this.getTipElement());
var tabClass = $tip.attr('class').match(BSCLS_PREFIX_REGEX);
if (tabClass !== null && tabClass.length > 0) {
$tip.removeClass(tabClass.join(''));
}
};
_proto._handlePopperPlacementChange = function _handlePopperPlacementChange(data) {
this._cleanTipClass();
this.addAttachmentClass(this._getAttachment(data.placement));
};
_proto._fixTransition = function _fixTransition() {
var tip = this.getTipElement();
var initConfigAnimation = this.config.animation;
if (tip.getAttribute('x-placement') !== null) {
return;
}
$(tip).removeClass(ClassName.FADE);
this.config.animation = false;
this.hide();
this.show();
this.config.animation = initConfigAnimation;
}; // static
Tooltip._jQueryInterface = function _jQueryInterface(config) {
return this.each(function () {
var data = $(this).data(DATA_KEY);
var _config = typeof config === 'object' && config;
if (!data && /dispose|hide/.test(config)) {
return;
}
if (!data) {
data = new Tooltip(this, _config);
$(this).data(DATA_KEY, data);
}
if (typeof config === 'string') {
if (typeof data[config] === 'undefined') {
throw new Error("No method named \"" + config + "\"");
}
data[config]();
}
});
};
createClass(Tooltip, null, [{
key: "VERSION",
get: function get() {
return VERSION;
}
}, {
key: "Default",
get: function get() {
return Default;
}
}, {
key: "NAME",
get: function get() {
return NAME;
}
}, {
key: "DATA_KEY",
get: function get() {
return DATA_KEY;
}
}, {
key: "Event",
get: function get() {
return Event;
}
}, {
key: "EVENT_KEY",
get: function get() {
return EVENT_KEY;
}
}, {
key: "DefaultType",
get: function get() {
return DefaultType;
}
}]);
return Tooltip;
}();
/**
* ------------------------------------------------------------------------
* jQuery
* ------------------------------------------------------------------------
*/
$.fn[NAME] = Tooltip._jQueryInterface;
$.fn[NAME].Constructor = Tooltip;
$.fn[NAME].noConflict = function () {
$.fn[NAME] = JQUERY_NO_CONFLICT;
return Tooltip._jQueryInterface;
};
return Tooltip;
}($, Popper);
/**
* --------------------------------------------------------------------------
* Bootstrap (v4.0.0-beta.2): popover.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
var Popover = function () {
/**
* ------------------------------------------------------------------------
* Constants
* ------------------------------------------------------------------------
*/
var NAME = 'popover';
var VERSION = '4.0.0-beta.2';
var DATA_KEY = 'bs.popover';
var EVENT_KEY = "." + DATA_KEY;
var JQUERY_NO_CONFLICT = $.fn[NAME];
var CLASS_PREFIX = 'bs-popover';
var BSCLS_PREFIX_REGEX = new RegExp("(^|\\s)" + CLASS_PREFIX + "\\S+", 'g');
var Default = $.extend({}, Tooltip.Default, {
placement: 'right',
trigger: 'click',
content: '',
template: '<div class="popover" role="tooltip">' + '<div class="arrow"></div>' + '<h3 class="popover-header"></h3>' + '<div class="popover-body"></div></div>'
});
var DefaultType = $.extend({}, Tooltip.DefaultType, {
content: '(string|element|function)'
});
var ClassName = {
FADE: 'fade',
SHOW: 'show'
};
var Selector = {
TITLE: '.popover-header',
CONTENT: '.popover-body'
};
var Event = {
HIDE: "hide" + EVENT_KEY,
HIDDEN: "hidden" + EVENT_KEY,
SHOW: "show" + EVENT_KEY,
SHOWN: "shown" + EVENT_KEY,
INSERTED: "inserted" + EVENT_KEY,
CLICK: "click" + EVENT_KEY,
FOCUSIN: "focusin" + EVENT_KEY,
FOCUSOUT: "focusout" + EVENT_KEY,
MOUSEENTER: "mouseenter" + EVENT_KEY,
MOUSELEAVE: "mouseleave" + EVENT_KEY
/**
* ------------------------------------------------------------------------
* Class Definition
* ------------------------------------------------------------------------
*/
};
var Popover =
/*#__PURE__*/
function (_Tooltip) {
inheritsLoose(Popover, _Tooltip);
function Popover() {
return _Tooltip.apply(this, arguments) || this;
}
var _proto = Popover.prototype;
// overrides
_proto.isWithContent = function isWithContent() {
return this.getTitle() || this._getContent();
};
_proto.addAttachmentClass = function addAttachmentClass(attachment) {
$(this.getTipElement()).addClass(CLASS_PREFIX + "-" + attachment);
};
_proto.getTipElement = function getTipElement() {
this.tip = this.tip || $(this.config.template)[0];
return this.tip;
};
_proto.setContent = function setContent() {
var $tip = $(this.getTipElement()); // we use append for html objects to maintain js events
this.setElementContent($tip.find(Selector.TITLE), this.getTitle());
this.setElementContent($tip.find(Selector.CONTENT), this._getContent());
$tip.removeClass(ClassName.FADE + " " + ClassName.SHOW);
}; // private
_proto._getContent = function _getContent() {
return this.element.getAttribute('data-content') || (typeof this.config.content === 'function' ? this.config.content.call(this.element) : this.config.content);
};
_proto._cleanTipClass = function _cleanTipClass() {
var $tip = $(this.getTipElement());
var tabClass = $tip.attr('class').match(BSCLS_PREFIX_REGEX);
if (tabClass !== null && tabClass.length > 0) {
$tip.removeClass(tabClass.join(''));
}
}; // static
Popover._jQueryInterface = function _jQueryInterface(config) {
return this.each(function () {
var data = $(this).data(DATA_KEY);
var _config = typeof config === 'object' ? config : null;
if (!data && /destroy|hide/.test(config)) {
return;
}
if (!data) {
data = new Popover(this, _config);
$(this).data(DATA_KEY, data);
}
if (typeof config === 'string') {
if (typeof data[config] === 'undefined') {
throw new Error("No method named \"" + config + "\"");
}
data[config]();
}
});
};
createClass(Popover, null, [{
key: "VERSION",
// getters
get: function get() {
return VERSION;
}
}, {
key: "Default",
get: function get() {
return Default;
}
}, {
key: "NAME",
get: function get() {
return NAME;
}
}, {
key: "DATA_KEY",
get: function get() {
return DATA_KEY;
}
}, {
key: "Event",
get: function get() {
return Event;
}
}, {
key: "EVENT_KEY",
get: function get() {
return EVENT_KEY;
}
}, {
key: "DefaultType",
get: function get() {
return DefaultType;
}
}]);
return Popover;
}(Tooltip);
/**
* ------------------------------------------------------------------------
* jQuery
* ------------------------------------------------------------------------
*/
$.fn[NAME] = Popover._jQueryInterface;
$.fn[NAME].Constructor = Popover;
$.fn[NAME].noConflict = function () {
$.fn[NAME] = JQUERY_NO_CONFLICT;
return Popover._jQueryInterface;
};
return Popover;
}($);
/**
* --------------------------------------------------------------------------
* Bootstrap (v4.0.0-beta.2): scrollspy.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
var ScrollSpy = function () {
/**
* ------------------------------------------------------------------------
* Constants
* ------------------------------------------------------------------------
*/
var NAME = 'scrollspy';
var VERSION = '4.0.0-beta.2';
var DATA_KEY = 'bs.scrollspy';
var EVENT_KEY = "." + DATA_KEY;
var DATA_API_KEY = '.data-api';
var JQUERY_NO_CONFLICT = $.fn[NAME];
var Default = {
offset: 10,
method: 'auto',
target: ''
};
var DefaultType = {
offset: 'number',
method: 'string',
target: '(string|element)'
};
var Event = {
ACTIVATE: "activate" + EVENT_KEY,
SCROLL: "scroll" + EVENT_KEY,
LOAD_DATA_API: "load" + EVENT_KEY + DATA_API_KEY
};
var ClassName = {
DROPDOWN_ITEM: 'dropdown-item',
DROPDOWN_MENU: 'dropdown-menu',
ACTIVE: 'active'
};
var Selector = {
DATA_SPY: '[data-spy="scroll"]',
ACTIVE: '.active',
NAV_LIST_GROUP: '.nav, .list-group',
NAV_LINKS: '.nav-link',
NAV_ITEMS: '.nav-item',
LIST_ITEMS: '.list-group-item',
DROPDOWN: '.dropdown',
DROPDOWN_ITEMS: '.dropdown-item',
DROPDOWN_TOGGLE: '.dropdown-toggle'
};
var OffsetMethod = {
OFFSET: 'offset',
POSITION: 'position'
/**
* ------------------------------------------------------------------------
* Class Definition
* ------------------------------------------------------------------------
*/
};
var ScrollSpy =
/*#__PURE__*/
function () {
function ScrollSpy(element, config) {
var _this = this;
this._element = element;
this._scrollElement = element.tagName === 'BODY' ? window : element;
this._config = this._getConfig(config);
this._selector = this._config.target + " " + Selector.NAV_LINKS + "," + (this._config.target + " " + Selector.LIST_ITEMS + ",") + (this._config.target + " " + Selector.DROPDOWN_ITEMS);
this._offsets = [];
this._targets = [];
this._activeTarget = null;
this._scrollHeight = 0;
$(this._scrollElement).on(Event.SCROLL, function (event) {
return _this._process(event);
});
this.refresh();
this._process();
} // getters
var _proto = ScrollSpy.prototype;
// public
_proto.refresh = function refresh() {
var _this2 = this;
var autoMethod = this._scrollElement !== this._scrollElement.window ? OffsetMethod.POSITION : OffsetMethod.OFFSET;
var offsetMethod = this._config.method === 'auto' ? autoMethod : this._config.method;
var offsetBase = offsetMethod === OffsetMethod.POSITION ? this._getScrollTop() : 0;
this._offsets = [];
this._targets = [];
this._scrollHeight = this._getScrollHeight();
var targets = $.makeArray($(this._selector));
targets.map(function (element) {
var target;
var targetSelector = Util.getSelectorFromElement(element);
if (targetSelector) {
target = $(targetSelector)[0];
}
if (target) {
var targetBCR = target.getBoundingClientRect();
if (targetBCR.width || targetBCR.height) {
// todo (fat): remove sketch reliance on jQuery position/offset
return [$(target)[offsetMethod]().top + offsetBase, targetSelector];
}
}
return null;
}).filter(function (item) {
return item;
}).sort(function (a, b) {
return a[0] - b[0];
}).forEach(function (item) {
_this2._offsets.push(item[0]);
_this2._targets.push(item[1]);
});
};
_proto.dispose = function dispose() {
$.removeData(this._element, DATA_KEY);
$(this._scrollElement).off(EVENT_KEY);
this._element = null;
this._scrollElement = null;
this._config = null;
this._selector = null;
this._offsets = null;
this._targets = null;
this._activeTarget = null;
this._scrollHeight = null;
}; // private
_proto._getConfig = function _getConfig(config) {
config = $.extend({}, Default, config);
if (typeof config.target !== 'string') {
var id = $(config.target).attr('id');
if (!id) {
id = Util.getUID(NAME);
$(config.target).attr('id', id);
}
config.target = "#" + id;
}
Util.typeCheckConfig(NAME, config, DefaultType);
return config;
};
_proto._getScrollTop = function _getScrollTop() {
return this._scrollElement === window ? this._scrollElement.pageYOffset : this._scrollElement.scrollTop;
};
_proto._getScrollHeight = function _getScrollHeight() {
return this._scrollElement.scrollHeight || Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);
};
_proto._getOffsetHeight = function _getOffsetHeight() {
return this._scrollElement === window ? window.innerHeight : this._scrollElement.getBoundingClientRect().height;
};
_proto._process = function _process() {
var scrollTop = this._getScrollTop() + this._config.offset;
var scrollHeight = this._getScrollHeight();
var maxScroll = this._config.offset + scrollHeight - this._getOffsetHeight();
if (this._scrollHeight !== scrollHeight) {
this.refresh();
}
if (scrollTop >= maxScroll) {
var target = this._targets[this._targets.length - 1];
if (this._activeTarget !== target) {
this._activate(target);
}
return;
}
if (this._activeTarget && scrollTop < this._offsets[0] && this._offsets[0] > 0) {
this._activeTarget = null;
this._clear();
return;
}
for (var i = this._offsets.length; i--;) {
var isActiveTarget = this._activeTarget !== this._targets[i] && scrollTop >= this._offsets[i] && (typeof this._offsets[i + 1] === 'undefined' || scrollTop < this._offsets[i + 1]);
if (isActiveTarget) {
this._activate(this._targets[i]);
}
}
};
_proto._activate = function _activate(target) {
this._activeTarget = target;
this._clear();
var queries = this._selector.split(','); // eslint-disable-next-line arrow-body-style
queries = queries.map(function (selector) {
return selector + "[data-target=\"" + target + "\"]," + (selector + "[href=\"" + target + "\"]");
});
var $link = $(queries.join(','));
if ($link.hasClass(ClassName.DROPDOWN_ITEM)) {
$link.closest(Selector.DROPDOWN).find(Selector.DROPDOWN_TOGGLE).addClass(ClassName.ACTIVE);
$link.addClass(ClassName.ACTIVE);
} else {
// Set triggered link as active
$link.addClass(ClassName.ACTIVE); // Set triggered links parents as active
// With both <ul> and <nav> markup a parent is the previous sibling of any nav ancestor
$link.parents(Selector.NAV_LIST_GROUP).prev(Selector.NAV_LINKS + ", " + Selector.LIST_ITEMS).addClass(ClassName.ACTIVE); // Handle special case when .nav-link is inside .nav-item
$link.parents(Selector.NAV_LIST_GROUP).prev(Selector.NAV_ITEMS).children(Selector.NAV_LINKS).addClass(ClassName.ACTIVE);
}
$(this._scrollElement).trigger(Event.ACTIVATE, {
relatedTarget: target
});
};
_proto._clear = function _clear() {
$(this._selector).filter(Selector.ACTIVE).removeClass(ClassName.ACTIVE);
}; // static
ScrollSpy._jQueryInterface = function _jQueryInterface(config) {
return this.each(function () {
var data = $(this).data(DATA_KEY);
var _config = typeof config === 'object' && config;
if (!data) {
data = new ScrollSpy(this, _config);
$(this).data(DATA_KEY, data);
}
if (typeof config === 'string') {
if (typeof data[config] === 'undefined') {
throw new Error("No method named \"" + config + "\"");
}
data[config]();
}
});
};
createClass(ScrollSpy, null, [{
key: "VERSION",
get: function get() {
return VERSION;
}
}, {
key: "Default",
get: function get() {
return Default;
}
}]);
return ScrollSpy;
}();
/**
* ------------------------------------------------------------------------
* Data Api implementation
* ------------------------------------------------------------------------
*/
$(window).on(Event.LOAD_DATA_API, function () {
var scrollSpys = $.makeArray($(Selector.DATA_SPY));
for (var i = scrollSpys.length; i--;) {
var $spy = $(scrollSpys[i]);
ScrollSpy._jQueryInterface.call($spy, $spy.data());
}
});
/**
* ------------------------------------------------------------------------
* jQuery
* ------------------------------------------------------------------------
*/
$.fn[NAME] = ScrollSpy._jQueryInterface;
$.fn[NAME].Constructor = ScrollSpy;
$.fn[NAME].noConflict = function () {
$.fn[NAME] = JQUERY_NO_CONFLICT;
return ScrollSpy._jQueryInterface;
};
return ScrollSpy;
}($);
/**
* --------------------------------------------------------------------------
* Bootstrap (v4.0.0-beta.2): tab.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
var Tab = function () {
/**
* ------------------------------------------------------------------------
* Constants
* ------------------------------------------------------------------------
*/
var NAME = 'tab';
var VERSION = '4.0.0-beta.2';
var DATA_KEY = 'bs.tab';
var EVENT_KEY = "." + DATA_KEY;
var DATA_API_KEY = '.data-api';
var JQUERY_NO_CONFLICT = $.fn[NAME];
var TRANSITION_DURATION = 150;
var Event = {
HIDE: "hide" + EVENT_KEY,
HIDDEN: "hidden" + EVENT_KEY,
SHOW: "show" + EVENT_KEY,
SHOWN: "shown" + EVENT_KEY,
CLICK_DATA_API: "click" + EVENT_KEY + DATA_API_KEY
};
var ClassName = {
DROPDOWN_MENU: 'dropdown-menu',
ACTIVE: 'active',
DISABLED: 'disabled',
FADE: 'fade',
SHOW: 'show'
};
var Selector = {
DROPDOWN: '.dropdown',
NAV_LIST_GROUP: '.nav, .list-group',
ACTIVE: '.active',
ACTIVE_UL: '> li > .active',
DATA_TOGGLE: '[data-toggle="tab"], [data-toggle="pill"], [data-toggle="list"]',
DROPDOWN_TOGGLE: '.dropdown-toggle',
DROPDOWN_ACTIVE_CHILD: '> .dropdown-menu .active'
/**
* ------------------------------------------------------------------------
* Class Definition
* ------------------------------------------------------------------------
*/
};
var Tab =
/*#__PURE__*/
function () {
function Tab(element) {
this._element = element;
} // getters
var _proto = Tab.prototype;
// public
_proto.show = function show() {
var _this = this;
if (this._element.parentNode && this._element.parentNode.nodeType === Node.ELEMENT_NODE && $(this._element).hasClass(ClassName.ACTIVE) || $(this._element).hasClass(ClassName.DISABLED)) {
return;
}
var target;
var previous;
var listElement = $(this._element).closest(Selector.NAV_LIST_GROUP)[0];
var selector = Util.getSelectorFromElement(this._element);
if (listElement) {
var itemSelector = listElement.nodeName === 'UL' ? Selector.ACTIVE_UL : Selector.ACTIVE;
previous = $.makeArray($(listElement).find(itemSelector));
previous = previous[previous.length - 1];
}
var hideEvent = $.Event(Event.HIDE, {
relatedTarget: this._element
});
var showEvent = $.Event(Event.SHOW, {
relatedTarget: previous
});
if (previous) {
$(previous).trigger(hideEvent);
}
$(this._element).trigger(showEvent);
if (showEvent.isDefaultPrevented() || hideEvent.isDefaultPrevented()) {
return;
}
if (selector) {
target = $(selector)[0];
}
this._activate(this._element, listElement);
var complete = function complete() {
var hiddenEvent = $.Event(Event.HIDDEN, {
relatedTarget: _this._element
});
var shownEvent = $.Event(Event.SHOWN, {
relatedTarget: previous
});
$(previous).trigger(hiddenEvent);
$(_this._element).trigger(shownEvent);
};
if (target) {
this._activate(target, target.parentNode, complete);
} else {
complete();
}
};
_proto.dispose = function dispose() {
$.removeData(this._element, DATA_KEY);
this._element = null;
}; // private
_proto._activate = function _activate(element, container, callback) {
var _this2 = this;
var activeElements;
if (container.nodeName === 'UL') {
activeElements = $(container).find(Selector.ACTIVE_UL);
} else {
activeElements = $(container).children(Selector.ACTIVE);
}
var active = activeElements[0];
var isTransitioning = callback && Util.supportsTransitionEnd() && active && $(active).hasClass(ClassName.FADE);
var complete = function complete() {
return _this2._transitionComplete(element, active, isTransitioning, callback);
};
if (active && isTransitioning) {
$(active).one(Util.TRANSITION_END, complete).emulateTransitionEnd(TRANSITION_DURATION);
} else {
complete();
}
if (active) {
$(active).removeClass(ClassName.SHOW);
}
};
_proto._transitionComplete = function _transitionComplete(element, active, isTransitioning, callback) {
if (active) {
$(active).removeClass(ClassName.ACTIVE);
var dropdownChild = $(active.parentNode).find(Selector.DROPDOWN_ACTIVE_CHILD)[0];
if (dropdownChild) {
$(dropdownChild).removeClass(ClassName.ACTIVE);
}
if (active.getAttribute('role') === 'tab') {
active.setAttribute('aria-selected', false);
}
}
$(element).addClass(ClassName.ACTIVE);
if (element.getAttribute('role') === 'tab') {
element.setAttribute('aria-selected', true);
}
if (isTransitioning) {
Util.reflow(element);
$(element).addClass(ClassName.SHOW);
} else {
$(element).removeClass(ClassName.FADE);
}
if (element.parentNode && $(element.parentNode).hasClass(ClassName.DROPDOWN_MENU)) {
var dropdownElement = $(element).closest(Selector.DROPDOWN)[0];
if (dropdownElement) {
$(dropdownElement).find(Selector.DROPDOWN_TOGGLE).addClass(ClassName.ACTIVE);
}
element.setAttribute('aria-expanded', true);
}
if (callback) {
callback();
}
}; // static
Tab._jQueryInterface = function _jQueryInterface(config) {
return this.each(function () {
var $this = $(this);
var data = $this.data(DATA_KEY);
if (!data) {
data = new Tab(this);
$this.data(DATA_KEY, data);
}
if (typeof config === 'string') {
if (typeof data[config] === 'undefined') {
throw new Error("No method named \"" + config + "\"");
}
data[config]();
}
});
};
createClass(Tab, null, [{
key: "VERSION",
get: function get() {
return VERSION;
}
}]);
return Tab;
}();
/**
* ------------------------------------------------------------------------
* Data Api implementation
* ------------------------------------------------------------------------
*/
$(document).on(Event.CLICK_DATA_API, Selector.DATA_TOGGLE, function (event) {
event.preventDefault();
Tab._jQueryInterface.call($(this), 'show');
});
/**
* ------------------------------------------------------------------------
* jQuery
* ------------------------------------------------------------------------
*/
$.fn[NAME] = Tab._jQueryInterface;
$.fn[NAME].Constructor = Tab;
$.fn[NAME].noConflict = function () {
$.fn[NAME] = JQUERY_NO_CONFLICT;
return Tab._jQueryInterface;
};
return Tab;
}($);
/**
* --------------------------------------------------------------------------
* Bootstrap (v4.0.0-alpha.6): index.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
(function () {
if (typeof $ === 'undefined') {
throw new Error('Bootstrap\'s JavaScript requires jQuery. jQuery must be included before Bootstrap\'s JavaScript.');
}
var version = $.fn.jquery.split(' ')[0].split('.');
var minMajor = 1;
var ltMajor = 2;
var minMinor = 9;
var minPatch = 1;
var maxMajor = 4;
if (version[0] < ltMajor && version[1] < minMinor || version[0] === minMajor && version[1] === minMinor && version[2] < minPatch || version[0] >= maxMajor) {
throw new Error('Bootstrap\'s JavaScript requires at least jQuery v1.9.1 but less than v4.0.0');
}
})($);
exports.Util = Util;
exports.Alert = Alert;
exports.Button = Button;
exports.Carousel = Carousel;
exports.Collapse = Collapse;
exports.Dropdown = Dropdown;
exports.Modal = Modal;
exports.Popover = Popover;
exports.Scrollspy = ScrollSpy;
exports.Tab = Tab;
exports.Tooltip = Tooltip;
return exports;
}({},$,Popper));
/*
Unobtrusive JavaScript
https://github.com/rails/rails/blob/master/actionview/app/assets/javascripts
Released under the MIT license
*/
(function() {
var context = this;
(function() {
(function() {
this.Rails = {
linkClickSelector: 'a[data-confirm], a[data-method], a[data-remote]:not([disabled]), a[data-disable-with], a[data-disable]',
buttonClickSelector: {
selector: 'button[data-remote]:not([form]), button[data-confirm]:not([form])',
exclude: 'form button'
},
inputChangeSelector: 'select[data-remote], input[data-remote], textarea[data-remote]',
formSubmitSelector: 'form',
formInputClickSelector: 'form input[type=submit], form input[type=image], form button[type=submit], form button:not([type]), input[type=submit][form], input[type=image][form], button[type=submit][form], button[form]:not([type])',
formDisableSelector: 'input[data-disable-with]:enabled, button[data-disable-with]:enabled, textarea[data-disable-with]:enabled, input[data-disable]:enabled, button[data-disable]:enabled, textarea[data-disable]:enabled',
formEnableSelector: 'input[data-disable-with]:disabled, button[data-disable-with]:disabled, textarea[data-disable-with]:disabled, input[data-disable]:disabled, button[data-disable]:disabled, textarea[data-disable]:disabled',
fileInputSelector: 'input[name][type=file]:not([disabled])',
linkDisableSelector: 'a[data-disable-with], a[data-disable]',
buttonDisableSelector: 'button[data-remote][data-disable-with], button[data-remote][data-disable]'
};
}).call(this);
}).call(context);
var Rails = context.Rails;
(function() {
(function() {
var expando, m;
m = Element.prototype.matches || Element.prototype.matchesSelector || Element.prototype.mozMatchesSelector || Element.prototype.msMatchesSelector || Element.prototype.oMatchesSelector || Element.prototype.webkitMatchesSelector;
Rails.matches = function(element, selector) {
if (selector.exclude != null) {
return m.call(element, selector.selector) && !m.call(element, selector.exclude);
} else {
return m.call(element, selector);
}
};
expando = '_ujsData';
Rails.getData = function(element, key) {
var ref;
return (ref = element[expando]) != null ? ref[key] : void 0;
};
Rails.setData = function(element, key, value) {
if (element[expando] == null) {
element[expando] = {};
}
return element[expando][key] = value;
};
Rails.$ = function(selector) {
return Array.prototype.slice.call(document.querySelectorAll(selector));
};
}).call(this);
(function() {
var $, csrfParam, csrfToken;
$ = Rails.$;
csrfToken = Rails.csrfToken = function() {
var meta;
meta = document.querySelector('meta[name=csrf-token]');
return meta && meta.content;
};
csrfParam = Rails.csrfParam = function() {
var meta;
meta = document.querySelector('meta[name=csrf-param]');
return meta && meta.content;
};
Rails.CSRFProtection = function(xhr) {
var token;
token = csrfToken();
if (token != null) {
return xhr.setRequestHeader('X-CSRF-Token', token);
}
};
Rails.refreshCSRFTokens = function() {
var param, token;
token = csrfToken();
param = csrfParam();
if ((token != null) && (param != null)) {
return $('form input[name="' + param + '"]').forEach(function(input) {
return input.value = token;
});
}
};
}).call(this);
(function() {
var CustomEvent, fire, matches;
matches = Rails.matches;
CustomEvent = window.CustomEvent;
if (typeof CustomEvent !== 'function') {
CustomEvent = function(event, params) {
var evt;
evt = document.createEvent('CustomEvent');
evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);
return evt;
};
CustomEvent.prototype = window.Event.prototype;
}
fire = Rails.fire = function(obj, name, data) {
var event;
event = new CustomEvent(name, {
bubbles: true,
cancelable: true,
detail: data
});
obj.dispatchEvent(event);
return !event.defaultPrevented;
};
Rails.stopEverything = function(e) {
fire(e.target, 'ujs:everythingStopped');
e.preventDefault();
e.stopPropagation();
return e.stopImmediatePropagation();
};
Rails.delegate = function(element, selector, eventType, handler) {
return element.addEventListener(eventType, function(e) {
var target;
target = e.target;
while (!(!(target instanceof Element) || matches(target, selector))) {
target = target.parentNode;
}
if (target instanceof Element && handler.call(target, e) === false) {
e.preventDefault();
return e.stopPropagation();
}
});
};
}).call(this);
(function() {
var AcceptHeaders, CSRFProtection, createXHR, fire, prepareOptions, processResponse;
CSRFProtection = Rails.CSRFProtection, fire = Rails.fire;
AcceptHeaders = {
'*': '*/*',
text: 'text/plain',
html: 'text/html',
xml: 'application/xml, text/xml',
json: 'application/json, text/javascript',
script: 'text/javascript, application/javascript, application/ecmascript, application/x-ecmascript'
};
Rails.ajax = function(options) {
var xhr;
options = prepareOptions(options);
xhr = createXHR(options, function() {
var response;
response = processResponse(xhr.response, xhr.getResponseHeader('Content-Type'));
if (Math.floor(xhr.status / 100) === 2) {
if (typeof options.success === "function") {
options.success(response, xhr.statusText, xhr);
}
} else {
if (typeof options.error === "function") {
options.error(response, xhr.statusText, xhr);
}
}
return typeof options.complete === "function" ? options.complete(xhr, xhr.statusText) : void 0;
});
if (typeof options.beforeSend === "function") {
options.beforeSend(xhr, options);
}
if (xhr.readyState === XMLHttpRequest.OPENED) {
return xhr.send(options.data);
} else {
return fire(document, 'ajaxStop');
}
};
prepareOptions = function(options) {
options.url = options.url || location.href;
options.type = options.type.toUpperCase();
if (options.type === 'GET' && options.data) {
if (options.url.indexOf('?') < 0) {
options.url += '?' + options.data;
} else {
options.url += '&' + options.data;
}
}
if (AcceptHeaders[options.dataType] == null) {
options.dataType = '*';
}
options.accept = AcceptHeaders[options.dataType];
if (options.dataType !== '*') {
options.accept += ', */*; q=0.01';
}
return options;
};
createXHR = function(options, done) {
var xhr;
xhr = new XMLHttpRequest();
xhr.open(options.type, options.url, true);
xhr.setRequestHeader('Accept', options.accept);
if (typeof options.data === 'string') {
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
}
if (!options.crossDomain) {
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
}
CSRFProtection(xhr);
xhr.withCredentials = !!options.withCredentials;
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
return done(xhr);
}
};
return xhr;
};
processResponse = function(response, type) {
var parser, script;
if (typeof response === 'string' && typeof type === 'string') {
if (type.match(/\bjson\b/)) {
try {
response = JSON.parse(response);
} catch (error) {}
} else if (type.match(/\b(?:java|ecma)script\b/)) {
script = document.createElement('script');
script.text = response;
document.head.appendChild(script).parentNode.removeChild(script);
} else if (type.match(/\b(xml|html|svg)\b/)) {
parser = new DOMParser();
type = type.replace(/;.+/, '');
try {
response = parser.parseFromString(response, type);
} catch (error) {}
}
}
return response;
};
Rails.href = function(element) {
return element.href;
};
Rails.isCrossDomain = function(url) {
var e, originAnchor, urlAnchor;
originAnchor = document.createElement('a');
originAnchor.href = location.href;
urlAnchor = document.createElement('a');
try {
urlAnchor.href = url;
return !(((!urlAnchor.protocol || urlAnchor.protocol === ':') && !urlAnchor.host) || (originAnchor.protocol + '//' + originAnchor.host === urlAnchor.protocol + '//' + urlAnchor.host));
} catch (error) {
e = error;
return true;
}
};
}).call(this);
(function() {
var matches, toArray;
matches = Rails.matches;
toArray = function(e) {
return Array.prototype.slice.call(e);
};
Rails.serializeElement = function(element, additionalParam) {
var inputs, params;
inputs = [element];
if (matches(element, 'form')) {
inputs = toArray(element.elements);
}
params = [];
inputs.forEach(function(input) {
if (!input.name) {
return;
}
if (matches(input, 'select')) {
return toArray(input.options).forEach(function(option) {
if (option.selected) {
return params.push({
name: input.name,
value: option.value
});
}
});
} else if (input.checked || ['radio', 'checkbox', 'submit'].indexOf(input.type) === -1) {
return params.push({
name: input.name,
value: input.value
});
}
});
if (additionalParam) {
params.push(additionalParam);
}
return params.map(function(param) {
if (param.name != null) {
return (encodeURIComponent(param.name)) + "=" + (encodeURIComponent(param.value));
} else {
return param;
}
}).join('&');
};
Rails.formElements = function(form, selector) {
if (matches(form, 'form')) {
return toArray(form.elements).filter(function(el) {
return matches(el, selector);
});
} else {
return toArray(form.querySelectorAll(selector));
}
};
}).call(this);
(function() {
var allowAction, fire, stopEverything;
fire = Rails.fire, stopEverything = Rails.stopEverything;
Rails.handleConfirm = function(e) {
if (!allowAction(this)) {
return stopEverything(e);
}
};
allowAction = function(element) {
var answer, callback, message;
message = element.getAttribute('data-confirm');
if (!message) {
return true;
}
answer = false;
if (fire(element, 'confirm')) {
try {
answer = confirm(message);
} catch (error) {}
callback = fire(element, 'confirm:complete', [answer]);
}
return answer && callback;
};
}).call(this);
(function() {
var disableFormElement, disableFormElements, disableLinkElement, enableFormElement, enableFormElements, enableLinkElement, formElements, getData, matches, setData, stopEverything;
matches = Rails.matches, getData = Rails.getData, setData = Rails.setData, stopEverything = Rails.stopEverything, formElements = Rails.formElements;
Rails.handleDisabledElement = function(e) {
var element;
element = this;
if (element.disabled) {
return stopEverything(e);
}
};
Rails.enableElement = function(e) {
var element;
element = e instanceof Event ? e.target : e;
if (matches(element, Rails.linkDisableSelector)) {
return enableLinkElement(element);
} else if (matches(element, Rails.buttonDisableSelector) || matches(element, Rails.formEnableSelector)) {
return enableFormElement(element);
} else if (matches(element, Rails.formSubmitSelector)) {
return enableFormElements(element);
}
};
Rails.disableElement = function(e) {
var element;
element = e instanceof Event ? e.target : e;
if (matches(element, Rails.linkDisableSelector)) {
return disableLinkElement(element);
} else if (matches(element, Rails.buttonDisableSelector) || matches(element, Rails.formDisableSelector)) {
return disableFormElement(element);
} else if (matches(element, Rails.formSubmitSelector)) {
return disableFormElements(element);
}
};
disableLinkElement = function(element) {
var replacement;
replacement = element.getAttribute('data-disable-with');
if (replacement != null) {
setData(element, 'ujs:enable-with', element.innerHTML);
element.innerHTML = replacement;
}
element.addEventListener('click', stopEverything);
return setData(element, 'ujs:disabled', true);
};
enableLinkElement = function(element) {
var originalText;
originalText = getData(element, 'ujs:enable-with');
if (originalText != null) {
element.innerHTML = originalText;
setData(element, 'ujs:enable-with', null);
}
element.removeEventListener('click', stopEverything);
return setData(element, 'ujs:disabled', null);
};
disableFormElements = function(form) {
return formElements(form, Rails.formDisableSelector).forEach(disableFormElement);
};
disableFormElement = function(element) {
var replacement;
replacement = element.getAttribute('data-disable-with');
if (replacement != null) {
if (matches(element, 'button')) {
setData(element, 'ujs:enable-with', element.innerHTML);
element.innerHTML = replacement;
} else {
setData(element, 'ujs:enable-with', element.value);
element.value = replacement;
}
}
element.disabled = true;
return setData(element, 'ujs:disabled', true);
};
enableFormElements = function(form) {
return formElements(form, Rails.formEnableSelector).forEach(enableFormElement);
};
enableFormElement = function(element) {
var originalText;
originalText = getData(element, 'ujs:enable-with');
if (originalText != null) {
if (matches(element, 'button')) {
element.innerHTML = originalText;
} else {
element.value = originalText;
}
setData(element, 'ujs:enable-with', null);
}
element.disabled = false;
return setData(element, 'ujs:disabled', null);
};
}).call(this);
(function() {
var stopEverything;
stopEverything = Rails.stopEverything;
Rails.handleMethod = function(e) {
var csrfParam, csrfToken, form, formContent, href, link, method;
link = this;
method = link.getAttribute('data-method');
if (!method) {
return;
}
href = Rails.href(link);
csrfToken = Rails.csrfToken();
csrfParam = Rails.csrfParam();
form = document.createElement('form');
formContent = "<input name='_method' value='" + method + "' type='hidden' />";
if ((csrfParam != null) && (csrfToken != null) && !Rails.isCrossDomain(href)) {
formContent += "<input name='" + csrfParam + "' value='" + csrfToken + "' type='hidden' />";
}
formContent += '<input type="submit" />';
form.method = 'post';
form.action = href;
form.target = link.target;
form.innerHTML = formContent;
form.style.display = 'none';
document.body.appendChild(form);
form.querySelector('[type="submit"]').click();
return stopEverything(e);
};
}).call(this);
(function() {
var ajax, fire, getData, isCrossDomain, isRemote, matches, serializeElement, setData, stopEverything,
slice = [].slice;
matches = Rails.matches, getData = Rails.getData, setData = Rails.setData, fire = Rails.fire, stopEverything = Rails.stopEverything, ajax = Rails.ajax, isCrossDomain = Rails.isCrossDomain, serializeElement = Rails.serializeElement;
isRemote = function(element) {
var value;
value = element.getAttribute('data-remote');
return (value != null) && value !== 'false';
};
Rails.handleRemote = function(e) {
var button, data, dataType, element, method, url, withCredentials;
element = this;
if (!isRemote(element)) {
return true;
}
if (!fire(element, 'ajax:before')) {
fire(element, 'ajax:stopped');
return false;
}
withCredentials = element.getAttribute('data-with-credentials');
dataType = element.getAttribute('data-type') || 'script';
if (matches(element, Rails.formSubmitSelector)) {
button = getData(element, 'ujs:submit-button');
method = getData(element, 'ujs:submit-button-formmethod') || element.method;
url = getData(element, 'ujs:submit-button-formaction') || element.getAttribute('action') || location.href;
if (method.toUpperCase() === 'GET') {
url = url.replace(/\?.*$/, '');
}
if (element.enctype === 'multipart/form-data') {
data = new FormData(element);
if (button != null) {
data.append(button.name, button.value);
}
} else {
data = serializeElement(element, button);
}
setData(element, 'ujs:submit-button', null);
setData(element, 'ujs:submit-button-formmethod', null);
setData(element, 'ujs:submit-button-formaction', null);
} else if (matches(element, Rails.buttonClickSelector) || matches(element, Rails.inputChangeSelector)) {
method = element.getAttribute('data-method');
url = element.getAttribute('data-url');
data = serializeElement(element, element.getAttribute('data-params'));
} else {
method = element.getAttribute('data-method');
url = Rails.href(element);
data = element.getAttribute('data-params');
}
ajax({
type: method || 'GET',
url: url,
data: data,
dataType: dataType,
beforeSend: function(xhr, options) {
if (fire(element, 'ajax:beforeSend', [xhr, options])) {
return fire(element, 'ajax:send', [xhr]);
} else {
fire(element, 'ajax:stopped');
return xhr.abort();
}
},
success: function() {
var args;
args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
return fire(element, 'ajax:success', args);
},
error: function() {
var args;
args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
return fire(element, 'ajax:error', args);
},
complete: function() {
var args;
args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
return fire(element, 'ajax:complete', args);
},
crossDomain: isCrossDomain(url),
withCredentials: (withCredentials != null) && withCredentials !== 'false'
});
return stopEverything(e);
};
Rails.formSubmitButtonClick = function(e) {
var button, form;
button = this;
form = button.form;
if (!form) {
return;
}
if (button.name) {
setData(form, 'ujs:submit-button', {
name: button.name,
value: button.value
});
}
setData(form, 'ujs:formnovalidate-button', button.formNoValidate);
setData(form, 'ujs:submit-button-formaction', button.getAttribute('formaction'));
return setData(form, 'ujs:submit-button-formmethod', button.getAttribute('formmethod'));
};
Rails.handleMetaClick = function(e) {
var data, link, metaClick, method;
link = this;
method = (link.getAttribute('data-method') || 'GET').toUpperCase();
data = link.getAttribute('data-params');
metaClick = e.metaKey || e.ctrlKey;
if (metaClick && method === 'GET' && !data) {
return e.stopImmediatePropagation();
}
};
}).call(this);
(function() {
var $, CSRFProtection, delegate, disableElement, enableElement, fire, formSubmitButtonClick, getData, handleConfirm, handleDisabledElement, handleMetaClick, handleMethod, handleRemote, refreshCSRFTokens;
fire = Rails.fire, delegate = Rails.delegate, getData = Rails.getData, $ = Rails.$, refreshCSRFTokens = Rails.refreshCSRFTokens, CSRFProtection = Rails.CSRFProtection, enableElement = Rails.enableElement, disableElement = Rails.disableElement, handleDisabledElement = Rails.handleDisabledElement, handleConfirm = Rails.handleConfirm, handleRemote = Rails.handleRemote, formSubmitButtonClick = Rails.formSubmitButtonClick, handleMetaClick = Rails.handleMetaClick, handleMethod = Rails.handleMethod;
if ((typeof jQuery !== "undefined" && jQuery !== null) && (jQuery.ajax != null) && !jQuery.rails) {
jQuery.rails = Rails;
jQuery.ajaxPrefilter(function(options, originalOptions, xhr) {
if (!options.crossDomain) {
return CSRFProtection(xhr);
}
});
}
Rails.start = function() {
if (window._rails_loaded) {
throw new Error('rails-ujs has already been loaded!');
}
window.addEventListener('pageshow', function() {
$(Rails.formEnableSelector).forEach(function(el) {
if (getData(el, 'ujs:disabled')) {
return enableElement(el);
}
});
return $(Rails.linkDisableSelector).forEach(function(el) {
if (getData(el, 'ujs:disabled')) {
return enableElement(el);
}
});
});
delegate(document, Rails.linkDisableSelector, 'ajax:complete', enableElement);
delegate(document, Rails.linkDisableSelector, 'ajax:stopped', enableElement);
delegate(document, Rails.buttonDisableSelector, 'ajax:complete', enableElement);
delegate(document, Rails.buttonDisableSelector, 'ajax:stopped', enableElement);
delegate(document, Rails.linkClickSelector, 'click', handleDisabledElement);
delegate(document, Rails.linkClickSelector, 'click', handleConfirm);
delegate(document, Rails.linkClickSelector, 'click', handleMetaClick);
delegate(document, Rails.linkClickSelector, 'click', disableElement);
delegate(document, Rails.linkClickSelector, 'click', handleRemote);
delegate(document, Rails.linkClickSelector, 'click', handleMethod);
delegate(document, Rails.buttonClickSelector, 'click', handleDisabledElement);
delegate(document, Rails.buttonClickSelector, 'click', handleConfirm);
delegate(document, Rails.buttonClickSelector, 'click', disableElement);
delegate(document, Rails.buttonClickSelector, 'click', handleRemote);
delegate(document, Rails.inputChangeSelector, 'change', handleDisabledElement);
delegate(document, Rails.inputChangeSelector, 'change', handleConfirm);
delegate(document, Rails.inputChangeSelector, 'change', handleRemote);
delegate(document, Rails.formSubmitSelector, 'submit', handleDisabledElement);
delegate(document, Rails.formSubmitSelector, 'submit', handleConfirm);
delegate(document, Rails.formSubmitSelector, 'submit', handleRemote);
delegate(document, Rails.formSubmitSelector, 'submit', function(e) {
return setTimeout((function() {
return disableElement(e);
}), 13);
});
delegate(document, Rails.formSubmitSelector, 'ajax:send', disableElement);
delegate(document, Rails.formSubmitSelector, 'ajax:complete', enableElement);
delegate(document, Rails.formInputClickSelector, 'click', handleDisabledElement);
delegate(document, Rails.formInputClickSelector, 'click', handleConfirm);
delegate(document, Rails.formInputClickSelector, 'click', formSubmitButtonClick);
document.addEventListener('DOMContentLoaded', refreshCSRFTokens);
return window._rails_loaded = true;
};
if (window.Rails === Rails && fire(document, 'rails:attachBindings')) {
Rails.start();
}
}).call(this);
}).call(this);
if (typeof module === "object" && module.exports) {
module.exports = Rails;
} else if (typeof define === "function" && define.amd) {
define(Rails);
}
}).call(this);
/*
Turbolinks 5.0.3
Copyright © 2017 Basecamp, LLC
*/
(function(){(function(){(function(){this.Turbolinks={supported:function(){return null!=window.history.pushState&&null!=window.requestAnimationFrame&&null!=window.addEventListener}(),visit:function(e,r){return t.controller.visit(e,r)},clearCache:function(){return t.controller.clearCache()}}}).call(this)}).call(this);var t=this.Turbolinks;(function(){(function(){var e,r,n=[].slice;t.copyObject=function(t){var e,r,n;r={};for(e in t)n=t[e],r[e]=n;return r},t.closest=function(t,r){return e.call(t,r)},e=function(){var t,e;return t=document.documentElement,null!=(e=t.closest)?e:function(t){var e;for(e=this;e;){if(e.nodeType===Node.ELEMENT_NODE&&r.call(e,t))return e;e=e.parentNode}}}(),t.defer=function(t){return setTimeout(t,1)},t.throttle=function(t){var e;return e=null,function(){var r;return r=1<=arguments.length?n.call(arguments,0):[],null!=e?e:e=requestAnimationFrame(function(n){return function(){return e=null,t.apply(n,r)}}(this))}},t.dispatch=function(t,e){var r,n,o,i,s;return i=null!=e?e:{},s=i.target,r=i.cancelable,n=i.data,o=document.createEvent("Events"),o.initEvent(t,!0,r===!0),o.data=null!=n?n:{},(null!=s?s:document).dispatchEvent(o),o},t.match=function(t,e){return r.call(t,e)},r=function(){var t,e,r,n;return t=document.documentElement,null!=(e=null!=(r=null!=(n=t.matchesSelector)?n:t.webkitMatchesSelector)?r:t.msMatchesSelector)?e:t.mozMatchesSelector}(),t.uuid=function(){var t,e,r;for(r="",t=e=1;36>=e;t=++e)r+=9===t||14===t||19===t||24===t?"-":15===t?"4":20===t?(Math.floor(4*Math.random())+8).toString(16):Math.floor(15*Math.random()).toString(16);return r}}).call(this),function(){t.Location=function(){function t(t){var e,r;null==t&&(t=""),r=document.createElement("a"),r.href=t.toString(),this.absoluteURL=r.href,e=r.hash.length,2>e?this.requestURL=this.absoluteURL:(this.requestURL=this.absoluteURL.slice(0,-e),this.anchor=r.hash.slice(1))}var e,r,n,o;return t.wrap=function(t){return t instanceof this?t:new this(t)},t.prototype.getOrigin=function(){return this.absoluteURL.split("/",3).join("/")},t.prototype.getPath=function(){var t,e;return null!=(t=null!=(e=this.absoluteURL.match(/\/\/[^\/]*(\/[^?;]*)/))?e[1]:void 0)?t:"/"},t.prototype.getPathComponents=function(){return this.getPath().split("/").slice(1)},t.prototype.getLastPathComponent=function(){return this.getPathComponents().slice(-1)[0]},t.prototype.getExtension=function(){var t,e;return null!=(t=null!=(e=this.getLastPathComponent().match(/\.[^.]*$/))?e[0]:void 0)?t:""},t.prototype.isHTML=function(){return this.getExtension().match(/^(?:|\.(?:htm|html|xhtml))$/)},t.prototype.isPrefixedBy=function(t){var e;return e=r(t),this.isEqualTo(t)||o(this.absoluteURL,e)},t.prototype.isEqualTo=function(t){return this.absoluteURL===(null!=t?t.absoluteURL:void 0)},t.prototype.toCacheKey=function(){return this.requestURL},t.prototype.toJSON=function(){return this.absoluteURL},t.prototype.toString=function(){return this.absoluteURL},t.prototype.valueOf=function(){return this.absoluteURL},r=function(t){return e(t.getOrigin()+t.getPath())},e=function(t){return n(t,"/")?t:t+"/"},o=function(t,e){return t.slice(0,e.length)===e},n=function(t,e){return t.slice(-e.length)===e},t}()}.call(this),function(){var e=function(t,e){return function(){return t.apply(e,arguments)}};t.HttpRequest=function(){function r(r,n,o){this.delegate=r,this.requestCanceled=e(this.requestCanceled,this),this.requestTimedOut=e(this.requestTimedOut,this),this.requestFailed=e(this.requestFailed,this),this.requestLoaded=e(this.requestLoaded,this),this.requestProgressed=e(this.requestProgressed,this),this.url=t.Location.wrap(n).requestURL,this.referrer=t.Location.wrap(o).absoluteURL,this.createXHR()}return r.NETWORK_FAILURE=0,r.TIMEOUT_FAILURE=-1,r.timeout=60,r.prototype.send=function(){var t;return this.xhr&&!this.sent?(this.notifyApplicationBeforeRequestStart(),this.setProgress(0),this.xhr.send(),this.sent=!0,"function"==typeof(t=this.delegate).requestStarted?t.requestStarted():void 0):void 0},r.prototype.cancel=function(){return this.xhr&&this.sent?this.xhr.abort():void 0},r.prototype.requestProgressed=function(t){return t.lengthComputable?this.setProgress(t.loaded/t.total):void 0},r.prototype.requestLoaded=function(){return this.endRequest(function(t){return function(){var e;return 200<=(e=t.xhr.status)&&300>e?t.delegate.requestCompletedWithResponse(t.xhr.responseText,t.xhr.getResponseHeader("Turbolinks-Location")):(t.failed=!0,t.delegate.requestFailedWithStatusCode(t.xhr.status,t.xhr.responseText))}}(this))},r.prototype.requestFailed=function(){return this.endRequest(function(t){return function(){return t.failed=!0,t.delegate.requestFailedWithStatusCode(t.constructor.NETWORK_FAILURE)}}(this))},r.prototype.requestTimedOut=function(){return this.endRequest(function(t){return function(){return t.failed=!0,t.delegate.requestFailedWithStatusCode(t.constructor.TIMEOUT_FAILURE)}}(this))},r.prototype.requestCanceled=function(){return this.endRequest()},r.prototype.notifyApplicationBeforeRequestStart=function(){return t.dispatch("turbolinks:request-start",{data:{url:this.url,xhr:this.xhr}})},r.prototype.notifyApplicationAfterRequestEnd=function(){return t.dispatch("turbolinks:request-end",{data:{url:this.url,xhr:this.xhr}})},r.prototype.createXHR=function(){return this.xhr=new XMLHttpRequest,this.xhr.open("GET",this.url,!0),this.xhr.timeout=1e3*this.constructor.timeout,this.xhr.setRequestHeader("Accept","text/html, application/xhtml+xml"),this.xhr.setRequestHeader("Turbolinks-Referrer",this.referrer),this.xhr.onprogress=this.requestProgressed,this.xhr.onload=this.requestLoaded,this.xhr.onerror=this.requestFailed,this.xhr.ontimeout=this.requestTimedOut,this.xhr.onabort=this.requestCanceled},r.prototype.endRequest=function(t){return this.xhr?(this.notifyApplicationAfterRequestEnd(),null!=t&&t.call(this),this.destroy()):void 0},r.prototype.setProgress=function(t){var e;return this.progress=t,"function"==typeof(e=this.delegate).requestProgressed?e.requestProgressed(this.progress):void 0},r.prototype.destroy=function(){var t;return this.setProgress(1),"function"==typeof(t=this.delegate).requestFinished&&t.requestFinished(),this.delegate=null,this.xhr=null},r}()}.call(this),function(){var e=function(t,e){return function(){return t.apply(e,arguments)}};t.ProgressBar=function(){function t(){this.trickle=e(this.trickle,this),this.stylesheetElement=this.createStylesheetElement(),this.progressElement=this.createProgressElement()}var r;return r=300,t.defaultCSS=".turbolinks-progress-bar {\n position: fixed;\n display: block;\n top: 0;\n left: 0;\n height: 3px;\n background: #0076ff;\n z-index: 9999;\n transition: width "+r+"ms ease-out, opacity "+r/2+"ms "+r/2+"ms ease-in;\n transform: translate3d(0, 0, 0);\n}",t.prototype.show=function(){return this.visible?void 0:(this.visible=!0,this.installStylesheetElement(),this.installProgressElement(),this.startTrickling())},t.prototype.hide=function(){return this.visible&&!this.hiding?(this.hiding=!0,this.fadeProgressElement(function(t){return function(){return t.uninstallProgressElement(),t.stopTrickling(),t.visible=!1,t.hiding=!1}}(this))):void 0},t.prototype.setValue=function(t){return this.value=t,this.refresh()},t.prototype.installStylesheetElement=function(){return document.head.insertBefore(this.stylesheetElement,document.head.firstChild)},t.prototype.installProgressElement=function(){return this.progressElement.style.width=0,this.progressElement.style.opacity=1,document.documentElement.insertBefore(this.progressElement,document.body),this.refresh()},t.prototype.fadeProgressElement=function(t){return this.progressElement.style.opacity=0,setTimeout(t,1.5*r)},t.prototype.uninstallProgressElement=function(){return this.progressElement.parentNode?document.documentElement.removeChild(this.progressElement):void 0},t.prototype.startTrickling=function(){return null!=this.trickleInterval?this.trickleInterval:this.trickleInterval=setInterval(this.trickle,r)},t.prototype.stopTrickling=function(){return clearInterval(this.trickleInterval),this.trickleInterval=null},t.prototype.trickle=function(){return this.setValue(this.value+Math.random()/100)},t.prototype.refresh=function(){return requestAnimationFrame(function(t){return function(){return t.progressElement.style.width=10+90*t.value+"%"}}(this))},t.prototype.createStylesheetElement=function(){var t;return t=document.createElement("style"),t.type="text/css",t.textContent=this.constructor.defaultCSS,t},t.prototype.createProgressElement=function(){var t;return t=document.createElement("div"),t.className="turbolinks-progress-bar",t},t}()}.call(this),function(){var e=function(t,e){return function(){return t.apply(e,arguments)}};t.BrowserAdapter=function(){function r(r){this.controller=r,this.showProgressBar=e(this.showProgressBar,this),this.progressBar=new t.ProgressBar}var n,o,i,s;return s=t.HttpRequest,n=s.NETWORK_FAILURE,i=s.TIMEOUT_FAILURE,o=500,r.prototype.visitProposedToLocationWithAction=function(t,e){return this.controller.startVisitToLocationWithAction(t,e)},r.prototype.visitStarted=function(t){return t.issueRequest(),t.changeHistory(),t.loadCachedSnapshot()},r.prototype.visitRequestStarted=function(t){return this.progressBar.setValue(0),t.hasCachedSnapshot()||"restore"!==t.action?this.showProgressBarAfterDelay():this.showProgressBar()},r.prototype.visitRequestProgressed=function(t){return this.progressBar.setValue(t.progress)},r.prototype.visitRequestCompleted=function(t){return t.loadResponse()},r.prototype.visitRequestFailedWithStatusCode=function(t,e){switch(e){case n:case i:return this.reload();default:return t.loadResponse()}},r.prototype.visitRequestFinished=function(t){return this.hideProgressBar()},r.prototype.visitCompleted=function(t){return t.followRedirect()},r.prototype.pageInvalidated=function(){return this.reload()},r.prototype.showProgressBarAfterDelay=function(){return this.progressBarTimeout=setTimeout(this.showProgressBar,o)},r.prototype.showProgressBar=function(){return this.progressBar.show()},r.prototype.hideProgressBar=function(){return this.progressBar.hide(),clearTimeout(this.progressBarTimeout)},r.prototype.reload=function(){return window.location.reload()},r}()}.call(this),function(){var e=function(t,e){return function(){return t.apply(e,arguments)}};t.History=function(){function r(t){this.delegate=t,this.onPageLoad=e(this.onPageLoad,this),this.onPopState=e(this.onPopState,this)}return r.prototype.start=function(){return this.started?void 0:(addEventListener("popstate",this.onPopState,!1),addEventListener("load",this.onPageLoad,!1),this.started=!0)},r.prototype.stop=function(){return this.started?(removeEventListener("popstate",this.onPopState,!1),removeEventListener("load",this.onPageLoad,!1),this.started=!1):void 0},r.prototype.push=function(e,r){return e=t.Location.wrap(e),this.update("push",e,r)},r.prototype.replace=function(e,r){return e=t.Location.wrap(e),this.update("replace",e,r)},r.prototype.onPopState=function(e){var r,n,o,i;return this.shouldHandlePopState()&&(i=null!=(n=e.state)?n.turbolinks:void 0)?(r=t.Location.wrap(window.location),o=i.restorationIdentifier,this.delegate.historyPoppedToLocationWithRestorationIdentifier(r,o)):void 0},r.prototype.onPageLoad=function(e){return t.defer(function(t){return function(){return t.pageLoaded=!0}}(this))},r.prototype.shouldHandlePopState=function(){return this.pageIsLoaded()},r.prototype.pageIsLoaded=function(){return this.pageLoaded||"complete"===document.readyState},r.prototype.update=function(t,e,r){var n;return n={turbolinks:{restorationIdentifier:r}},history[t+"State"](n,null,e)},r}()}.call(this),function(){t.Snapshot=function(){function e(t){var e,r;r=t.head,e=t.body,this.head=null!=r?r:document.createElement("head"),this.body=null!=e?e:document.createElement("body")}return e.wrap=function(t){return t instanceof this?t:this.fromHTML(t)},e.fromHTML=function(t){var e;return e=document.createElement("html"),e.innerHTML=t,this.fromElement(e)},e.fromElement=function(t){return new this({head:t.querySelector("head"),body:t.querySelector("body")})},e.prototype.clone=function(){return new e({head:this.head.cloneNode(!0),body:this.body.cloneNode(!0)})},e.prototype.getRootLocation=function(){var e,r;return r=null!=(e=this.getSetting("root"))?e:"/",new t.Location(r)},e.prototype.getCacheControlValue=function(){return this.getSetting("cache-control")},e.prototype.hasAnchor=function(t){try{return null!=this.body.querySelector("[id='"+t+"']")}catch(e){}},e.prototype.isPreviewable=function(){return"no-preview"!==this.getCacheControlValue()},e.prototype.isCacheable=function(){return"no-cache"!==this.getCacheControlValue()},e.prototype.getSetting=function(t){var e,r;return r=this.head.querySelectorAll("meta[name='turbolinks-"+t+"']"),e=r[r.length-1],null!=e?e.getAttribute("content"):void 0},e}()}.call(this),function(){var e=[].slice;t.Renderer=function(){function t(){}var r;return t.render=function(){var t,r,n,o;return n=arguments[0],r=arguments[1],t=3<=arguments.length?e.call(arguments,2):[],o=function(t,e,r){r.prototype=t.prototype;var n=new r,o=t.apply(n,e);return Object(o)===o?o:n}(this,t,function(){}),o.delegate=n,o.render(r),o},t.prototype.renderView=function(t){return this.delegate.viewWillRender(this.newBody),t(),this.delegate.viewRendered(this.newBody)},t.prototype.invalidateView=function(){return this.delegate.viewInvalidated()},t.prototype.createScriptElement=function(t){var e;return"false"===t.getAttribute("data-turbolinks-eval")?t:(e=document.createElement("script"),e.textContent=t.textContent,r(e,t),e)},r=function(t,e){var r,n,o,i,s,a,u;for(i=e.attributes,a=[],r=0,n=i.length;n>r;r++)s=i[r],o=s.name,u=s.value,a.push(t.setAttribute(o,u));return a},t}()}.call(this),function(){t.HeadDetails=function(){function t(t){var e,r,i,s,a,u,l;for(this.element=t,this.elements={},l=this.element.childNodes,s=0,u=l.length;u>s;s++)i=l[s],i.nodeType===Node.ELEMENT_NODE&&(a=i.outerHTML,r=null!=(e=this.elements)[a]?e[a]:e[a]={type:o(i),tracked:n(i),elements:[]},r.elements.push(i))}var e,r,n,o;return t.prototype.hasElementWithKey=function(t){return t in this.elements},t.prototype.getTrackedElementSignature=function(){var t,e;return function(){var r,n;r=this.elements,n=[];for(t in r)e=r[t].tracked,e&&n.push(t);return n}.call(this).join("")},t.prototype.getScriptElementsNotInDetails=function(t){return this.getElementsMatchingTypeNotInDetails("script",t)},t.prototype.getStylesheetElementsNotInDetails=function(t){return this.getElementsMatchingTypeNotInDetails("stylesheet",t)},t.prototype.getElementsMatchingTypeNotInDetails=function(t,e){var r,n,o,i,s,a;o=this.elements,s=[];for(n in o)i=o[n],a=i.type,r=i.elements,a!==t||e.hasElementWithKey(n)||s.push(r[0]);return s},t.prototype.getProvisionalElements=function(){var t,e,r,n,o,i,s;r=[],n=this.elements;for(e in n)o=n[e],s=o.type,i=o.tracked,t=o.elements,null!=s||i?t.length>1&&r.push.apply(r,t.slice(1)):r.push.apply(r,t);return r},o=function(t){return e(t)?"script":r(t)?"stylesheet":void 0},n=function(t){return"reload"===t.getAttribute("data-turbolinks-track")},e=function(t){var e;return e=t.tagName.toLowerCase(),"script"===e},r=function(t){var e;return e=t.tagName.toLowerCase(),"style"===e||"link"===e&&"stylesheet"===t.getAttribute("rel")},t}()}.call(this),function(){var e=function(t,e){function n(){this.constructor=t}for(var o in e)r.call(e,o)&&(t[o]=e[o]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},r={}.hasOwnProperty;t.SnapshotRenderer=function(r){function n(e,r){this.currentSnapshot=e,this.newSnapshot=r,this.currentHeadDetails=new t.HeadDetails(this.currentSnapshot.head),this.newHeadDetails=new t.HeadDetails(this.newSnapshot.head),this.newBody=this.newSnapshot.body}return e(n,r),n.prototype.render=function(t){return this.trackedElementsAreIdentical()?(this.mergeHead(),this.renderView(function(e){return function(){return e.replaceBody(),e.focusFirstAutofocusableElement(),t()}}(this))):this.invalidateView()},n.prototype.mergeHead=function(){return this.copyNewHeadStylesheetElements(),this.copyNewHeadScriptElements(),this.removeCurrentHeadProvisionalElements(),this.copyNewHeadProvisionalElements()},n.prototype.replaceBody=function(){return this.activateBodyScriptElements(),this.importBodyPermanentElements(),this.assignNewBody()},n.prototype.trackedElementsAreIdentical=function(){return this.currentHeadDetails.getTrackedElementSignature()===this.newHeadDetails.getTrackedElementSignature()},n.prototype.copyNewHeadStylesheetElements=function(){var t,e,r,n,o;for(n=this.getNewHeadStylesheetElements(),o=[],e=0,r=n.length;r>e;e++)t=n[e],o.push(document.head.appendChild(t));return o},n.prototype.copyNewHeadScriptElements=function(){var t,e,r,n,o;for(n=this.getNewHeadScriptElements(),o=[],e=0,r=n.length;r>e;e++)t=n[e],o.push(document.head.appendChild(this.createScriptElement(t)));return o},n.prototype.removeCurrentHeadProvisionalElements=function(){var t,e,r,n,o;for(n=this.getCurrentHeadProvisionalElements(),o=[],e=0,r=n.length;r>e;e++)t=n[e],o.push(document.head.removeChild(t));return o},n.prototype.copyNewHeadProvisionalElements=function(){var t,e,r,n,o;for(n=this.getNewHeadProvisionalElements(),o=[],e=0,r=n.length;r>e;e++)t=n[e],o.push(document.head.appendChild(t));return o},n.prototype.importBodyPermanentElements=function(){var t,e,r,n,o,i;for(n=this.getNewBodyPermanentElements(),i=[],e=0,r=n.length;r>e;e++)o=n[e],(t=this.findCurrentBodyPermanentElement(o))?i.push(o.parentNode.replaceChild(t,o)):i.push(void 0);return i},n.prototype.activateBodyScriptElements=function(){var t,e,r,n,o,i;for(n=this.getNewBodyScriptElements(),i=[],e=0,r=n.length;r>e;e++)o=n[e],t=this.createScriptElement(o),i.push(o.parentNode.replaceChild(t,o));return i},n.prototype.assignNewBody=function(){return document.body=this.newBody},n.prototype.focusFirstAutofocusableElement=function(){var t;return null!=(t=this.findFirstAutofocusableElement())?t.focus():void 0},n.prototype.getNewHeadStylesheetElements=function(){return this.newHeadDetails.getStylesheetElementsNotInDetails(this.currentHeadDetails)},n.prototype.getNewHeadScriptElements=function(){return this.newHeadDetails.getScriptElementsNotInDetails(this.currentHeadDetails)},n.prototype.getCurrentHeadProvisionalElements=function(){return this.currentHeadDetails.getProvisionalElements()},n.prototype.getNewHeadProvisionalElements=function(){return this.newHeadDetails.getProvisionalElements()},n.prototype.getNewBodyPermanentElements=function(){return this.newBody.querySelectorAll("[id][data-turbolinks-permanent]")},n.prototype.findCurrentBodyPermanentElement=function(t){return document.body.querySelector("#"+t.id+"[data-turbolinks-permanent]")},n.prototype.getNewBodyScriptElements=function(){return this.newBody.querySelectorAll("script")},n.prototype.findFirstAutofocusableElement=function(){return document.body.querySelector("[autofocus]")},n}(t.Renderer)}.call(this),function(){var e=function(t,e){function n(){this.constructor=t}for(var o in e)r.call(e,o)&&(t[o]=e[o]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},r={}.hasOwnProperty;t.ErrorRenderer=function(t){function r(t){this.html=t}return e(r,t),r.prototype.render=function(t){return this.renderView(function(e){return function(){return e.replaceDocumentHTML(),e.activateBodyScriptElements(),t()}}(this))},r.prototype.replaceDocumentHTML=function(){return document.documentElement.innerHTML=this.html},r.prototype.activateBodyScriptElements=function(){var t,e,r,n,o,i;for(n=this.getScriptElements(),i=[],e=0,r=n.length;r>e;e++)o=n[e],t=this.createScriptElement(o),i.push(o.parentNode.replaceChild(t,o));return i},r.prototype.getScriptElements=function(){return document.documentElement.querySelectorAll("script")},r}(t.Renderer)}.call(this),function(){t.View=function(){function e(t){this.delegate=t,this.element=document.documentElement}return e.prototype.getRootLocation=function(){return this.getSnapshot().getRootLocation()},e.prototype.getSnapshot=function(){return t.Snapshot.fromElement(this.element)},e.prototype.render=function(t,e){var r,n,o;return o=t.snapshot,r=t.error,n=t.isPreview,this.markAsPreview(n),null!=o?this.renderSnapshot(o,e):this.renderError(r,e)},e.prototype.markAsPreview=function(t){return t?this.element.setAttribute("data-turbolinks-preview",""):this.element.removeAttribute("data-turbolinks-preview")},e.prototype.renderSnapshot=function(e,r){return t.SnapshotRenderer.render(this.delegate,r,this.getSnapshot(),t.Snapshot.wrap(e))},e.prototype.renderError=function(e,r){return t.ErrorRenderer.render(this.delegate,r,e)},e}()}.call(this),function(){var e=function(t,e){return function(){return t.apply(e,arguments)}};t.ScrollManager=function(){function r(r){this.delegate=r,this.onScroll=e(this.onScroll,this),this.onScroll=t.throttle(this.onScroll)}return r.prototype.start=function(){return this.started?void 0:(addEventListener("scroll",this.onScroll,!1),this.onScroll(),this.started=!0)},r.prototype.stop=function(){return this.started?(removeEventListener("scroll",this.onScroll,!1),this.started=!1):void 0},r.prototype.scrollToElement=function(t){return t.scrollIntoView()},r.prototype.scrollToPosition=function(t){var e,r;return e=t.x,r=t.y,window.scrollTo(e,r)},r.prototype.onScroll=function(t){return this.updatePosition({x:window.pageXOffset,y:window.pageYOffset})},r.prototype.updatePosition=function(t){var e;return this.position=t,null!=(e=this.delegate)?e.scrollPositionChanged(this.position):void 0},r}()}.call(this),function(){t.SnapshotCache=function(){function e(t){this.size=t,this.keys=[],this.snapshots={}}var r;return e.prototype.has=function(t){var e;return e=r(t),e in this.snapshots},e.prototype.get=function(t){var e;if(this.has(t))return e=this.read(t),this.touch(t),e},e.prototype.put=function(t,e){return this.write(t,e),this.touch(t),e},e.prototype.read=function(t){var e;return e=r(t),this.snapshots[e]},e.prototype.write=function(t,e){var n;return n=r(t),this.snapshots[n]=e},e.prototype.touch=function(t){var e,n;return n=r(t),e=this.keys.indexOf(n),e>-1&&this.keys.splice(e,1),this.keys.unshift(n),this.trim()},e.prototype.trim=function(){var t,e,r,n,o;for(n=this.keys.splice(this.size),o=[],t=0,r=n.length;r>t;t++)e=n[t],o.push(delete this.snapshots[e]);return o},r=function(e){return t.Location.wrap(e).toCacheKey()},e}()}.call(this),function(){var e=function(t,e){return function(){return t.apply(e,arguments)}};t.Visit=function(){function r(r,n,o){this.controller=r,this.action=o,this.performScroll=e(this.performScroll,this),this.identifier=t.uuid(),this.location=t.Location.wrap(n),this.adapter=this.controller.adapter,this.state="initialized",this.timingMetrics={}}var n;return r.prototype.start=function(){return"initialized"===this.state?(this.recordTimingMetric("visitStart"),this.state="started",this.adapter.visitStarted(this)):void 0},r.prototype.cancel=function(){var t;return"started"===this.state?(null!=(t=this.request)&&t.cancel(),this.cancelRender(),this.state="canceled"):void 0},r.prototype.complete=function(){var t;return"started"===this.state?(this.recordTimingMetric("visitEnd"),this.state="completed","function"==typeof(t=this.adapter).visitCompleted&&t.visitCompleted(this),this.controller.visitCompleted(this)):void 0},r.prototype.fail=function(){var t;return"started"===this.state?(this.state="failed","function"==typeof(t=this.adapter).visitFailed?t.visitFailed(this):void 0):void 0},r.prototype.changeHistory=function(){var t,e;return this.historyChanged?void 0:(t=this.location.isEqualTo(this.referrer)?"replace":this.action,e=n(t),this.controller[e](this.location,this.restorationIdentifier),this.historyChanged=!0)},r.prototype.issueRequest=function(){return this.shouldIssueRequest()&&null==this.request?(this.progress=0,this.request=new t.HttpRequest(this,this.location,this.referrer),this.request.send()):void 0},r.prototype.getCachedSnapshot=function(){var t;return!(t=this.controller.getCachedSnapshotForLocation(this.location))||null!=this.location.anchor&&!t.hasAnchor(this.location.anchor)||"restore"!==this.action&&!t.isPreviewable()?void 0:t},r.prototype.hasCachedSnapshot=function(){return null!=this.getCachedSnapshot()},r.prototype.loadCachedSnapshot=function(){var t,e;return(e=this.getCachedSnapshot())?(t=this.shouldIssueRequest(),this.render(function(){var r;return this.cacheSnapshot(),this.controller.render({snapshot:e,isPreview:t},this.performScroll),"function"==typeof(r=this.adapter).visitRendered&&r.visitRendered(this),t?void 0:this.complete()})):void 0},r.prototype.loadResponse=function(){return null!=this.response?this.render(function(){var t,e;return this.cacheSnapshot(),this.request.failed?(this.controller.render({error:this.response},this.performScroll),"function"==typeof(t=this.adapter).visitRendered&&t.visitRendered(this),this.fail()):(this.controller.render({snapshot:this.response},this.performScroll),"function"==typeof(e=this.adapter).visitRendered&&e.visitRendered(this),this.complete())}):void 0},r.prototype.followRedirect=function(){return this.redirectedToLocation&&!this.followedRedirect?(this.location=this.redirectedToLocation,this.controller.replaceHistoryWithLocationAndRestorationIdentifier(this.redirectedToLocation,this.restorationIdentifier),this.followedRedirect=!0):void 0},r.prototype.requestStarted=function(){var t;return this.recordTimingMetric("requestStart"),"function"==typeof(t=this.adapter).visitRequestStarted?t.visitRequestStarted(this):void 0},r.prototype.requestProgressed=function(t){var e;return this.progress=t,"function"==typeof(e=this.adapter).visitRequestProgressed?e.visitRequestProgressed(this):void 0},r.prototype.requestCompletedWithResponse=function(e,r){return this.response=e,null!=r&&(this.redirectedToLocation=t.Location.wrap(r)),this.adapter.visitRequestCompleted(this)},r.prototype.requestFailedWithStatusCode=function(t,e){return this.response=e,this.adapter.visitRequestFailedWithStatusCode(this,t)},r.prototype.requestFinished=function(){var t;return this.recordTimingMetric("requestEnd"),"function"==typeof(t=this.adapter).visitRequestFinished?t.visitRequestFinished(this):void 0},r.prototype.performScroll=function(){return this.scrolled?void 0:("restore"===this.action?this.scrollToRestoredPosition()||this.scrollToTop():this.scrollToAnchor()||this.scrollToTop(),this.scrolled=!0)},r.prototype.scrollToRestoredPosition=function(){var t,e;return t=null!=(e=this.restorationData)?e.scrollPosition:void 0,null!=t?(this.controller.scrollToPosition(t),!0):void 0},r.prototype.scrollToAnchor=function(){return null!=this.location.anchor?(this.controller.scrollToAnchor(this.location.anchor),!0):void 0},r.prototype.scrollToTop=function(){return this.controller.scrollToPosition({x:0,y:0})},r.prototype.recordTimingMetric=function(t){var e;return null!=(e=this.timingMetrics)[t]?e[t]:e[t]=(new Date).getTime()},r.prototype.getTimingMetrics=function(){return t.copyObject(this.timingMetrics)},n=function(t){switch(t){case"replace":return"replaceHistoryWithLocationAndRestorationIdentifier";case"advance":case"restore":return"pushHistoryWithLocationAndRestorationIdentifier"}},r.prototype.shouldIssueRequest=function(){return"restore"===this.action?!this.hasCachedSnapshot():!0},r.prototype.cacheSnapshot=function(){return this.snapshotCached?void 0:(this.controller.cacheSnapshot(),this.snapshotCached=!0)},r.prototype.render=function(t){return this.cancelRender(),this.frame=requestAnimationFrame(function(e){return function(){return e.frame=null,t.call(e)}}(this))},r.prototype.cancelRender=function(){return this.frame?cancelAnimationFrame(this.frame):void 0},r}()}.call(this),function(){var e=function(t,e){return function(){return t.apply(e,arguments)}};t.Controller=function(){function r(){this.clickBubbled=e(this.clickBubbled,this),this.clickCaptured=e(this.clickCaptured,this),this.pageLoaded=e(this.pageLoaded,this),this.history=new t.History(this),this.view=new t.View(this),this.scrollManager=new t.ScrollManager(this),this.restorationData={},this.clearCache()}return r.prototype.start=function(){return t.supported&&!this.started?(addEventListener("click",this.clickCaptured,!0),addEventListener("DOMContentLoaded",this.pageLoaded,!1),this.scrollManager.start(),this.startHistory(),this.started=!0,this.enabled=!0):void 0},r.prototype.disable=function(){return this.enabled=!1},r.prototype.stop=function(){return this.started?(removeEventListener("click",this.clickCaptured,!0),removeEventListener("DOMContentLoaded",this.pageLoaded,!1),this.scrollManager.stop(),this.stopHistory(),this.started=!1):void 0},r.prototype.clearCache=function(){return this.cache=new t.SnapshotCache(10)},r.prototype.visit=function(e,r){var n,o;return null==r&&(r={}),e=t.Location.wrap(e),this.applicationAllowsVisitingLocation(e)?this.locationIsVisitable(e)?(n=null!=(o=r.action)?o:"advance",this.adapter.visitProposedToLocationWithAction(e,n)):window.location=e:void 0},r.prototype.startVisitToLocationWithAction=function(e,r,n){var o;return t.supported?(o=this.getRestorationDataForIdentifier(n),this.startVisit(e,r,{restorationData:o})):window.location=e},r.prototype.startHistory=function(){return this.location=t.Location.wrap(window.location),this.restorationIdentifier=t.uuid(),this.history.start(),this.history.replace(this.location,this.restorationIdentifier)},r.prototype.stopHistory=function(){return this.history.stop()},r.prototype.pushHistoryWithLocationAndRestorationIdentifier=function(e,r){return this.restorationIdentifier=r,this.location=t.Location.wrap(e),this.history.push(this.location,this.restorationIdentifier)},r.prototype.replaceHistoryWithLocationAndRestorationIdentifier=function(e,r){return this.restorationIdentifier=r,this.location=t.Location.wrap(e),this.history.replace(this.location,this.restorationIdentifier)},r.prototype.historyPoppedToLocationWithRestorationIdentifier=function(e,r){var n;return this.restorationIdentifier=r,this.enabled?(n=this.getRestorationDataForIdentifier(this.restorationIdentifier),this.startVisit(e,"restore",{restorationIdentifier:this.restorationIdentifier,restorationData:n,historyChanged:!0}),this.location=t.Location.wrap(e)):this.adapter.pageInvalidated()},r.prototype.getCachedSnapshotForLocation=function(t){var e;return e=this.cache.get(t),e?e.clone():void 0},r.prototype.shouldCacheSnapshot=function(){return this.view.getSnapshot().isCacheable()},r.prototype.cacheSnapshot=function(){var t;return this.shouldCacheSnapshot()?(this.notifyApplicationBeforeCachingSnapshot(),t=this.view.getSnapshot(),this.cache.put(this.lastRenderedLocation,t.clone())):void 0},r.prototype.scrollToAnchor=function(t){var e;return(e=document.getElementById(t))?this.scrollToElement(e):this.scrollToPosition({x:0,y:0})},r.prototype.scrollToElement=function(t){return this.scrollManager.scrollToElement(t)},r.prototype.scrollToPosition=function(t){return this.scrollManager.scrollToPosition(t)},r.prototype.scrollPositionChanged=function(t){var e;return e=this.getCurrentRestorationData(),e.scrollPosition=t},r.prototype.render=function(t,e){return this.view.render(t,e)},r.prototype.viewInvalidated=function(){return this.adapter.pageInvalidated()},r.prototype.viewWillRender=function(t){return this.notifyApplicationBeforeRender(t)},r.prototype.viewRendered=function(){return this.lastRenderedLocation=this.currentVisit.location,this.notifyApplicationAfterRender()},r.prototype.pageLoaded=function(){return this.lastRenderedLocation=this.location,this.notifyApplicationAfterPageLoad()},r.prototype.clickCaptured=function(){return removeEventListener("click",this.clickBubbled,!1),addEventListener("click",this.clickBubbled,!1)},r.prototype.clickBubbled=function(t){var e,r,n;return this.enabled&&this.clickEventIsSignificant(t)&&(r=this.getVisitableLinkForNode(t.target))&&(n=this.getVisitableLocationForLink(r))&&this.applicationAllowsFollowingLinkToLocation(r,n)?(t.preventDefault(),e=this.getActionForLink(r),this.visit(n,{action:e})):void 0},r.prototype.applicationAllowsFollowingLinkToLocation=function(t,e){var r;return r=this.notifyApplicationAfterClickingLinkToLocation(t,e),!r.defaultPrevented},r.prototype.applicationAllowsVisitingLocation=function(t){var e;return e=this.notifyApplicationBeforeVisitingLocation(t),!e.defaultPrevented},r.prototype.notifyApplicationAfterClickingLinkToLocation=function(e,r){return t.dispatch("turbolinks:click",{target:e,data:{url:r.absoluteURL},cancelable:!0})},r.prototype.notifyApplicationBeforeVisitingLocation=function(e){return t.dispatch("turbolinks:before-visit",{data:{url:e.absoluteURL},cancelable:!0})},r.prototype.notifyApplicationAfterVisitingLocation=function(e){return t.dispatch("turbolinks:visit",{data:{url:e.absoluteURL}})},r.prototype.notifyApplicationBeforeCachingSnapshot=function(){return t.dispatch("turbolinks:before-cache")},r.prototype.notifyApplicationBeforeRender=function(e){
return t.dispatch("turbolinks:before-render",{data:{newBody:e}})},r.prototype.notifyApplicationAfterRender=function(){return t.dispatch("turbolinks:render")},r.prototype.notifyApplicationAfterPageLoad=function(e){return null==e&&(e={}),t.dispatch("turbolinks:load",{data:{url:this.location.absoluteURL,timing:e}})},r.prototype.startVisit=function(t,e,r){var n;return null!=(n=this.currentVisit)&&n.cancel(),this.currentVisit=this.createVisit(t,e,r),this.currentVisit.start(),this.notifyApplicationAfterVisitingLocation(t)},r.prototype.createVisit=function(e,r,n){var o,i,s,a,u;return i=null!=n?n:{},a=i.restorationIdentifier,s=i.restorationData,o=i.historyChanged,u=new t.Visit(this,e,r),u.restorationIdentifier=null!=a?a:t.uuid(),u.restorationData=t.copyObject(s),u.historyChanged=o,u.referrer=this.location,u},r.prototype.visitCompleted=function(t){return this.notifyApplicationAfterPageLoad(t.getTimingMetrics())},r.prototype.clickEventIsSignificant=function(t){return!(t.defaultPrevented||t.target.isContentEditable||t.which>1||t.altKey||t.ctrlKey||t.metaKey||t.shiftKey)},r.prototype.getVisitableLinkForNode=function(e){return this.nodeIsVisitable(e)?t.closest(e,"a[href]:not([target]):not([download])"):void 0},r.prototype.getVisitableLocationForLink=function(e){var r;return r=new t.Location(e.getAttribute("href")),this.locationIsVisitable(r)?r:void 0},r.prototype.getActionForLink=function(t){var e;return null!=(e=t.getAttribute("data-turbolinks-action"))?e:"advance"},r.prototype.nodeIsVisitable=function(e){var r;return(r=t.closest(e,"[data-turbolinks]"))?"false"!==r.getAttribute("data-turbolinks"):!0},r.prototype.locationIsVisitable=function(t){return t.isPrefixedBy(this.view.getRootLocation())&&t.isHTML()},r.prototype.getCurrentRestorationData=function(){return this.getRestorationDataForIdentifier(this.restorationIdentifier)},r.prototype.getRestorationDataForIdentifier=function(t){var e;return null!=(e=this.restorationData)[t]?e[t]:e[t]={}},r}()}.call(this),function(){var e,r,n;t.start=function(){return r()?(null==t.controller&&(t.controller=e()),t.controller.start()):void 0},r=function(){return null==window.Turbolinks&&(window.Turbolinks=t),n()},e=function(){var e;return e=new t.Controller,e.adapter=new t.BrowserAdapter(e),e},n=function(){return window.Turbolinks===t},n()&&t.start()}.call(this)}).call(this),"object"==typeof module&&module.exports?module.exports=t:"function"==typeof define&&define.amd&&define(t)}).call(this);
(function() {
var context = this;
(function() {
(function() {
var slice = [].slice;
this.ActionCable = {
INTERNAL: {
"message_types": {
"welcome": "welcome",
"ping": "ping",
"confirmation": "confirm_subscription",
"rejection": "reject_subscription"
},
"default_mount_path": "/cable",
"protocols": ["actioncable-v1-json", "actioncable-unsupported"]
},
WebSocket: window.WebSocket,
logger: window.console,
createConsumer: function(url) {
var ref;
if (url == null) {
url = (ref = this.getConfig("url")) != null ? ref : this.INTERNAL.default_mount_path;
}
return new ActionCable.Consumer(this.createWebSocketURL(url));
},
getConfig: function(name) {
var element;
element = document.head.querySelector("meta[name='action-cable-" + name + "']");
return element != null ? element.getAttribute("content") : void 0;
},
createWebSocketURL: function(url) {
var a;
if (url && !/^wss?:/i.test(url)) {
a = document.createElement("a");
a.href = url;
a.href = a.href;
a.protocol = a.protocol.replace("http", "ws");
return a.href;
} else {
return url;
}
},
startDebugging: function() {
return this.debugging = true;
},
stopDebugging: function() {
return this.debugging = null;
},
log: function() {
var messages, ref;
messages = 1 <= arguments.length ? slice.call(arguments, 0) : [];
if (this.debugging) {
messages.push(Date.now());
return (ref = this.logger).log.apply(ref, ["[ActionCable]"].concat(slice.call(messages)));
}
}
};
}).call(this);
}).call(context);
var ActionCable = context.ActionCable;
(function() {
(function() {
var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
ActionCable.ConnectionMonitor = (function() {
var clamp, now, secondsSince;
ConnectionMonitor.pollInterval = {
min: 3,
max: 30
};
ConnectionMonitor.staleThreshold = 6;
function ConnectionMonitor(connection) {
this.connection = connection;
this.visibilityDidChange = bind(this.visibilityDidChange, this);
this.reconnectAttempts = 0;
}
ConnectionMonitor.prototype.start = function() {
if (!this.isRunning()) {
this.startedAt = now();
delete this.stoppedAt;
this.startPolling();
document.addEventListener("visibilitychange", this.visibilityDidChange);
return ActionCable.log("ConnectionMonitor started. pollInterval = " + (this.getPollInterval()) + " ms");
}
};
ConnectionMonitor.prototype.stop = function() {
if (this.isRunning()) {
this.stoppedAt = now();
this.stopPolling();
document.removeEventListener("visibilitychange", this.visibilityDidChange);
return ActionCable.log("ConnectionMonitor stopped");
}
};
ConnectionMonitor.prototype.isRunning = function() {
return (this.startedAt != null) && (this.stoppedAt == null);
};
ConnectionMonitor.prototype.recordPing = function() {
return this.pingedAt = now();
};
ConnectionMonitor.prototype.recordConnect = function() {
this.reconnectAttempts = 0;
this.recordPing();
delete this.disconnectedAt;
return ActionCable.log("ConnectionMonitor recorded connect");
};
ConnectionMonitor.prototype.recordDisconnect = function() {
this.disconnectedAt = now();
return ActionCable.log("ConnectionMonitor recorded disconnect");
};
ConnectionMonitor.prototype.startPolling = function() {
this.stopPolling();
return this.poll();
};
ConnectionMonitor.prototype.stopPolling = function() {
return clearTimeout(this.pollTimeout);
};
ConnectionMonitor.prototype.poll = function() {
return this.pollTimeout = setTimeout((function(_this) {
return function() {
_this.reconnectIfStale();
return _this.poll();
};
})(this), this.getPollInterval());
};
ConnectionMonitor.prototype.getPollInterval = function() {
var interval, max, min, ref;
ref = this.constructor.pollInterval, min = ref.min, max = ref.max;
interval = 5 * Math.log(this.reconnectAttempts + 1);
return Math.round(clamp(interval, min, max) * 1000);
};
ConnectionMonitor.prototype.reconnectIfStale = function() {
if (this.connectionIsStale()) {
ActionCable.log("ConnectionMonitor detected stale connection. reconnectAttempts = " + this.reconnectAttempts + ", pollInterval = " + (this.getPollInterval()) + " ms, time disconnected = " + (secondsSince(this.disconnectedAt)) + " s, stale threshold = " + this.constructor.staleThreshold + " s");
this.reconnectAttempts++;
if (this.disconnectedRecently()) {
return ActionCable.log("ConnectionMonitor skipping reopening recent disconnect");
} else {
ActionCable.log("ConnectionMonitor reopening");
return this.connection.reopen();
}
}
};
ConnectionMonitor.prototype.connectionIsStale = function() {
var ref;
return secondsSince((ref = this.pingedAt) != null ? ref : this.startedAt) > this.constructor.staleThreshold;
};
ConnectionMonitor.prototype.disconnectedRecently = function() {
return this.disconnectedAt && secondsSince(this.disconnectedAt) < this.constructor.staleThreshold;
};
ConnectionMonitor.prototype.visibilityDidChange = function() {
if (document.visibilityState === "visible") {
return setTimeout((function(_this) {
return function() {
if (_this.connectionIsStale() || !_this.connection.isOpen()) {
ActionCable.log("ConnectionMonitor reopening stale connection on visibilitychange. visbilityState = " + document.visibilityState);
return _this.connection.reopen();
}
};
})(this), 200);
}
};
now = function() {
return new Date().getTime();
};
secondsSince = function(time) {
return (now() - time) / 1000;
};
clamp = function(number, min, max) {
return Math.max(min, Math.min(max, number));
};
return ConnectionMonitor;
})();
}).call(this);
(function() {
var i, message_types, protocols, ref, supportedProtocols, unsupportedProtocol,
slice = [].slice,
bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };
ref = ActionCable.INTERNAL, message_types = ref.message_types, protocols = ref.protocols;
supportedProtocols = 2 <= protocols.length ? slice.call(protocols, 0, i = protocols.length - 1) : (i = 0, []), unsupportedProtocol = protocols[i++];
ActionCable.Connection = (function() {
Connection.reopenDelay = 500;
function Connection(consumer) {
this.consumer = consumer;
this.open = bind(this.open, this);
this.subscriptions = this.consumer.subscriptions;
this.monitor = new ActionCable.ConnectionMonitor(this);
this.disconnected = true;
}
Connection.prototype.send = function(data) {
if (this.isOpen()) {
this.webSocket.send(JSON.stringify(data));
return true;
} else {
return false;
}
};
Connection.prototype.open = function() {
if (this.isActive()) {
ActionCable.log("Attempted to open WebSocket, but existing socket is " + (this.getState()));
return false;
} else {
ActionCable.log("Opening WebSocket, current state is " + (this.getState()) + ", subprotocols: " + protocols);
if (this.webSocket != null) {
this.uninstallEventHandlers();
}
this.webSocket = new ActionCable.WebSocket(this.consumer.url, protocols);
this.installEventHandlers();
this.monitor.start();
return true;
}
};
Connection.prototype.close = function(arg) {
var allowReconnect, ref1;
allowReconnect = (arg != null ? arg : {
allowReconnect: true
}).allowReconnect;
if (!allowReconnect) {
this.monitor.stop();
}
if (this.isActive()) {
return (ref1 = this.webSocket) != null ? ref1.close() : void 0;
}
};
Connection.prototype.reopen = function() {
var error;
ActionCable.log("Reopening WebSocket, current state is " + (this.getState()));
if (this.isActive()) {
try {
return this.close();
} catch (error1) {
error = error1;
return ActionCable.log("Failed to reopen WebSocket", error);
} finally {
ActionCable.log("Reopening WebSocket in " + this.constructor.reopenDelay + "ms");
setTimeout(this.open, this.constructor.reopenDelay);
}
} else {
return this.open();
}
};
Connection.prototype.getProtocol = function() {
var ref1;
return (ref1 = this.webSocket) != null ? ref1.protocol : void 0;
};
Connection.prototype.isOpen = function() {
return this.isState("open");
};
Connection.prototype.isActive = function() {
return this.isState("open", "connecting");
};
Connection.prototype.isProtocolSupported = function() {
var ref1;
return ref1 = this.getProtocol(), indexOf.call(supportedProtocols, ref1) >= 0;
};
Connection.prototype.isState = function() {
var ref1, states;
states = 1 <= arguments.length ? slice.call(arguments, 0) : [];
return ref1 = this.getState(), indexOf.call(states, ref1) >= 0;
};
Connection.prototype.getState = function() {
var ref1, state, value;
for (state in WebSocket) {
value = WebSocket[state];
if (value === ((ref1 = this.webSocket) != null ? ref1.readyState : void 0)) {
return state.toLowerCase();
}
}
return null;
};
Connection.prototype.installEventHandlers = function() {
var eventName, handler;
for (eventName in this.events) {
handler = this.events[eventName].bind(this);
this.webSocket["on" + eventName] = handler;
}
};
Connection.prototype.uninstallEventHandlers = function() {
var eventName;
for (eventName in this.events) {
this.webSocket["on" + eventName] = function() {};
}
};
Connection.prototype.events = {
message: function(event) {
var identifier, message, ref1, type;
if (!this.isProtocolSupported()) {
return;
}
ref1 = JSON.parse(event.data), identifier = ref1.identifier, message = ref1.message, type = ref1.type;
switch (type) {
case message_types.welcome:
this.monitor.recordConnect();
return this.subscriptions.reload();
case message_types.ping:
return this.monitor.recordPing();
case message_types.confirmation:
return this.subscriptions.notify(identifier, "connected");
case message_types.rejection:
return this.subscriptions.reject(identifier);
default:
return this.subscriptions.notify(identifier, "received", message);
}
},
open: function() {
ActionCable.log("WebSocket onopen event, using '" + (this.getProtocol()) + "' subprotocol");
this.disconnected = false;
if (!this.isProtocolSupported()) {
ActionCable.log("Protocol is unsupported. Stopping monitor and disconnecting.");
return this.close({
allowReconnect: false
});
}
},
close: function(event) {
ActionCable.log("WebSocket onclose event");
if (this.disconnected) {
return;
}
this.disconnected = true;
this.monitor.recordDisconnect();
return this.subscriptions.notifyAll("disconnected", {
willAttemptReconnect: this.monitor.isRunning()
});
},
error: function() {
return ActionCable.log("WebSocket onerror event");
}
};
return Connection;
})();
}).call(this);
(function() {
var slice = [].slice;
ActionCable.Subscriptions = (function() {
function Subscriptions(consumer) {
this.consumer = consumer;
this.subscriptions = [];
}
Subscriptions.prototype.create = function(channelName, mixin) {
var channel, params, subscription;
channel = channelName;
params = typeof channel === "object" ? channel : {
channel: channel
};
subscription = new ActionCable.Subscription(this.consumer, params, mixin);
return this.add(subscription);
};
Subscriptions.prototype.add = function(subscription) {
this.subscriptions.push(subscription);
this.consumer.ensureActiveConnection();
this.notify(subscription, "initialized");
this.sendCommand(subscription, "subscribe");
return subscription;
};
Subscriptions.prototype.remove = function(subscription) {
this.forget(subscription);
if (!this.findAll(subscription.identifier).length) {
this.sendCommand(subscription, "unsubscribe");
}
return subscription;
};
Subscriptions.prototype.reject = function(identifier) {
var i, len, ref, results, subscription;
ref = this.findAll(identifier);
results = [];
for (i = 0, len = ref.length; i < len; i++) {
subscription = ref[i];
this.forget(subscription);
this.notify(subscription, "rejected");
results.push(subscription);
}
return results;
};
Subscriptions.prototype.forget = function(subscription) {
var s;
this.subscriptions = (function() {
var i, len, ref, results;
ref = this.subscriptions;
results = [];
for (i = 0, len = ref.length; i < len; i++) {
s = ref[i];
if (s !== subscription) {
results.push(s);
}
}
return results;
}).call(this);
return subscription;
};
Subscriptions.prototype.findAll = function(identifier) {
var i, len, ref, results, s;
ref = this.subscriptions;
results = [];
for (i = 0, len = ref.length; i < len; i++) {
s = ref[i];
if (s.identifier === identifier) {
results.push(s);
}
}
return results;
};
Subscriptions.prototype.reload = function() {
var i, len, ref, results, subscription;
ref = this.subscriptions;
results = [];
for (i = 0, len = ref.length; i < len; i++) {
subscription = ref[i];
results.push(this.sendCommand(subscription, "subscribe"));
}
return results;
};
Subscriptions.prototype.notifyAll = function() {
var args, callbackName, i, len, ref, results, subscription;
callbackName = arguments[0], args = 2 <= arguments.length ? slice.call(arguments, 1) : [];
ref = this.subscriptions;
results = [];
for (i = 0, len = ref.length; i < len; i++) {
subscription = ref[i];
results.push(this.notify.apply(this, [subscription, callbackName].concat(slice.call(args))));
}
return results;
};
Subscriptions.prototype.notify = function() {
var args, callbackName, i, len, results, subscription, subscriptions;
subscription = arguments[0], callbackName = arguments[1], args = 3 <= arguments.length ? slice.call(arguments, 2) : [];
if (typeof subscription === "string") {
subscriptions = this.findAll(subscription);
} else {
subscriptions = [subscription];
}
results = [];
for (i = 0, len = subscriptions.length; i < len; i++) {
subscription = subscriptions[i];
results.push(typeof subscription[callbackName] === "function" ? subscription[callbackName].apply(subscription, args) : void 0);
}
return results;
};
Subscriptions.prototype.sendCommand = function(subscription, command) {
var identifier;
identifier = subscription.identifier;
return this.consumer.send({
command: command,
identifier: identifier
});
};
return Subscriptions;
})();
}).call(this);
(function() {
ActionCable.Subscription = (function() {
var extend;
function Subscription(consumer, params, mixin) {
this.consumer = consumer;
if (params == null) {
params = {};
}
this.identifier = JSON.stringify(params);
extend(this, mixin);
}
Subscription.prototype.perform = function(action, data) {
if (data == null) {
data = {};
}
data.action = action;
return this.send(data);
};
Subscription.prototype.send = function(data) {
return this.consumer.send({
command: "message",
identifier: this.identifier,
data: JSON.stringify(data)
});
};
Subscription.prototype.unsubscribe = function() {
return this.consumer.subscriptions.remove(this);
};
extend = function(object, properties) {
var key, value;
if (properties != null) {
for (key in properties) {
value = properties[key];
object[key] = value;
}
}
return object;
};
return Subscription;
})();
}).call(this);
(function() {
ActionCable.Consumer = (function() {
function Consumer(url) {
this.url = url;
this.subscriptions = new ActionCable.Subscriptions(this);
this.connection = new ActionCable.Connection(this);
}
Consumer.prototype.send = function(data) {
return this.connection.send(data);
};
Consumer.prototype.connect = function() {
return this.connection.open();
};
Consumer.prototype.disconnect = function() {
return this.connection.close({
allowReconnect: false
});
};
Consumer.prototype.ensureActiveConnection = function() {
if (!this.connection.isActive()) {
return this.connection.open();
}
};
return Consumer;
})();
}).call(this);
}).call(this);
if (typeof module === "object" && module.exports) {
module.exports = ActionCable;
} else if (typeof define === "function" && define.amd) {
define(ActionCable);
}
}).call(this);
// Action Cable provides the framework to deal with WebSockets in Rails.
// You can generate new channels where WebSocket features live using the `rails generate channel` command.
//
(function() {
this.App || (this.App = {});
App.cable = ActionCable.createConsumer();
}).call(this);
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, or any plugin's
// vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file. JavaScript code in this file should be added after the last require_* statement.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
;
|
/* eslint-disable prettier/prettier */
const User = require('../models/userModel');
const catchAsync = require('../helpers/catchAsync');
const AppError = require('../helpers/appError');
const factory = require('../controllers/handlerFactory');
const filterObj = (obj, ...allowedFields) => {
const newObj = {};
Object.keys(obj).forEach((el) => {
if (allowedFields.includes(el)) newObj[el] = obj[el];
});
return newObj;
};
exports.getMe = catchAsync(async (req, res, next) => {
const user = await User.findById(req.user.id);
if (!user) return next(new AppError('The user data couldnot be obtained!', 401));
res.status(200).json({
status: 'success',
data: user,
});
});
exports.updateMe = catchAsync(async (req, res, next) => {
//*1.Create error if user post password data
if (req.body.password) {
return next(new AppError('You are not allowed to update password', 400));
}
//*2. Update user document
const filterBody = filterObj(req.body, 'name', 'email', 'contact', 'address');
const updatedUser = await User.findByIdAndUpdate(req.user.id, filterBody, {
new: true,
runValidators: true,
});
res.status(200).json({
status: 'success',
data: updatedUser,
});
});
exports.deleteMe = catchAsync(async (req, res, next) => {
await User.findByIdAndUpdate(req.user.id, {
active: false,
});
res.status(200).json({
status: 'success',
message: ' The user is successfully deleted!!',
});
});
exports.updateUser = factory.updateOne(User);
exports.deleteUser = factory.deleteOne(User);
exports.getAllUsers = factory.getAll(User);
exports.getOneUser = factory.getOne(User);
exports.createUser = factory.createOne(User);
|
// Copyright (c) 2015 - 2017 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.
/* eslint-disable max-len */
// Intialize globals, check version
import './lib/init';
// Import shaderlib to make sure shader modules are initialized
import './shaderlib';
// Core Library
export {COORDINATE_SYSTEM} from './lib/constants';
// Experimental Pure JS (non-React) bindings
export {default as Deck} from './lib/deck';
export {default as LayerManager} from './lib/layer-manager';
export {default as AttributeManager} from './lib/attribute-manager';
export {default as Layer} from './lib/layer';
export {default as CompositeLayer} from './lib/composite-layer';
// Viewports
export {default as Viewport} from './viewports/viewport';
export {default as WebMercatorViewport} from './viewports/web-mercator-viewport';
// Shader modules
export {default as project} from './shaderlib/project/project';
export {default as project64} from './shaderlib/project64/project64';
export {default as lighting} from './shaderlib/lighting/lighting';
export {default as View} from './views/view';
export {default as MapView} from './views/map-view';
export {default as FirstPersonView} from './views/first-person-view';
export {default as ThirdPersonView} from './views/third-person-view';
export {default as OrbitView} from './views/orbit-view';
export {default as PerspectiveView} from './views/perspective-view';
export {default as OrthographicView} from './views/orthographic-view';
// Controllers
export {default as Controller} from './controllers/controller';
export {default as MapController} from './controllers/map-controller';
// Experimental Controllers
export {default as _FirstPersonController} from './controllers/first-person-controller';
export {default as _OrbitController} from './controllers/orbit-controller';
// EXPERIMENTAL EXPORTS
// Experimental Effects (non-React) bindings
export {default as _EffectManager} from './experimental/lib/effect-manager';
export {default as _Effect} from './experimental/lib/effect';
export {default as _ReflectionEffect} from './experimental/reflection-effect/reflection-effect';
// Eperimental Transitions
export {TRANSITION_EVENTS as _TRANSITION_EVENTS} from './controllers/transition-manager';
export {default as _LinearInterpolator} from './transitions/linear-interpolator';
export {default as _ViewportFlyToInterpolator} from './transitions/viewport-fly-to-interpolator';
// Layer utilities
export {default as log} from './utils/log';
import {flattenVertices, fillArray} from './utils/flatten'; // Export? move to luma.gl or math.gl?
import {default as BinSorter} from './utils/bin-sorter';
import {defaultColorRange} from './utils/color-utils';
import {linearScale, getLinearScale, quantizeScale, getQuantizeScale} from './utils/scale-utils';
export {default as _GPUGridAggregator} from './experimental/utils/gpu-grid-aggregator';
// Exports for layers
// Experimental Features may change in minor version bumps, use at your own risk)
export const experimental = {
BinSorter,
linearScale,
getLinearScale,
quantizeScale,
getQuantizeScale,
defaultColorRange,
flattenVertices,
fillArray
};
|
// utils
const logger = require("../../utils/logger");
exports.up = knex => {
return knex.schema
.table("settings", table => {
table.text("labs").defaultTo("{}");
})
.then(() => {
logger.info({
code: "DATABASE_MIGRATIONS",
message: "Insert column 'labs' into settings"
});
})
.then(() => {
return knex("settings").update({
labs: knex.raw("labs::jsonb || '{\"comments\": false}'")
});
})
.then(() => {
logger.info({
code: "DATABASE_MIGRATIONS",
message: "Insert 'comments' into labs column"
});
})
.catch(err => {
logger.error(err);
});
};
exports.down = knex => {
return knex.schema
.table("settings", table => {
table.dropColumn("labs");
})
.then(() => {
logger.info({
message: "Dropping column 'labs' from settings"
});
})
.catch(err => {
logger.error(err);
});
};
|
// Create a new panel
chrome.devtools.panels.create("XPath Finder",
"icon.png",
"panel.html",
function(extensionPanel) {
function log(){alert('I am log function.');}
chrome.devtools.panels.elements.onSelectionChanged.addListener(llog);
// var _window; // Going to hold the reference to panel.html's `window`
//
// var data = [];
// var port = chrome.runtime.connect({name: 'devtools'});
// port.onMessage.addListener(function(msg) {
// // Write information to the panel, if exists.
// // If we don't have a panel reference (yet), queue the data.
// if (_window) {
// _window.do_something(msg);
// } else {
// data.push(msg);
// }
// });
//
// extensionPanel.onShown.addListener(function tmp(panelWindow) {
// extensionPanel.onShown.removeListener(tmp); // Run once only
// _window = panelWindow;
//
// // Release queued data
// var msg;
// while (msg == data.shift())
// _window.do_something(msg);
// // Just to show that it's easy to talk to pass a message back:
// _window.respond = function(msg) {
// port.postMessage(msg);
// };
//
// // Each time when user changes the selection, i will be getting the letest selection.
//
//
//
// });
});
|
import React, { Component } from 'react';
import ReactRouterPropTypes from 'react-router-prop-types';
import PropTypes from 'prop-types';
import { NoteEditPage } from '@folio/stripes/smart-components';
import { formatNoteReferrer, urls } from '../components/utils';
export default class NoteEditRoute extends Component {
static propTypes = {
history: ReactRouterPropTypes.history.isRequired,
location: ReactRouterPropTypes.location.isRequired,
match: PropTypes.shape({
params: PropTypes.shape({
noteId: PropTypes.string.isRequired,
}).isRequired,
}).isRequired,
};
goToNoteView = () => {
const { history, location, match } = this.props;
history.replace({
pathname: urls.noteView(match.params.noteId),
state: location.state,
});
}
render() {
const { location, match } = this.props;
return (
<NoteEditPage
referredEntityData={formatNoteReferrer(location.state)}
entityTypeTranslationKeys={{ license: 'ui-licenses.license' }}
entityTypePluralizedTranslationKeys={{ license: 'ui-licenses.licensePlural' }}
paneHeaderAppIcon="license"
domain="licenses"
navigateBack={this.goToNoteView}
noteId={match.params.noteId}
/>
);
}
}
|
module.exports = require('../images/2/1f52c.png');
|
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
//require('../models/ImageSchema');
//require('../models/TagSchema');
module.exports = (settings) => {
mongoose.connect(settings.db, err => {
if (err) {
console.log(err);
return;
}
console.log('MongoDB up and running...');
}
)};
|
import homeRouter from './home-router'
const routes = [
{
path: '/',
name: 'Home',
redirect: '/main',
component: () => import('@/view/home/home'),
children: [...homeRouter],
},
{
path: '/login',
name: 'login',
component: () => import('@/view/login/login'),
},
{
redirect: '/404',
path: '*',
},
]
export default routes
|
import "./bottomnavpage.css";
import bottomnavpage from "./bottomnavpage.html";
export default { title: "Pages/Nav Page" };
export const BottomNavPage = () => bottomnavpage;
|
'use strict'
// Tab functionality
const openTab = (tabName) => (event) => {
var i, x, tablinks
x = document.getElementsByClassName('content-tab')
for (i = 0; i < x.length; i++) {
x[i].style.display = 'none'
}
tablinks = document.getElementsByClassName('tab')
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace(' is-active', '')
}
document.getElementById(tabName).style.display = 'block'
event.currentTarget.className += ' is-active'
}
document.addEventListener('DOMContentLoaded', function () {
// Add click listeners to tabs
var i, x, tablinks
x = document.getElementsByClassName('content-tab')
tablinks = document.getElementsByClassName('tab')
for (i = 0; i < tablinks.length; i++) {
tablinks[i].addEventListener('click', openTab(tablinks[i].title))
}
// Hide all tabs except the first
for (i = 1; i < x.length; i++) {
x[i].style.display = 'none'
}
for (i = 1; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace(' is-active', '')
}
})
/*
* Settings functionality
*/
// Toggle buttons
const toggleProperty = (property) => (event) => {
chrome.storage.local.set({
[property.id]: event.target.checked,
})
}
document.addEventListener('DOMContentLoaded', function () {
// Add change listeners to switches
var i, x
x = document.getElementsByClassName('switch')
for (i = 0; i < x.length; i++) {
x[i].addEventListener('change', toggleProperty(x[i]))
}
// Set initial checked state from storage
chrome.storage.local.get(
[].map.call(x, (el) => el.id),
(res) => {
if (res) {
for (i = 0; i < x.length; i++) {
x[i].checked = res[x[i].id]
}
}
}
)
})
document.addEventListener('DOMContentLoaded', function () {
// Add change listeners to main switch
var x = document.getElementById('main-toggle')
x.addEventListener('change', toggleProperty(x))
// Set initial checked state from storage
chrome.storage.local.get([x.id], (res) => {
if (res) {
x.checked = res[x.id]
}
})
})
// Selection dropdowns
const selectProperty = (property) => (event) => {
chrome.storage.local.set({
[property.id]: event.target.value,
})
}
document.addEventListener('DOMContentLoaded', function () {
// Add change listeners to selectors
var i, x
x = document.querySelectorAll('select')
for (i = 0; i < x.length; i++) {
x[i].addEventListener('change', selectProperty(x[i]))
}
// Set initial select state from storage
chrome.storage.local.get(
[].map.call(x, (el) => el.id),
(res) => {
if (res) {
for (i = 0; i < x.length; i++) {
x[i].value = res[x[i].id || 'disabled']
}
}
}
)
})
// Action buttons
const actionEvent = (action) => () => {
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
chrome.tabs.sendMessage(tabs[0].id, { [action.id]: true })
})
}
document.addEventListener('DOMContentLoaded', function () {
// Add change listeners to switches
var i, x
x = document.querySelectorAll('button')
for (i = 0; i < x.length; i++) {
x[i].addEventListener('click', actionEvent(x[i]))
}
})
// Feed hide by keywords
const feedKeywordList = [
'Be the first to comment',
'Be the first to react',
'New post in',
'Jobs recommended for you',
]
const feedKeywords = document.querySelector('input[id=hide-by-keywords]')
const feedTagify = new Tagify(feedKeywords, {
whitelist: feedKeywordList,
dropdown: {
position: 'input',
enabled: 0,
placeAbove: true,
},
originalInputValueFormat: (valuesArr) =>
valuesArr.map((item) => item.value).join(', '),
})
function onChange(e) {
chrome.storage.local.set({ 'feed-keywords': e.target.value }, () => {})
}
feedKeywords.addEventListener('change', onChange)
window.onload = function () {
chrome.storage.local.get('feed-keywords', function (res) {
feedTagify.addTags(res['feed-keywords'])
})
}
|
var webpack = require("webpack")
var WebpackDevServer = require("webpack-dev-server")
var config = require("./webpack.config")
new WebpackDevServer(webpack(config), {
publicPath: config.output.publicPath,
hot: true,
historyApiFallback: true
}).listen(5000, "localhost", function (err, result) {
if (err) {
console.log(err)
}
console.log("\nListening at localhost: 5000\n")
})
var WebSocketServer = require("ws").Server
var wss = new WebSocketServer({ port: 5001 })
var connections = {}
wss.on("connection", function connection(ws) {
var uuid = "" + Math.random()
connections[uuid] = ws
ws.on("message", function incoming(message) {
message.sender = ws.uuid
broadcast(uuid, message)
})
})
function broadcast(sender, message) {
console.log("\n" + message)
for (var key in connections)
if (key !== sender) {
try {
connections[key].send(message)
} catch (e) {
delete connections[key]
}
}
}
|
import 'moment/locale/it';
import { cardinal } from 'locale/grammars/italian';
const phrases = {
'action-badge-add': "aggiungere",
'action-badge-approve': "approvare",
'action-badge-archive': "archiviare",
'action-badge-disable': "disattivare",
'action-badge-reactivate': "riattivare",
'action-badge-remove': "rimuovere",
'action-badge-restore': "ripristinare",
'activity-chart-legend-branch': "Nuovi branch",
'activity-chart-legend-issue': "Problemi",
'activity-chart-legend-member': "Cambiamenti di appartenenza",
'activity-chart-legend-merge': "Merge",
'activity-chart-legend-merge-request': "Merge richieste",
'activity-chart-legend-milestone': "Traguardi",
'activity-chart-legend-post': "Post",
'activity-chart-legend-push': "Push",
'activity-chart-legend-repo': "Cambiamenti del repository",
'activity-chart-legend-survey': "Sondaggi",
'activity-chart-legend-tag': "Tag",
'activity-chart-legend-task-list': "Elenchi di attività",
'activity-chart-legend-wiki': "Modifiche wiki",
'activity-tooltip-$count': (count) => {
return cardinal(count, "1 storia", "2 storie");
},
'activity-tooltip-$count-branch': (count) => {
return `${count} branch`;
},
'activity-tooltip-$count-issue': (count) => {
return cardinal(count, "1 problema", "2 problemi");
},
'activity-tooltip-$count-member': (count) => {
return cardinal(count, "1 cambiamento di appartenenza", "2 cambiamenti di appartenenza");
},
'activity-tooltip-$count-merge': (count) => {
return `${count} merge`;
},
'activity-tooltip-$count-merge-request': (count) => {
return cardinal(count, "1 merge richiesta", "2 merge richieste");
},
'activity-tooltip-$count-milestone': (count) => {
return cardinal(count, "1 traguardo", "2 traguardi");
},
'activity-tooltip-$count-post': (count) => {
return `${count} post`;
},
'activity-tooltip-$count-push': (count) => {
return `${count} push`;
},
'activity-tooltip-$count-repo': (count) => {
return cardinal(count, "1 cambiamento del repository", "2 cambiamenti del repository");
},
'activity-tooltip-$count-survey': (count) => {
return cardinal(count, "1 sondaggio", "2 sondaggi");
},
'activity-tooltip-$count-tag': (count) => {
return `${count} tag`;
},
'activity-tooltip-$count-task-list': (count) => {
return cardinal(count, "1 elenco di attività", "2 elenchi di attività");
},
'activity-tooltip-$count-wiki': (count) => {
return cardinal(count, "1 modifica wiki", "2 modifiche Wiki");
},
'app-name': "Trambar",
'app-title': "Trambar - Console amministrativa",
'confirmation-cancel': "Annulla",
'confirmation-confirm': "Conferma",
'confirmation-data-loss': "Sei sicuro di voler abbandonare le modifiche che hai apportato?",
'date-range-$start-$end': (start, end) => {
if (start) {
if (end) {
return `${start}–${end}`;
} else {
return `${start}–`;
}
}
return "";
},
'image-album-cancel': "Annulla",
'image-album-done': "Fatto",
'image-album-manage': "Gestisci album",
'image-album-remove': "Rimuovi i selezionati",
'image-album-select': "Utilizzare il selezionato",
'image-album-upload': "Carica file",
'image-cropping-cancel': "Annulla",
'image-cropping-select': "OK",
'image-selector-choose-from-album': "Scegli dall'album",
'image-selector-crop-image': "Regola dimensione/posizione",
'image-selector-upload-file': "Carica immagine",
'member-list-$name-with-$username': (name, username) => {
if (name) {
if (username) {
return `${name} (${username})`;
} else {
return name;
}
} else {
return username;
}
},
'member-list-add': "Aggiungi un nuovo utente",
'member-list-approve-all': "Approva tutte le richieste",
'member-list-cancel': "Annulla",
'member-list-edit': "Modifica la lista dei membri",
'member-list-reject-all': "Rifiuta tutte le richieste",
'member-list-save': "Salva la lista dei membri",
'member-list-status-non-member': "Non un membro",
'member-list-status-pending': "Richiesta in sospeso",
'member-list-title': "Membri",
'nav-member-new': "Nuovo membro",
'nav-members': "Membri",
'nav-project-new': "Nuovo progetto",
'nav-projects': "Progetti",
'nav-repositories': "Repositories",
'nav-role-new': "Nuovo ruolo",
'nav-roles': "Ruoli",
'nav-server-new': "Nuovo server",
'nav-servers': "Server",
'nav-settings': "Impostazioni",
'nav-user-new': "Nuovo utente",
'nav-users': "Utenti",
'project-list-add': "Aggiungi un nuovo progetto",
'project-list-cancel': "Annulla",
'project-list-confirm-archive-$count': (count) => {
let projects = cardinal(count, "il progetto selezionato", "questi 2 progetti");
return `Sei sicuro di voler archiviare ${projects}?`;
},
'project-list-confirm-restore-$count': (count) => {
let projects = cardinal(count, "il progetto selezionato", "questi 2 progetti");
return `Sei sicuro di voler ripristinare ${projects}?`;
},
'project-list-edit': "Modifica la lista dei progetti",
'project-list-save': "Salva la lista dei progetti",
'project-list-status-archived': "Archiviato",
'project-list-status-deleted': "Eliminato",
'project-list-title': "Progetti",
'project-summary-$title': (title) => {
let text = "Progetto";
if (title) {
text += `: ${title}`;
}
return text;
},
'project-summary-access-control': "Controllo di accesso",
'project-summary-access-control-member-only': "I contenuti del progetto sono riservati ai soli membri",
'project-summary-access-control-non-member-comment': "I non membri possono commentare storie",
'project-summary-access-control-non-member-view': "I non membri possono visualizzare i contenuti",
'project-summary-add': "Aggiungi un nuovo progetto",
'project-summary-archive': "Archivia il progetto",
'project-summary-cancel': "Annulla",
'project-summary-confirm-archive': "Sei sicuro di voler archiviare questo progetto?",
'project-summary-confirm-delete': "Sei sicuro di voler eliminare questo progetto?",
'project-summary-confirm-restore': "Sei sicuro di voler ripristinare questo progetto?",
'project-summary-delete': "Elimina il progetto",
'project-summary-description': "Descrizione",
'project-summary-edit': "Modifica il progetto",
'project-summary-emblem': "Emblema",
'project-summary-name': "Identifier",
'project-summary-new-members': "Nuovi membri",
'project-summary-new-members-auto-accept-guest': "Gli utenti ospiti sono accettati automaticamente",
'project-summary-new-members-auto-accept-user': "Gli utenti regolari sono accettati automaticamente",
'project-summary-new-members-join-guest': "Gli utenti ospiti possono richiedere di partecipare al progetto",
'project-summary-new-members-join-user': "Gli utenti regolari possono richiedere di partecipare al progetto",
'project-summary-new-members-manual': "I membri vengono aggiunti manualmente",
'project-summary-other-actions': "Altre azioni",
'project-summary-restore': "Ripristina il progetto",
'project-summary-return': "Ritorna alla lista dei progetti",
'project-summary-save': "Salva il progetto",
'project-summary-statistics': "Attività",
'project-summary-title': "Nome",
'project-tooltip-$count-others': (count) => {
return (count === 1) ? `altro` : `altri ${count}`;
},
'repo-list-cancel': "Annulla",
'repo-list-confirm-remove-$count': (count) => {
let repositories = cardinal(count, "il repository selezionato", "questoi 2 repository");
return `Sei sicuro di voler rimuovere ${repositories} dal progetto?`;
},
'repo-list-edit': "Modifica la lista dei repository",
'repo-list-issue-tracker-enabled-false': "",
'repo-list-issue-tracker-enabled-true': "Attivato",
'repo-list-save': "Salva la lista dei repository",
'repo-list-title': "Repositories",
'repo-summary-$title': (title) => {
let text = `Repository`;
if (title) {
text += `: ${title}`;
}
return text;
},
'repo-summary-cancel': "Annulla",
'repo-summary-confirm-remove': "Sei sicuro di voler rimuovere questo repository dal progetto?",
'repo-summary-confirm-restore': "Sei sicuro di voler aggiungere nuovamente questo repository al progetto?",
'repo-summary-edit': "Modifica il repository",
'repo-summary-gitlab-name': "Nome del repository in GitLab",
'repo-summary-issue-tracker': "Bug tracker",
'repo-summary-issue-tracker-disabled': "Disattivato",
'repo-summary-issue-tracker-enabled': "Attivato",
'repo-summary-remove': "Rimuovi il repository",
'repo-summary-restore': "Ripristina il repository",
'repo-summary-return': "Ritorna alla lista dei repository",
'repo-summary-save': "Salva il repository",
'repo-summary-statistics': "Attività",
'repo-summary-title': "Nome",
'repository-tooltip-$count': (count) => {
return `${count} repository`;
},
'role-list-add': "Aggiungi un nuovo ruolo",
'role-list-cancel': "Annulla",
'role-list-confirm-disable-$count': (count) => {
let roles = cardinal(count, "il ruolo selezionato", "questi 2 ruoli");
return `Sei sicuro di voler disattivare ${roles}?`
},
'role-list-confirm-reactivate-$count': (count) => {
let roles = cardinal(count, "il ruolo selezionato", "questi 2 ruoli");
return `Sei sicuro di voler riattivare questo ${roles}?`
},
'role-list-edit': "Modifica la lista dei ruoli",
'role-list-save': "Salva la lista dei ruoli",
'role-list-status-deleted': "Eliminato",
'role-list-status-disabled': "Disattivato",
'role-list-title': "Ruoli",
'role-summary-$title': (title) => {
let text = "Ruolo";
if (title) {
text += `: ${title}`;
}
return text;
},
'role-summary-add': "Aggiungi un nuovo ruolo",
'role-summary-cancel': "Annulla",
'role-summary-confirm-delete': "Sei sicuro di voler eliminare questo ruolo?",
'role-summary-confirm-disable': "Sei sicuro di voler disattivare questo ruolo?",
'role-summary-confirm-reactivate': "Sei sicuro di voler riattivare questo ruolo?",
'role-summary-delete': "Elimina il ruolo",
'role-summary-description': "Descrizione",
'role-summary-disable': "Disattiva il ruolo",
'role-summary-edit': "Modifica il ruolo",
'role-summary-name': "Identifier",
'role-summary-rating': "Priorità delle storie",
'role-summary-rating-high': "Alta",
'role-summary-rating-low': "Bassa",
'role-summary-rating-normal': "Normale",
'role-summary-rating-very-high': "Molto alta",
'role-summary-rating-very-low': "Molto bassa",
'role-summary-reactivate': "Riattivare ruolo",
'role-summary-return': "Ritorna alla lista dei ruoli",
'role-summary-save': "Salva il ruolo",
'role-summary-title': "Nome",
'role-summary-users': "Utenti",
'role-tooltip-$count-others': (count) => {
return (count === 1) ? `Altro 1` : `Altri ${count}`;
},
'server-list-add': "Aggiungi un nuovo server",
'server-list-api-access-false': "",
'server-list-api-access-true': "Acquisito",
'server-list-cancel': "Annulla",
'server-list-confirm-disable-$count': (count) => {
let servers = cardinal(count, "il server selezionato", "questi 2 server");
return `Sei sicuro di voler disattivare ${servers}?`
},
'server-list-confirm-reactivate-$count': (count) => {
let servers = cardinal(count, "il server selezionato", "questi 2 server");
return `Sei sicuro di voler riattivare ${servers}?`
},
'server-list-edit': "Modifica la lista dei server",
'server-list-oauth-false': "",
'server-list-oauth-true': "Attivo",
'server-list-save': "Salva la lista dei server",
'server-list-status-deleted': "Eliminato",
'server-list-status-disabled': "Disattivato",
'server-list-title': "Server",
'server-summary-acquire': "Acquisisci l'accesso API",
'server-summary-activities': "Attività",
'server-summary-add': "Aggiungi new server",
'server-summary-api-access': "Accesso API",
'server-summary-api-access-acquired': "Accesso amministrativo acquisito",
'server-summary-api-access-not-applicable': "Non applicabile",
'server-summary-api-access-pending': "In attesa di azione dell'utente",
'server-summary-cancel': "Annulla",
'server-summary-confirm-delete': "Sei sicuro di voler eliminare questo server?",
'server-summary-confirm-disable': "Sei sicuro di voler disattivare questo server?",
'server-summary-confirm-reactivate': "Sei sicuro di voler riattivare questo server?",
'server-summary-delete': "Elimina il server",
'server-summary-disable': "Disattiva il server",
'server-summary-edit': "Modifica il server",
'server-summary-gitlab-admin': "Amministratore GitLab",
'server-summary-gitlab-external-user': "Utente esterno GitLab",
'server-summary-gitlab-regular-user': "Utente normale GitLab",
'server-summary-member-$name': (name) => {
return `Server: ${name}`;
},
'server-summary-name': "Identifier",
'server-summary-new-user': "Nuovo utente",
'server-summary-new-users': "Nuovi utenti",
'server-summary-oauth-app-id': "ID app",
'server-summary-oauth-app-key': "Chiave app",
'server-summary-oauth-app-secret': "Segreto app",
'server-summary-oauth-application-id': "ID applicazione",
'server-summary-oauth-application-secret': "Segreto applicazione",
'server-summary-oauth-callback-url': "URL di callback",
'server-summary-oauth-client-id': "ID client",
'server-summary-oauth-client-secret': "Segreto client",
'server-summary-oauth-deauthorize-callback-url': "URL di callback di deauthorization",
'server-summary-oauth-gitlab-url': "URL del server GitLab",
'server-summary-oauth-redirect-uri': "URI di reindirizzamento",
'server-summary-oauth-redirect-url': "URL di reindirizzamento",
'server-summary-oauth-site-url': "Indirizzo del sito",
'server-summary-privacy-policy-url': "URL della politica sulla privacy",
'server-summary-reactivate': "Riattivare il server",
'server-summary-return': "Ritorna alla litsa dei server",
'server-summary-role-none': "Non assegnare alcun ruolo ai nuovi utenti",
'server-summary-roles': "Assegnazione del ruolo",
'server-summary-save': "Salva il server",
'server-summary-system-address-missing': "L'indirizzo di sistema non è stato impostato",
'server-summary-terms-and-conditions-url': "Termini e condizioni URL",
'server-summary-test-oauth': "Prova l'integrazione con OAuth",
'server-summary-title': "Nome",
'server-summary-type': "Tipo di server",
'server-summary-user-automatic-approval': "Approva automaticamente i nuovi utenti",
'server-summary-user-import-disabled': "Non registrare nuovi utenti",
'server-summary-user-import-gitlab-admin-disabled': "Non importare gli amministratori GitLab",
'server-summary-user-import-gitlab-external-user-disabled': "Non importare utenti esterni GitLab",
'server-summary-user-import-gitlab-user-disabled': "Non importare utenti normale GitLab",
'server-summary-user-type-admin': "Amministratore",
'server-summary-user-type-guest': "Utente ospite",
'server-summary-user-type-moderator': "Moderatore",
'server-summary-user-type-regular': "Utente normale",
'server-summary-whitelist': "Lista bianca indirizzo email",
'server-type-dropbox': "Dropbox",
'server-type-facebook': "Facebook",
'server-type-github': "GitHub",
'server-type-gitlab': "GitLab",
'server-type-google': "Google",
'server-type-windows': "Windows Live",
'settings-background-image': "Immagine di sfondo",
'settings-cancel': "Annulla",
'settings-company-name': "Nome della ditta",
'settings-edit': "Modifica settings",
'settings-input-languages': "Lingue di input",
'settings-push-relay': "Relè di notifica push",
'settings-save': "Salva le impostazioni",
'settings-site-address': "Indirizzo",
'settings-site-description': "Descrizione",
'settings-site-title': "Nome del sito",
'settings-title': "Impostazioni",
'sign-in-$title': (title) => {
let text = `Accedi`;
if (title) {
text += `: ${title}`;
}
return text;
},
'sign-in-error-access-denied': "Richiesta di accesso rifiutata",
'sign-in-error-account-disabled': "L'account è attualmente disabilitato",
'sign-in-error-existing-users-only': "Solo il personale autorizzato può accedere a questo sistema",
'sign-in-error-restricted-area': "L'utente non è un amministratore",
'sign-in-oauth': "Accedi utilizzando OAuth",
'sign-in-password': "Password:",
'sign-in-problem-incorrect-username-password': "Nome utente o password errati",
'sign-in-problem-no-support-for-username-password': "Il sistema non accetta la password",
'sign-in-problem-unexpected-error': "Si è verificato un errore imprevisto",
'sign-in-submit': "Invia",
'sign-in-username': "Nome utente:",
'sign-off-menu-sign-off': "Disconnettersi",
'table-heading-api-access': "Accesso API",
'table-heading-date-range': "Periodo attivo",
'table-heading-email': "E-mail",
'table-heading-issue-tracker': "Bug tracker",
'table-heading-last-modified': "Ultima modifica",
'table-heading-last-month': "Lo scorso mese",
'table-heading-name': "Nome e cognome",
'table-heading-oauth': "Autenticazione OAuth",
'table-heading-projects': "Progetti",
'table-heading-repositories': "Repository",
'table-heading-roles': "Ruoli",
'table-heading-server': "Server",
'table-heading-this-month': "Questo mese",
'table-heading-title': "Nome",
'table-heading-to-date': "Ad oggi",
'table-heading-type': "Tipo",
'table-heading-username': "Nome utente",
'table-heading-users': "Utenti",
'task-$seconds': (seconds) => {
return (seconds === 1) ? `1 secondo` : `${seconds} secondi`;
},
'task-imported-$count-commit-comments-from-$repo': (count, repo) => {
if (count === 1) {
return `Si 1 commento del commit è importato dal repository «${repo}»`;
} else {
return `Si ${count} commenti del commit sono importati dal repository «${repo}»`;
}
},
'task-imported-$count-events-from-$repo': (count, repo) => {
if (count === 1) {
return `Si 1 evento è importato dal repository «${repo}»`;
} else {
return `Si ${count} eventi sono importati dal repository «${repo}»`;
}
},
'task-imported-$count-issue-comments-from-$repo': (count, repo) => {
if (count === 1) {
return `Si 1 commento del problema è importato dal repository «${repo}»`;
} else {
return `Si ${count} commenti del problema sono importati dal repository «${repo}»`;
}
},
'task-imported-$count-merge-request-comments-from-$repo': (count, repo) => {
if (count === 1) {
return `Si 1 commento delle merge richieste è importato dal repository «${repo}»`;
} else {
return `Si ${count} commenti delle merge richieste sono importati dal repository «${repo}»`;
}
},
'task-imported-$count-repos': (count) => {
if (count === 1) {
return `Si 1 repository è importato`;
} else {
return `Si ${count} repository sono importati`;
}
},
'task-imported-$count-users': (count) => {
if (count === 1) {
return `Si 1 utente è importato`;
} else {
return `Si ${count} utenti sono importati`;
}
},
'task-imported-push-with-$count-commits-from-$repo-$branch': (count, repo, branch) => {
let commits = `${count} commit`;
return `Si un push con ${commits} è importato dal branch «${branch}» del repository «${repo}»`
},
'task-importing-commit-comments-from-$repo': (repo) => {
return `Si sta importando i commenti del commit dal repository «${repo}»`;
},
'task-importing-events-from-$repo': (repo) => {
return `Si sta importando gli eventi dal repository «${repo}»`;
},
'task-importing-issue-comments-from-$repo': (repo) => {
return `Si sta importando i commenti del problema dal repository «${repo}»`;
},
'task-importing-merge-request-comments-from-$repo': (repo) => {
return `Si sta importando i commenti delle merge richieste dal repository «${repo}»`;
},
'task-importing-push-from-$repo': (repo) => {
return `Si sta importando un push dal repository «${repo}»`;
},
'task-importing-repos': "Si sta importando i repository",
'task-importing-users': "Si sta importando gli utenti",
'task-installed-$count-hooks': (count) => {
if (count === 1) {
return `Si 1 webhook è installato`;
} else {
return `Si ${count} webhook sono installati`;
}
},
'task-installing-hooks': "Si sta installando i webhook",
'task-removed-$count-hooks': (count) => {
if (count === 1) {
return `Si 1 webhook è disinstallato`;
} else {
return `Si ${count} webhook sono disinstallati`;
}
},
'task-removed-$count-repos': (count) => {
if (count === 1) {
return `Si 1 repository è rimosso`;
} else {
return `Si ${count} repository sono rimossi`;
}
},
'task-removed-$count-users': (count) => {
if (count === 1) {
return `Si 1 utente è rimosso`;
} else {
return `Si ${count} utenti sono rimossi`;
}
},
'task-removing-hooks': "Si sta disinstallando i webhook",
'task-updated-$count-repos': (count) => {
if (count === 1) {
return `Si 1 repository è modificato`;
} else {
return `Si ${count} repository sono modificati`;
}
},
'task-updated-$count-users': (count) => {
if (count === 1) {
return `Si 1 utente è modificato`;
} else {
return `Si ${count} utenti sono modificati`;
}
},
'text-field-placeholder-none': "nessuno",
'tooltip-$first-and-$tooltip': (first, tooltip) => {
return [ first, ' e ', tooltip ];
},
'tooltip-more': "Altri",
'upload-progress-uploading-$count-files-$size-remaining': (count, size) => {
return `Caricamento di ${count} file, ${size} rimanenti`;
},
'user-list-add': "Aggiungi un nuovo utente",
'user-list-approve-all': "Approva tutte le richieste",
'user-list-cancel': "Annulla",
'user-list-confirm-disable-$count': (count) => {
let accounts = cardinal(count, "l'account utente selezionato", [ "questi", "account utente" ], true);
return `Sei sicuro di voler disabilitare ${accounts}?`
},
'user-list-confirm-reactivate-$count': (count) => {
let accounts = cardinal(count, "l'account utente selezionato", [ "questi", "account utente" ], true);
return `Sei sicuro di voler riattivare questo ${accounts}?`
},
'user-list-edit': "Modifica la lista degli utenti",
'user-list-reject-all': "Rifiuta tutte le richieste",
'user-list-save': "Salva la lista degli utenti",
'user-list-status-deleted': "Eliminato",
'user-list-status-disabled': "Disabilitato",
'user-list-status-pending': "In attesa",
'user-list-title': "Utenti",
'user-list-type-admin': "Amministratore",
'user-list-type-guest': "Utente ospite",
'user-list-type-moderator': "Moderatore",
'user-list-type-regular': "Utente normale",
'user-summary-$name': (name) => {
let text = "Utente";
if (name) {
text += `: ${name}`;
}
return text;
},
'user-summary-add': "Aggiungi un nuovo utente",
'user-summary-cancel': "Annulla",
'user-summary-confirm-delete': "Sei sicuro di voler eliminare questo account utente?",
'user-summary-confirm-disable': "Sei sicuro di voler disabilitare questo account utente?",
'user-summary-confirm-reactivate': "Sei sicuro di voler riattivare questo account utente?",
'user-summary-delete': "Elimina l'account utente",
'user-summary-disable': "Disabilita l'account utente",
'user-summary-edit': "Modifica l'account utente",
'user-summary-email': "Indirizzo e-mail",
'user-summary-github': "URL del profilo GitHub",
'user-summary-gitlab': "URL del profilo GitLab",
'user-summary-ichat': "Nome utente iChat",
'user-summary-linkedin': "URL del profilo LinkedIn",
'user-summary-member-$name': (name) => {
let text = "Membro";
if (name) {
text += `: ${name}`;
}
return text;
},
'user-summary-member-edit': "Modifica il membro",
'user-summary-member-return': "Ritorna alla lista dei membri",
'user-summary-member-save': "Salva il membro",
'user-summary-name': "Nome e cognome",
'user-summary-phone': "Numero di telefono",
'user-summary-profile-image': "Immagine del profilo",
'user-summary-reactivate': "Riattiva l'account utente",
'user-summary-return': "Ritorna allala lista degli utenti",
'user-summary-role-none': "Nessun",
'user-summary-roles': "Ruoli",
'user-summary-save': "Salva il utente",
'user-summary-skype': "Nome utente Skype",
'user-summary-slack': "ID utente Slack",
'user-summary-slack-team': "ID della squadra Slack",
'user-summary-social-links': "Collegamenti di social network",
'user-summary-stackoverflow': "URL del profilo StackOverflow",
'user-summary-statistics': "Attività",
'user-summary-twitter': "Nome utente Twitter",
'user-summary-type': "Tipo di utente",
'user-summary-type-admin': "Amministratore",
'user-summary-type-guest': "Utente ospite",
'user-summary-type-moderator': "Moderatore",
'user-summary-type-regular': "Utente normale",
'user-summary-username': "Nome utente",
'user-tooltip-$count': (count) => {
return cardinal(count, "1 utente", "2 untenti");
},
'validation-duplicate-project-name': "Esiste già un progetto con quell'identificatore",
'validation-duplicate-role-name': "Esiste già un ruolo con quell'identificatore",
'validation-duplicate-server-name': "Un server con quell'identificatore esiste già",
'validation-duplicate-user-name': "Esiste già un utente con quel nome",
'validation-illegal-project-name': "L'identificatore del progetto non può essere «global», «admin», «public» o «srv»",
'validation-localhost-is-wrong': "«localhost» non è valido",
'validation-password-for-admin-only': "Solo gli amministratori possono accedere utilizzando la password",
'validation-required': "Necessario",
'welcome': "Benvenuto!",
};
export {
phrases,
};
|
const category = state => state.category;
export default {
category
};
|
import React, { Component } from "react";
import Avatar from "../assets/avatar.svg";
class Aboutme extends Component {
state = {};
render() {
return (
<div className="face-rec">
<div className="text-button-wrapper">
<h2>Who I am and What I do</h2>
<p>I am Elaheh and currently I am a web development student.</p>
<p>
I’ve always been drawn to technology and design. After years of
academic tarining in other fields , and some unexpected turns in
life,I finally decided to shift my focus on web development AND I
found it amazing! I value teamwork as an essential part of any
project as well as being dedicated to fulfill the tasks as an
individual.
</p>
<p>
I’ve started putting more consideration in strategies and best
practices of structuring code for better efficiency and
maintanability of projects.You can also see some of the technologies
that I work with on the right/below!
</p>
<div className="buttons">
<a href="https://www.linkedin.com/in/elaheharjomandi/">
<div className="app-btn">Get in toch</div>
</a>
</div>
</div>
<img id="phone" src={Avatar} alt="" />
</div>
);
}
}
export default Aboutme;
|
import React, {useState} from 'react';
import useFormless from "react-useformless";
import classnames from "classnames"
import { Textarea, Checkbox } from "../Elements";
import { ProfileForm } from "./ProfileForm";
import { AddressForm } from "./AddressForm";
import { StateDataFormless } from "./StateDataFormless";
export default (props) => {
const [isOpen, toggle] = useState(false)
const { values, touched, errors, party, reset, onSubmit, validateForm, field } = useFormless({
onSuccess: (ev) => {
ev.preventDefault()
toggle(true)
},
onError: (ev) => {
ev.preventDefault()
},
validate: (name, value) => {
const validations = {
terms: value === false && 'you must accept terms!',
aboutyou: value === '' && 'please tell us a little bit about you',
}
return validations[name] || ''
}
})
return (
<>
<form onSubmit={onSubmit} {...props}>
<ProfileForm party={party}/>
<AddressForm party={party} />
<Textarea label="About you" field={field('aboutyou')} />
<Checkbox label="Accept the terms and conditions" field={field('terms', false)}/>
<div className="field">
<div className="buttons has-addons">
<button className="button is-primary is-outlined" type="button" onClick={validateForm}>validate form</button>
<button className="button is-dark" type="button" onClick={reset}>reset</button>
<button className="button is-success" type="submit">Send</button>
</div>
</div>
</form>
<StateDataFormless className="column" values={values} touched={touched} errors={errors}/>
<div className={classnames("modal", {'is-active': isOpen})}>
<div className="modal-background"></div>
<div className="modal-content">
<div className="box has-text-centered has-text-success">
Validation has passed!
</div>
</div>
<button className="modal-close is-large" onClick={() => toggle(false)} aria-label="close"></button>
</div>
</>)
}
|
/** @type {import('vls').VeturConfig} */
module.exports = {
// **optional** default: `{}`
// override vscode settings
// Notice: It only affects the settings used by Vetur.
settings: {
'vetur.useWorkspaceDependencies': true,
'vetur.experimental.templateInterpolationService': true
},
// **optional** default: `[{ root: './' }]`
// support monorepos
projects: [
{
// **required**
// Where is your project?
// It is relative to `vetur.config.js`.
root: './src/renderer',
// **optional** default: `'package.json'`
// Where is `package.json` in the project?
// We use it to determine the version of vue.
// It is relative to root property.
package: '../../package.json',
// **optional**
// Where is TypeScript config file in the project?
// It is relative to root property.
tsconfig: './tsconfig.json',
// **optional** default: `[]`
// Register globally Vue component glob.
// If you set it, you can get completion by that components.
// It is relative to root property.
// Notice: It won't actually do it. You need to use `require.context` or `Vue.component`
globalComponents: [
'./components/**/*.vue'
]
}
]
}
|
/**
* Auto-generated action file for "Cloud SQL Admin" API.
*
* Generated at: 2019-05-23T09:13:42.479Z
* Mass generator version: 1.1.0
*
* flowground :- Telekom iPaaS / googleapis-com-sqladmin-connector
* Copyright © 2019, Deutsche Telekom AG
* contact: flowground@telekom.de
*
* All files of this connector are licensed under the Apache 2.0 License. For details
* see the file LICENSE on the toplevel directory.
*
*
* Operation: 'sql.operations.list'
* Endpoint Path: '/projects/{project}/operations'
* Method: 'get'
*
*/
const Swagger = require('swagger-client');
const processWrapper = require('../services/process-wrapper');
const spec = require('../spec.json');
// this wrapers offers a simplified emitData(data) function
module.exports.process = processWrapper(processAction);
// parameter names for this call
const PARAMETERS = [
"instance",
"maxResults",
"pageToken",
"project",
"prettyPrint",
"quotaUser",
"userIp"
];
// mappings from connector field names to API field names
const FIELD_MAP = {
"instance": "instance",
"maxResults": "maxResults",
"pageToken": "pageToken",
"project": "project",
"prettyPrint": "prettyPrint",
"quotaUser": "quotaUser",
"userIp": "userIp"
};
function processAction(msg, cfg) {
var isVerbose = process.env.debug || cfg.verbose;
if (isVerbose) {
console.log(`---MSG: ${JSON.stringify(msg)}`);
console.log(`---CFG: ${JSON.stringify(cfg)}`);
console.log(`---ENV: ${JSON.stringify(process.env)}`);
}
const contentType = undefined;
const body = msg.body;
mapFieldNames(body);
let parameters = {};
for(let param of PARAMETERS) {
parameters[param] = body[param];
}
// credentials for this operation
let securities = {};
securities['Oauth2'] = {token: cfg['auth_Oauth2']};
let callParams = {
spec: spec,
operationId: 'sql.operations.list',
pathName: '/projects/{project}/operations',
method: 'get',
parameters: parameters,
requestContentType: contentType,
requestBody: body.requestBody,
securities: {authorized: securities},
server: spec.servers[cfg.server] || cfg.otherServer,
};
if (isVerbose) {
let out = Object.assign({}, callParams);
out.spec = '[omitted]';
console.log(`--SWAGGER CALL: ${JSON.stringify(out)}`);
}
// Call operation via Swagger client
return Swagger.execute(callParams).then(data => {
// emit a single message with data
this.emitData(data);
// if the response contains an array of entities, you can emit them one by one:
// data.obj.someItems.forEach((item) => {
// this.emitData(item);
// }
});
}
function mapFieldNames(obj) {
if(Array.isArray(obj)) {
obj.forEach(mapFieldNames);
}
else if(typeof obj === 'object' && obj) {
Object.keys(obj).forEach(key => {
mapFieldNames(obj[key]);
let goodKey = FIELD_MAP[key];
if(goodKey && goodKey !== key) {
obj[goodKey] = obj[key];
delete obj[key];
}
});
}
}
|
import React from 'react'
import { Link } from "gatsby"
import { css } from '@emotion/core'
import fallBackImage from '../images/cape-makers-things.png';
const style = css`
margin-bottom: 1.5rem;
display: flex;
flex-direction: column;
background-color: rgba(0, 147, 208, 0.2);
@media (min-width: 768px) {
flex-direction: row;
}
.blog-cover {
img {
display: block;
width: 100%;
}
@media (min-width: 768px) {
flex: 0 0 25%;
}
@media (min-width: 992px) {
flex: 0 0 33%;
}
}
.blog-content {
padding: 1rem;
h3 {
margin: 0;
}
@media (min-width: 768px) {
flex: 1 1 auto;
}
@media (min-width: 992px) {
font-size: 1.1rem;
}
time {
display: block;
}
}
`
const BlogCard = ({
uri,
title,
date,
summary,
coverPicture
}) => {
return (
<div css={style}>
{coverPicture ? (
<Link className="blog-cover" to={uri}>
<img src={coverPicture} alt={`${title}`} />
</Link>
) : (
<Link className="blog-cover" to={uri}>
<img src={fallBackImage} alt={`${title}`} />
</Link>
)}
<div className="blog-content">
<Link to={uri}><h3>{title}</h3></Link>
<time>{date}</time>
<p>{summary}</p>
<Link className="button" to={uri}>View More</Link>
</div>
</div>
)
}
export default BlogCard
|
import gql from 'graphql-tag';
export default gql`
subscription data {
suscribe_to_patch_propuesta_delete_moderador {
id
propuesta {
id
titulo
descripcion
}
usuario {
id
nombre
avatar
}
}
}
`;
|
'use strict';
require('../common');
var assert = require('assert');
var r = process.memoryUsage();
assert.ok(r.rss > 0);
assert.ok(r.heapTotal > 0);
assert.ok(r.heapUsed > 0);
|
$(document).ready(() => {
// Getting references to our form and input
var signUpForm = $("form.signup");
var emailInput = $("input#email-input");
var passwordInput = $("input#password-input");
// When the signup button is clicked, we validate the email and password are not blank
signUpForm.on("submit", function(event) {
event.preventDefault();
var userData = {
email: emailInput.val().trim(),
password: passwordInput.val().trim()
};
if (!userData.email || !userData.password) {
return;
}
// If we have an email and password, run the signUpUser function
signUpUser(userData.email, userData.password);
emailInput.val("");
passwordInput.val("");
});
// Does a post to the signup route. If successful, we are redirected to the members page
// Otherwise we log any errors
function signUpUser(email, password) {
$.post("/api/signup", {
email: email,
password: password
})
.then(function(data) {
window.location.replace("/members");
// If there's an error, handle it by throwing up a bootstrap alert
})
.catch(handleSignupErr);
}
function handleSignupErr(err) {
console.log(err)
if(err.responseJSON.errors[0].message = "accounts.email must be unique") {
$("#alert .msg").text(` ${err.responseJSON.errors[0].value} is already taken`);
$("#alert").fadeIn(500);
} else {
$("#alert .msg").text(` Unknown`);
$("#alert").fadeIn(500);
};
}
});
|
/*!
* OpenUI5
* (c) Copyright 2009-2021 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
// Provides control sap.m.MessageListItem.
sap.ui.define([
"sap/ui/core/library",
"sap/ui/core/InvisibleText",
"./library",
'./StandardListItem',
'./Link',
"./MessageListItemRenderer"
],
function (coreLibrary, InvisibleText, library, StandardListItem, Link, MessageListItemRenderer) {
"use strict";
// shortcut for sap.ui.core.MessageType
var MessageType = coreLibrary.MessageType;
/**
* Constructor for a new MessageListItem.
*
* @param {string} [sId] Id for the new control, generated automatically if no id is given
* @param {object} [mSettings] Initial settings for the new control
*
* @class
* <code>sap.m.MessageListItem</code> is an extension of the <code>sap.m.StandardListItem</code> with an interactive title.
* @extends sap.m.StandardListItem
*
* @author SAP SE
* @version 1.95.0
*
* @constructor
* @private
* @alias sap.m.MessageListItem
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var MessageListItem = StandardListItem.extend("sap.m.MessageListItem", /** @lends sap.m.MessageListItem.prototype */ {
metadata: {
library: "sap.m",
properties: {
activeTitle: { type: "boolean", group: "Misc", defaultValue: false},
messageType: { type: "sap.ui.core.MessageType", group: "Appearance", defaultValue: MessageType.Error }
},
aggregations: {
link: { type: "sap.m.Link", group: "Misc", multiple: false },
linkAriaDescribedBy: {type: "sap.ui.core.Control", group: "Misc", multiple: false}
},
events: {
activeTitlePress: {}
}
}
});
MessageListItem.prototype.onBeforeRendering = function () {
StandardListItem.prototype.onBeforeRendering.apply(this, arguments);
var oLink = this.getLink(), oDescribedByText;
if (!oLink && this.getActiveTitle()) {
oLink = new Link({
press: [this.fireActiveTitlePress, this]
});
this.setLink(oLink);
}
//prevent unneeded creation of sap.ui.core.InvisibleText
if (oLink && !oLink.getAriaDescribedBy().length) {
oDescribedByText = this._getLinkAriaDescribedBy();
oLink.setProperty("text", this.getTitle(), true);
oLink.addAssociation('ariaDescribedBy', oDescribedByText.getId(), true);
this.setAggregation("linkAriaDescribedBy", oDescribedByText, true);
}
};
MessageListItem.prototype._getLinkAriaDescribedBy = function () {
var sAccessibilityText = sap.ui.getCore().getLibraryResourceBundle("sap.m").getText("MESSAGE_VIEW_LINK_FOCUS_TEXT", [this.getMessageType()]);
return new InvisibleText(this.getId() + "-link", {
text: sAccessibilityText
});
};
/**
* Handles the ALT + Enter event
* @param {jQuery.Event} oEvent - the keyboard event.
* @private
*/
MessageListItem.prototype.onkeydown = function(oEvent) {
if (this.getActiveTitle() && oEvent.altKey && oEvent.key === 'Enter') {
this.fireActiveTitlePress(this);
}
};
MessageListItem.prototype.getContentAnnouncement = function(oBundle) {
var sAnnouncement = StandardListItem.prototype.getContentAnnouncement.apply(this, arguments),
sAdditionalText, sMessageType;
if (this.getActiveTitle()) {
sMessageType = oBundle.getText("MESSAGEVIEW_BUTTON_TOOLTIP_" + this.getMessageType().toUpperCase());
sAdditionalText = oBundle.getText("MESSAGE_LIST_ITEM_FOCUS_TEXT", [sMessageType]);
sAnnouncement += " ".concat(sAdditionalText);
}
return sAnnouncement;
};
return MessageListItem;
});
|
const express = require('express')
const path = require('path')
const port = process.env.PORT || 8080
const app = express()
app.use(express.static(__dirname + '/dist'))
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'index.html'))
})
console.log("Listen on 'localhost:8080...'")
console.log('Ctrl + C to stop')
app.listen(port)
|
'use strict';
const types = require('../utils/types');
const ember = require('../utils/ember');
//------------------------------------------------------------------------------
// General rule - Use brace expansion
//------------------------------------------------------------------------------
module.exports = {
meta: {
docs: {
description: 'Enforces usage of brace expansion',
category: 'Stylistic Issues',
recommended: true,
url:
'https://github.com/ember-cli/eslint-plugin-ember/tree/master/docs/rules/use-brace-expansion.md',
},
fixable: null, // or "code" or "whitespace"
},
create(context) {
const message = 'Use brace expansion';
function report(node) {
context.report(node, message);
}
return {
CallExpression(node) {
if (!ember.isComputedProp(node) || types.isMemberExpression(node.callee)) {
return;
}
const matchesBraces = x => Boolean(x.match(/[{}]/g));
const hasBraces = arr => arr.some(matchesBraces);
const beforeBraces = arr => arr.slice(0, arr.indexOf(arr.find(matchesBraces)));
const arrayDeepEqual = (a, b) =>
a.length === b.length && a.reduce((acc, e, i) => acc && e === b[i], true);
const problem = node.arguments
.filter(
arg =>
types.isLiteral(arg) && typeof arg.value === 'string' && arg.value.indexOf('.') >= 0
)
.map(e => e.value.split('.'))
.find(
(prop, i, props) =>
props.filter(e => {
const propHasBraces = hasBraces(prop);
const eHasBraces = hasBraces(e);
if (propHasBraces && eHasBraces) {
return arrayDeepEqual(beforeBraces(e), beforeBraces(prop));
} else if (!propHasBraces && !eHasBraces) {
return prop[0] === e[0];
}
const withBraces = propHasBraces ? prop : e;
const withoutBraces = propHasBraces ? e : prop;
const shareable = beforeBraces(withBraces);
return arrayDeepEqual(shareable, withoutBraces.slice(0, shareable.length));
}).length > 1
);
if (problem) {
report(node);
}
},
};
},
};
|
/* jshint node: true */
'use strict';
var path = require('path');
var Funnel = require('broccoli-funnel');
var merge = require('broccoli-merge-trees');
module.exports = {
name: 'ember-mobiledoc-dom-renderer',
treeForAddon: function(tree) {
var libRoot = require.resolve('mobiledoc-dom-renderer/lib');
var libPath = path.dirname(libRoot);
var rendererTree = new Funnel(libPath, {
include: ['**/*.js'],
destDir: '/mobiledoc-dom-renderer'
});
var mergedTree = merge([tree, rendererTree]);
return this._super.treeForAddon.call(this, mergedTree);
}
};
|
import UniversalDate from "@ui5/webcomponents-core/dist/sap/ui/core/date/UniversalDate.js";
import Locale from "@ui5/webcomponents-core/dist/sap/ui/core/Locale.js";
import LocaleData from "@ui5/webcomponents-core/dist/sap/ui/core/LocaleData.js";
const calculateWeekNumber = (oDate, iYear, oLocale, oLocaleData) => {
let iWeekNum = 0;
let iWeekDay = 0;
const iFirstDayOfWeek = oLocaleData.getFirstDayOfWeek();
// search Locale for containing "en-US", since sometimes
// when any user settings have been defined, subtag "sapufmt" is added to the locale name
// this is described inside sap.ui.core.Configuration file
if (oLocale && (oLocale.getLanguage() === "en" && oLocale.getRegion() === "US")) {
/*
* in US the week starts with Sunday
* The first week of the year starts with January 1st. But Dec. 31 is still in the last year
* So the week beginning in December and ending in January has 2 week numbers
*/
const oJanFirst = new UniversalDate(oDate.getTime());
oJanFirst.setUTCFullYear(iYear, 0, 1);
iWeekDay = oJanFirst.getUTCDay();
// get the date for the same weekday like jan 1.
const oCheckDate = new UniversalDate(oDate.getTime());
oCheckDate.setUTCDate(oCheckDate.getUTCDate() - oCheckDate.getUTCDay() + iWeekDay);
iWeekNum = Math.round((oCheckDate.getTime() - oJanFirst.getTime()) / 86400000 / 7) + 1;
} else {
// normally the first week of the year is the one where the first Thursday of the year is
// find Thursday of this week
// if the checked day is before the 1. day of the week use a day of the previous week to check
const oThursday = new UniversalDate(oDate.getTime());
oThursday.setUTCDate(oThursday.getUTCDate() - iFirstDayOfWeek);
iWeekDay = oThursday.getUTCDay();
oThursday.setUTCDate(oThursday.getUTCDate() - iWeekDay + 4);
const oFirstDayOfYear = new UniversalDate(oThursday.getTime());
oFirstDayOfYear.setUTCMonth(0, 1);
iWeekDay = oFirstDayOfYear.getUTCDay();
let iAddDays = 0;
if (iWeekDay > 4) {
iAddDays = 7; // first day of year is after Thursday, so first Thursday is in the next week
}
const oFirstThursday = new UniversalDate(oFirstDayOfYear.getTime());
oFirstThursday.setUTCDate(1 - iWeekDay + 4 + iAddDays);
iWeekNum = Math.round((oThursday.getTime() - oFirstThursday.getTime()) / 86400000 / 7) + 1;
}
return iWeekNum;
};
const getFirstDateOfWeek = oDate => {
const oUniversalDate = new UniversalDate(oDate.getTime()),
oLocaleData = LocaleData.getInstance(new Locale("en")),
iCLDRFirstWeekDay = oLocaleData.getFirstDayOfWeek();
const oWeek = UniversalDate.getWeekByDate(oUniversalDate.getCalendarType(), oUniversalDate.getUTCFullYear(),
oUniversalDate.getUTCMonth(), oUniversalDate.getUTCDate());
const oFirstDateOfWeek = UniversalDate.getFirstDateOfWeek(oUniversalDate.getCalendarType(), oWeek.year, oWeek.week);
const oFirstUniversalDateOfWeek = new UniversalDate(Date.UTC(oFirstDateOfWeek.year, oFirstDateOfWeek.month, oFirstDateOfWeek.day));
// In case the day of the computed weekFirstDate is not as in CLDR(e.g. en_US locales), make sure we align it
while (oFirstUniversalDateOfWeek.getUTCDay() !== iCLDRFirstWeekDay) {
oFirstUniversalDateOfWeek.setUTCDate(oFirstUniversalDateOfWeek.getUTCDate() - 1);
}
return new UniversalDate(Date.UTC(oFirstUniversalDateOfWeek.getUTCFullYear(), oFirstUniversalDateOfWeek.getUTCMonth(),
oFirstUniversalDateOfWeek.getUTCDate(), oDate.getUTCHours(), oDate.getUTCMinutes(), oDate.getUTCSeconds())).getJSDate();
};
const getFirstDateOfMonth = oDate => {
const oNewDate = new UniversalDate(oDate.getTime());
oNewDate.setUTCDate(1);
return oNewDate;
};
const monthsDiffer = (oDate1, oDate2) => {
return (oDate1.getMonth() !== oDate2.getMonth() || oDate1.getFullYear() !== oDate2.getFullYear());
};
const isDateLastInMonth = oDate => {
const oNextDay = new Date(oDate.getTime() + 24 * 60 * 60 * 1000);
return oNextDay.getUTCDate() < oDate.getUTCDate();
};
export {
calculateWeekNumber,
getFirstDateOfWeek,
getFirstDateOfMonth,
monthsDiffer,
isDateLastInMonth,
};
|
/**
* emojiarea - A rich textarea control that supports emojis, WYSIWYG-style.
* Copyright (c) 2012 DIY Co
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
* file except in compliance with the License. You may obtain a copy of the License at:
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
* ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*
* @author Brian Reavis <brian@diy.org>
*/
(function($, window, document) {
var ELEMENT_NODE = 1;
var TEXT_NODE = 3;
var TAGS_BLOCK = ['p', 'div', 'pre', 'form'];
var KEY_ESC = 27;
var KEY_TAB = 9;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
$.emojiarea = {
path: '',
icons: {},
defaults: {
button: null,
buttonLabel: 'Emojis',
buttonPosition: 'after'
}
};
$.fn.emojiarea = function(options) {
options = $.extend({}, $.emojiarea.defaults, options);
return this.each(function() {
var $textarea = $(this);
if ('contentEditable' in document.body && options.wysiwyg !== false) {
new EmojiArea_WYSIWYG($textarea, options);
} else {
new EmojiArea_Plain($textarea, options);
}
});
};
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
var util = {};
util.restoreSelection = (function() {
if (window.getSelection) {
return function(savedSelection) {
var sel = window.getSelection();
sel.removeAllRanges();
for (var i = 0, len = savedSelection.length; i < len; ++i) {
sel.addRange(savedSelection[i]);
}
};
} else if (document.selection && document.selection.createRange) {
return function(savedSelection) {
if (savedSelection) {
savedSelection.select();
}
};
}
})();
util.saveSelection = (function() {
if (window.getSelection) {
return function() {
var sel = window.getSelection(), ranges = [];
if (sel.rangeCount) {
for (var i = 0, len = sel.rangeCount; i < len; ++i) {
ranges.push(sel.getRangeAt(i));
}
}
return ranges;
};
} else if (document.selection && document.selection.createRange) {
return function() {
var sel = document.selection;
return (sel.type.toLowerCase() !== 'none') ? sel.createRange() : null;
};
}
})();
util.replaceSelection = (function() {
if (window.getSelection) {
return function(content) {
var range, sel = window.getSelection();
var node = typeof content === 'string' ? document.createTextNode(content) : content;
if (sel.getRangeAt && sel.rangeCount) {
range = sel.getRangeAt(0);
range.deleteContents();
range.insertNode(document.createTextNode(' '));
range.insertNode(node);
range.setStart(node, 0);
window.setTimeout(function() {
range = document.createRange();
range.setStartAfter(node);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}, 0);
}
}
} else if (document.selection && document.selection.createRange) {
return function(content) {
var range = document.selection.createRange();
if (typeof content === 'string') {
range.text = content;
} else {
range.pasteHTML(content.outerHTML);
}
}
}
})();
util.insertAtCursor = function(text, el) {
text = ' ' + text;
var val = el.value, endIndex, startIndex, range;
if (typeof el.selectionStart != 'undefined' && typeof el.selectionEnd != 'undefined') {
startIndex = el.selectionStart;
endIndex = el.selectionEnd;
el.value = val.substring(0, startIndex) + text + val.substring(el.selectionEnd);
el.selectionStart = el.selectionEnd = startIndex + text.length;
} else if (typeof document.selection != 'undefined' && typeof document.selection.createRange != 'undefined') {
el.focus();
range = document.selection.createRange();
range.text = text;
range.select();
}
};
util.extend = function(a, b) {
if (typeof a === 'undefined' || !a) { a = {}; }
if (typeof b === 'object') {
for (var key in b) {
if (b.hasOwnProperty(key)) {
a[key] = b[key];
}
}
}
return a;
};
util.escapeRegex = function(str) {
return (str + '').replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1');
};
util.htmlEntities = function(str) {
return String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
};
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
var EmojiArea = function() {};
EmojiArea.prototype.setup = function() {
var self = this;
this.$editor.on('focus', function() { self.hasFocus = true; });
this.$editor.on('blur', function() { self.hasFocus = false; });
this.setupButton();
};
EmojiArea.prototype.setupButton = function() {
var self = this;
var $button;
if (this.options.button) {
$button = $(this.options.button);
} else if (this.options.button !== false) {
$button = $('<a href="javascript:void(0)">');
$button.html(this.options.buttonLabel);
$button.addClass('emoji-button');
$button.attr({title: this.options.buttonLabel});
this.$editor[this.options.buttonPosition]($button);
} else {
$button = $('');
}
$button.on('click', function(e) {
EmojiMenu.show(self);
e.stopPropagation();
});
this.$button = $button;
};
EmojiArea.createIcon = function(emoji) {
var filename = $.emojiarea.icons[emoji];
var path = $.emojiarea.path || '';
if (path.length && path.charAt(path.length - 1) !== '/') {
path += '/';
}
return '<img src="' + path + filename + '" alt="' + util.htmlEntities(emoji) + '">';
};
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
/**
* Editor (plain-text)
*
* @constructor
* @param {object} $textarea
* @param {object} options
*/
var EmojiArea_Plain = function($textarea, options) {
this.options = options;
this.$textarea = $textarea;
this.$editor = $textarea;
this.setup();
};
EmojiArea_Plain.prototype.insert = function(emoji) {
if (!$.emojiarea.icons.hasOwnProperty(emoji)) return;
util.insertAtCursor(emoji, this.$textarea[0]);
this.$textarea.trigger('change');
};
EmojiArea_Plain.prototype.val = function() {
return this.$textarea.val();
};
util.extend(EmojiArea_Plain.prototype, EmojiArea.prototype);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
/**
* Editor (rich)
*
* @constructor
* @param {object} $textarea
* @param {object} options
*/
var EmojiArea_WYSIWYG = function($textarea, options) {
var self = this;
this.options = options;
this.$textarea = $textarea;
this.$editor = $('<div>').addClass('emoji-wysiwyg-editor');
this.$editor.text($textarea.val());
this.$editor.attr({contenteditable: 'true'});
this.$editor.on('blur keyup paste', function() { return self.onChange.apply(self, arguments); });
this.$editor.on('mousedown focus', function() { document.execCommand('enableObjectResizing', false, false); });
this.$editor.on('blur', function() { document.execCommand('enableObjectResizing', true, true); });
var html = this.$editor.text();
var emojis = $.emojiarea.icons;
for (var key in emojis) {
if (emojis.hasOwnProperty(key)) {
html = html.replace(new RegExp(util.escapeRegex(key), 'g'), EmojiArea.createIcon(key));
}
}
this.$editor.html(html);
$textarea.hide().after(this.$editor);
this.setup();
this.$button.on('mousedown', function() {
if (self.hasFocus) {
self.selection = util.saveSelection();
}
});
};
EmojiArea_WYSIWYG.prototype.onChange = function() {
this.$textarea.val(this.val()).trigger('change');
};
EmojiArea_WYSIWYG.prototype.insert = function(emoji) {
var content;
var $img = $(EmojiArea.createIcon(emoji));
if ($img[0].attachEvent) {
$img[0].attachEvent('onresizestart', function(e) { e.returnValue = false; }, false);
}
this.$editor.trigger('focus');
if (this.selection) {
util.restoreSelection(this.selection);
}
try { util.replaceSelection($img[0]); } catch (e) {}
this.onChange();
};
EmojiArea_WYSIWYG.prototype.val = function() {
var lines = [];
var line = [];
var flush = function() {
lines.push(line.join(''));
line = [];
};
var sanitizeNode = function(node) {
if (node.nodeType === TEXT_NODE) {
line.push(node.nodeValue);
} else if (node.nodeType === ELEMENT_NODE) {
var tagName = node.tagName.toLowerCase();
var isBlock = TAGS_BLOCK.indexOf(tagName) !== -1;
if (isBlock && line.length) flush();
if (tagName === 'img') {
var alt = node.getAttribute('alt') || '';
if (alt) line.push(alt);
return;
} else if (tagName === 'br') {
flush();
}
var children = node.childNodes;
for (var i = 0; i < children.length; i++) {
sanitizeNode(children[i]);
}
if (isBlock && line.length) flush();
}
};
var children = this.$editor[0].childNodes;
for (var i = 0; i < children.length; i++) {
sanitizeNode(children[i]);
}
if (line.length) flush();
return lines.join('\n');
};
util.extend(EmojiArea_WYSIWYG.prototype, EmojiArea.prototype);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
/**
* Emoji Dropdown Menu
*
* @constructor
* @param {object} emojiarea
*/
var EmojiMenu = function() {
var self = this;
var $body = $(document.body);
var $window = $(window);
this.visible = false;
this.emojiarea = null;
this.$menu = $('<div>');
this.$menu.addClass('emoji-menu');
this.$menu.hide();
this.$items = $('<div>').appendTo(this.$menu);
$body.append(this.$menu);
$body.on('keydown', function(e) {
if (e.keyCode === KEY_ESC || e.keyCode === KEY_TAB) {
self.hide();
}
});
$body.on('mouseup', function() {
self.hide();
});
$window.on('resize', function() {
if (self.visible) self.reposition();
});
this.$menu.on('mouseup', 'a', function(e) {
e.stopPropagation();
return false;
});
this.$menu.on('click', 'a', function(e) {
var emoji = $('.label', $(this)).text();
window.setTimeout(function() {
self.onItemSelected.apply(self, [emoji]);
}, 0);
e.stopPropagation();
return false;
});
this.load();
};
EmojiMenu.prototype.onItemSelected = function(emoji) {
this.emojiarea.insert(emoji);
this.hide();
};
EmojiMenu.prototype.load = function() {
var html = [];
var options = $.emojiarea.icons;
var path = $.emojiarea.path;
if (path.length && path.charAt(path.length - 1) !== '/') {
path += '/';
}
for (var key in options) {
if (options.hasOwnProperty(key)) {
var filename = options[key];
html.push('<a href="javascript:void(0)" title="' + util.htmlEntities(key) + '">' + EmojiArea.createIcon(key) + '<span class="label">' + util.htmlEntities(key) + '</span></a>');
}
}
this.$items.html(html.join(''));
};
EmojiMenu.prototype.reposition = function() {
var $button = this.emojiarea.$button;
var offset = $button.offset();
offset.top += $button.outerHeight();
offset.left += Math.round($button.outerWidth() / 2);
this.$menu.css({
top: offset.top,
left: offset.left
});
};
EmojiMenu.prototype.hide = function(callback) {
if (this.emojiarea) {
this.emojiarea.menu = null;
this.emojiarea.$button.removeClass('on');
this.emojiarea = null;
}
this.visible = false;
this.$menu.hide();
};
EmojiMenu.prototype.show = function(emojiarea) {
if (this.emojiarea && this.emojiarea === emojiarea) return;
this.emojiarea = emojiarea;
this.emojiarea.menu = this;
this.reposition();
this.$menu.show();
this.visible = true;
};
EmojiMenu.show = (function() {
var menu = null;
return function(emojiarea) {
menu = menu || new EmojiMenu();
menu.show(emojiarea);
};
})();
})(jQuery, window, document);
|
window.console&&console.warn(),function(t,s){if(!t)return s;var i=function(){this.el=s,this.items=s,this.sizes=[],this.max=[0,0],this.current=0,this.interval=s,this.opts={speed:500,delay:3e3,complete:s,keys:!s,dots:s,fluid:s};var i=this;this.init=function(s,i){return this.el=s,this.ul=s.children("ul"),this.max=[s.outerWidth(),s.outerHeight()],this.items=this.ul.children("li").each(this.calculate),this.opts=t.extend(this.opts,i),this.setup(),this},this.calculate=function(s){var e=t(this),n=e.outerWidth(),h=e.outerHeight();i.sizes[s]=[n,h],n>i.max[0]&&(i.max[0]=n),h>i.max[1]&&(i.max[1]=h)},this.setup=function(){if(this.el.css({overflow:"hidden",width:i.max[0],height:this.items.first().outerHeight()}),this.ul.css({width:100*this.items.length+"%",position:"relative"}),this.items.css("width",100/this.items.length+"%"),this.opts.delay!==s&&(this.start(),this.el.hover(this.stop,this.start)),this.opts.keys&&t(document).keydown(this.keys),this.opts.dots&&this.dots(),this.opts.fluid){var e=function(){i.el.css("width",Math.min(Math.round(i.el.outerWidth()/i.el.parent().outerWidth()*100),100)+"%")};e(),t(window).resize(e)}this.opts.arrows&&this.el.parent().append('<p class="arrows"><span class="prev">â†</span><span class="next">→</span></p>').find(".arrows span").click(function(){t.isFunction(i[this.className])&&i[this.className]()}),t.event.swipe&&this.el.on("swipeleft",i.prev).on("swiperight",i.next)},this.move=function(s,e){this.items.eq(s).length||(s=0),0>s&&(s=this.items.length-1);var n=this.items.eq(s),h={height:n.outerHeight()},o=e?5:this.opts.speed;this.ul.is(":animated")||(i.el.find(".dot:eq("+s+")").addClass("active").siblings().removeClass("active"),this.el.animate(h,o)&&this.ul.animate(t.extend({left:"-"+s+"00%"},h),o,function(){i.current=s,t.isFunction(i.opts.complete)&&!e&&i.opts.complete(i.el)}))},this.start=function(){i.interval=setInterval(function(){i.move(i.current+1)},i.opts.delay)},this.stop=function(){return i.interval=clearInterval(i.interval),i},this.keys=function(s){var e=s.which,n={37:i.prev,39:i.next,27:i.stop};t.isFunction(n[e])&&n[e]()},this.next=function(){return i.stop().move(i.current+1)},this.prev=function(){return i.stop().move(i.current-1)},this.dots=function(){var s='<ol class="dots">';t.each(this.items,function(t){s+='<li class="dot'+(1>t?" active":"")+'">'+(t+1)+"</li>"}),s+="</ol>",this.el.addClass("has-dots").append(s).find(".dot").click(function(){i.move(t(this).index())})}};t.fn.unslider=function(s){var e=this.length;return this.each(function(n){var h=t(this),o=(new i).init(h,s);h.data("unslider"+(e>1?"-"+(n+1):""),o)})}}(window.jQuery,!1);
|
function initUI() {
$("#slides_panel").resizable({
containment: "#wrapper",
start: function(){
iframe = $('iframe');
var div = $('<div></div>');
$('#slides_panel').append(div[0]);
div[0].id = 'temp_div';
div.css({position:'absolute'});
div.css({top: iframe.position().top, left:0});
div.height(iframe.height());
div.width('100%');
},
stop: function(){
$('#temp_div').remove();
}
});
$("#slides_panel").draggable({
containment: "#wrapper",
scroll: false,
snap: true,
snapMode: "corner"
});
$("#webcam_panel").resizable({
aspectRatio: 4/3,
containment: "#wrapper",
});
$("#webcam_panel").draggable({
containment: "#wrapper",
scroll: false,
snap: true,
snapMode: "corner"
});
}
function showOptions() {
$('#options_panel').animate({
right: '-80px'
}, 'slow');
}
|
const configMainnet = require('./networks/ark/mainnet.json')
const configDevnet = require('./networks/ark/devnet.json')
const configTestnet = require('./networks/ark/testnet.json')
/**
* The Arktoshi base.
* @type {Number}
*/
exports.ARKTOSHI = Math.pow(10, 8)
/**
* Available transaction types.
* @type {Object}
*/
exports.TRANSACTION_TYPES = Object.freeze({
TRANSFER: 0,
SECOND_SIGNATURE: 1,
DELEGATE_REGISTRATION: 2,
VOTE: 3,
MULTI_SIGNATURE: 4,
IPFS: 5,
TIMELOCK_TRANSFER: 6,
MULTI_PAYMENT: 7,
DELEGATE_RESIGNATION: 8,
ULTRANODE_REGISTRATION: 9,
ATTACH_INFO: 11
})
/**
* Available network configurations.
* @type {Object}
*/
exports.CONFIGURATIONS = Object.freeze({
ARK: {
MAINNET: configMainnet,
DEVNET: configDevnet,
TESTNET: configTestnet
}
})
|
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/*!
* @license
* Copyright 2019 Alfresco Software, Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Injectable } from '@angular/core';
import { from, of } from 'rxjs';
import { AlfrescoApiService } from './alfresco-api.service';
import { UserPreferencesService } from './user-preferences.service';
import { catchError } from 'rxjs/operators';
import * as i0 from "@angular/core";
import * as i1 from "./alfresco-api.service";
import * as i2 from "./user-preferences.service";
export class DeletedNodesApiService {
/**
* @param {?} apiService
* @param {?} preferences
*/
constructor(apiService, preferences) {
this.apiService = apiService;
this.preferences = preferences;
}
/**
* @private
* @return {?}
*/
get nodesApi() {
return this.apiService.getInstance().core.nodesApi;
}
/**
* Gets a list of nodes in the trash.
* @param {?=} options Options for JS-API call
* @return {?} List of nodes in the trash
*/
getDeletedNodes(options) {
/** @type {?} */
const defaultOptions = {
include: ['path', 'properties'],
maxItems: this.preferences.paginationSize,
skipCount: 0
};
/** @type {?} */
const queryOptions = Object.assign(defaultOptions, options);
/** @type {?} */
const promise = this.nodesApi.getDeletedNodes(queryOptions);
return from(promise).pipe(catchError((/**
* @param {?} err
* @return {?}
*/
(err) => of(err))));
}
}
DeletedNodesApiService.decorators = [
{ type: Injectable, args: [{
providedIn: 'root'
},] }
];
/** @nocollapse */
DeletedNodesApiService.ctorParameters = () => [
{ type: AlfrescoApiService },
{ type: UserPreferencesService }
];
/** @nocollapse */ DeletedNodesApiService.ngInjectableDef = i0.defineInjectable({ factory: function DeletedNodesApiService_Factory() { return new DeletedNodesApiService(i0.inject(i1.AlfrescoApiService), i0.inject(i2.UserPreferencesService)); }, token: DeletedNodesApiService, providedIn: "root" });
if (false) {
/**
* @type {?}
* @private
*/
DeletedNodesApiService.prototype.apiService;
/**
* @type {?}
* @private
*/
DeletedNodesApiService.prototype.preferences;
}
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZGVsZXRlZC1ub2Rlcy1hcGkuc2VydmljZS5qcyIsInNvdXJjZVJvb3QiOiJuZzovL0BhbGZyZXNjby9hZGYtY29yZS8iLCJzb3VyY2VzIjpbInNlcnZpY2VzL2RlbGV0ZWQtbm9kZXMtYXBpLnNlcnZpY2UudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7QUFpQkEsT0FBTyxFQUFFLFVBQVUsRUFBRSxNQUFNLGVBQWUsQ0FBQztBQUMzQyxPQUFPLEVBQWMsSUFBSSxFQUFFLEVBQUUsRUFBRSxNQUFNLE1BQU0sQ0FBQztBQUc1QyxPQUFPLEVBQUUsa0JBQWtCLEVBQUUsTUFBTSx3QkFBd0IsQ0FBQztBQUM1RCxPQUFPLEVBQUUsc0JBQXNCLEVBQUUsTUFBTSw0QkFBNEIsQ0FBQztBQUNwRSxPQUFPLEVBQUUsVUFBVSxFQUFFLE1BQU0sZ0JBQWdCLENBQUM7Ozs7QUFLNUMsTUFBTSxPQUFPLHNCQUFzQjs7Ozs7SUFDL0IsWUFDWSxVQUE4QixFQUM5QixXQUFtQztRQURuQyxlQUFVLEdBQVYsVUFBVSxDQUFvQjtRQUM5QixnQkFBVyxHQUFYLFdBQVcsQ0FBd0I7SUFDNUMsQ0FBQzs7Ozs7SUFFSixJQUFZLFFBQVE7UUFDakIsT0FBTyxJQUFJLENBQUMsVUFBVSxDQUFDLFdBQVcsRUFBRSxDQUFDLElBQUksQ0FBQyxRQUFRLENBQUM7SUFDdEQsQ0FBQzs7Ozs7O0lBT0QsZUFBZSxDQUFDLE9BQWdCOztjQUN0QixjQUFjLEdBQUc7WUFDbkIsT0FBTyxFQUFFLENBQUUsTUFBTSxFQUFFLFlBQVksQ0FBRTtZQUNqQyxRQUFRLEVBQUUsSUFBSSxDQUFDLFdBQVcsQ0FBQyxjQUFjO1lBQ3pDLFNBQVMsRUFBRSxDQUFDO1NBQ2Y7O2NBQ0ssWUFBWSxHQUFHLE1BQU0sQ0FBQyxNQUFNLENBQUMsY0FBYyxFQUFFLE9BQU8sQ0FBQzs7Y0FDckQsT0FBTyxHQUFHLElBQUksQ0FBQyxRQUFRLENBQUMsZUFBZSxDQUFDLFlBQVksQ0FBQztRQUUzRCxPQUFPLElBQUksQ0FBQyxPQUFPLENBQUMsQ0FBQyxJQUFJLENBQ3JCLFVBQVU7Ozs7UUFBQyxDQUFDLEdBQUcsRUFBRSxFQUFFLENBQUMsRUFBRSxDQUFDLEdBQUcsQ0FBQyxFQUFDLENBQy9CLENBQUM7SUFDTixDQUFDOzs7WUE5QkosVUFBVSxTQUFDO2dCQUNSLFVBQVUsRUFBRSxNQUFNO2FBQ3JCOzs7O1lBTlEsa0JBQWtCO1lBQ2xCLHNCQUFzQjs7Ozs7Ozs7SUFRdkIsNENBQXNDOzs7OztJQUN0Qyw2Q0FBMkMiLCJzb3VyY2VzQ29udGVudCI6WyIvKiFcbiAqIEBsaWNlbnNlXG4gKiBDb3B5cmlnaHQgMjAxOSBBbGZyZXNjbyBTb2Z0d2FyZSwgTHRkLlxuICpcbiAqIExpY2Vuc2VkIHVuZGVyIHRoZSBBcGFjaGUgTGljZW5zZSwgVmVyc2lvbiAyLjAgKHRoZSBcIkxpY2Vuc2VcIik7XG4gKiB5b3UgbWF5IG5vdCB1c2UgdGhpcyBmaWxlIGV4Y2VwdCBpbiBjb21wbGlhbmNlIHdpdGggdGhlIExpY2Vuc2UuXG4gKiBZb3UgbWF5IG9idGFpbiBhIGNvcHkgb2YgdGhlIExpY2Vuc2UgYXRcbiAqXG4gKiAgICAgaHR0cDovL3d3dy5hcGFjaGUub3JnL2xpY2Vuc2VzL0xJQ0VOU0UtMi4wXG4gKlxuICogVW5sZXNzIHJlcXVpcmVkIGJ5IGFwcGxpY2FibGUgbGF3IG9yIGFncmVlZCB0byBpbiB3cml0aW5nLCBzb2Z0d2FyZVxuICogZGlzdHJpYnV0ZWQgdW5kZXIgdGhlIExpY2Vuc2UgaXMgZGlzdHJpYnV0ZWQgb24gYW4gXCJBUyBJU1wiIEJBU0lTLFxuICogV0lUSE9VVCBXQVJSQU5USUVTIE9SIENPTkRJVElPTlMgT0YgQU5ZIEtJTkQsIGVpdGhlciBleHByZXNzIG9yIGltcGxpZWQuXG4gKiBTZWUgdGhlIExpY2Vuc2UgZm9yIHRoZSBzcGVjaWZpYyBsYW5ndWFnZSBnb3Zlcm5pbmcgcGVybWlzc2lvbnMgYW5kXG4gKiBsaW1pdGF0aW9ucyB1bmRlciB0aGUgTGljZW5zZS5cbiAqL1xuXG5pbXBvcnQgeyBJbmplY3RhYmxlIH0gZnJvbSAnQGFuZ3VsYXIvY29yZSc7XG5pbXBvcnQgeyBPYnNlcnZhYmxlLCBmcm9tLCBvZiB9IGZyb20gJ3J4anMnO1xuXG5pbXBvcnQgeyBOb2RlUGFnaW5nIH0gZnJvbSAnQGFsZnJlc2NvL2pzLWFwaSc7XG5pbXBvcnQgeyBBbGZyZXNjb0FwaVNlcnZpY2UgfSBmcm9tICcuL2FsZnJlc2NvLWFwaS5zZXJ2aWNlJztcbmltcG9ydCB7IFVzZXJQcmVmZXJlbmNlc1NlcnZpY2UgfSBmcm9tICcuL3VzZXItcHJlZmVyZW5jZXMuc2VydmljZSc7XG5pbXBvcnQgeyBjYXRjaEVycm9yIH0gZnJvbSAncnhqcy9vcGVyYXRvcnMnO1xuXG5ASW5qZWN0YWJsZSh7XG4gICAgcHJvdmlkZWRJbjogJ3Jvb3QnXG59KVxuZXhwb3J0IGNsYXNzIERlbGV0ZWROb2Rlc0FwaVNlcnZpY2Uge1xuICAgIGNvbnN0cnVjdG9yKFxuICAgICAgICBwcml2YXRlIGFwaVNlcnZpY2U6IEFsZnJlc2NvQXBpU2VydmljZSxcbiAgICAgICAgcHJpdmF0ZSBwcmVmZXJlbmNlczogVXNlclByZWZlcmVuY2VzU2VydmljZVxuICAgICkge31cblxuICAgIHByaXZhdGUgZ2V0IG5vZGVzQXBpKCkge1xuICAgICAgIHJldHVybiB0aGlzLmFwaVNlcnZpY2UuZ2V0SW5zdGFuY2UoKS5jb3JlLm5vZGVzQXBpO1xuICAgIH1cblxuICAgIC8qKlxuICAgICAqIEdldHMgYSBsaXN0IG9mIG5vZGVzIGluIHRoZSB0cmFzaC5cbiAgICAgKiBAcGFyYW0gb3B0aW9ucyBPcHRpb25zIGZvciBKUy1BUEkgY2FsbFxuICAgICAqIEByZXR1cm5zIExpc3Qgb2Ygbm9kZXMgaW4gdGhlIHRyYXNoXG4gICAgICovXG4gICAgZ2V0RGVsZXRlZE5vZGVzKG9wdGlvbnM/OiBPYmplY3QpOiBPYnNlcnZhYmxlPE5vZGVQYWdpbmc+IHtcbiAgICAgICAgY29uc3QgZGVmYXVsdE9wdGlvbnMgPSB7XG4gICAgICAgICAgICBpbmNsdWRlOiBbICdwYXRoJywgJ3Byb3BlcnRpZXMnIF0sXG4gICAgICAgICAgICBtYXhJdGVtczogdGhpcy5wcmVmZXJlbmNlcy5wYWdpbmF0aW9uU2l6ZSxcbiAgICAgICAgICAgIHNraXBDb3VudDogMFxuICAgICAgICB9O1xuICAgICAgICBjb25zdCBxdWVyeU9wdGlvbnMgPSBPYmplY3QuYXNzaWduKGRlZmF1bHRPcHRpb25zLCBvcHRpb25zKTtcbiAgICAgICAgY29uc3QgcHJvbWlzZSA9IHRoaXMubm9kZXNBcGkuZ2V0RGVsZXRlZE5vZGVzKHF1ZXJ5T3B0aW9ucyk7XG5cbiAgICAgICAgcmV0dXJuIGZyb20ocHJvbWlzZSkucGlwZShcbiAgICAgICAgICAgIGNhdGNoRXJyb3IoKGVycikgPT4gb2YoZXJyKSlcbiAgICAgICAgKTtcbiAgICB9XG59XG4iXX0=
|
define([ "jquery", "vo", "permissions", "options" ], function( $, vo, permissions, options ) {
"use strict";
var FOLDER_NAME = "favorites",
fs, curURI, count = 0;
function errorHandler( error ) {
console.error( "File Operations error.", error );
}
function createFavFolder( errorBack ) {
fs.root.getDirectory( FOLDER_NAME , { create: true }, function( dirEntry ) {
console.log( "You have just created the " + dirEntry.name + " directory." );
}, errorBack );
}
function dataURItoBlob( dataURI ) {
// convert base64 to raw binary data held in a string
var byteString = atob( dataURI.split(',')[1] );
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
// write the bytes of the string to an ArrayBuffer
var ab = new ArrayBuffer( byteString.length );
var ia = new Uint8Array( ab );
for ( var i = 0; i < byteString.length; i++ ) {
ia[i] = byteString.charCodeAt(i);
}
var blob = new Blob( [ia], { type: "image/jpg" });
return blob;
}
function getDataURI( url , def ) {
var img = new Image();
img.onload = onload;
img.onerror = errored;
img.onabort = errored;
img.crossOrigin = "*";
img.src = url;
function onload() {
unbindEvent();
var canvas = document.createElement( "canvas" );
canvas.width = img.width;
canvas.height = img.height;
canvas.getContext( "2d" ).drawImage( img, 0, 0 );
def.resolve( canvas.toDataURL( "image/jpeg" ));
canvas = null;
img = null;
}
function errored ( error ) {
unbindEvent();
def.reject( error );
}
function unbindEvent() {
img.onload = null;
img.onerror = null;
img.onabort = null;
}
return def.promise();
}
function readAsDataURL( file, arr, i, len, def ) {
arr.push( new FileReader() );
arr[i].onloadend = function( result ) {
arr[i].onloadend = null;
if ( count == len - 1 ) {
arr = [];
count = 0;
} else { count++; }
result.type == "loadend" ? def.resolve( result.currentTarget.result ) : def.reject( result );
};
arr[i].readAsDataURL( file );
return def.promise();
}
return {
Init: function( errorBack ) {
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
window.requestFileSystem( window.TEMPORARY , 52428800, function( fileEntry ) {
fs = fileEntry;
console.log( "File init complete.", fs );
createFavFolder( errorBack );
}, errorBack );
},
Add: function( file_name, uri ) {
var path = file_name == vo.constructor.BACKGROUND ? file_name : FOLDER_NAME + "/" + file_name + ".jpg";
var def = $.Deferred();
fs.root.getFile( path, { create : true }, function( fileEntry ) {
fileEntry.createWriter( function( fileWriter ) {
console.log("fileEntry.toURL() = " + fileEntry.toURL());
fileWriter.onwritestart = function(e) { def.notify( e ); };
fileWriter.onprogress = function(e) { def.notify( e ); };
fileWriter.onwriteend = unBindEvent;
fileWriter.onabort = unBindEvent;
fileWriter.onerror = unBindEvent;
fileWriter.write( dataURItoBlob( uri ));
function unBindEvent(e) {
fileWriter.onwritestart = null;
fileWriter.onprogress = null;
fileWriter.onabort = null;
fileWriter.onerror = null;
fileWriter.onwriteend = null;
e && e.type == "writeend" ? def.resolve( e, fileEntry.toURL() ) : def.reject( e );
};
}, function( error ) {
console.log( "Save background fail, error is", error );
def.reject( error );
});
},
function( error ) {
console.log( "Get background fail, error is", error );
def.reject( error );
});
return def.promise();
},
Delete: function( file_name, callback, errorBack ) {
fs.root.getDirectory( FOLDER_NAME, {}, function( dirEntry ) {
var dirReader = dirEntry.createReader(),
is_del = false,
del_entry;
dirReader.readEntries(function( entries ) {
for( var i = 0, len = entries.length; i < len; i++ ) {
var entry = entries[i];
if ( entry.isDirectory ) {
console.log("Directory: " + entry.fullPath );
}
else if ( entry.isFile ) {
//console.log("File: " + entry.fullPath );
if ( file_name + ".jpg" == entry.name ) {
is_del = true;
del_entry = entry;
break;
}
}
}
if ( is_del ) {
del_entry.remove(function() {
console.log( "File successufully removed." );
callback( file_name );
}, errorBack );
}
else {
console.error( "Not found delete favorite background in filesystem, id is " + file_name );
callback( file_name );
}
}, errorBack );
}, errorBack );
},
DeleteAny: function ( url, callback, errorBack ) {
fs.root.getFile( url , { create: false }, function( fileEntry ) {
fileEntry.remove( function() {
callback( url );
}, errorBack );
}, errorBack );
},
List: function( callback ) {
fs.root.getDirectory( FOLDER_NAME, {}, function( dirEntry ) {
var dirReader = dirEntry.createReader();
var name_arry = [];
dirReader.readEntries(function( entries ) {
for( var i = 0, len = entries.length; i < len; i++ ) {
var entry = entries[i];
if ( entry.isDirectory ) {
console.log("Directory: " + entry.fullPath );
}
else if ( entry.isFile ) {
//console.log("File: " + entry.fullPath );
name_arry.push( vo.constructor.FAVORITE + entry.name );
}
}
callback( name_arry );
}, errorHandler );
}, errorHandler );
},
GetDataURI: function() {
var def = $.Deferred();
arguments.constructor.prototype.push = Array.prototype.push;
arguments.push( def );
if ( arguments && arguments.length == 2 && typeof arguments[0] === "string" ) {
getDataURI.apply( this, arguments );
}
else if ( arguments && arguments.length == 5 && typeof arguments[0] === "object" ) {
readAsDataURL.apply( this, arguments );
}
delete arguments.constructor.prototype.push;
return def.promise();
},
DataURI: function( result ) {
return curURI = result || curURI;
},
VerifyUploadFile: function( arr ) {
if ( !arr.filter ) arr.constructor.prototype.filter = Array.prototype.filter;
return arr.filter(function( item ) {
return item.type.split("/")[0] === "image";
});
},
FavoriteVO: function() {
return JSON.parse( localStorage["simptab-favorites"] || "[]" );
},
AddFavorite: function( favorite_vo, file_name, result ) {
var obj = { "file_name" : file_name, "result" : JSON.stringify( result ) };
favorite_vo.push( JSON.stringify( obj ));
localStorage[ "simptab-favorites" ] = JSON.stringify( favorite_vo );
},
FindFavorite: function( favorite_vo, file_name ) {
var result;
try {
favorite_vo.forEach( function( item ) {
item = JSON.parse( item );
if ( item.file_name == file_name ) {
result = JSON.parse( item.result );
}
});
return result;
} catch( error ) {
return result;
}
},
DeleteFavorite: function( favorite_vo, file_name ) {
var obj = {};
for( var idx = 0, len = favorite_vo.length; idx < len; idx++ ) {
obj = JSON.parse( favorite_vo[idx] );
if ( obj.file_name == file_name ) {
favorite_vo.splice( idx, 1 );
localStorage[ "simptab-favorites" ] = JSON.stringify( favorite_vo );
break;
}
}
},
FavBingVO: function() {
return JSON.parse( localStorage[ "simptab-bing-fav" ] || "[]" );
},
AddFavBing: function( fav_bing, result ) {
fav_bing.push( result );
localStorage[ "simptab-bing-fav" ] = JSON.stringify( fav_bing );
},
DeleteFavBing: function( fav_bing, result ) {
var val = {};
for( var idx = 0, len = fav_bing.length; idx < len; idx++ ) {
val = fav_bing[idx];
if ( val.split(":")[1] == result ) {
fav_bing.splice( idx, 1 );
localStorage[ "simptab-bing-fav" ] = JSON.stringify( fav_bing );
break;
}
}
},
FindFavBing: function( fav_bing, result ) {
var val = {};
for( var idx = 0, len = fav_bing.length; idx < len; idx++ ) {
val = fav_bing[idx];
if ( val.split(":")[0] == result ) {
return val.split(":")[1];
}
}
return -1;
},
Download: function( url, name ) {
permissions.Verify( [ "downloads" ], function( result ) {
if ( result && options.Storage.db.download != "" ) {
var end = options.Storage.db.download.endsWith( "/" ) ? "" : "/";
chrome.downloads.download({
url: url,
filename: options.Storage.db.download + end + name,
saveAs: false,
conflictAction: "uniquify"
}, function( downloadId ) {
console.log( downloadId )
});
} else {
var $a = $( '<a style="display:none" href=' + url + ' download="' + name + '"></a>' ).appendTo( "body" );
$a[0].click();
$a.remove();
}
});
},
// hack code source from Add()
SaveBgfromURI: function( file_name, uri ) {
var path = file_name + ".jpg";
var def = $.Deferred();
fs.root.getFile( path, { create : true }, function( fileEntry ) {
fileEntry.createWriter( function( fileWriter ) {
console.log("fileEntry.toURL() = " + fileEntry.toURL());
fileWriter.onwritestart = function(e) { def.notify( e ); };
fileWriter.onprogress = function(e) { def.notify( e ); };
fileWriter.onwriteend = unBindEvent;
fileWriter.onabort = unBindEvent;
fileWriter.onerror = unBindEvent;
fileWriter.write( dataURItoBlob( uri ));
function unBindEvent(e) {
fileWriter.onwritestart = null;
fileWriter.onprogress = null;
fileWriter.onabort = null;
fileWriter.onerror = null;
fileWriter.onwriteend = null;
e && e.type == "writeend" ? def.resolve( fileEntry.toURL() ) : def.reject( e );
};
}, function( error ) {
console.log( "Save background fail, error is", error );
def.reject( error );
});
},
function( error ) {
console.log( "Get background fail, error is", error );
def.reject( error );
});
return def.promise();
},
};
});
|
import React from 'react';
import PropTypes from 'prop-types';
import {CSSTransitionGroup} from 'react-transition-group';
import Question from '../components/Question';
import AnswerOption from '../components/AnswerOption';
import ProgressBar from "react-bootstrap/ProgressBar";
function Quiz(props) {
function renderAnswerOptions(key) {
return (
<AnswerOption
key={key.content}
answerContent={key.content}
answerType={key.type}
answerValue={key.eligible}
answer={props.answer}
questionId={props.questionId}
onAnswerSelected={props.onAnswerSelected}
/>
);
}
return (
<CSSTransitionGroup
className="container"
component="div"
transitionName="fade"
transitionEnterTimeout={800}
transitionLeaveTimeout={500}
transitionAppear={false}
transitionAppearTimeout={500}
>
<div key={props.questionId}>
<div className="bootstrap-iso">
<ProgressBar className="right" now={props.progress}/>
</div>
<Question content={props.question}/>
<ul className="answerOptions">
{props.answerOptions.map(renderAnswerOptions)}
</ul>
</div>
</CSSTransitionGroup>
);
}
Quiz.propTypes = {
answer: PropTypes.string.isRequired,
answerOptions: PropTypes.array.isRequired,
question: PropTypes.string.isRequired,
questionId: PropTypes.number.isRequired,
questionTotal: PropTypes.number.isRequired,
progress: PropTypes.number.isRequired,
onAnswerSelected: PropTypes.func.isRequired
};
export default Quiz;
|
'use strict';
//Wettkampf service used for wettkampf REST endpoint
angular.module('mean.wettkampf').factory('Wettkampf', ['$resource',
function($resource) {
return $resource('api/wettkampf', {
}, {
update: {
method: 'PUT'
}
});
}
]);
|
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
module.exports = {
entry: [path.join(__dirname, 'src', 'public/js/index.js')],
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'src/dist'),
publicPath: '/'
},
plugins: [
new CleanWebpackPlugin(['src/dist']),
new HtmlWebpackPlugin({
filename: 'index.html',
title: 'OurPic',
template: path.join(__dirname, 'src', 'public/index.html')
}),
new HtmlWebpackPlugin({
filename: '404.html',
title: 'OurPic-404',
template: path.join(__dirname, 'src', 'public/404.html'),
chunks: ['404']
})
],
module: {
rules: [
{
test: /\.(png|svg|jpg|gif)$/,
use: ['file-loader']
}
]
}
};
|
/* -*- mode: javascript; tab-width: 4; indent-tabs-mode: nil; -*-
*
* Copyright (c) 2011-2013 Marcus Geelnard
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*
*/
// only change to original SoundBox source code is exporting CPlayer so it can be loaded via ES6 imports
export default CPlayer = function() {
//--------------------------------------------------------------------------
// Private methods
//--------------------------------------------------------------------------
// Oscillators
var osc_sin = function (value) {
return Math.sin(value * 6.283184);
};
var osc_saw = function (value) {
return 2 * (value % 1) - 1;
};
var osc_square = function (value) {
return (value % 1) < 0.5 ? 1 : -1;
};
var osc_tri = function (value) {
var v2 = (value % 1) * 4;
if(v2 < 2) return v2 - 1;
return 3 - v2;
};
var getnotefreq = function (n) {
// 174.61.. / 44100 = 0.003959503758 (F3)
return 0.003959503758 * Math.pow(2, (n - 128) / 12);
};
var createNote = function (instr, n, rowLen) {
var osc1 = mOscillators[instr.i[0]],
o1vol = instr.i[1],
o1xenv = instr.i[3],
osc2 = mOscillators[instr.i[4]],
o2vol = instr.i[5],
o2xenv = instr.i[8],
noiseVol = instr.i[9],
attack = instr.i[10] * instr.i[10] * 4,
sustain = instr.i[11] * instr.i[11] * 4,
release = instr.i[12] * instr.i[12] * 4,
releaseInv = 1 / release,
arp = instr.i[13],
arpInterval = rowLen * Math.pow(2, 2 - instr.i[14]);
var noteBuf = new Int32Array(attack + sustain + release);
// Re-trig oscillators
var c1 = 0, c2 = 0;
// Local variables.
var j, j2, e, t, rsample, o1t, o2t;
// Generate one note (attack + sustain + release)
for (j = 0, j2 = 0; j < attack + sustain + release; j++, j2++) {
if (j2 >= 0) {
// Switch arpeggio note.
arp = (arp >> 8) | ((arp & 255) << 4);
j2 -= arpInterval;
// Calculate note frequencies for the oscillators
o1t = getnotefreq(n + (arp & 15) + instr.i[2] - 128);
o2t = getnotefreq(n + (arp & 15) + instr.i[6] - 128) * (1 + 0.0008 * instr.i[7]);
}
// Envelope
e = 1;
if (j < attack) {
e = j / attack;
} else if (j >= attack + sustain) {
e -= (j - attack - sustain) * releaseInv;
}
// Oscillator 1
t = o1t;
if (o1xenv) {
t *= e * e;
}
c1 += t;
rsample = osc1(c1) * o1vol;
// Oscillator 2
t = o2t;
if (o2xenv) {
t *= e * e;
}
c2 += t;
rsample += osc2(c2) * o2vol;
// Noise oscillator
if (noiseVol) {
rsample += (2 * Math.random() - 1) * noiseVol;
}
// Add to (mono) channel buffer
noteBuf[j] = (80 * rsample * e) | 0;
}
return noteBuf;
};
//--------------------------------------------------------------------------
// Private members
//--------------------------------------------------------------------------
// Array of oscillator functions
var mOscillators = [
osc_sin,
osc_square,
osc_saw,
osc_tri
];
// Private variables set up by init()
var mSong, mLastRow, mCurrentCol, mNumWords, mMixBuf;
//--------------------------------------------------------------------------
// Initialization
//--------------------------------------------------------------------------
this.init = function (song) {
// Define the song
mSong = song;
// Init iteration state variables
mLastRow = song.endPattern;
mCurrentCol = 0;
// Prepare song info
mNumWords = song.rowLen * song.patternLen * (mLastRow + 1) * 2;
// Create work buffer (initially cleared)
mMixBuf = new Int32Array(mNumWords);
};
//--------------------------------------------------------------------------
// Public methods
//--------------------------------------------------------------------------
// Generate audio data for a single track
this.generate = function () {
// Local variables
var i, j, b, p, row, col, n, cp,
k, t, lfor, e, x, rsample, rowStartSample, f, da;
// Put performance critical items in local variables
var chnBuf = new Int32Array(mNumWords),
instr = mSong.songData[mCurrentCol],
rowLen = mSong.rowLen,
patternLen = mSong.patternLen;
// Clear effect state
var low = 0, band = 0, high;
var lsample, filterActive = false;
// Clear note cache.
var noteCache = [];
// Patterns
for (p = 0; p <= mLastRow; ++p) {
cp = instr.p[p];
// Pattern rows
for (row = 0; row < patternLen; ++row) {
// Execute effect command.
var cmdNo = cp ? instr.c[cp - 1].f[row] : 0;
if (cmdNo) {
instr.i[cmdNo - 1] = instr.c[cp - 1].f[row + patternLen] || 0;
// Clear the note cache since the instrument has changed.
if (cmdNo < 16) {
noteCache = [];
}
}
// Put performance critical instrument properties in local variables
var oscLFO = mOscillators[instr.i[15]],
lfoAmt = instr.i[16] / 512,
lfoFreq = Math.pow(2, instr.i[17] - 9) / rowLen,
fxLFO = instr.i[18],
fxFilter = instr.i[19],
fxFreq = instr.i[20] * 43.23529 * 3.141592 / 44100,
q = 1 - instr.i[21] / 255,
dist = instr.i[22] * 1e-5,
drive = instr.i[23] / 32,
panAmt = instr.i[24] / 512,
panFreq = 6.283184 * Math.pow(2, instr.i[25] - 9) / rowLen,
dlyAmt = instr.i[26] / 255,
dly = instr.i[27] * rowLen & ~1; // Must be an even number
// Calculate start sample number for this row in the pattern
rowStartSample = (p * patternLen + row) * rowLen;
// Generate notes for this pattern row
for (col = 0; col < 4; ++col) {
n = cp ? instr.c[cp - 1].n[row + col * patternLen] : 0;
if (n) {
if (!noteCache[n]) {
noteCache[n] = createNote(instr, n, rowLen);
}
// Copy note from the note cache
var noteBuf = noteCache[n];
for (j = 0, i = rowStartSample * 2; j < noteBuf.length; j++, i += 2) {
chnBuf[i] += noteBuf[j];
}
}
}
// Perform effects for this pattern row
for (j = 0; j < rowLen; j++) {
// Dry mono-sample
k = (rowStartSample + j) * 2;
rsample = chnBuf[k];
// We only do effects if we have some sound input
if (rsample || filterActive) {
// State variable filter
f = fxFreq;
if (fxLFO) {
f *= oscLFO(lfoFreq * k) * lfoAmt + 0.5;
}
f = 1.5 * Math.sin(f);
low += f * band;
high = q * (rsample - band) - low;
band += f * high;
rsample = fxFilter == 3 ? band : fxFilter == 1 ? high : low;
// Distortion
if (dist) {
rsample *= dist;
rsample = rsample < 1 ? rsample > -1 ? osc_sin(rsample*.25) : -1 : 1;
rsample /= dist;
}
// Drive
rsample *= drive;
// Is the filter active (i.e. still audiable)?
filterActive = rsample * rsample > 1e-5;
// Panning
t = Math.sin(panFreq * k) * panAmt + 0.5;
lsample = rsample * (1 - t);
rsample *= t;
} else {
lsample = 0;
}
// Delay is always done, since it does not need sound input
if (k >= dly) {
// Left channel = left + right[-p] * t
lsample += chnBuf[k-dly+1] * dlyAmt;
// Right channel = right + left[-p] * t
rsample += chnBuf[k-dly] * dlyAmt;
}
// Store in stereo channel buffer (needed for the delay effect)
chnBuf[k] = lsample | 0;
chnBuf[k+1] = rsample | 0;
// ...and add to stereo mix buffer
mMixBuf[k] += lsample | 0;
mMixBuf[k+1] += rsample | 0;
}
}
}
// Next iteration. Return progress (1.0 == done!).
mCurrentCol++;
return mCurrentCol / mSong.numChannels;
};
// Create a WAVE formatted Uint8Array from the generated audio data
this.createWave = function() {
// Create WAVE header
var headerLen = 44;
var l1 = headerLen + mNumWords * 2 - 8;
var l2 = l1 - 36;
var wave = new Uint8Array(headerLen + mNumWords * 2);
wave.set(
[82,73,70,70,
l1 & 255,(l1 >> 8) & 255,(l1 >> 16) & 255,(l1 >> 24) & 255,
87,65,86,69,102,109,116,32,16,0,0,0,1,0,2,0,
68,172,0,0,16,177,2,0,4,0,16,0,100,97,116,97,
l2 & 255,(l2 >> 8) & 255,(l2 >> 16) & 255,(l2 >> 24) & 255]
);
// Append actual wave data
for (var i = 0, idx = headerLen; i < mNumWords; ++i) {
// Note: We clamp here
var y = mMixBuf[i];
y = y < -32767 ? -32767 : (y > 32767 ? 32767 : y);
wave[idx++] = y & 255;
wave[idx++] = (y >> 8) & 255;
}
// Return the WAVE formatted typed array
return wave;
};
// Get n samples of wave data at time t [s]. Wave data in range [-2,2].
this.getData = function(t, n) {
var i = 2 * Math.floor(t * 44100);
var d = new Array(n);
for (var j = 0; j < 2*n; j += 1) {
var k = i + j;
d[j] = t > 0 && k < mMixBuf.length ? mMixBuf[k] / 32768 : 0;
}
return d;
};
};
|
import styled from 'styled-components';
const QuestionStyled = styled.div`
padding: 2rem;
`;
const QuestionCounter = styled.div`
font-size: 0.9rem;
margin-bottom: 0.5rem;
`;
const QuestionLabel = styled.div`
font-weight: 900;
font-size: 1.5rem;
`;
export { QuestionStyled, QuestionCounter, QuestionLabel };
|
// @flow
import type { Interpolation } from '../types'
const stringifyRules = (
rules: Array<Interpolation>,
selector: ?string,
prefix: ?string,
): string =>
rules.reduce(
(str: string, partial: Interpolation, index: number): string =>
str +
// NOTE: This is to not prefix keyframes with the animation name
((index > 0 || !prefix) && selector ? selector : '') +
(partial && Array.isArray(partial)
? partial.join('')
: partial.toString()),
'',
)
export default stringifyRules
|
/*
* Javascript Quadtree
* @version 1.1.1
* @licence MIT
* @author Timo Hausmann
* https://github.com/timohausmann/quadtree-js/
*/
/*
Copyright © 2012 Timo Hausmann
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
NONINFRINGEMENthis. 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.
*/
const QuadTree = (function(window, Math) {
/*
* Quadtree Constructor
* @param Object bounds bounds of the node, object with x, y, width, height
* @param Integer max_objects (optional) max objects a node can hold before splitting into 4 subnodes (default: 10)
* @param Integer max_levels (optional) total max levels inside root Quadtree (default: 4)
* @param Integer level (optional) deepth level, required for subnodes
*/
function Quadtree( bounds, max_objects, max_levels, level ) {
this.max_objects = max_objects || 10;
this.max_levels = max_levels || 4;
this.level = level || 0;
this.bounds = bounds;
this.objects = [];
this.nodes = [];
};
/*
* Split the node into 4 subnodes
*/
Quadtree.prototype.split = function() {
var nextLevel = this.level + 1,
subWidth = Math.round( this.bounds.width / 2 ),
subHeight = Math.round( this.bounds.height / 2 ),
x = Math.round( this.bounds.x ),
y = Math.round( this.bounds.y );
//top right node
this.nodes[0] = new Quadtree({
x : x + subWidth,
y : y,
width : subWidth,
height : subHeight
}, this.max_objects, this.max_levels, nextLevel);
//top left node
this.nodes[1] = new Quadtree({
x : x,
y : y,
width : subWidth,
height : subHeight
}, this.max_objects, this.max_levels, nextLevel);
//bottom left node
this.nodes[2] = new Quadtree({
x : x,
y : y + subHeight,
width : subWidth,
height : subHeight
}, this.max_objects, this.max_levels, nextLevel);
//bottom right node
this.nodes[3] = new Quadtree({
x : x + subWidth,
y : y + subHeight,
width : subWidth,
height : subHeight
}, this.max_objects, this.max_levels, nextLevel);
};
/*
* Determine which node the object belongs to
* @param Object pRect bounds of the area to be checked, with x, y, width, height
* @return Integer index of the subnode (0-3), or -1 if pRect cannot completely fit within a subnode and is part of the parent node
*/
Quadtree.prototype.getIndex = function( pRect ) {
var index = -1,
verticalMidpoint = this.bounds.x + (this.bounds.width / 2),
horizontalMidpoint = this.bounds.y + (this.bounds.height / 2),
//pRect can completely fit within the top quadrants
topQuadrant = (pRect.y < horizontalMidpoint && pRect.y + pRect.height < horizontalMidpoint),
//pRect can completely fit within the bottom quadrants
bottomQuadrant = (pRect.y > horizontalMidpoint);
//pRect can completely fit within the left quadrants
if( pRect.x < verticalMidpoint && pRect.x + pRect.width < verticalMidpoint ) {
if( topQuadrant ) {
index = 1;
} else if( bottomQuadrant ) {
index = 2;
}
//pRect can completely fit within the right quadrants
} else if( pRect.x > verticalMidpoint ) {
if( topQuadrant ) {
index = 0;
} else if( bottomQuadrant ) {
index = 3;
}
}
return index;
};
/*
* Insert the object into the node. If the node
* exceeds the capacity, it will split and add all
* objects to their corresponding subnodes.
* @param Object pRect bounds of the object to be added, with x, y, width, height
*/
Quadtree.prototype.insert = function( pRect ) {
var i = 0,
index;
//if we have subnodes ...
if( typeof this.nodes[0] !== 'undefined' ) {
index = this.getIndex( pRect );
if( index !== -1 ) {
this.nodes[index].insert( pRect );
return;
}
}
this.objects.push( pRect );
if( this.objects.length > this.max_objects && this.level < this.max_levels ) {
//split if we don't already have subnodes
if( typeof this.nodes[0] === 'undefined' ) {
this.split();
}
//add all objects to there corresponding subnodes
while( i < this.objects.length ) {
index = this.getIndex( this.objects[ i ] );
if( index !== -1 ) {
this.nodes[index].insert( this.objects.splice(i, 1)[0] );
} else {
i = i + 1;
}
}
}
};
/*
* Return all objects that could collide with the given object
* @param Object pRect bounds of the object to be checked, with x, y, width, height
* @Return Array array with all detected objects
*/
Quadtree.prototype.retrieve = function( pRect ) {
var index = this.getIndex( pRect ),
returnObjects = this.objects;
//if we have subnodes ...
if( typeof this.nodes[0] !== 'undefined' ) {
//if pRect fits into a subnode ..
if( index !== -1 ) {
returnObjects = returnObjects.concat( this.nodes[index].retrieve( pRect ) );
//if pRect does not fit into a subnode, check it against all subnodes
} else {
for( var i=0; i < this.nodes.length; i=i+1 ) {
returnObjects = returnObjects.concat( this.nodes[i].retrieve( pRect ) );
}
}
}
return returnObjects;
};
/*
* Clear the quadtree
*/
Quadtree.prototype.clear = function() {
this.objects = [];
for( var i=0; i < this.nodes.length; i=i+1 ) {
if( typeof this.nodes[i] !== 'undefined' ) {
this.nodes[i].clear();
}
}
this.nodes = [];
};
//make Quadtree available in the global namespace
return Quadtree;
})(window, Math);
export default QuadTree
|
/* -------------------------------------------------------------------------- */
/* Copyright 2002-2020, OpenNebula Project, OpenNebula Systems */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may */
/* not use this file except in compliance with the License. You may obtain */
/* a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */
/* See the License for the specific language governing permissions and */
/* limitations under the License. */
/* -------------------------------------------------------------------------- */
define(function(require) {
// Dependencies
var Locale = require('utils/locale');
var Tips = require('utils/tips');
var Config = require('sunstone-config');
var TemplateUtils = require("../../../utils/template-utils");
var TemplateHTML = require('hbs!./role-tab/html');
var HostsTable = require('./datatable');
function RoleTab(html_role_id) {
this.html_role_id = html_role_id;
this.host_affined = [];
this.host_anti_affined = [];
this.old_name = "none";
return this;
}
RoleTab.prototype = {
'html': _role_tab_content,
'setup': _setup_role_tab_content,
'onShow': _onShow,
'retrieve': _retrieve,
'fill': _fill,
'oldName': _get_old_name,
'changeNameTab': _change_name_tab
};
RoleTab.prototype.constructor = RoleTab;
return RoleTab;
function _role_tab_content(){
var opts = {
info: false,
select: true
};
var optsTable = {
info: false,
select: true,
selectOptions: {"multiple_choice": true}
};
this.hostsTable = new HostsTable("table_hosts_"+this.html_role_id, optsTable);
this.hostsTable.initialize();
return TemplateHTML({
'idRole': this.html_role_id,
'hostsTableHTML': this.hostsTable.dataTableHTML,
'value_host_affinity': "value_host_affinity_"+this.html_role_id,
'tf_btn_host_affined': "btn_host_vm_roles_affined"+this.html_role_id,
'tf_btn_host_anti_affined': "btn_host_vm_roles_anti_affined"+this.html_role_id,
'group_vm_host_roles':"group_vm_host_roles_"+this.html_role_id,
'hostAffinityEnabled': Config.isTabEnabled('hosts-tab')
})
}
function _setup_role_tab_content(role_section,context) {
var that = this;
this.role_section = role_section;
Tips.setup(role_section);
this.hostsTable.initialize();
$("#btn_host_vm_roles_anti_affined"+this.html_role_id, context).bind("click",function(){
var selectedHostsList = that.hostsTable.retrieveResourceTableSelect();
var selectedHosts = {};
$.each(selectedHostsList, function(i,e){
selectedHosts[e] = 1;
});
var text = "";
for(key in selectedHosts){
_generateBox("ANTI_AFFINED",key,that);
}
});
$("#btn_host_vm_roles_affined"+this.html_role_id, context).bind("click",function(){
var selectedHostsList = that.hostsTable.retrieveResourceTableSelect();
var selectedHosts = {};
$.each(selectedHostsList, function(i,e){
selectedHosts[e] = 1;
});
var text = "";
for(key in selectedHosts){
_generateBox("AFFINED",key,that);
}
});
}
function _generateBox(affinity,text, that){
var html = "";
if(affinity == "ANTI_AFFINED"){
if(text != ""){
if(!equals(that.host_affined, text) && !equals(that.host_anti_affined, text)){
html = "<a value="+text+" id='btn_HOST_ANTI_AFFINED_"+that.html_role_id+"' class='button alert radius btn_group_host_vm_roles' style='margin-top: 0.5em;'>\
<i class='fas fa-lg fa-times-circle remove_host_affinity'> "+text+" </i>\
</a>";
var div = '<div style="margin: 3px; display: inline;" id="ANTI_AFFINED_'+that.html_role_id+'" class="group_host_role_content" typeAffinity="ANTI_AFFINED">' + html + '</div>';
$("#group_vm_host_roles_"+that.html_role_id+"_anti_affined").append(div);
that.host_anti_affined.push(text);
}
}
}
else{
if(text != ""){
if(!equals(that.host_affined, text) && !equals(that.host_anti_affined, text)){
html = "<a value="+text+" id='btn_HOST_AFFINED_"+that.html_role_id+"' class='button success radius btn_group_host_vm_roles' style='margin-top: 0.5em;'>\
<i class='fas fa-lg fa-times-circle remove_host_affinity'> "+text+" </i>\
</a>";
var div = '<div style="margin: 3px; display: inline;" id="AFFINED_'+that.html_role_id+'" class="group_host_role_content" typeAffinity="AFFINED">' + html + '</div>';
$("#group_vm_host_roles_"+that.html_role_id+"_affined").append(div);
that.host_affined.push(text);
}
}
}
$(".btn_group_host_vm_roles").on("click", "i.remove_host_affinity", function() {
var affinity = $(this.parentElement.parentElement).attr('typeAffinity');
var value = $(this.parentElement).attr('value');
$(this.parentElement.parentElement).remove();
var index = -1;
if(affinity == "AFFINED"){
index = that.host_affined.indexOf(text);
delete that.host_affined[index];
}
else{
index = that.host_anti_affined.indexOf(text);
delete that.host_anti_affined[index];
}
return false;
});
$.each($('tr', that.role_section),function(index, row) {
if(row.childNodes[0].className == "markrowchecked"){
var row_id = row.childNodes[0].innerText;
$('td', row).removeClass('markrowchecked');
$('td', row).prop('checked', false);
$('#selected_ids_row_table_hosts_'+that.html_role_id + ' span[row_id="' + row_id + '"]', that.role_section).remove();
}
});
}
function _onShow(){
this.hostsTable.refreshResourceTableSelect();
}
function _retrieve(context){
var role = {};
var text = "";
role['NAME'] = TemplateUtils.removeHTMLTags($('input[name="name"]', context).val());
role['VIRTUAL_MACHINES'] = TemplateUtils.removeHTMLTags($('input[name="cardinality"]', context).val());
role['POLICY'] = TemplateUtils.removeHTMLTags($('input[name="protocol_'+this.html_role_id+'"]:checked', context).val());
if(this.host_affined.length > 0){
for(data in this.host_affined)
text += this.host_affined[data] + ", ";
text = text.slice(0,-2);
role['HOST_AFFINED'] = TemplateUtils.removeHTMLTags(text)
text = "";
}
if(this.host_anti_affined.length > 0){
for(data in this.host_anti_affined)
text += this.host_anti_affined[data] + ", ";
text = text.slice(0,-2);
role['HOST_ANTI_AFFINED'] = TemplateUtils.removeHTMLTags(text);
}
role = _removeEmptyObjects(role);
return role;
}
function _fill(context, value, element) {
this.host_anti_affined ="";
this.host_affined = "";
$("#role_name", context).val(value.NAME);
$("#role_name", context).change();
$("#role_cardinality", context).val(value.VIRTUAL_MACHINES);
$('input[name="protocol_'+this.html_role_id+', value='+value.POLICY+']', context).attr("checked", true);
if(value.HOST_AFFINED)
_generateBox("AFFINED",value.HOST_AFFINED, this);
if(value.HOST_ANTI_AFFINED)
_generateBox("ANTI_AFFINED", value.HOST_ANTI_AFFINED, this);
}
function _get_old_name() {
return this.old_name;
}
function _change_name_tab(name){
if(this.old_name != name){
this.old_name = name;
$("#" + this.html_role_id +" #role_name_text").html(name);
}
}
//----------------------------------------------------------------------------
function _removeEmptyObjects(obj){
for (var elem in obj){
var remove = false;
var value = obj[elem];
if (value instanceof Array){
if (value.length == 0)
remove = true;
else if (value.length > 0){
value = jQuery.grep(value, function (n) {
var obj_length = 0;
for (e in n)
obj_length += 1;
if (obj_length == 0)
return false;
return true;
});
if (value.length == 0)
remove = true;
}
}
else if (value instanceof Object){
var obj_length = 0;
for (e in value)
obj_length += 1;
if (obj_length == 0)
remove = true;
}else{
value = String(value);
if (value.length == 0)
remove = true;
}
if (remove)
delete obj[elem];
}
return obj;
}
function equals(list, term) {
for(data in list){
if(list[data] == term)
return true;
}
return false;
}
});
|
Ext.define("Hatimeria.tour.view.TourMainView", {
extend: 'Ext.container.Viewport',
title: 'Tour',
layout: 'border',
items: [
{
region: 'north',
xtype: 'container',
padding: 10,
style: 'font-size: 18px; background: white',
html: 'Hatimeria CMF'
},
{
region: 'center',
bodyPadding: 20,
html: '<a href="/compiled/js/docs/index.html">Javascript classes documentation</a><br/>' +
'<a href="/admin">Administration</a>'
}
]
})
|
/*
* Copyright (C) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import media from '@ohos.multimedia.media'
import fileio from '@ohos.fileio'
import router from '@system.router'
import {getFileDescriptor, closeFileDescriptor} from './VideoDecoderTestBase.test.js'
import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index'
describe('VideoDecoderFuncPromiseTest', function () {
let videoDecodeProcessor = null;
let readStreamSync = undefined;
let frameCountIn = 0;
let frameCountOut = 0;
let timestamp = 0;
let inputQueue = [];
let outputQueue = [];
let isCodecData = false;
let inputEosFlag = false;
let surfaceID = '';
const events = require('events');
const eventEmitter = new events.EventEmitter();
const BASIC_PATH = '/data/accounts/account_0/appdata/ohos.acts.multimedia.video.videodecoder/';
let ES_FRAME_SIZE = [];
const H264_FRAME_SIZE_60FPS_320 =
[ 2106, 11465, 321, 72, 472, 68, 76, 79, 509, 90, 677, 88, 956, 99, 347, 77, 452, 681, 81, 1263, 94, 106, 97,
998, 97, 797, 93, 1343, 150, 116, 117, 926, 1198, 128, 110, 78, 1582, 158, 135, 112, 1588, 165, 132,
128, 1697, 168, 149, 117, 1938, 170, 141, 142, 1830, 106, 161, 122, 1623, 160, 154, 156, 1998, 230,
177, 139, 1650, 186, 128, 134, 1214, 122, 1411, 120, 1184, 128, 1591, 195, 145, 105, 1587, 169, 140,
118, 1952, 177, 150, 161, 1437, 159, 123, 1758, 180, 165, 144, 1936, 214, 191, 175, 2122, 180, 179,
160, 1927, 161, 184, 119, 1973, 218, 210, 129, 1962, 196, 127, 154, 2308, 173, 127, 1572, 142, 122,
2065, 262, 159, 206, 2251, 269, 179, 170, 2056, 308, 168, 191, 2090, 303, 191, 110, 1932, 272, 162,
122, 1877, 245, 167, 141, 1908, 294, 162, 118, 1493, 132, 1782, 273, 184, 133, 1958, 274, 180, 149,
2070, 216, 169, 143, 1882, 224, 149, 139, 1749, 277, 184, 139, 2141, 197, 170, 140, 2002, 269, 162,
140, 1862, 202, 179, 131, 1868, 214, 164, 140, 1546, 226, 150, 130, 1707, 162, 146, 1824, 181, 147,
130, 1898, 209, 143, 131, 1805, 180, 148, 106, 1776, 147, 141, 1572, 177, 130, 105, 1776, 178, 144,
122, 1557, 142, 124, 114, 1436, 143, 126, 1326, 127, 1755, 169, 127, 105, 1807, 177, 131, 134, 1613,
187, 137, 136, 1314, 134, 118, 2005, 194, 129, 147, 1566, 185, 132, 131, 1236, 174, 137, 106, 11049,
574, 126, 1242, 188, 130, 119, 1450, 187, 137, 141, 1116, 124, 1848, 138, 122, 1605, 186, 127, 140,
1798, 170, 124, 121, 1666, 157, 128, 130, 1678, 135, 118, 1804, 169, 135, 125, 1837, 168, 124, 124];
const H263_FRAME_SIZE =
[ 96618, 3515, 4132, 4336, 4646, 3497, 4430, 5437, 7560, 4613, 4876, 4734, 53617, 4079, 4507, 5222, 6244,
5843, 6601, 6622, 6751, 6539, 7666, 7706, 53977, 7311, 12906, 10308, 26791, 15983, 34794, 22110, 37165,
24267, 36171, 18330, 53228, 7893, 13088, 9502, 8485, 9207, 8681, 9202, 8537, 7603, 9726, 8191, 51872,
5535, 6146, 6341, 6933, 9365, 7828, 6547, 7638, 7009, 7025, 8873, 51045, 5056, 4858, 4887, 9614, 5953,
5972, 6116, 6060, 6296, 6239, 6400, 50928, 4937, 5054, 5371, 6728, 6286, 6524, 6646, 6549, 6036, 6214,
5866, 51109, 4778, 5273, 6327];
const MPEG2_FRAME_SIZE =
[ 38462, 55096, 8660, 3417, 1197, 2209, 984, 718, 783, 623, 659, 694, 14174, 580, 421, 495, 480, 476, 534,
660, 699, 601, 603, 720, 12585, 555, 532, 776, 789, 762, 766, 732, 671, 735, 777, 948, 12650, 827, 766,
835, 747, 847, 940, 1121, 1092, 1001, 980, 989, 12746, 945, 912, 1046, 1118, 1134, 1050, 1073, 1051, 1195,
1085, 1182, 12874, 992, 1007, 985, 1040, 1143, 1157, 1150, 1247, 1149, 1246, 1145, 12870, 1041, 1066, 1314,
1239, 1283, 1223, 1224, 1270, 1427, 1406, 1516, 12949, 1228, 1299, 1439, 1358, 1455, 1311, 1396, 1416, 1470,
1393, 1502, 12999, 1232, 1400, 1348, 1335, 1461, 1404, 1412, 1426, 1548, 1481, 1488, 12840, 1229, 1342, 1323,
1353, 1524, 1363, 1475, 1540, 1495, 1489, 1438, 12762, 1291, 1303, 1470, 1494, 1488, 1474, 1453, 1607, 1485,
1589, 1762, 12548, 1363, 1317, 1435, 1411, 1338, 1373, 1605, 1639, 1429, 1392, 1543, 12332, 1255, 1200, 1291,
1337, 1341, 1356, 1214, 1456, 1353, 1314, 1502, 12151, 1192, 1290, 1203, 1284, 1154, 1264, 1358, 1390, 1433,
1194, 1325, 11904, 993, 1007, 1149, 1099, 1182, 1076, 1074, 1092, 1030, 1272, 1178, 11710, 966, 879, 860, 955,
898, 967, 927, 1066, 997, 1083, 940, 11717, 648, 705, 901, 925, 930, 868, 798, 846, 781, 825, 1027, 11587, 785,
733, 731, 848, 753, 806, 699, 837, 750, 762, 748, 11541, 678, 742, 667, 735, 702, 837, 695, 773, 849, 869, 769,
11381, 664, 705, 714, 698, 814, 846, 757, 802, 857, 905, 772, 11265, 718, 643, 597, 687, 774, 843, 747, 785,
683, 1135, 676, 11259, 616, 595, 773, 746, 798, 722, 798, 790, 959, 771, 907, 11234, 705, 675, 773, 764, 846,
789, 840, 853, 828, 774, 842, 11263, 758, 758, 757, 820, 847, 834, 884, 842, 988, 750, 952, 11236, 776, 640, 727,
832, 855, 733, 822, 827, 862, 697, 924, 11176, 675, 615, 688, 818, 783, 746, 901, 834, 892, 759, 923, 11181, 661,
578, 720, 697];
const MPEG4_FRAME_SIZE =
[ 11895, 8109, 1578, 1616, 1313, 572, 805, 837, 755, 706, 952, 879, 13193, 422, 389, 509, 725, 465, 479, 959,
677, 364, 541, 696, 9306, 322, 318, 767, 590, 422, 530, 403, 505, 566, 445, 508, 7783, 460, 405, 343, 451,
608, 431, 411, 543, 487, 527, 400, 6287, 385, 418, 391, 592, 434, 412, 398, 504, 492, 479, 561, 5413, 317,
355, 422, 467, 452, 476, 460, 490, 492, 485, 451, 5036, 312, 408, 460, 432, 502, 388, 475, 407, 544, 401,
487, 4404, 362, 378, 427, 416, 426, 456, 414, 438, 424, 442, 444, 4310, 362, 388, 393, 390, 441, 398, 423,
369, 443, 406, 392, 4231, 343, 363, 355, 390, 459, 371, 378, 381, 405, 392, 426, 3975, 387, 337, 393, 439,
378, 355, 374, 484, 381, 373, 423, 3869, 312, 350, 400, 345, 356, 320, 473, 431, 386, 338, 431, 3426, 268,
315, 416, 383, 373, 381, 354, 383, 328, 348, 418, 3715, 324, 361, 331, 350, 302, 409, 377, 359, 384, 334,
326, 3439, 266, 324, 329, 353, 405, 303, 357, 332, 292, 361, 333, 3542, 294, 284, 247, 331, 306, 322, 287,
367, 341, 276, 258, 3980, 246, 245, 259, 309, 333, 250, 275, 334, 281, 253, 371, 3640, 213, 231, 301, 302,
228, 289, 290, 281, 201, 284, 277, 4242, 205, 328, 237, 283, 295, 266, 230, 321, 348, 212, 308, 4103, 259,
238, 245, 298, 330, 265, 271, 287, 267, 286, 290, 3856, 269, 242, 209, 314, 267, 278, 280, 314, 250, 433,
238, 3654, 195, 246, 301, 298, 250, 270, 320, 269, 305, 258, 368, 3810, 231, 212, 279, 289, 252, 303, 287,
295, 206, 264, 349, 4071, 242, 296, 271, 231, 307, 265, 254, 267, 317, 232, 348, 4077, 259, 222, 268, 235,
324, 266, 256, 312, 246, 248, 325, 4000, 266, 201, 230, 293, 264, 265, 273, 301, 304, 253, 266, 3978, 228,
232, 250, 248, 281, 219, 243, 293, 287, 253, 328, 3719];
let fdRead;
let readpath;
beforeAll(function() {
console.info('beforeAll case');
// getSurfaceID();
})
beforeEach(async function() {
console.info('beforeEach case');
await toDisplayPage().then(() => {
}, failCallback).catch(failCatch);
await msleep(1000).then(() => {
}, failCallback).catch(failCatch);
frameCountIn = 0;
frameCountOut = 0;
timestamp = 0;
inputQueue = [];
outputQueue = [];
isCodecData = false;
inputEosFlag = false;
surfaceID = globalThis.value;
})
afterEach(async function() {
console.info('afterEach case');
if (videoDecodeProcessor != null) {
await videoDecodeProcessor.release().then(() => {
console.info('in case : videoDecodeProcessor release success');
}, failCallback).catch(failCatch);
videoDecodeProcessor = null;
}
await router.clear().then(() => {
}, failCallback).catch(failCatch);
})
afterAll(function() {
console.info('afterAll case');
})
let failCallback = function(err) {
console.info(`in case error failCallback called, errMessage is ${error.message}`);
expect(err).assertUndefined();
}
let failCatch = function(err) {
console.info(`in case error failCatch called,errMessage is ${error.message}`);
expect(err).assertUndefined();
}
function msleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function toDisplayPage() {
let path = 'pages/display/display';
let options = {
uri: path,
}
try {
await router.push(options);
} catch (e) {
console.error('in case toDisplayPage' + e);
}
}
async function getFdRead(pathName, done) {
await getFileDescriptor(pathName).then((res) => {
if (res == undefined) {
expect().assertFail();
console.info('case error fileDescriptor undefined, open file fail');
done();
} else {
fdRead = res.fd;
console.info("case fdRead is: " + fdRead);
}
})
}
function readFile(path) {
console.info('case read file start execution');
try{
console.info('case filepath: ' + path);
readStreamSync = fileio.fdopenStreamSync(fdRead, 'rb');
}catch(e) {
console.info(e);
}
}
function getContent(buf, len) {
console.info("case start get content");
console.info("case start get content length is: " + len);
let lengthreal = -1;
lengthreal = readStreamSync.readSync(buf,{length:len});
console.info('case lengthreal is :' + lengthreal);
}
/* push inputbuffers into codec */
async function enqueueInputs(inputObject) {
console.log('in case: inputObject.index: ' + inputObject.index);
if (frameCountIn < ES_FRAME_SIZE.length) {
getContent(inputObject.data, ES_FRAME_SIZE[frameCountIn]);
inputObject.timeMs = timestamp;
inputObject.offset = 0;
inputObject.length = ES_FRAME_SIZE[frameCountIn];
console.info('in case: frameCountIn ' + frameCountIn);
frameCountIn++;
timestamp += 16.67;
}
if (isCodecData) {
inputObject.flags = 8;
isCodecData = false;
timestamp = 0;
} else if (frameCountIn >= ES_FRAME_SIZE.length - 1) {
inputObject.flags = 1;
inputEosFlag = true;
} else {
inputObject.flags = 4;
}
if (frameCountIn == ES_FRAME_SIZE.length / 2) {
videoDecodeProcessor.setParameter({
'bitrate': 6400,
}).then(() => {
console.info('in case: setParameter success ');
}, failCallback).catch(failCatch);
}
videoDecodeProcessor.pushInputData(inputObject).then(() => {
console.info('in case: queueInput success ');
}, failCallback).catch(failCatch);
}
/* get outputbuffers from codec */
async function dequeueOutputs(nextStep, outputObject) {
if (outputObject.flags == 1) {
nextStep();
return;
}
frameCountOut++;
await videoDecodeProcessor.freeOutputBuffer(outputObject).then(() => {
console.log('in case: release output count:' + frameCountOut);
}, failCallback).catch(failCatch);
}
function setCallback(nextStep){
console.info('in case: setCallback in');
videoDecodeProcessor.on('needInputData', async (inBuffer) => {
console.info('in case: inputBufferAvailable inBuffer.index: '+ inBuffer.index);
enqueueInputs(inBuffer);
});
videoDecodeProcessor.on('newOutputData', async (outBuffer) => {
console.info('in case: outputBufferAvailable outBuffer.index: '+ outBuffer.index);
videoDecodeProcessor.getOutputMediaDescription().then((MediaDescription) => {
console.info('get outputMediaDescription : ' + MediaDescription);
}, failCallback).catch(failCatch);
dequeueOutputs(nextStep, outBuffer);
});
videoDecodeProcessor.on('error',(err) => {
console.info('in case: error called,errName is' + err);
});
videoDecodeProcessor.on('streamChanged',(format) => {
console.info('in case: Output format changed: ' + format.toString());
});
console.info('in case: setCallback out');
}
async function toCreateVideoDecoderByMime(mime, done) {
await media.createVideoDecoderByMime(mime).then((processor) => {
if (typeof (processor) != 'undefined') {
videoDecodeProcessor = processor;
console.info('in case : createVideoDecoderByMime success');
} else {
console.info('in case : createVideoDecoderByMime fail');
expect().assertFail();
done();
}
}, failCallback).catch(failCatch);
}
async function toGetVideoDecoderCaps() {
await videoDecodeProcessor.getVideoDecoderCaps().then((videoCaps) => {
console.info("case get getVideoDecoderCaps success");
console.info(`print videoCaps:
codecInfo.name ${videoCaps.codecInfo.name}
codecInfo.type ${videoCaps.codecInfo.type}
codecInfo.mimeType ${videoCaps.codecInfo.mimeType}
codecInfo.isHardwareAccelerated ${videoCaps.codecInfo.isHardwareAccelerated}
codecInfo.isSoftwareOnly ${videoCaps.codecInfo.isSoftwareOnly}
codecInfo.isVendor ${videoCaps.codecInfo.isVendor}
supportedBitrate [${videoCaps.supportedBitrate.min}, ${videoCaps.supportedBitrate.max}]
supportedFormats ${videoCaps.supportedFormats}
supportedHeightAlignment ${videoCaps.supportedHeightAlignment}
supportedWidthAlignment ${videoCaps.supportedWidthAlignment}
supportedWidth [${videoCaps.supportedWidth.min}, ${videoCaps.supportedWidth.max}]
supportedHeight [${videoCaps.supportedHeight.min}, ${videoCaps.supportedHeight.max}]
supportedProfiles ${videoCaps.supportedProfiles}
supportedLevels ${videoCaps.supportedLevels}
supportedBitrateMode ${videoCaps.supportedBitrateMode}
supportedQuality [${videoCaps.supportedQuality.min}, ${videoCaps.supportedQuality.max}]
supportedComplexity [${videoCaps.supportedComplexity.min}, ${videoCaps.supportedComplexity.max}]
`);
}, failCallback).catch(failCatch);
}
async function toConfigure(mediaDescription, srcPath) {
await videoDecodeProcessor.configure(mediaDescription).then(() =>{
console.info('in case : configure success');
readFile(srcPath);
}, failCallback).catch(failCatch);
}
async function toSetOutputSurface(isDisplay) {
await videoDecodeProcessor.setOutputSurface(surfaceID, isDisplay).then(() => {
console.info('in case : setOutputSurface success. surfaceID ' + surfaceID);
}, failCallback).catch(failCatch);
}
eventEmitter.on('nextStep', async (done) => {
console.info('in case : nextStep success');
await videoDecodeProcessor.stop().then(() => {
console.info('in case : stop success');
}, failCallback).catch(failCatch);
await videoDecodeProcessor.reset().then(() => {
console.info('in case : reset success');
}, failCallback).catch(failCatch);
await videoDecodeProcessor.release().then(() => {
console.info('in case : release success');
}, failCallback).catch(failCatch);
videoDecodeProcessor = null;
await closeFileDescriptor(readpath);
console.info('in case : done');
done();
});
async function toPrepare() {
await videoDecodeProcessor.prepare().then(() => {
console.info('in case : prepare success');
}, failCallback).catch(failCatch);
}
async function toStart() {
await videoDecodeProcessor.start().then(() => {
console.info('in case : start success');
}, failCallback).catch(failCatch);
}
/* *
* @tc.number : SUB_MEDIA_VIDEO_DECODER_H264_PROMISE_0100
* @tc.name : 001.basic Video decode function
* @tc.desc : start-> EOS -> stop -> reset
* @tc.size : MediumTest
* @tc.type : Function test
* @tc.level : Level0
*/
it('SUB_MEDIA_VIDEO_DECODER_H264_PROMISE_0100', 0, async function (done) {
ES_FRAME_SIZE = H264_FRAME_SIZE_60FPS_320;
isCodecData = true;
let srcPath = 'out_320_240_10s.h264';
readpath = srcPath;
await getFdRead(readpath, done);
let mediaDescription = {
'track_type': 1,
'codec_mime': 'video/avc',
'width': 320,
'height': 240,
'pixel_format': 4,
'frame_rate': 60.00,
'max_input_size': 150000,
}
await toCreateVideoDecoderByMime('video/avc', done);
await toGetVideoDecoderCaps();
await toConfigure(mediaDescription, srcPath);
await toSetOutputSurface(true);
setCallback(
function(){eventEmitter.emit('nextStep', done);}
);
await toPrepare();
await toStart();
})
/* *
* @tc.number : SUB_MEDIA_VIDEO_DECODER_MPEG2_PROMISE_0100
* @tc.name : 001.basic Video decode function
* @tc.desc : start-> EOS -> stop -> reset
* @tc.size : MediumTest
* @tc.type : Function test
* @tc.level : Level0
*/
it('SUB_MEDIA_VIDEO_DECODER_MPEG2_PROMISE_0100', 0, async function (done) {
ES_FRAME_SIZE = MPEG2_FRAME_SIZE;
let srcPath = 'MPEG2_720_480.es';
readpath = srcPath;
await getFdRead(readpath, done);
let mediaDescription = {
'track_type': 1,
'codec_mime': 'video/mpeg2',
'width': 720,
'height': 480,
'pixel_format': 4,
'frame_rate': 60.00,
'max_input_size': 150000,
}
await toCreateVideoDecoderByMime('video/mpeg2', done);
await toGetVideoDecoderCaps();
await toConfigure(mediaDescription, srcPath);
await toSetOutputSurface(true);
setCallback(
function(){eventEmitter.emit('nextStep', done);}
);
await toPrepare();
await toStart();
})
/* *
* @tc.number : SUB_MEDIA_VIDEO_DECODER_MPEG4_PROMISE_0100
* @tc.name : 001.basic Video decode function
* @tc.desc : start-> EOS -> stop -> reset
* @tc.size : MediumTest
* @tc.type : Function test
* @tc.level : Level0
*/
it('SUB_MEDIA_VIDEO_DECODER_MPEG4_PROMISE_0100', 0, async function (done) {
ES_FRAME_SIZE = MPEG4_FRAME_SIZE;
let srcPath = 'mpeg4_320_240.es';
readpath = srcPath;
await getFdRead(readpath, done);
let mediaDescription = {
'track_type': 1,
'codec_mime': 'video/mp4v-es',
'width': 320,
'height': 240,
'pixel_format': 4,
'frame_rate': 60.00,
'max_input_size': 150000,
}
await toCreateVideoDecoderByMime('video/mp4v-es', done);
await toGetVideoDecoderCaps();
await toConfigure(mediaDescription, srcPath);
await toSetOutputSurface(true);
setCallback(
function(){eventEmitter.emit('nextStep', done);}
);
await toPrepare();
await toStart();
})
/* *
* @tc.number : SUB_MEDIA_VIDEO_DECODER_MULTIINSTANCE_PROMISE_0100
* @tc.name : 001.creat multiple video decoders
* @tc.desc : creat multiple video decoders
* @tc.size : MediumTest
* @tc.type : Function test
* @tc.level : Level0
*/
it('SUB_MEDIA_VIDEO_DECODER_MULTIINSTANCE_PROMISE_0100', 0, async function (done) {
ES_FRAME_SIZE = H264_FRAME_SIZE_60FPS_320;
isCodecData = true;
let srcPath = 'out_320_240_10s.h264';
readpath = srcPath;
await getFdRead(readpath, done);
let mediaDescription = {
'track_type': 1,
'codec_mime': 'video/avc',
'width': 320,
'height': 240,
'pixel_format': 4,
'frame_rate': 60.00,
'max_input_size': 150000,
}
let array = new Array();
eventEmitter.on('releaseAllDecoder', async () => {
for (let j = 0; j < 2; j++) {
await array[j].release().then(() => {
array[j] = null;
}, failCallback).catch(failCatch);
}
await videoDecodeProcessor.release().then(() => {
console.info('in case : release success');
}, failCallback).catch(failCatch);
videoDecodeProcessor = null;
await closeFileDescriptor(readpath);
done();
})
for (let i = 0; i < 3; i++) {
await media.createVideoDecoderByMime('video/avc').then((processor) => {
if (typeof (processor) != 'undefined') {
console.info('in case : createVideoDecoderByMime success');
if (i == 2) {
videoDecodeProcessor = processor;
} else {
array[i] = processor;
}
} else {
console.info('in case : createVideoDecoderByMime fail');
expect().assertFail();
done();
}
}, failCallback).catch(failCatch);
}
await toConfigure(mediaDescription, srcPath);
await toSetOutputSurface(true);
setCallback(
function(){eventEmitter.emit('releaseAllDecoder', done);}
);
await toPrepare();
await toStart();
})
})
|
/***
* Excerpted from "Test-Driving JavaScript Applications",
* published by The Pragmatic Bookshelf.
* Copyrights apply to this code. It may not be used to create training material,
* courses, books, articles, and the like. Contact us if you are in doubt.
* We make no guarantees that this code is fit for any purpose.
* Visit http://www.pragmaticprogrammer.com/titles/vsjavas for more book information.
***/
module.exports = function(phrase) {
return true;
};
|
var data = {
"body": "<path d=\"M17 16.5c.28 0 .5-.22.5-.5s-.22-.5-.5-.5s-.5.22-.5.5s.22.5.5.5z\" fill=\"currentColor\"/><circle cx=\"9\" cy=\"12\" r=\"1\" fill=\"currentColor\"/><circle cx=\"13\" cy=\"8\" r=\"1\" fill=\"currentColor\"/><circle cx=\"13\" cy=\"16\" r=\"1\" fill=\"currentColor\"/><path d=\"M17 12.5c.28 0 .5-.22.5-.5s-.22-.5-.5-.5s-.5.22-.5.5s.22.5.5.5z\" fill=\"currentColor\"/><circle cx=\"13\" cy=\"12\" r=\"1\" fill=\"currentColor\"/><path d=\"M3 3h18v2H3z\" fill=\"currentColor\"/><circle cx=\"5\" cy=\"8\" r=\"1.5\" fill=\"currentColor\"/><circle cx=\"5\" cy=\"12\" r=\"1.5\" fill=\"currentColor\"/><circle cx=\"5\" cy=\"16\" r=\"1.5\" fill=\"currentColor\"/><path d=\"M17 8.5c.28 0 .5-.22.5-.5s-.22-.5-.5-.5s-.5.22-.5.5s.22.5.5.5z\" fill=\"currentColor\"/><circle cx=\"9\" cy=\"16\" r=\"1\" fill=\"currentColor\"/><circle cx=\"9\" cy=\"8\" r=\"1\" fill=\"currentColor\"/><path d=\"M3 19h18v2H3z\" fill=\"currentColor\"/>",
"width": 24,
"height": 24
};
exports.__esModule = true;
exports.default = data;
|
import React, { useState, useEffect, useRef } from 'react'
import '../App.css'
import InfoCard from './Info'
import {fontList, INP_TYPES, BORDER_STYLES, FONT_WEIGHTS} from './Constants'
import { builders, constructRGB } from './Utils'
import {ChromePicker} from 'react-color'
import { Evaluators } from './evaluator'
let SimpleInput = ({title, value, onChangeParams}) => {
return (
<div className="input_container row">
<div className="col-md-3 col-12 label">{title}</div>
<div className="input_o_container col-md-9 col-12">
<input
className="simple-input-option"
type="text"
value={value}
onChange={(e) => onChangeParams(e.target.value)} />
</div>
</div>
)
}
let SelectorInput = ({title, value, keys, onChangeParams}) => {
return (
<div className="input_container row">
<div className="col-md-3 col-12 label">{title}</div>
<div className="col-md-9 col-12 input_o_container">
<select
value={value} onChange={(e) => onChangeParams(e.target.value)}
className="simple-input-option" >
{ keys.map((item, index) => <option className="inp_select_option" key={index} value={item}>{item}</option>) }
</select>
</div>
</div>
)
}
let CheckBoxInput = ({title, value, onChangeParams}) => {
console.log("CheckBox")
console.log(title)
console.log(value)
return (
<div className="input_container row">
<div className="col-md-3 col-12 label">{title}</div>
<div className="col-md-9 col-12 input_o_container">
<input
type="checkbox"
className="checkbox"
checked={value == 'true' ? true : false} onChange={(e) => onChangeParams(value == 'true' ? 'false' : 'true')} />
</div>
</div>
)
}
let ColorSelector = ({show, value, onClose, onChange}) => {
return (
<div className="color_container" style={{display: show ? "block": "none"}}>
<button className="close_btn" onClick={() => onClose()}>x</button>
<div className="chrome_picker">
<ChromePicker color={value} onChange={(c, e) => onChange(constructRGB(c.rgb))} />
</div>
</div>
)
}
let ColorInput = ({title, value, onChangeParams}) => {
console.log(value)
let [show, setShow] = useState(false)
return (
<div className="input_container row">
<div className="col-md-3 col-12 label">{title}</div>
<div className="col-md-9 col-12 input_o_container">
<div className="selected_color" style={{
backgroundColor: value
}}
onClick={() => setShow(true)} />
<ColorSelector
show={show}
onClose={() => setShow(false)}
value={value}
onChange={(hex) => onChangeParams(hex)} />
</div>
</div>
)
}
let TileRender = ({type, config}) => {
let TRender = null
switch(type) {
case INP_TYPES.SIMPLE_INPUT: TRender = <SimpleInput title={config.title} value={config.value} onChangeParams={(e) => config.onChange(config.k1, config.k2, e)} />; break;
case INP_TYPES.SELECTPANEL: TRender = <SelectorInput title={config.title} value={config.value} keys={config.keys} onChangeParams={(e) => config.onChange(config.k1, config.k2, e)} />; break;
case INP_TYPES.CHECKBOX: TRender = <CheckBoxInput title={config.title} value={config.value} onChangeParams={(e) => config.onChange(config.k1, config.k2, e)} />; break;
case INP_TYPES.COLOR_INPUT: TRender = <ColorInput title={config.title} value={config.value} onChangeParams={(e) => config.onChange(config.k1, config.k2, e)}/>; break;
}
return TRender;
}
let RenderTitle = ({title, varInfo}) => {
return (<div className="title_container">
<div className="title">{title}</div>
{
varInfo.render ?
<input
className="simple_input"
type="text"
value={varInfo.value}
onChange={(e) => varInfo.set(e.target.value)}/>:
<></>
}
</div>
)
}
let RenderTileArray = (a) => {
return a.map(
(item, index) => <TileRender key={index} {...item} />
)
}
let Settings = ({cs, onChangeSettings}) => {
let [tempTitleText, setTempTitleText] = useState("Mario")
let [tempUrlImage, setUrlImage] = useState("https://purepng.com/public/uploads/large/purepng.com-mariomariofictional-charactervideo-gamefranchisenintendodesigner-1701528634653vywuz.png")
let [tempTimeText, setTempTimeText] = useState("12 Years Old")
let [tempMoreInfoText, setTempMoreInfoText] = useState("More Info goes Here")
let ChangeSimpleInputType = (key1, key2, e) => {
onChangeSettings(key1, key2, e)
}
console.log(cs)
console.log(cs.evalInfo.evaluator === 'date')
console.log(cs.evalInfo.evaluator)
console.log(cs.evalConfig.applyFormat)
return (
<div className="container-fluid" style={{width: "100%"}}>
<div className="row">
<div className="col-lg-6 col-12" style={{position: "relative", height: "80vh"}} >
<div style={{position: "relative", display: "block", margin: "auto", paddingTop: "8px", margin: "16px 8px", borderRadius: "4px", height: "100%", width: "100%"}}>
<div style={{position: "absolute", top: "75%", left: "50%"}}>
<InfoCard
rPosition="50px"
infoStyleInfo={cs.infoStyleInfo}
titleInfo={{
text: `${tempTitleText}`,
styleInfo: cs.titleTextStyleInfo
}}
imageInfo={{
imageURL: `${tempUrlImage}`,
styleInfo: cs.imageStyleInfo
}}
timeInfo={{
timeText:`${cs.evalConfig.prefix}${tempTimeText}${cs.evalConfig.suffix}`,
styleInfo: cs.timeStyleInfo
}}
barInfo = {{
currentHeight: cs.barStyleInfo.height,
styleInfo: cs.barStyleInfo,
dummyBar: true
}}
moreInfo={{
moreInfoText: tempMoreInfoText,
styleInfo: cs.moreInfo
}}
renderMoreInfo={true}
/>
</div>
</div>
</div>
<div className="col-lg-6 col-12" style={{overflowY: "scroll", height: "80vh"}}>
<div className="col-12" style={{margin: "0px", padding: "0px"}}>
<RenderTitle title="title" varInfo={{render: true, set: setTempTitleText, value: tempTitleText}} />
<div>
<ul>
{
RenderTileArray([
builders.makeSimpleInput("Padding", cs.titleTextStyleInfo.padding, ChangeSimpleInputType, "titleTextStyleInfo", "padding"),
builders.makeSimpleInput("Border Radius", cs.titleTextStyleInfo.borderRadius, ChangeSimpleInputType, "titleTextStyleInfo", "borderRadius"),
builders.makeColorInput("Background Color", cs.titleTextStyleInfo.backgroundColor, ChangeSimpleInputType, "titleTextStyleInfo", "backgroundColor"),
builders.makeSelectPanel("Font Family", cs.titleTextStyleInfo.fontFamily, Object.keys(fontList), ChangeSimpleInputType, "titleTextStyleInfo", "fontFamily"),
builders.makeColorInput('Text Color', cs.titleTextStyleInfo.color, ChangeSimpleInputType, "titleTextStyleInfo", "color"),
builders.makeSimpleInput("Text Size", cs.titleTextStyleInfo.fontSize, ChangeSimpleInputType, "titleTextStyleInfo", "fontSize"),
builders.makeSelectPanel("Font Weight", cs.titleTextStyleInfo.fontWeight, FONT_WEIGHTS, ChangeSimpleInputType, "titleTextStyleInfo", "fontWeight")
])
}
</ul>
</div>
</div>
<div className="col-12" style={{margin: "0px", padding: "0px"}}>
<RenderTitle title="Image Setting" varInfo={{render: true, set: setUrlImage, value: tempUrlImage}} />
<div>
<ul>
{
RenderTileArray([
builders.makeSimpleInput("Padding", cs.imageStyleInfo.padding, ChangeSimpleInputType, "imageStyleInfo", "padding"),
builders.makeSimpleInput("Height", cs.imageStyleInfo.height, ChangeSimpleInputType, "imageStyleInfo", "height"),
builders.makeSimpleInput("Width", cs.imageStyleInfo.width, ChangeSimpleInputType, "imageStyleInfo", "width"),
builders.makeSimpleInput("Border Radius", cs.imageStyleInfo.borderRadius, ChangeSimpleInputType, "imageStyleInfo", "borderRadius"),
builders.makeColorInput("Background Color", cs.imageStyleInfo.backgroundColor, ChangeSimpleInputType, "imageStyleInfo", "backgroundColor"),
builders.makeSimpleInput("Bottom Margin", cs.imageStyleInfo.marginBottom, ChangeSimpleInputType, "imageStyleInfo", "marginBottom")
])
}
</ul>
</div>
</div>
<div className="col-12" style={{margin: "0px", padding: "0px"}}>
<RenderTitle title="Time Settings" varInfo={{render: true, set: setTempTimeText, value: tempTimeText}} />
<div>
<ul>
{
RenderTileArray([
builders.makeSimpleInput("Bottom Margin", cs.timeStyleInfo.marginBottom, ChangeSimpleInputType, "timeStyleInfo", "marginBottom"),
builders.makeSimpleInput("Font Size", cs.timeStyleInfo.fontSize, ChangeSimpleInputType, "timeStyleInfo", "fontSize"),
builders.makeSelectPanel("Font Family", cs.timeStyleInfo.fontFamily, Object.keys(fontList), ChangeSimpleInputType, "timeStyleInfo", "fontFamily"),
builders.makeColorInput("Text Color", cs.timeStyleInfo.color, ChangeSimpleInputType, "timeStyleInfo", "color"),
builders.makeSelectPanel("Font Weight", cs.timeStyleInfo.fontWeight, FONT_WEIGHTS, ChangeSimpleInputType, "timeStyleInfo", "fontWeight")
])
}
</ul>
</div>
</div>
<div className="col-12" style={{margin: "0px", padding: "0px"}}>
<RenderTitle title="Bar Settings" varInfo={{render: false}}/>
<div>
<ul>
{
RenderTileArray([
builders.makeSimpleInput("Border Radius", cs.barStyleInfo.borderRadius, ChangeSimpleInputType, "barStyleInfo", "borderRadius"),
builders.makeSimpleInput("Bar Width", cs.barStyleInfo.barWidth, ChangeSimpleInputType, "barStyleInfo", "barWidth"),
builders.makeColorInput("Background Color", cs.barStyleInfo.backgroundColor, ChangeSimpleInputType, "barStyleInfo", "backgroundColor"),
builders.makeSimpleInput("Bar Height", cs.barStyleInfo.height, ChangeSimpleInputType, "barStyleInfo", "height"),
])
}
</ul>
</div>
</div>
<div className="col-12" style={{margin: "0px", padding: "0px"}}>
<RenderTitle title="Card Settings" varInfo={{render: false}}/>
<div>
<ul>
{
RenderTileArray([
builders.makeSimpleInput("Card Width", cs.infoStyleInfo.width, ChangeSimpleInputType, "infoStyleInfo", "width")
])
}
</ul>
</div>
</div>
<div className="col-12" style={{margin: "0px", padding: "0px"}}>
<RenderTitle title="Begin Point Info" varInfo={{render: false}}/>
<div>
<ul>
{
RenderTileArray([
builders.makeSimpleInput("Ball Radius", cs.beginPointInfo.ballSize, ChangeSimpleInputType, "beginPointInfo", "ballSize"),
builders.makeCheckPanel("Show Begin Point", cs.beginPointInfo.show, ChangeSimpleInputType, "beginPointInfo", "show"),
builders.makeSimpleInput("Bar Width", cs.beginPointInfo.barWidth, ChangeSimpleInputType, "beginPointInfo", "barWidth")
])
}
</ul>
</div>
</div>
<div className="col-12" style={{margin: "0px", padding: "0px"}}>
<RenderTitle title="Evaluator Info" varInfo={{render: false}}/>
<div>
<ul>
{
cs.evalInfo.evaluator == "date" ?
RenderTileArray([
builders.makeSelectPanel("Evaluator", cs.evalInfo.evaluator, ['date', 'number', 'string'], ChangeSimpleInputType, "evalInfo", "evaluator"),
builders.makeSimpleInput("Prefix", cs.evalConfig.prefix, ChangeSimpleInputType, "evalConfig", "prefix"),
builders.makeSimpleInput("Suffix", cs.evalConfig.suffix, ChangeSimpleInputType, "evalConfig", "suffix"),
builders.makeCheckPanel("Apply Format", cs.evalConfig.applyFormat, ChangeSimpleInputType, "evalConfig", "applyFormat")
]):
RenderTileArray([
builders.makeSelectPanel("Evaluator", cs.evalInfo.evaluator, ['date', 'number', 'string'], ChangeSimpleInputType, "evalInfo", "evaluator"),
builders.makeSimpleInput("Prefix", cs.evalConfig.prefix, ChangeSimpleInputType, "evalConfig", "prefix"),
builders.makeSimpleInput("Suffix", cs.evalConfig.suffix, ChangeSimpleInputType, "evalConfig", "suffix")
])
}
</ul>
</div>
</div>
<div className="col-12" style={{margin: "0px", padding: "0px"}}>
<RenderTitle title="More Info" varInfo={{render: false}}/>
<div>
<ul>
{
RenderTileArray([
builders.makeColorInput("Background Color", cs.moreInfo.background, ChangeSimpleInputType, "moreInfo", "background"),
builders.makeSimpleInput("Padding", cs.moreInfo.padding, ChangeSimpleInputType, "moreInfo", "padding"),
builders.makeSelectPanel("Font Family", cs.moreInfo.fontFamily, Object.keys(fontList), ChangeSimpleInputType, "moreInfo", "fontFamily"),
builders.makeSimpleInput("Bottom", cs.moreInfo.bottom, ChangeSimpleInputType, "moreInfo", "bottom"),
builders.makeSimpleInput("Border Radius", cs.moreInfo.borderRadius, ChangeSimpleInputType, "moreInfo", "borderRadius"),
builders.makeSimpleInput("Border Width", cs.moreInfo.borderWidth, ChangeSimpleInputType, "moreInfo", "borderWidth"),
builders.makeSelectPanel("Border Style", cs.moreInfo.borderStyle, BORDER_STYLES,ChangeSimpleInputType, "moreInfo", "borderStyle"),
builders.makeColorInput("Border Color", cs.moreInfo.borderColor, ChangeSimpleInputType, "moreInfo", "borderColor"),
builders.makeColorInput("Text Color", cs.moreInfo.color, ChangeSimpleInputType, "moreInfo", "color"),
builders.makeSimpleInput("Font Size", cs.moreInfo.fontSize, ChangeSimpleInputType, "moreInfo", "fontSize"),
builders.makeSelectPanel("Font Weight", cs.moreInfo.fontWeight, FONT_WEIGHTS, ChangeSimpleInputType, "moreInfo", "fontWeight")
])
}
</ul>
</div>
</div>
<div className="col-12" style={{margin: "0px", padding: "0px"}}>
<RenderTitle title="Player State" varInfo={{render: false}}/>
<div>
<ul>
{
RenderTileArray([
builders.makeColorInput("Background Color", cs.playerState.backgroundColor, ChangeSimpleInputType, "playerState", "backgroundColor"),
builders.makeSimpleInput("Max Count", cs.playerState.maxCount, ChangeSimpleInputType, "playerState", "maxCount"),
builders.makeSimpleInput("Spawn Interval", cs.playerState.delay, ChangeSimpleInputType, "playerState", "delay"),
builders.makeSimpleInput("Height Transition Time", cs.playerState.hTransitionTime, ChangeSimpleInputType, "playerState", "hTransitionTime")
])
}
</ul>
</div>
</div>
</div>
</div>
</div>
)
}
export default Settings
|
import * as types from "./actionTypes";
import axios from "axios";
import { getToken, getUserIdFromUserData } from "../../token.helper";
import { API_URL } from "../../app.json";
export function addUserData(formData) {
return function (dispatch) {
dispatch({ type: "CLIENT_POST_LOADING", payload: true });
// alert("http://127.0.0.1/myapi/clients/signup");
// return;
axios({
method: "post",
url: `${API_URL}/myapi/clients/${getUserIdFromUserData()}`,
// url: `127.0.0.1/myapi/clients/${getUserIdFromUserData()}`,
// url: `http://127.0.0.1/myapi/${getUserIdFromUserData()}/`,
// url: `${API_URL}/myapi/clients/preferences/${getUserIdFromUserData()}`,
// data: { hello: "world" },
data: formData,
headers: {
Accept: "multipart/form-data",
"Content-Type": "multipart/form-data",
Authorization: "Bearer " + getToken(),
},
})
.then(function (response) {
dispatch({ type: "CLIENT_POST_LOADING", payload: false });
// alert(JSON.stringify(response.data.data));
if (response?.status === 200 && response.data?.success) {
alert(JSON.stringify(response?.data?.data));
dispatch({
type: "CLIENT_DATA_SUCSESS",
step: response?.data?.data?.step,
userData: response?.data?.data,
});
} else {
dispatch({
type: "CLIENT_ERROR",
payload: response.data?.message,
});
}
})
.catch(function (error) {
// alert(JSON.stringify(error.message));
// alert(JSON.stringify(error));
dispatch({
type: "CLIENT_ERROR",
payload: error.message,
});
})
.finally(() => {
dispatch({ type: "CLIENT_POST_LOADING", payload: false });
});
};
}
export function editUserData(formData) {
return function (dispatch) {
dispatch({ type: "CLIENT_POST_LOADING", payload: true });
// alert("http://127.0.0.1/myapi/clients/signup");
// return;
axios({
method: "put",
url: `${API_URL}/myapi/clients/${getUserIdFromUserData()}`,
// url: `127.0.0.1/myapi/clients/${getUserIdFromUserData()}`,
// url: `http://127.0.0.1/myapi/${getUserIdFromUserData()}/`,
// url: `${API_URL}/myapi/clients/preferences/${getUserIdFromUserData()}`,
// data: { hello: "world" },
data: formData,
headers: {
Accept: "multipart/form-data",
"Content-Type": "multipart/form-data",
Authorization: "Bearer " + getToken(),
},
})
.then(function (response) {
dispatch({ type: "CLIENT_POST_LOADING", payload: false });
// alert(JSON.stringify(response.data.data));
if (response?.status === 200 && response.data?.success) {
// alert(JSON.stringify(response?.data?.data));
dispatch({
type: "CLIENT_DATA_SUCSESS",
step: response?.data?.data?.step,
userData: response?.data?.data,
});
} else {
dispatch({
type: "CLIENT_ERROR",
payload: response.data?.message,
});
}
})
.catch(function (error) {
// alert(JSON.stringify(error.message));
// alert(JSON.stringify(error));
dispatch({
type: "CLIENT_ERROR",
payload: error.message,
});
})
.finally(() => {
dispatch({ type: "CLIENT_POST_LOADING", payload: false });
});
};
}
export function addUserPreferences(formData) {
return function (dispatch) {
dispatch({ type: "CLIENT_POST_LOADING", payload: true });
// alert(getUserIdFromUserData());
// return;
axios({
method: "post",
url: `${API_URL}/myapi/clients/preferences/${getUserIdFromUserData()}`,
data: formData,
// data: { hello: "ff" },
headers: {
Authorization: "Bearer " + getToken(),
},
})
.then(function (response) {
dispatch({ type: "CLIENT_POST_LOADING", payload: false });
if (response?.status === 200 && response.data?.success) {
dispatch({
type: "CLIENT_DATA_SUCSESS",
step: response?.data?.data?.step,
userData: response?.data?.data,
});
} else {
dispatch({
type: "CLIENT_ERROR",
payload: response.data?.message,
});
}
})
.catch(function (error) {
alert(error.message);
dispatch({
type: "CLIENT_ERROR",
payload: error,
});
})
.finally(() => {
dispatch({ type: "CLIENT_POST_LOADING", payload: false });
});
};
}
export function editUserPreferences(formData) {
return function (dispatch) {
dispatch({ type: "CLIENT_POST_LOADING", payload: true });
// alert(getUserIdFromUserData());
// return;
axios({
method: "put",
url: `${API_URL}/myapi/clients/preferences/${getUserIdFromUserData()}`,
data: formData,
// data: { hello: "ff" },
headers: {
Authorization: "Bearer " + getToken(),
},
})
.then(function (response) {
dispatch({ type: "CLIENT_POST_LOADING", payload: false });
if (response?.status === 200 && response.data?.success) {
dispatch({
type: "CLIENT_DATA_SUCSESS",
step: response?.data?.data?.step,
userData: response?.data?.data,
});
} else {
dispatch({
type: "CLIENT_ERROR",
payload: response.data?.message,
});
}
})
.catch(function (error) {
alert(
`${API_URL}/myapi/clients/preferences/${getUserIdFromUserData()}`
);
// alert(error.message);
dispatch({
type: "CLIENT_ERROR",
payload: response.data?.message,
});
})
.finally(() => {
dispatch({ type: "CLIENT_POST_LOADING", payload: false });
});
};
}
|
import React, { useState, useEffect, useContext } from 'react'
import '../Styles/Graphics.css'
import { Doughnut } from 'react-chartjs-2'
import Context from '../GlobalState/context';
const DonnutChart = props => {
const {state, actions} = useContext(Context)
const [chartData, setChartData] = useState({})
const [options, setOptions] = useState({})
useEffect(() => {
setChartData({
labels: props.data.labels,
datasets: [{
data: props.data.data,
borderColor: props.data.backgroundColor,
backgroundColor: props.data.colors,
hoverBackgroundColor: props.data.colors
}],
text: '20%'
});
setOptions({
title: {
display: true,
text: 'Tiempo dedicado en tareas',
position: 'top',
fontColor: 'cyan',
fontSize: '20',
fontFamily: "Montserrat"
},
legend: {
display: false,
position: 'right',
labels: {
fontColor: 'white',
fontStyle: 'bolder',
fontFamily: "Montserrat"
}
}
})
})
return (
<div className='main-barchart-container'>
<div style={{ width: props.data.size}}>
<Doughnut
data={chartData}
options={options}
/>
</div>
</div>
)
}
export default DonnutChart
|
/* eslint-env mocha */
'use strict'
const chai = require('chai')
chai.use(require('dirty-chai'))
const expect = chai.expect
const parallel = require('async/parallel')
const series = require('async/series')
const signalling = require('eth-libp2p-webrtc-star/src/sig-server')
const rendezvous = require('eth-libp2p-websocket-star-rendezvous')
const TCP = require('libp2p-tcp')
const WS = require('libp2p-websockets')
const WSStar = require('eth-libp2p-websocket-star')
const WRTCStar = require('eth-libp2p-webrtc-star')
const wrtc = require('wrtc')
const createNode = require('./utils/create-node.js')
const tryEcho = require('./utils/try-echo')
const echo = require('./utils/echo')
describe('transports', () => {
describe('TCP only', () => {
let nodeA
let nodeB
before((done) => {
parallel([
(cb) => createNode('/ip4/0.0.0.0/tcp/0', (err, node) => {
expect(err).to.not.exist()
nodeA = node
node.handle('/echo/1.0.0', echo)
node.start(cb)
}),
(cb) => createNode('/ip4/0.0.0.0/tcp/0', (err, node) => {
expect(err).to.not.exist()
nodeB = node
node.handle('/echo/1.0.0', echo)
node.start(cb)
})
], done)
})
after((done) => {
parallel([
(cb) => nodeA.stop(cb),
(cb) => nodeB.stop(cb)
], done)
})
it('nodeA.dial nodeB using PeerInfo without proto (warmup)', (done) => {
nodeA.dial(nodeB.peerInfo, (err) => {
expect(err).to.not.exist()
// Some time for Identify to finish
setTimeout(check, 500)
function check () {
parallel([
(cb) => {
const peers = nodeA.peerBook.getAll()
expect(err).to.not.exist()
expect(Object.keys(peers)).to.have.length(1)
cb()
},
(cb) => {
const peers = nodeB.peerBook.getAll()
expect(err).to.not.exist()
expect(Object.keys(peers)).to.have.length(1)
cb()
}
], done)
}
})
})
it('nodeA.dial nodeB using PeerInfo', (done) => {
nodeA.dialProtocol(nodeB.peerInfo, '/echo/1.0.0', (err, conn) => {
expect(err).to.not.exist()
tryEcho(conn, done)
})
})
it('nodeA.hangUp nodeB using PeerInfo (first)', (done) => {
nodeA.hangUp(nodeB.peerInfo, (err) => {
expect(err).to.not.exist()
setTimeout(check, 500)
function check () {
parallel([
(cb) => {
const peers = nodeA.peerBook.getAll()
expect(Object.keys(peers)).to.have.length(1)
expect(nodeA._switch.connection.getAll()).to.have.length(0)
cb()
},
(cb) => {
const peers = nodeB.peerBook.getAll()
expect(Object.keys(peers)).to.have.length(1)
expect(nodeB._switch.connection.getAll()).to.have.length(0)
cb()
}
], done)
}
})
})
it('nodeA.dialProtocol nodeB using multiaddr', (done) => {
nodeA.dialProtocol(nodeB.peerInfo.multiaddrs.toArray()[0], '/echo/1.0.0', (err, conn) => {
// Some time for Identify to finish
setTimeout(check, 500)
function check () {
expect(err).to.not.exist()
series([
(cb) => {
const peers = nodeA.peerBook.getAll()
expect(Object.keys(peers)).to.have.length(1)
expect(nodeA._switch.connection.getAll()).to.have.length(1)
cb()
},
(cb) => {
const peers = nodeB.peerBook.getAll()
expect(Object.keys(peers)).to.have.length(1)
expect(nodeA._switch.connection.getAll()).to.have.length(1)
cb()
}
], () => tryEcho(conn, done))
}
})
})
it('nodeA.hangUp nodeB using multiaddr (second)', (done) => {
nodeA.hangUp(nodeB.peerInfo.multiaddrs.toArray()[0], (err) => {
expect(err).to.not.exist()
setTimeout(check, 500)
function check () {
parallel([
(cb) => {
const peers = nodeA.peerBook.getAll()
expect(Object.keys(peers)).to.have.length(1)
expect(nodeA._switch.connection.getAll()).to.have.length(0)
cb()
},
(cb) => {
const peers = nodeB.peerBook.getAll()
expect(Object.keys(peers)).to.have.length(1)
expect(nodeB._switch.connection.getAll()).to.have.length(0)
cb()
}
], done)
}
})
})
it('nodeA.dialProtocol nodeB using PeerId', (done) => {
nodeA.dialProtocol(nodeB.peerInfo.id, '/echo/1.0.0', (err, conn) => {
// Some time for Identify to finish
setTimeout(check, 500)
function check () {
expect(err).to.not.exist()
series([
(cb) => {
const peers = nodeA.peerBook.getAll()
expect(Object.keys(peers)).to.have.length(1)
expect(nodeA._switch.connection.getAll()).to.have.length(1)
cb()
},
(cb) => {
const peers = nodeB.peerBook.getAll()
expect(Object.keys(peers)).to.have.length(1)
expect(nodeA._switch.connection.getAll()).to.have.length(1)
cb()
}
], () => tryEcho(conn, done))
}
})
})
it('nodeA.hangUp nodeB using PeerId (third)', (done) => {
nodeA.hangUp(nodeB.peerInfo.id, (err) => {
expect(err).to.not.exist()
setTimeout(check, 500)
function check () {
parallel([
(cb) => {
const peers = nodeA.peerBook.getAll()
expect(Object.keys(peers)).to.have.length(1)
expect(nodeA._switch.connection.getAll()).to.have.length(0)
cb()
},
(cb) => {
const peers = nodeB.peerBook.getAll()
expect(Object.keys(peers)).to.have.length(1)
expect(nodeB._switch.connection.getAll()).to.have.length(0)
cb()
}
], done)
}
})
})
it('.dialFSM check conn and close', (done) => {
nodeA.dialFSM(nodeB.peerInfo, (err, connFSM) => {
expect(err).to.not.exist()
connFSM.once('muxed', () => {
expect(
nodeA._switch.connection.getAllById(nodeB.peerInfo.id.toB58String())
).to.have.length(1)
connFSM.once('error', done)
connFSM.once('close', () => {
// ensure the connection is closed
expect(
nodeA._switch.connection.getAllById(nodeB.peerInfo.id.toB58String())
).to.have.length(0)
done()
})
connFSM.close()
})
})
})
it('.dialFSM with a protocol, do an echo and close', (done) => {
nodeA.dialFSM(nodeB.peerInfo, '/echo/1.0.0', (err, connFSM) => {
expect(err).to.not.exist()
connFSM.once('connection', (conn) => {
expect(
nodeA._switch.connection.getAllById(nodeB.peerInfo.id.toB58String())
).to.have.length(1)
tryEcho(conn, () => {
connFSM.close()
})
})
connFSM.once('error', done)
connFSM.once('close', () => {
// ensure the connection is closed
expect(
nodeA._switch.connection.getAllById(nodeB.peerInfo.id.toB58String())
).to.have.length(0)
done()
})
})
})
})
describe('TCP + WebSockets', () => {
let nodeTCP
let nodeTCPnWS
let nodeWS
before((done) => {
parallel([
(cb) => createNode([
'/ip4/0.0.0.0/tcp/0'
], (err, node) => {
expect(err).to.not.exist()
nodeTCP = node
node.handle('/echo/1.0.0', echo)
node.start(cb)
}),
(cb) => createNode([
'/ip4/0.0.0.0/tcp/0',
'/ip4/127.0.0.1/tcp/25011/ws'
], (err, node) => {
expect(err).to.not.exist()
nodeTCPnWS = node
node.handle('/echo/1.0.0', echo)
node.start(cb)
}),
(cb) => createNode([
'/ip4/127.0.0.1/tcp/25022/ws'
], (err, node) => {
expect(err).to.not.exist()
nodeWS = node
node.handle('/echo/1.0.0', echo)
node.start(cb)
})
], done)
})
after((done) => {
parallel([
(cb) => nodeTCP.stop(cb),
(cb) => nodeTCPnWS.stop(cb),
(cb) => nodeWS.stop(cb)
], done)
})
it('nodeTCP.dial nodeTCPnWS using PeerInfo', (done) => {
nodeTCP.dial(nodeTCPnWS.peerInfo, (err) => {
expect(err).to.not.exist()
// Some time for Identify to finish
setTimeout(check, 500)
function check () {
parallel([
(cb) => {
const peers = nodeTCP.peerBook.getAll()
expect(Object.keys(peers)).to.have.length(1)
expect(nodeTCP._switch.connection.getAll()).to.have.length(1)
cb()
},
(cb) => {
const peers = nodeTCPnWS.peerBook.getAll()
expect(Object.keys(peers)).to.have.length(1)
expect(nodeTCPnWS._switch.connection.getAll()).to.have.length(1)
cb()
}
], done)
}
})
})
it('nodeTCP.hangUp nodeTCPnWS using PeerInfo', (done) => {
nodeTCP.hangUp(nodeTCPnWS.peerInfo, (err) => {
expect(err).to.not.exist()
setTimeout(check, 500)
function check () {
parallel([
(cb) => {
const peers = nodeTCP.peerBook.getAll()
expect(Object.keys(peers)).to.have.length(1)
expect(nodeTCP._switch.connection.getAll()).to.have.length(0)
cb()
},
(cb) => {
const peers = nodeTCPnWS.peerBook.getAll()
expect(Object.keys(peers)).to.have.length(1)
expect(nodeTCPnWS._switch.connection.getAll()).to.have.length(0)
cb()
}
], done)
}
})
})
it('nodeTCPnWS.dial nodeWS using PeerInfo', (done) => {
nodeTCPnWS.dial(nodeWS.peerInfo, (err) => {
expect(err).to.not.exist()
// Some time for Identify to finish
setTimeout(check, 500)
function check () {
parallel([
(cb) => {
const peers = nodeTCPnWS.peerBook.getAll()
expect(Object.keys(peers)).to.have.length(2)
expect(nodeTCPnWS._switch.connection.getAll()).to.have.length(1)
cb()
},
(cb) => {
const peers = nodeWS.peerBook.getAll()
expect(Object.keys(peers)).to.have.length(1)
expect(nodeWS._switch.connection.getAll()).to.have.length(1)
cb()
}
], done)
}
})
})
it('nodeTCPnWS.hangUp nodeWS using PeerInfo', (done) => {
nodeTCPnWS.hangUp(nodeWS.peerInfo, (err) => {
expect(err).to.not.exist()
setTimeout(check, 500)
function check () {
parallel([
(cb) => {
const peers = nodeTCPnWS.peerBook.getAll()
expect(Object.keys(peers)).to.have.length(2)
expect(nodeTCPnWS._switch.connection.getAll()).to.have.length(0)
cb()
},
(cb) => {
const peers = nodeWS.peerBook.getAll()
expect(Object.keys(peers)).to.have.length(1)
expect(nodeWS._switch.connection.getAll()).to.have.length(0)
cb()
}
], done)
}
})
})
// Until https://github.com/libp2p/js-libp2p/issues/46 is resolved
// Everynode will be able to dial in WebSockets
it.skip('nodeTCP.dial nodeWS using PeerInfo is unsuccesful', (done) => {
nodeTCP.dial(nodeWS.peerInfo, (err) => {
expect(err).to.exist()
done()
})
})
})
describe('TCP + WebSockets + WebRTCStar', () => {
let nodeAll
let nodeTCP
let nodeWS
let nodeWebRTCStar
let ss
before(function (done) {
this.timeout(5 * 1000)
parallel([
(cb) => signalling.start({ port: 24642 }).then(server => {
ss = server
cb()
}),
(cb) => {
const wstar = new WRTCStar({ wrtc: wrtc })
createNode([
'/ip4/0.0.0.0/tcp/0',
'/ip4/127.0.0.1/tcp/25011/ws',
'/ip4/127.0.0.1/tcp/24642/ws/p2p-webrtc-star'
], {
modules: {
transport: [
TCP,
WS,
wstar
],
peerDiscovery: [wstar.discovery]
},
config: {
peerDiscovery: {
autoDial: false,
[wstar.discovery.tag]: {
enabled: true
}
}
}
}, (err, node) => {
expect(err).to.not.exist()
nodeAll = node
node.handle('/echo/1.0.0', echo)
node.start(cb)
})
},
(cb) => createNode([
'/ip4/0.0.0.0/tcp/0'
], {
config: {
peerDiscovery: {
autoDial: false
}
}
}, (err, node) => {
expect(err).to.not.exist()
nodeTCP = node
node.handle('/echo/1.0.0', echo)
node.start(cb)
}),
(cb) => createNode([
'/ip4/127.0.0.1/tcp/25022/ws'
], {
config: {
peerDiscovery: {
autoDial: false
}
}
}, (err, node) => {
expect(err).to.not.exist()
nodeWS = node
node.handle('/echo/1.0.0', echo)
node.start(cb)
}),
(cb) => {
const wstar = new WRTCStar({ wrtc: wrtc })
createNode([
'/ip4/127.0.0.1/tcp/24642/ws/p2p-webrtc-star'
], {
modules: {
transport: [wstar],
peerDiscovery: [wstar.discovery]
},
config: {
peerDiscovery: {
autoDial: false,
[wstar.discovery.tag]: {
enabled: true
}
}
}
}, (err, node) => {
expect(err).to.not.exist()
nodeWebRTCStar = node
node.handle('/echo/1.0.0', echo)
node.start(cb)
})
}
], done)
})
after(function (done) {
this.timeout(10 * 1000)
parallel([
(cb) => nodeAll.stop(cb),
(cb) => nodeTCP.stop(cb),
(cb) => nodeWS.stop(cb),
(cb) => nodeWebRTCStar.stop(cb),
(cb) => ss.stop().then(cb)
], done)
})
function check (otherNode, muxed, peers, callback) {
let i = 1;
[nodeAll, otherNode].forEach((node) => {
expect(Object.keys(node.peerBook.getAll())).to.have.length(i-- ? peers : 1)
expect(node._switch.connection.getAll()).to.have.length(muxed)
})
callback()
}
it('nodeAll.dial nodeTCP using PeerInfo', (done) => {
nodeAll.dial(nodeTCP.peerInfo, (err) => {
expect(err).to.not.exist()
// Some time for Identify to finish
setTimeout(() => check(nodeTCP, 1, 1, done), 500)
})
})
it('nodeAll.hangUp nodeTCP using PeerInfo', (done) => {
nodeAll.hangUp(nodeTCP.peerInfo, (err) => {
expect(err).to.not.exist()
// Some time for Identify to finish
setTimeout(() => check(nodeTCP, 0, 1, done), 500)
})
})
it('nodeAll.dial nodeWS using PeerInfo', (done) => {
nodeAll.dial(nodeWS.peerInfo, (err) => {
expect(err).to.not.exist()
// Some time for Identify to finish
setTimeout(() => check(nodeWS, 1, 2, done), 500)
})
})
it('nodeAll.hangUp nodeWS using PeerInfo', (done) => {
nodeAll.hangUp(nodeWS.peerInfo, (err) => {
expect(err).to.not.exist()
// Some time for Identify to finish
setTimeout(() => check(nodeWS, 0, 2, done), 500)
})
})
it('nodeAll.dial nodeWebRTCStar using PeerInfo', function (done) {
this.timeout(40 * 1000)
nodeAll.dial(nodeWebRTCStar.peerInfo, (err) => {
expect(err).to.not.exist()
// Some time for Identify to finish
setTimeout(() => check(nodeWebRTCStar, 1, 3, done), 500)
})
})
it('nodeAll.hangUp nodeWebRTCStar using PeerInfo', (done) => {
nodeAll.hangUp(nodeWebRTCStar.peerInfo, (err) => {
expect(err).to.not.exist()
setTimeout(() => check(nodeWebRTCStar, 0, 3, done), 500)
})
})
})
describe('TCP + WebSockets + WebSocketStar', () => {
let nodeAll
let nodeTCP
let nodeWS
let nodeWebSocketStar
let ss
before((done) => {
parallel([
(cb) => {
rendezvous.start({ port: 24642 }, (err, server) => {
expect(err).to.not.exist()
ss = server
cb()
})
},
(cb) => {
const wstar = new WSStar()
createNode([
'/ip4/0.0.0.0/tcp/0',
'/ip4/127.0.0.1/tcp/25011/ws',
'/ip4/127.0.0.1/tcp/24642/ws/p2p-websocket-star'
], {
modules: {
transport: [
TCP,
WS,
wstar
],
peerDiscovery: [wstar.discovery]
},
config: {
peerDiscovery: {
[wstar.discovery.tag]: {
enabled: true
}
}
}
}, (err, node) => {
expect(err).to.not.exist()
nodeAll = node
wstar.lazySetId(node.peerInfo.id)
node.handle('/echo/1.0.0', echo)
node.start(cb)
})
},
(cb) => createNode([
'/ip4/0.0.0.0/tcp/0'
], (err, node) => {
expect(err).to.not.exist()
nodeTCP = node
node.handle('/echo/1.0.0', echo)
node.start(cb)
}),
(cb) => createNode([
'/ip4/127.0.0.1/tcp/25022/ws'
], (err, node) => {
expect(err).to.not.exist()
nodeWS = node
node.handle('/echo/1.0.0', echo)
node.start(cb)
}),
(cb) => {
const wstar = new WSStar({})
createNode([
'/ip4/127.0.0.1/tcp/24642/ws/p2p-websocket-star'
], {
modules: {
transport: [wstar],
peerDiscovery: [wstar.discovery]
},
config: {
peerDiscovery: {
[wstar.discovery.tag]: {
enabled: true
}
}
}
}, (err, node) => {
expect(err).to.not.exist()
nodeWebSocketStar = node
wstar.lazySetId(node.peerInfo.id)
node.handle('/echo/1.0.0', echo)
node.start(cb)
})
}
], done)
})
after((done) => {
parallel([
(cb) => nodeAll.stop(cb),
(cb) => nodeTCP.stop(cb),
(cb) => nodeWS.stop(cb),
(cb) => nodeWebSocketStar.stop(cb),
(cb) => ss.stop(cb)
], done)
})
function check (otherNode, muxed, peers, done) {
let i = 1;
[nodeAll, otherNode].forEach((node) => {
expect(Object.keys(node.peerBook.getAll())).to.have.length(i-- ? peers : 1)
expect(node._switch.connection.getAll()).to.have.length(muxed)
})
done()
}
it('nodeAll.dial nodeTCP using PeerInfo', (done) => {
nodeAll.dial(nodeTCP.peerInfo, (err) => {
expect(err).to.not.exist()
// Some time for Identify to finish
setTimeout(() => check(nodeTCP, 1, 1, done), 500)
})
})
it('nodeAll.hangUp nodeTCP using PeerInfo', (done) => {
nodeAll.hangUp(nodeTCP.peerInfo, (err) => {
expect(err).to.not.exist()
// Some time for Identify to finish
setTimeout(() => check(nodeTCP, 0, 1, done), 500)
})
})
it('nodeAll.dial nodeWS using PeerInfo', (done) => {
nodeAll.dial(nodeWS.peerInfo, (err) => {
expect(err).to.not.exist()
// Some time for Identify to finish
setTimeout(() => check(nodeWS, 1, 2, done), 500)
})
})
it('nodeAll.hangUp nodeWS using PeerInfo', (done) => {
nodeAll.hangUp(nodeWS.peerInfo, (err) => {
expect(err).to.not.exist()
// Some time for Identify to finish
setTimeout(() => check(nodeWS, 0, 2, done), 500)
})
})
it('nodeAll.dial nodeWebSocketStar using PeerInfo', (done) => {
nodeAll.dial(nodeWebSocketStar.peerInfo, (err) => {
expect(err).to.not.exist()
// Some time for Identify to finish
setTimeout(() => check(nodeWebSocketStar, 1, 3, done), 500)
})
})
it('nodeAll.hangUp nodeWebSocketStar using PeerInfo', (done) => {
nodeAll.hangUp(nodeWebSocketStar.peerInfo, (err) => {
expect(err).to.not.exist()
// Some time for Identify to finish
setTimeout(() => check(nodeWebSocketStar, 0, 3, done), 500)
})
})
})
})
|
'use strict';
angular.module('artstudio.prices', ['ngRoute'])
.controller('pricesCtrl', [function() {
}]);
|
module.exports = {
parser: '@typescript-eslint/parser',
plugins: ['import'],
parserOptions: {
ecmaVersion: 6,
sourceType: 'module',
},
env: {
es6: true,
},
settings: {
'import/resolver': {
node: {
extensions: ['.mjs', '.js', '.json'],
},
},
'import/extensions': ['.js', '.mjs', '.jsx'],
'import/core-modules': [],
'import/ignore': ['node_modules', '\\.(coffee|scss|css|less|hbs|svg|json)$'],
},
rules: {
// Ensure imports point to files/modules that can be resolved
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-unresolved.md
'import/no-unresolved': ['off', { commonjs: true, caseSensitive: true }],
// Ensure named imports coupled with named exports
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/named.md#when-not-to-use-it
'import/named': 'error',
// Ensure default import coupled with default export
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/default.md#when-not-to-use-it
'import/default': 'off',
// Enforces names exist at the time they are dereferenced
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/namespace.md
'import/namespace': 'off',
// Disallow invalid exports, e.g. multiple defaults
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/export.md
'import/export': 'error',
// Do not allow a default import name to match a named export
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-named-as-default.md
'import/no-named-as-default': 'off',
// Warn on accessing default export property names that are also named exports
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-named-as-default-member.md
'import/no-named-as-default-member': 'error',
// Disallow use of jsdoc-marked-deprecated imports
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-deprecated.md
'import/no-deprecated': 'off',
// Forbid the use of extraneous packages
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-extraneous-dependencies.md
// paths are treated both as absolute paths, and relative to process.cwd()
'import/no-extraneous-dependencies': [
'off',
{
devDependencies: [
'test/**', // tape, common npm pattern
'tests/**', // also common npm pattern
'spec/**', // mocha, rspec-like pattern
'**/__tests__/**', // jest pattern
'**/__mocks__/**', // jest pattern
'test.{js,jsx}', // repos with a single test file
'test-*.{js,jsx}', // repos with multiple top-level test files
'**/*{.,_}{test,spec}.{js,jsx}', // tests where the extension or filename suffix denotes that it is a test
'**/jest.config.js', // jest config
'**/jest.setup.js', // jest setup
'**/jest/setup.js', // jest setup
'**/vue.config.js', // vue-cli config
'**/webpack.config.js', // webpack config
'**/webpack.config.*.js', // webpack config
'**/rollup.config.js', // rollup config
'**/rollup.config.*.js', // rollup config
'**/gulpfile.js', // gulp config
'**/gulpfile.*.js', // gulp config
'**/Gruntfile{,.js}', // grunt config
'**/protractor.conf.js', // protractor config
'**/protractor.conf.*.js', // protractor config
'**/karma.conf.js', // karma config
'**/compile/**',
'**/scripts/**',
'**/compile.js',
],
optionalDependencies: false,
},
],
// Forbid mutable exports
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-mutable-exports.md
'import/no-mutable-exports': 'error',
// Disallow require()
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-commonjs.md
'import/no-commonjs': 'off',
// Disallow AMD require/define
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-amd.md
'import/no-amd': 'error',
// No Node.js builtin modules
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-nodejs-modules.md
// TODO: enable?
'import/no-nodejs-modules': 'off',
// Disallow non-import statements appearing before import statements
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/first.md
'import/first': 'off',
// Disallow non-import statements appearing before import statements
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/imports-first.md
// deprecated: use `import/first`
'import/imports-first': 'off',
// Disallow duplicate imports
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-duplicates.md
'import/no-duplicates': 'error',
// Disallow namespace imports
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-namespace.md
'import/no-namespace': 'off',
// Ensure consistent use of file extension within the import path
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/extensions.md
'import/extensions': [
'off',
'ignorePackages',
{
js: 'never',
mjs: 'never',
jsx: 'never',
},
],
// Ensure absolute imports are above relative imports and that unassigned imports are ignored
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/order.md
// TODO: enforce a stricter convention in module import order?
// 'import/order': ['error', { groups: [['builtin', 'external', 'internal']] }],
// Require a newline after the last import/require in a group
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/newline-after-import.md
'import/newline-after-import': 'error',
// Require modules with a single export to use a default export
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/prefer-default-export.md
'import/prefer-default-export': 'off',
// Restrict which files can be imported in a given folder
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-restricted-paths.md
'import/no-restricted-paths': 'off',
// Forbid modules to have too many dependencies
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/max-dependencies.md
'import/max-dependencies': ['off', { max: 10 }],
// Forbid import of modules using absolute paths
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-absolute-path.md
'import/no-absolute-path': 'error',
// Forbid require() calls with expressions
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-dynamic-require.md
'import/no-dynamic-require': 'error',
// Prevent importing the submodules of other modules
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-internal-modules.md
'import/no-internal-modules': [
'off',
{
allow: [],
},
],
// Warn if a module could be mistakenly parsed as a script by a consumer
// leveraging Unambiguous JavaScript Grammar
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/unambiguous.md
// this should not be enabled until this proposal has at least been *presented* to TC39.
// At the moment, it's not a thing.
'import/unambiguous': 'off',
// Forbid Webpack loader syntax in imports
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-webpack-loader-syntax.md
'import/no-webpack-loader-syntax': 'error',
// Prevent unassigned imports
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-unassigned-import.md
// importing for side effects is perfectly acceptable, if you need side effects.
'import/no-unassigned-import': 'off',
// Prevent importing the default as if it were named
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-named-default.md
'import/no-named-default': 'error',
// Reports if a module's default export is unnamed
// https://github.com/benmosher/eslint-plugin-import/blob/d9b712ac7fd1fddc391f7b234827925c160d956f/docs/rules/no-anonymous-default-export.md
'import/no-anonymous-default-export': [
'off',
{
allowArray: false,
allowArrowFunction: false,
allowAnonymousClass: false,
allowAnonymousFunction: false,
allowLiteral: false,
allowObject: false,
},
],
// This rule enforces that all exports are declared at the bottom of the file.
// https://github.com/benmosher/eslint-plugin-import/blob/98acd6afd04dcb6920b81330114e146dc8532ea4/docs/rules/exports-last.md
// TODO: enable?
'import/exports-last': 'off',
// Reports when named exports are not grouped together in a single export declaration
// or when multiple assignments to CommonJS module.exports or exports object are present
// in a single file.
// https://github.com/benmosher/eslint-plugin-import/blob/44a038c06487964394b1e15b64f3bd34e5d40cde/docs/rules/group-exports.md
'import/group-exports': 'off',
// Forbid default exports. this is a terrible rule, do not use it.
// https://github.com/benmosher/eslint-plugin-import/blob/44a038c06487964394b1e15b64f3bd34e5d40cde/docs/rules/no-default-export.md
'import/no-default-export': 'off',
// Prohibit named exports. this is a terrible rule, do not use it.
// https://github.com/benmosher/eslint-plugin-import/blob/1ec80fa35fa1819e2d35a70e68fb6a149fb57c5e/docs/rules/no-named-export.md
'import/no-named-export': 'off',
// Forbid a module from importing itself
// https://github.com/benmosher/eslint-plugin-import/blob/44a038c06487964394b1e15b64f3bd34e5d40cde/docs/rules/no-self-import.md
'import/no-self-import': 'error',
// Forbid cyclical dependencies between modules
// https://github.com/benmosher/eslint-plugin-import/blob/d81f48a2506182738409805f5272eff4d77c9348/docs/rules/no-cycle.md
'import/no-cycle': ['error', { maxDepth: Infinity }],
// Ensures that there are no useless path segments
// https://github.com/benmosher/eslint-plugin-import/blob/ebafcbf59ec9f653b2ac2a0156ca3bcba0a7cf57/docs/rules/no-useless-path-segments.md
'import/no-useless-path-segments': ['error', { commonjs: true }],
// Dynamic imports require a leading comment with a webpackChunkName
// https://github.com/benmosher/eslint-plugin-import/blob/ebafcbf59ec9f653b2ac2a0156ca3bcba0a7cf57/docs/rules/dynamic-import-chunkname.md
'import/dynamic-import-chunkname': [
'off',
{
importFunctions: [],
webpackChunknameFormat: '[0-9a-zA-Z-_/.]+',
},
],
// Use this rule to prevent imports to folders in relative parent paths.
// https://github.com/benmosher/eslint-plugin-import/blob/c34f14f67f077acd5a61b3da9c0b0de298d20059/docs/rules/no-relative-parent-imports.md
'import/no-relative-parent-imports': 'off',
// Reports modules without any exports, or with unused exports
// https://github.com/benmosher/eslint-plugin-import/blob/f63dd261809de6883b13b6b5b960e6d7f42a7813/docs/rules/no-unused-modules.md
'import/no-unused-modules': [
'off',
{
ignoreExports: [],
missingExports: true,
unusedExports: true,
},
],
},
};
|
/* eslint-disable no-undef */
/*import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
xit('renders without crashing', () => {
const div = document.createElement('div');
ReactDOM.render(<App />, div);
ReactDOM.unmountComponentAtNode(div);
});*/
test('Fake test', () =>{
expect(true).toBeTruthy();
});
|
/*
* Copyright © 2016-2018 The BeiDouApp Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* eslint-disable import/no-unresolved, import/default */
import devicesTemplate from './devices.tpl.html';
/* eslint-enable import/no-unresolved, import/default */
/*@ngInject*/
export default function DeviceRoutes($stateProvider, types) {
$stateProvider
.state('home.devices', {
url: '/devices',
params: {'topIndex': 0},
module: 'private',
auth: ['TENANT_ADMIN', 'CUSTOMER_USER'],
views: {
"content@home": {
templateUrl: devicesTemplate,
controller: 'DeviceController',
controllerAs: 'vm'
}
},
data: {
devicesType: 'tenant',
searchEnabled: true,
searchByEntitySubtype: true,
searchEntityType: types.entityType.device,
pageTitle: 'device.devices'
},
ncyBreadcrumb: {
label: '{"icon": "devices_other", "label": "device.devices"}'
}
})
.state('home.customers.devices', {
url: '/:customerId/devices',
params: {'topIndex': 0},
module: 'private',
auth: ['TENANT_ADMIN'],
views: {
"content@home": {
templateUrl: devicesTemplate,
controllerAs: 'vm',
controller: 'DeviceController'
}
},
data: {
devicesType: 'customer',
searchEnabled: true,
searchByEntitySubtype: true,
searchEntityType: types.entityType.device,
pageTitle: 'customer.devices'
},
ncyBreadcrumb: {
label: '{"icon": "devices_other", "label": "{{ vm.customerDevicesTitle }}", "translate": "false"}'
}
});
}
|
/**
* Copyright © 2014 Elastic Path Software Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*
*/
/* global config */
var dependencies = config.baseDependencyConfig;
var basePaths = config.baseDependencyConfig.paths;
var extensionPaths = {
};
var dependencyPaths = _.extend(basePaths, extensionPaths);
dependencies.paths = dependencyPaths;
require.config(dependencies);
require(['app', 'eventbus', 'i18n', 'bootstrap'],
function (App, EventBus, i18n) {
// Application DOM container is ready (viewport)
$(document).ready(function () {
// initialize the localization engine
i18n.init({
lng: 'en' // default to english
},
function () {
// trigger event to let the application know it is safe to kick off
EventBus.trigger('app.bootstrapInitSuccess');
}
);
}
);
});
|
import {
shape,
objectOf,
arrayOf,
number,
} from 'prop-types';
import MediaType from './Medium';
export default shape({
byId: objectOf(MediaType),
allIds: arrayOf(number),
});
|
import Hex from './models/Hex';
class GridGenerator {
static getGenerator(name) {
if (GridGenerator.hasOwnProperty(name))
return GridGenerator[name];
return null;
}
static parallelogram(q1, q2, r1, r2) {
let hexas = [];
for (let q = q1; q <= q2; q++) {
for (let r = r1; r <= r2; r++) {
hexas.push(new Hex(q, r, -q-r));
}
}
return hexas;
}
static triangle(mapSize) {
let hexas = [];
for (let q = 0; q <= mapSize; q++) {
for (let r = 0; r <= mapSize - q; r++) {
hexas.push(new Hex(q, r, -q-r));
}
}
return hexas;
}
static hexagon(mapRadius) {
let hexas = [];
for (let q = -mapRadius; q <= mapRadius; q++) {
let r1 = Math.max(-mapRadius, -q - mapRadius);
let r2 = Math.min(mapRadius, -q + mapRadius);
for (let r = r1; r <= r2; r++) {
hexas.push(new Hex(q, r, -q-r));
}
}
return hexas;
}
static rectangle(mapWidth, mapHeight) {
let hexas = [];
for (let r = 0; r < mapHeight; r++) {
let offset = Math.floor(r/2); // or r>>1
for (let q = -offset; q < mapWidth - offset; q++) {
hexas.push(new Hex(q, r, -q-r));
}
}
return hexas;
}
static orientedRectangle(mapWidth, mapHeight) {
let hexas = [];
for (let q = 0; q < mapWidth; q++) {
let offset = Math.floor(q/2); // or q>>1
for (let r = -offset; r < mapHeight - offset; r++) {
hexas.push(new Hex(q, r, -q-r));
}
}
return hexas;
}
}
export default GridGenerator;
|
jQuery(document).ready(function() {
jQuery('#itemNo').blur(function() {
validateItem(jQuery('#itemNo'));
});
jQuery('#submitBid').click(function() {
submitBid();
});
setInterval('getItemList()',1000);
getItemList();
});
// This function works
function validateItem(itemNumber) {
if (itemNumber.val() != "" && itemNumber.val() > 0) {
jQuery.getJSON('/bids/ajax/validateitem', { id: itemNumber.val() }, function(data) {
if (data.code == "success") {
jQuery('#bidAmount').val(parseInt(data.currentBid) + 5);
jQuery('#bidAmount').select();
jQuery('#item_name').html(data.itemName);
} else {
alert("Invalid item number.");
jQuery('#itemNo').val("");
jQuery('#itemNo').focus();
jQuery('#item_name').html('[item name]');
}
});
}
}
// This function works
function getItemList() {
$('#itemList').load('/bids/ajax/getitemlist');
}
//TODO: this function does not work yet
function submitBid () {
// Bid MUST be a multiple of 5. Complain if it isn't.
if (jQuery('#bidAmount').val() % 5 != 0) {
alert('Bid must be a multiple of $5.00');
jQuery('#bidAmount').focus();
jQuery('#bidAmount').select();
return;
}
// check the phone number
if (jQuery('#phone1').val() == '' || jQuery('#phone2').val() == '' || jQuery('#phone3').val() == ''){
alert('You must provide a proper phone number.');
return;
}
jQuery.getJSON('/bids/ajax/submitbid', { itemNo: jQuery("#itemNo").val(), bidAmount: jQuery("#bidAmount").val(), phone1: jQuery("#phone1").val(), phone2: jQuery("#phone2").val(), phone3: jQuery("#phone3").val() }, function(data) {
switch (data.code) {
case "success":
// All is well. Return focus to the item No.
alert('Bid accepted.');
jQuery("#itemNo").focus();
jQuery("#itemNo").val('');
jQuery("#bidAmount").val('');
jQuery('#item_name').html('[item name]');
//jQuery("#phone1").val() = '';
//jQuery("#phone2").val() = '';
//jQuery("#phone3").val() = '';
break;
case "scammer":
// The person is scamming us
alert('This bidder cannot bid in this auction.');
jQuery("#itemNo").focus();
jQuery("#itemNo").val('');
jQuery("#bidAmount").val('');
jQuery("#phone1").val('');
jQuery("#phone2").val('');
jQuery("#phone3").val('');
jQuery('#item_name').html('[item name]');
break;
case "invalidItem":
// item number was not valid.
alert('Invalid Item Number entered.');
jQuery("#itemNo").focus();
jQuery("#itemNo").select();
break;
case "tooLow":
alert('Minumum bid is $' + data.currentBid + '. Please enter a higher bid.');
jQuery("#bidAmount").focus();
jQuery("#bidAmount").select();
break;
case "bidCollision":
alert('Current bid is $' + data.currentBid + '. Please enter a higher bid.');
jQuery("#bidAmount").focus();
jQuery("#bidAmount").select();
break;
case "bidTooHigh":
// Someone already made a bid equal or higher than that amount.
alert('Bid is a lot higher than the last bid.\nPlease enter a lower bid, or speak to the admin.');
jQuery("#bidAmount").val('');
jQuery("#bidAmount").focus();
jQuery("#bidAmount").select();
break;
case "phoneError":
// Someone already made a bid equal or higher than that amount.
alert('The phone number was too short, please enter a proper phone number');
jQuery("#phone1").val('');
jQuery("#phone2").val('');
jQuery("#phone3").val('');
jQuery("#phone1").focus();
break;
default:
alert('No response code from server.');
}
});
}
function jumpField(theField, fieldLength, nextField){
if (theField.value.length >= fieldLength){
if (nextField == 2){
document.forms[0].phone2.focus();
document.forms[0].phone2.select();
} else if (nextField == 3){
document.forms[0].phone3.focus();
document.forms[0].phone3.select();
}
}
}
|
/**
* omi v5.0.16 http://omijs.org
* Omi === Preact + Scoped CSS + Store System + Native Support in 3kb javascript.
* By dntzhang https://github.com/dntzhang
* Github: https://github.com/Tencent/omi
* MIT Licensed.
*/
(function () {
'use strict';
/** Virtual DOM Node */
function VNode() {}
function getGlobal() {
if (typeof global !== 'object' || !global || global.Math !== Math || global.Array !== Array) {
return self || window || global || function () {
return this;
}();
}
return global;
}
/** Global options
* @public
* @namespace options {Object}
*/
var options = {
store: null,
root: getGlobal()
};
var stack = [];
var EMPTY_CHILDREN = [];
function h(nodeName, attributes) {
var children = EMPTY_CHILDREN,
lastSimple,
child,
simple,
i;
for (i = arguments.length; i-- > 2;) {
stack.push(arguments[i]);
}
if (attributes && attributes.children != null) {
if (!stack.length) stack.push(attributes.children);
delete attributes.children;
}
while (stack.length) {
if ((child = stack.pop()) && child.pop !== undefined) {
for (i = child.length; i--;) {
stack.push(child[i]);
}
} else {
if (typeof child === 'boolean') child = null;
if (simple = typeof nodeName !== 'function') {
if (child == null) child = '';else if (typeof child === 'number') child = String(child);else if (typeof child !== 'string') simple = false;
}
if (simple && lastSimple) {
children[children.length - 1] += child;
} else if (children === EMPTY_CHILDREN) {
children = [child];
} else {
children.push(child);
}
lastSimple = simple;
}
}
var p = new VNode();
p.nodeName = nodeName;
p.children = children;
p.attributes = attributes == null ? undefined : attributes;
p.key = attributes == null ? undefined : attributes.key;
// if a "vnode hook" is defined, pass every created VNode to it
if (options.vnode !== undefined) options.vnode(p);
return p;
}
/**
* @license
* Copyright (c) 2016 The Polymer Project Authors. All rights reserved.
* This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
* The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
* The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
* Code distributed by Google as part of the polymer project is also
* subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/
(function () {
if (
// No Reflect, no classes, no need for shim because native custom elements
// require ES2015 classes or Reflect.
window.Reflect === undefined || window.customElements === undefined ||
// The webcomponentsjs custom elements polyfill doesn't require
// ES2015-compatible construction (`super()` or `Reflect.construct`).
window.customElements.hasOwnProperty('polyfillWrapFlushCallback')) {
return;
}
var BuiltInHTMLElement = HTMLElement;
window.HTMLElement = function HTMLElement() {
return Reflect.construct(BuiltInHTMLElement, [], this.constructor);
};
HTMLElement.prototype = BuiltInHTMLElement.prototype;
HTMLElement.prototype.constructor = HTMLElement;
Object.setPrototypeOf(HTMLElement, BuiltInHTMLElement);
})();
function cssToDom(css) {
var node = document.createElement('style');
node.textContent = css;
return node;
}
function npn(str) {
return str.replace(/-(\w)/g, function ($, $1) {
return $1.toUpperCase();
});
}
function extend(obj, props) {
for (var i in props) {
obj[i] = props[i];
}return obj;
}
/** Invoke or update a ref, depending on whether it is a function or object ref.
* @param {object|function} [ref=null]
* @param {any} [value]
*/
function applyRef(ref, value) {
if (ref != null) {
if (typeof ref == 'function') ref(value);else ref.current = value;
}
}
/**
* Call a function asynchronously, as soon as possible. Makes
* use of HTML Promise to schedule the callback if available,
* otherwise falling back to `setTimeout` (mainly for IE<11).
* @type {(callback: function) => void}
*/
var defer = typeof Promise == 'function' ? Promise.resolve().then.bind(Promise.resolve()) : setTimeout;
function isArray(obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
}
function nProps(props) {
if (!props || isArray(props)) return {};
var result = {};
Object.keys(props).forEach(function (key) {
result[key] = props[key].value;
});
return result;
}
// DOM properties that should NOT have "px" added when numeric
var IS_NON_DIMENSIONAL = /acit|ex(?:s|g|n|p|$)|rph|ows|mnc|ntw|ine[ch]|zoo|^ord/i;
/**
* Check if two nodes are equivalent.
*
* @param {Node} node DOM Node to compare
* @param {VNode} vnode Virtual DOM node to compare
* @param {boolean} [hydrating=false] If true, ignores component constructors when comparing.
* @private
*/
function isSameNodeType(node, vnode, hydrating) {
if (typeof vnode === 'string' || typeof vnode === 'number') {
return node.splitText !== undefined;
}
if (typeof vnode.nodeName === 'string') {
return !node._componentConstructor && isNamedNode(node, vnode.nodeName);
}
return hydrating || node._componentConstructor === vnode.nodeName;
}
/**
* Check if an Element has a given nodeName, case-insensitively.
*
* @param {Element} node A DOM Element to inspect the name of.
* @param {String} nodeName Unnormalized name to compare against.
*/
function isNamedNode(node, nodeName) {
return node.normalizedNodeName === nodeName || node.nodeName.toLowerCase() === nodeName.toLowerCase();
}
/**
* Create an element with the given nodeName.
* @param {string} nodeName The DOM node to create
* @param {boolean} [isSvg=false] If `true`, creates an element within the SVG
* namespace.
* @returns {Element} The created DOM node
*/
function createNode(nodeName, isSvg) {
/** @type {Element} */
var node = isSvg ? document.createElementNS('http://www.w3.org/2000/svg', nodeName) : document.createElement(nodeName);
node.normalizedNodeName = nodeName;
return node;
}
/**
* Remove a child node from its parent if attached.
* @param {Node} node The node to remove
*/
function removeNode(node) {
var parentNode = node.parentNode;
if (parentNode) parentNode.removeChild(node);
}
/**
* Set a named attribute on the given Node, with special behavior for some names
* and event handlers. If `value` is `null`, the attribute/handler will be
* removed.
* @param {Element} node An element to mutate
* @param {string} name The name/key to set, such as an event or attribute name
* @param {*} old The last value that was set for this name/node pair
* @param {*} value An attribute value, such as a function to be used as an
* event handler
* @param {boolean} isSvg Are we currently diffing inside an svg?
* @private
*/
function setAccessor(node, name, old, value, isSvg) {
if (name === 'className') name = 'class';
if (name === 'key') {
// ignore
} else if (name === 'ref') {
applyRef(old, null);
applyRef(value, node);
} else if (name === 'class' && !isSvg) {
node.className = value || '';
} else if (name === 'style') {
if (!value || typeof value === 'string' || typeof old === 'string') {
node.style.cssText = value || '';
}
if (value && typeof value === 'object') {
if (typeof old !== 'string') {
for (var i in old) {
if (!(i in value)) node.style[i] = '';
}
}
for (var i in value) {
node.style[i] = typeof value[i] === 'number' && IS_NON_DIMENSIONAL.test(i) === false ? value[i] + 'px' : value[i];
}
}
} else if (name === 'dangerouslySetInnerHTML') {
if (value) node.innerHTML = value.__html || '';
} else if (name[0] == 'o' && name[1] == 'n') {
var useCapture = name !== (name = name.replace(/Capture$/, ''));
name = name.toLowerCase().substring(2);
if (value) {
if (!old) {
node.addEventListener(name, eventProxy, useCapture);
if (name == 'tap') {
node.addEventListener('touchstart', touchStart, useCapture);
node.addEventListener('touchend', touchEnd, useCapture);
}
}
} else {
node.removeEventListener(name, eventProxy, useCapture);
if (name == 'tap') {
node.removeEventListener('touchstart', touchStart, useCapture);
node.removeEventListener('touchend', touchEnd, useCapture);
}
}
(node._listeners || (node._listeners = {}))[name] = value;
} else if (name !== 'list' && name !== 'type' && !isSvg && name in node) {
// Attempt to set a DOM property to the given value.
// IE & FF throw for certain property-value combinations.
try {
node[name] = value == null ? '' : value;
} catch (e) {}
if ((value == null || value === false) && name != 'spellcheck') node.removeAttribute(name);
} else {
var ns = isSvg && name !== (name = name.replace(/^xlink:?/, ''));
// spellcheck is treated differently than all other boolean values and
// should not be removed when the value is `false`. See:
// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attr-spellcheck
if (value == null || value === false) {
if (ns) node.removeAttributeNS('http://www.w3.org/1999/xlink', name.toLowerCase());else node.removeAttribute(name);
} else if (typeof value !== 'function') {
if (ns) {
node.setAttributeNS('http://www.w3.org/1999/xlink', name.toLowerCase(), value);
} else {
node.setAttribute(name, value);
}
}
}
}
/**
* Proxy an event to hooked event handlers
* @param {Event} e The event object from the browser
* @private
*/
function eventProxy(e) {
return this._listeners[e.type](options.event && options.event(e) || e);
}
function touchStart(e) {
this.___touchX = e.touches[0].pageX;
this.___touchY = e.touches[0].pageY;
this.___scrollTop = document.body.scrollTop;
}
function touchEnd(e) {
if (Math.abs(e.changedTouches[0].pageX - this.___touchX) < 30 && Math.abs(e.changedTouches[0].pageY - this.___touchY) < 30 && Math.abs(document.body.scrollTop - this.___scrollTop) < 30) {
this.dispatchEvent(new CustomEvent('tap', { detail: e }));
}
}
/** Diff recursion count, used to track the end of the diff cycle. */
var diffLevel = 0;
/** Global flag indicating if the diff is currently within an SVG */
var isSvgMode = false;
/** Global flag indicating if the diff is performing hydration */
var hydrating = false;
/** Apply differences in a given vnode (and it's deep children) to a real DOM Node.
* @param {Element} [dom=null] A DOM node to mutate into the shape of the `vnode`
* @param {VNode} vnode A VNode (with descendants forming a tree) representing the desired DOM structure
* @returns {Element} dom The created/mutated element
* @private
*/
function diff(dom, vnode, context, mountAll, parent, componentRoot) {
// diffLevel having been 0 here indicates initial entry into the diff (not a subdiff)
var ret;
if (!diffLevel++) {
// when first starting the diff, check if we're diffing an SVG or within an SVG
isSvgMode = parent != null && parent.ownerSVGElement !== undefined;
// hydration is indicated by the existing element to be diffed not having a prop cache
hydrating = dom != null && !('__omiattr_' in dom);
}
if (isArray(vnode)) {
ret = [];
var parentNode = null;
if (isArray(dom)) {
var domLength = dom.length;
var vnodeLength = vnode.length;
var maxLength = domLength >= vnodeLength ? domLength : vnodeLength;
parentNode = dom[0].parentNode;
for (var i = 0; i < maxLength; i++) {
var ele = idiff(dom[i], vnode[i], context, mountAll, componentRoot);
ret.push(ele);
if (i > domLength - 1) {
parentNode.appendChild(ele);
}
}
} else {
vnode.forEach(function (item) {
var ele = idiff(dom, item, context, mountAll, componentRoot);
ret.push(ele);
parent && parent.appendChild(ele);
});
}
} else {
if (isArray(dom)) {
ret = idiff(dom[0], vnode, context, mountAll, componentRoot);
} else {
ret = idiff(dom, vnode, context, mountAll, componentRoot);
}
// append the element if its a new parent
if (parent && ret.parentNode !== parent) parent.appendChild(ret);
}
// diffLevel being reduced to 0 means we're exiting the diff
if (! --diffLevel) {
hydrating = false;
// invoke queued componentDidMount lifecycle methods
}
return ret;
}
/** Internals of `diff()`, separated to allow bypassing diffLevel / mount flushing. */
function idiff(dom, vnode, context, mountAll, componentRoot) {
if (dom && vnode && dom.props) {
dom.props.children = vnode.children;
}
var out = dom,
prevSvgMode = isSvgMode;
// empty values (null, undefined, booleans) render as empty Text nodes
if (vnode == null || typeof vnode === 'boolean') vnode = '';
// Fast case: Strings & Numbers create/update Text nodes.
if (typeof vnode === 'string' || typeof vnode === 'number') {
// update if it's already a Text node:
if (dom && dom.splitText !== undefined && dom.parentNode && (!dom._component || componentRoot)) {
/* istanbul ignore if */ /* Browser quirk that can't be covered: https://github.com/developit/preact/commit/fd4f21f5c45dfd75151bd27b4c217d8003aa5eb9 */
if (dom.nodeValue != vnode) {
dom.nodeValue = vnode;
}
} else {
// it wasn't a Text node: replace it with one and recycle the old Element
out = document.createTextNode(vnode);
if (dom) {
if (dom.parentNode) dom.parentNode.replaceChild(out, dom);
recollectNodeTree(dom, true);
}
}
out['__omiattr_'] = true;
return out;
}
// If the VNode represents a Component, perform a component diff:
var vnodeName = vnode.nodeName;
// Tracks entering and exiting SVG namespace when descending through the tree.
isSvgMode = vnodeName === 'svg' ? true : vnodeName === 'foreignObject' ? false : isSvgMode;
// If there's no existing element or it's the wrong type, create a new one:
vnodeName = String(vnodeName);
if (!dom || !isNamedNode(dom, vnodeName)) {
out = createNode(vnodeName, isSvgMode);
if (dom) {
// move children into the replacement node
while (dom.firstChild) {
out.appendChild(dom.firstChild);
} // if the previous Element was mounted into the DOM, replace it inline
if (dom.parentNode) dom.parentNode.replaceChild(out, dom);
// recycle the old element (skips non-Element node types)
recollectNodeTree(dom, true);
}
}
var fc = out.firstChild,
props = out['__omiattr_'],
vchildren = vnode.children;
if (props == null) {
props = out['__omiattr_'] = {};
for (var a = out.attributes, i = a.length; i--;) {
props[a[i].name] = a[i].value;
}
}
// Optimization: fast-path for elements containing a single TextNode:
if (!hydrating && vchildren && vchildren.length === 1 && typeof vchildren[0] === 'string' && fc != null && fc.splitText !== undefined && fc.nextSibling == null) {
if (fc.nodeValue != vchildren[0]) {
fc.nodeValue = vchildren[0];
}
}
// otherwise, if there are existing or new children, diff them:
else if (vchildren && vchildren.length || fc != null) {
if (!(out.constructor.is == 'WeElement' && out.constructor.noSlot)) {
innerDiffNode(out, vchildren, context, mountAll, hydrating || props.dangerouslySetInnerHTML != null);
}
}
// Apply attributes/props from VNode to the DOM Element:
diffAttributes(out, vnode.attributes, props, vnode.children);
if (out.props) {
out.props.children = vnode.children;
}
// restore previous SVG mode: (in case we're exiting an SVG namespace)
isSvgMode = prevSvgMode;
return out;
}
/** Apply child and attribute changes between a VNode and a DOM Node to the DOM.
* @param {Element} dom Element whose children should be compared & mutated
* @param {Array} vchildren Array of VNodes to compare to `dom.childNodes`
* @param {Object} context Implicitly descendant context object (from most recent `getChildContext()`)
* @param {Boolean} mountAll
* @param {Boolean} isHydrating If `true`, consumes externally created elements similar to hydration
*/
function innerDiffNode(dom, vchildren, context, mountAll, isHydrating) {
var originalChildren = dom.childNodes,
children = [],
keyed = {},
keyedLen = 0,
min = 0,
len = originalChildren.length,
childrenLen = 0,
vlen = vchildren ? vchildren.length : 0,
j,
c,
f,
vchild,
child;
// Build up a map of keyed children and an Array of unkeyed children:
if (len !== 0) {
for (var i = 0; i < len; i++) {
var _child = originalChildren[i],
props = _child['__omiattr_'],
key = vlen && props ? _child._component ? _child._component.__key : props.key : null;
if (key != null) {
keyedLen++;
keyed[key] = _child;
} else if (props || (_child.splitText !== undefined ? isHydrating ? _child.nodeValue.trim() : true : isHydrating)) {
children[childrenLen++] = _child;
}
}
}
if (vlen !== 0) {
for (var i = 0; i < vlen; i++) {
vchild = vchildren[i];
child = null;
// attempt to find a node based on key matching
var key = vchild.key;
if (key != null) {
if (keyedLen && keyed[key] !== undefined) {
child = keyed[key];
keyed[key] = undefined;
keyedLen--;
}
}
// attempt to pluck a node of the same type from the existing children
else if (!child && min < childrenLen) {
for (j = min; j < childrenLen; j++) {
if (children[j] !== undefined && isSameNodeType(c = children[j], vchild, isHydrating)) {
child = c;
children[j] = undefined;
if (j === childrenLen - 1) childrenLen--;
if (j === min) min++;
break;
}
}
}
// morph the matched/found/created DOM child to match vchild (deep)
child = idiff(child, vchild, context, mountAll);
f = originalChildren[i];
if (child && child !== dom && child !== f) {
if (f == null) {
dom.appendChild(child);
} else if (child === f.nextSibling) {
removeNode(f);
} else {
dom.insertBefore(child, f);
}
}
}
}
// remove unused keyed children:
if (keyedLen) {
for (var i in keyed) {
if (keyed[i] !== undefined) recollectNodeTree(keyed[i], false);
}
}
// remove orphaned unkeyed children:
while (min <= childrenLen) {
if ((child = children[childrenLen--]) !== undefined) recollectNodeTree(child, false);
}
}
/** Recursively recycle (or just unmount) a node and its descendants.
* @param {Node} node DOM node to start unmount/removal from
* @param {Boolean} [unmountOnly=false] If `true`, only triggers unmount lifecycle, skips removal
*/
function recollectNodeTree(node, unmountOnly) {
// If the node's VNode had a ref function, invoke it with null here.
// (this is part of the React spec, and smart for unsetting references)
if (node['__omiattr_'] != null && node['__omiattr_'].ref) node['__omiattr_'].ref(null);
if (unmountOnly === false || node['__omiattr_'] == null) {
removeNode(node);
}
removeChildren(node);
}
/** Recollect/unmount all children.
* - we use .lastChild here because it causes less reflow than .firstChild
* - it's also cheaper than accessing the .childNodes Live NodeList
*/
function removeChildren(node) {
node = node.lastChild;
while (node) {
var next = node.previousSibling;
recollectNodeTree(node, true);
node = next;
}
}
/** Apply differences in attributes from a VNode to the given DOM Element.
* @param {Element} dom Element with attributes to diff `attrs` against
* @param {Object} attrs The desired end-state key-value attribute pairs
* @param {Object} old Current/previous attributes (from previous VNode or element's prop cache)
*/
function diffAttributes(dom, attrs, old, children) {
var name;
var update = false;
var isWeElement = dom.update;
var oldClone;
if (dom.receiveProps) {
oldClone = Object.assign({}, old);
}
// remove attributes no longer present on the vnode by setting them to undefined
for (name in old) {
if (!(attrs && attrs[name] != null) && old[name] != null) {
setAccessor(dom, name, old[name], old[name] = undefined, isSvgMode);
if (isWeElement) {
delete dom.props[name];
update = true;
}
}
}
// add new & update changed attributes
for (name in attrs) {
if (isWeElement && typeof attrs[name] === 'object') {
if (name === 'style') {
setAccessor(dom, name, old[name], old[name] = attrs[name], isSvgMode);
}
if (dom.receiveProps) {
try {
old[name] = JSON.parse(JSON.stringify(attrs[name]));
} catch (e) {
console.warn('When using receiveProps, you cannot pass prop of cyclic dependencies down.');
}
}
dom.props[npn(name)] = attrs[name];
update = true;
} else if (name !== 'children' && name !== 'innerHTML' && (!(name in old) || attrs[name] !== (name === 'value' || name === 'checked' ? dom[name] : old[name]))) {
setAccessor(dom, name, old[name], old[name] = attrs[name], isSvgMode);
if (isWeElement) {
dom.props[npn(name)] = attrs[name];
update = true;
}
}
}
if (isWeElement && dom.parentNode) {
if (update || children.length > 0) {
dom.receiveProps(dom.props, dom.data, oldClone);
dom.update();
}
}
}
/*!
* https://github.com/Palindrom/JSONPatcherProxy
* (c) 2017 Starcounter
* MIT license
*/
/** Class representing a JS Object observer */
var JSONPatcherProxy = function () {
/**
* Deep clones your object and returns a new object.
*/
function deepClone(obj) {
switch (typeof obj) {
case 'object':
return JSON.parse(JSON.stringify(obj)); //Faster than ES5 clone - http://jsperf.com/deep-cloning-of-objects/5
case 'undefined':
return null; //this is how JSON.stringify behaves for array items
default:
return obj; //no need to clone primitives
}
}
JSONPatcherProxy.deepClone = deepClone;
function escapePathComponent(str) {
if (str.indexOf('/') == -1 && str.indexOf('~') == -1) return str;
return str.replace(/~/g, '~0').replace(/\//g, '~1');
}
JSONPatcherProxy.escapePathComponent = escapePathComponent;
/**
* Walk up the parenthood tree to get the path
* @param {JSONPatcherProxy} instance
* @param {Object} obj the object you need to find its path
*/
function findObjectPath(instance, obj) {
var pathComponents = [];
var parentAndPath = instance.parenthoodMap.get(obj);
while (parentAndPath && parentAndPath.path) {
// because we're walking up-tree, we need to use the array as a stack
pathComponents.unshift(parentAndPath.path);
parentAndPath = instance.parenthoodMap.get(parentAndPath.parent);
}
if (pathComponents.length) {
var path = pathComponents.join('/');
return '/' + path;
}
return '';
}
/**
* A callback to be used as th proxy set trap callback.
* It updates parenthood map if needed, proxifies nested newly-added objects, calls default callbacks with the changes occurred.
* @param {JSONPatcherProxy} instance JSONPatcherProxy instance
* @param {Object} target the affected object
* @param {String} key the effect property's name
* @param {Any} newValue the value being set
*/
function setTrap(instance, target, key, newValue) {
var parentPath = findObjectPath(instance, target);
var destinationPropKey = parentPath + '/' + escapePathComponent(key);
if (instance.proxifiedObjectsMap.has(newValue)) {
var newValueOriginalObject = instance.proxifiedObjectsMap.get(newValue);
instance.parenthoodMap.set(newValueOriginalObject.originalObject, {
parent: target,
path: key
});
}
/*
mark already proxified values as inherited.
rationale: proxy.arr.shift()
will emit
{op: replace, path: '/arr/1', value: arr_2}
{op: remove, path: '/arr/2'}
by default, the second operation would revoke the proxy, and this renders arr revoked.
That's why we need to remember the proxies that are inherited.
*/
var revokableInstance = instance.proxifiedObjectsMap.get(newValue);
/*
Why do we need to check instance.isProxifyingTreeNow?
We need to make sure we mark revokables as inherited ONLY when we're observing,
because throughout the first proxification, a sub-object is proxified and then assigned to
its parent object. This assignment of a pre-proxified object can fool us into thinking
that it's a proxified object moved around, while in fact it's the first assignment ever.
Checking isProxifyingTreeNow ensures this is not happening in the first proxification,
but in fact is is a proxified object moved around the tree
*/
if (revokableInstance && !instance.isProxifyingTreeNow) {
revokableInstance.inherited = true;
}
// if the new value is an object, make sure to watch it
if (newValue && typeof newValue == 'object' && !instance.proxifiedObjectsMap.has(newValue)) {
instance.parenthoodMap.set(newValue, {
parent: target,
path: key
});
newValue = instance._proxifyObjectTreeRecursively(target, newValue, key);
}
// let's start with this operation, and may or may not update it later
var operation = {
op: 'remove',
path: destinationPropKey
};
if (typeof newValue == 'undefined') {
// applying De Morgan's laws would be a tad faster, but less readable
if (!Array.isArray(target) && !target.hasOwnProperty(key)) {
// `undefined` is being set to an already undefined value, keep silent
return Reflect.set(target, key, newValue);
}
// when array element is set to `undefined`, should generate replace to `null`
if (Array.isArray(target)) {
operation.op = 'replace', operation.value = null;
}
var oldValue = instance.proxifiedObjectsMap.get(target[key]);
// was the deleted a proxified object?
if (oldValue) {
instance.parenthoodMap.delete(target[key]);
instance.disableTrapsForProxy(oldValue);
instance.proxifiedObjectsMap.delete(oldValue);
}
} else {
if (Array.isArray(target) && !Number.isInteger(+key.toString())) {
/* array props (as opposed to indices) don't emit any patches, to avoid needless `length` patches */
if (key != 'length') {
console.warn('JSONPatcherProxy noticed a non-integer prop was set for an array. This will not emit a patch');
}
return Reflect.set(target, key, newValue);
}
operation.op = 'add';
if (target.hasOwnProperty(key)) {
if (typeof target[key] !== 'undefined' || Array.isArray(target)) {
operation.op = 'replace'; // setting `undefined` array elements is a `replace` op
}
}
operation.value = newValue;
}
operation.oldValue = target[key];
var reflectionResult = Reflect.set(target, key, newValue);
instance.defaultCallback(operation);
return reflectionResult;
}
/**
* A callback to be used as th proxy delete trap callback.
* It updates parenthood map if needed, calls default callbacks with the changes occurred.
* @param {JSONPatcherProxy} instance JSONPatcherProxy instance
* @param {Object} target the effected object
* @param {String} key the effected property's name
*/
function deleteTrap(instance, target, key) {
if (typeof target[key] !== 'undefined') {
var parentPath = findObjectPath(instance, target);
var destinationPropKey = parentPath + '/' + escapePathComponent(key);
var revokableProxyInstance = instance.proxifiedObjectsMap.get(target[key]);
if (revokableProxyInstance) {
if (revokableProxyInstance.inherited) {
/*
this is an inherited proxy (an already proxified object that was moved around),
we shouldn't revoke it, because even though it was removed from path1, it is still used in path2.
And we know that because we mark moved proxies with `inherited` flag when we move them
it is a good idea to remove this flag if we come across it here, in deleteProperty trap.
We DO want to revoke the proxy if it was removed again.
*/
revokableProxyInstance.inherited = false;
} else {
instance.parenthoodMap.delete(revokableProxyInstance.originalObject);
instance.disableTrapsForProxy(revokableProxyInstance);
instance.proxifiedObjectsMap.delete(target[key]);
}
}
var reflectionResult = Reflect.deleteProperty(target, key);
instance.defaultCallback({
op: 'remove',
path: destinationPropKey
});
return reflectionResult;
}
}
/* pre-define resume and pause functions to enhance constructors performance */
function resume() {
var _this = this;
this.defaultCallback = function (operation) {
_this.isRecording && _this.patches.push(operation);
_this.userCallback && _this.userCallback(operation);
};
this.isObserving = true;
}
function pause() {
this.defaultCallback = function () {};
this.isObserving = false;
}
/**
* Creates an instance of JSONPatcherProxy around your object of interest `root`.
* @param {Object|Array} root - the object you want to wrap
* @param {Boolean} [showDetachedWarning = true] - whether to log a warning when a detached sub-object is modified @see {@link https://github.com/Palindrom/JSONPatcherProxy#detached-objects}
* @returns {JSONPatcherProxy}
* @constructor
*/
function JSONPatcherProxy(root, showDetachedWarning) {
this.isProxifyingTreeNow = false;
this.isObserving = false;
this.proxifiedObjectsMap = new Map();
this.parenthoodMap = new Map();
// default to true
if (typeof showDetachedWarning !== 'boolean') {
showDetachedWarning = true;
}
this.showDetachedWarning = showDetachedWarning;
this.originalObject = root;
this.cachedProxy = null;
this.isRecording = false;
this.userCallback;
/**
* @memberof JSONPatcherProxy
* Restores callback back to the original one provided to `observe`.
*/
this.resume = resume.bind(this);
/**
* @memberof JSONPatcherProxy
* Replaces your callback with a noop function.
*/
this.pause = pause.bind(this);
}
JSONPatcherProxy.prototype.generateProxyAtPath = function (parent, obj, path) {
var _this2 = this;
if (!obj) {
return obj;
}
var traps = {
set: function set(target, key, value, receiver) {
return setTrap(_this2, target, key, value, receiver);
},
deleteProperty: function deleteProperty(target, key) {
return deleteTrap(_this2, target, key);
}
};
var revocableInstance = Proxy.revocable(obj, traps);
// cache traps object to disable them later.
revocableInstance.trapsInstance = traps;
revocableInstance.originalObject = obj;
/* keeping track of object's parent and path */
this.parenthoodMap.set(obj, { parent: parent, path: path });
/* keeping track of all the proxies to be able to revoke them later */
this.proxifiedObjectsMap.set(revocableInstance.proxy, revocableInstance);
return revocableInstance.proxy;
};
// grab tree's leaves one by one, encapsulate them into a proxy and return
JSONPatcherProxy.prototype._proxifyObjectTreeRecursively = function (parent, root, path) {
for (var key in root) {
if (root.hasOwnProperty(key)) {
if (root[key] instanceof Object) {
root[key] = this._proxifyObjectTreeRecursively(root, root[key], escapePathComponent(key));
}
}
}
return this.generateProxyAtPath(parent, root, path);
};
// this function is for aesthetic purposes
JSONPatcherProxy.prototype.proxifyObjectTree = function (root) {
/*
while proxyifying object tree,
the proxyifying operation itself is being
recorded, which in an unwanted behavior,
that's why we disable recording through this
initial process;
*/
this.pause();
this.isProxifyingTreeNow = true;
var proxifiedObject = this._proxifyObjectTreeRecursively(undefined, root, '');
/* OK you can record now */
this.isProxifyingTreeNow = false;
this.resume();
return proxifiedObject;
};
/**
* Turns a proxified object into a forward-proxy object; doesn't emit any patches anymore, like a normal object
* @param {Proxy} proxy - The target proxy object
*/
JSONPatcherProxy.prototype.disableTrapsForProxy = function (revokableProxyInstance) {
if (this.showDetachedWarning) {
var message = "You're accessing an object that is detached from the observedObject tree, see https://github.com/Palindrom/JSONPatcherProxy#detached-objects";
revokableProxyInstance.trapsInstance.set = function (targetObject, propKey, newValue) {
console.warn(message);
return Reflect.set(targetObject, propKey, newValue);
};
revokableProxyInstance.trapsInstance.set = function (targetObject, propKey, newValue) {
console.warn(message);
return Reflect.set(targetObject, propKey, newValue);
};
revokableProxyInstance.trapsInstance.deleteProperty = function (targetObject, propKey) {
return Reflect.deleteProperty(targetObject, propKey);
};
} else {
delete revokableProxyInstance.trapsInstance.set;
delete revokableProxyInstance.trapsInstance.get;
delete revokableProxyInstance.trapsInstance.deleteProperty;
}
};
/**
* Proxifies the object that was passed in the constructor and returns a proxified mirror of it. Even though both parameters are options. You need to pass at least one of them.
* @param {Boolean} [record] - whether to record object changes to a later-retrievable patches array.
* @param {Function} [callback] - this will be synchronously called with every object change with a single `patch` as the only parameter.
*/
JSONPatcherProxy.prototype.observe = function (record, callback) {
if (!record && !callback) {
throw new Error('You need to either record changes or pass a callback');
}
this.isRecording = record;
this.userCallback = callback;
/*
I moved it here to remove it from `unobserve`,
this will also make the constructor faster, why initiate
the array before they decide to actually observe with recording?
They might need to use only a callback.
*/
if (record) this.patches = [];
this.cachedProxy = this.proxifyObjectTree(this.originalObject);
return this.cachedProxy;
};
/**
* If the observed is set to record, it will synchronously return all the patches and empties patches array.
*/
JSONPatcherProxy.prototype.generate = function () {
if (!this.isRecording) {
throw new Error('You should set record to true to get patches later');
}
return this.patches.splice(0, this.patches.length);
};
/**
* Revokes all proxies rendering the observed object useless and good for garbage collection @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/revocable}
*/
JSONPatcherProxy.prototype.revoke = function () {
this.proxifiedObjectsMap.forEach(function (el) {
el.revoke();
});
};
/**
* Disables all proxies' traps, turning the observed object into a forward-proxy object, like a normal object that you can modify silently.
*/
JSONPatcherProxy.prototype.disableTraps = function () {
this.proxifiedObjectsMap.forEach(this.disableTrapsForProxy, this);
};
return JSONPatcherProxy;
}();
var callbacks = [];
var nextTickCallback = [];
function tick(fn, scope) {
callbacks.push({ fn: fn, scope: scope });
}
function fireTick() {
callbacks.forEach(function (item) {
item.fn.call(item.scope);
});
nextTickCallback.forEach(function (nextItem) {
nextItem.fn.call(nextItem.scope);
});
nextTickCallback.length = 0;
}
function nextTick(fn, scope) {
nextTickCallback.push({ fn: fn, scope: scope });
}
function observe(target) {
target.observe = true;
}
function proxyUpdate(ele) {
var timeout = null;
ele.data = new JSONPatcherProxy(ele.data).observe(false, function () {
if (ele._willUpdate) {
return;
}
if (ele.constructor.mergeUpdate) {
clearTimeout(timeout);
timeout = setTimeout(function () {
ele.update();
fireTick();
}, 0);
} else {
ele.update();
fireTick();
}
});
}
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var id = 0;
var WeElement = function (_HTMLElement) {
_inherits(WeElement, _HTMLElement);
function WeElement() {
_classCallCheck(this, WeElement);
var _this = _possibleConstructorReturn(this, _HTMLElement.call(this));
_this.props = Object.assign(nProps(_this.constructor.props), _this.constructor.defaultProps);
_this.elementId = id++;
_this.data = _this.constructor.data || {};
return _this;
}
WeElement.prototype.connectedCallback = function connectedCallback() {
if (!this.constructor.pure) {
var p = this.parentNode;
while (p && !this.store) {
this.store = p.store;
p = p.parentNode || p.host;
}
if (this.store) {
this.store.instances.push(this);
}
}
this.beforeInstall();
!this._isInstalled && this.install();
this.afterInstall();
var shadowRoot;
if (!this.shadowRoot) {
shadowRoot = this.attachShadow({
mode: 'open'
});
} else {
shadowRoot = this.shadowRoot;
var fc;
while (fc = shadowRoot.firstChild) {
shadowRoot.removeChild(fc);
}
}
this.css && shadowRoot.appendChild(cssToDom(this.css()));
!this._isInstalled && this.beforeRender();
options.afterInstall && options.afterInstall(this);
if (this.constructor.observe) {
this.beforeObserve();
proxyUpdate(this);
this.observed();
}
this._host = diff(null, this.render(this.props, this.data, this.store), {}, false, null, false);
this.rendered();
if (isArray(this._host)) {
this._host.forEach(function (item) {
shadowRoot.appendChild(item);
});
} else {
shadowRoot.appendChild(this._host);
}
!this._isInstalled && this.installed();
this._isInstalled = true;
};
WeElement.prototype.disconnectedCallback = function disconnectedCallback() {
this.uninstall();
this._isInstalled = false;
if (this.store) {
for (var i = 0, len = this.store.instances.length; i < len; i++) {
if (this.store.instances[i] === this) {
this.store.instances.splice(i, 1);
break;
}
}
}
};
WeElement.prototype.update = function update() {
this._willUpdate = true;
this.beforeUpdate();
this.beforeRender();
this._host = diff(this._host, this.render(this.props, this.data, this.store), null, null, this.shadowRoot);
this.afterUpdate();
this.updated();
this._willUpdate = false;
};
WeElement.prototype.fire = function fire(name, data) {
this.dispatchEvent(new CustomEvent(name, { detail: data }));
};
WeElement.prototype.beforeInstall = function beforeInstall() {};
WeElement.prototype.install = function install() {};
WeElement.prototype.afterInstall = function afterInstall() {};
WeElement.prototype.installed = function installed() {};
WeElement.prototype.uninstall = function uninstall() {};
WeElement.prototype.beforeUpdate = function beforeUpdate() {};
WeElement.prototype.afterUpdate = function afterUpdate() {}; //deprecated, please use updated
WeElement.prototype.updated = function updated() {};
WeElement.prototype.beforeRender = function beforeRender() {};
WeElement.prototype.rendered = function rendered() {};
WeElement.prototype.receiveProps = function receiveProps() {};
WeElement.prototype.beforeObserve = function beforeObserve() {};
WeElement.prototype.observed = function observed() {};
return WeElement;
}(HTMLElement);
WeElement.is = 'WeElement';
function render(vnode, parent, store) {
parent = typeof parent === 'string' ? document.querySelector(parent) : parent;
if (store) {
store.instances = [];
extendStoreUpate(store);
var timeout = null;
var patchs = {};
store.data = new JSONPatcherProxy(store.data).observe(false, function (patch) {
clearTimeout(timeout);
if (patch.op === 'remove') {
// fix arr splice
var kv = getArrayPatch(patch.path, store);
patchs[kv.k] = kv.v;
timeout = setTimeout(function () {
update(patchs, store);
patchs = {};
}, 0);
} else {
var key = fixPath(patch.path);
patchs[key] = patch.value;
timeout = setTimeout(function () {
update(patchs, store);
patchs = {};
}, 0);
}
});
parent.store = store;
}
return diff(null, vnode, {}, false, parent, false);
}
function update(patch, store) {
store.update(patch);
}
function extendStoreUpate(store) {
store.update = function (patch) {
var _this = this;
var updateAll = matchGlobalData(this.globalData, patch);
if (Object.keys(patch).length > 0) {
this.instances.forEach(function (instance) {
if (updateAll || _this.updateAll || instance.constructor.updatePath && needUpdate(patch, instance.constructor.updatePath)) {
instance.update();
}
});
this.onChange && this.onChange(patch);
}
};
}
function matchGlobalData(globalData, diffResult) {
if (!globalData) return false;
for (var keyA in diffResult) {
if (globalData.indexOf(keyA) > -1) {
return true;
}
for (var i = 0, len = globalData.length; i < len; i++) {
if (includePath(keyA, globalData[i])) {
return true;
}
}
}
return false;
}
function needUpdate(diffResult, updatePath) {
for (var keyA in diffResult) {
if (updatePath[keyA]) {
return true;
}
for (var keyB in updatePath) {
if (includePath(keyA, keyB)) {
return true;
}
}
}
return false;
}
function includePath(pathA, pathB) {
if (pathA.indexOf(pathB) === 0) {
var next = pathA.substr(pathB.length, 1);
if (next === '[' || next === '.') {
return true;
}
}
return false;
}
function fixPath(path) {
var mpPath = '';
var arr = path.replace('/', '').split('/');
arr.forEach(function (item, index) {
if (index) {
if (isNaN(Number(item))) {
mpPath += '.' + item;
} else {
mpPath += '[' + item + ']';
}
} else {
mpPath += item;
}
});
return mpPath;
}
function getArrayPatch(path, store) {
var arr = path.replace('/', '').split('/');
var current = store.data[arr[0]];
for (var i = 1, len = arr.length; i < len - 1; i++) {
current = current[arr[i]];
}
return { k: fixArrPath(path), v: current };
}
function fixArrPath(path) {
var mpPath = '';
var arr = path.replace('/', '').split('/');
var len = arr.length;
arr.forEach(function (item, index) {
if (index < len - 1) {
if (index) {
if (isNaN(Number(item))) {
mpPath += '.' + item;
} else {
mpPath += '[' + item + ']';
}
} else {
mpPath += item;
}
}
});
return mpPath;
}
function _classCallCheck$1(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn$1(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits$1(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
function define(name, ctor) {
if (ctor.is === 'WeElement') {
customElements.define(name, ctor);
if (ctor.data && !ctor.pure) {
ctor.updatePath = getUpdatePath(ctor.data);
}
} else {
var Element = function (_WeElement) {
_inherits$1(Element, _WeElement);
function Element() {
var _temp, _this, _ret;
_classCallCheck$1(this, Element);
for (var _len = arguments.length, args = Array(_len), key = 0; key < _len; key++) {
args[key] = arguments[key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn$1(this, _WeElement.call.apply(_WeElement, [this].concat(args))), _this), _this._useId = 0, _this._useMap = {}, _this._preCss = null, _temp), _possibleConstructorReturn$1(_this, _ret);
}
Element.prototype.render = function render(props, data) {
return ctor.call(this, props, data);
};
Element.prototype.beforeRender = function beforeRender() {
this._useId = 0;
};
Element.prototype.useCss = function useCss(css) {
if (css === this._preCss) {
return;
}
this._preCss = css;
var style = this.shadowRoot.querySelector('style');
style && this.shadowRoot.removeChild(style);
this.shadowRoot.appendChild(cssToDom(css));
};
Element.prototype.useData = function useData(data) {
return this.use({ data: data });
};
Element.prototype.use = function use(option) {
var _this2 = this;
this._useId++;
var updater = function updater(newValue) {
var item = _this2._useMap[updater.id];
item.data = newValue;
_this2.update();
item.effect && item.effect();
};
updater.id = this._useId;
if (!this._isInstalled) {
this._useMap[this._useId] = option;
return [option.data, updater];
}
return [this._useMap[this._useId].data, updater];
};
Element.prototype.installed = function installed() {
this._isInstalled = true;
};
return Element;
}(WeElement);
customElements.define(name, Element);
}
}
function getUpdatePath(data) {
var result = {};
dataToPath(data, result);
return result;
}
function dataToPath(data, result) {
Object.keys(data).forEach(function (key) {
result[key] = true;
var type = Object.prototype.toString.call(data[key]);
if (type === '[object Object]') {
_objToPath(data[key], key, result);
} else if (type === '[object Array]') {
_arrayToPath(data[key], key, result);
}
});
}
function _objToPath(data, path, result) {
Object.keys(data).forEach(function (key) {
result[path + '.' + key] = true;
delete result[path];
var type = Object.prototype.toString.call(data[key]);
if (type === '[object Object]') {
_objToPath(data[key], path + '.' + key, result);
} else if (type === '[object Array]') {
_arrayToPath(data[key], path + '.' + key, result);
}
});
}
function _arrayToPath(data, path, result) {
data.forEach(function (item, index) {
result[path + '[' + index + ']'] = true;
delete result[path];
var type = Object.prototype.toString.call(item);
if (type === '[object Object]') {
_objToPath(item, path + '[' + index + ']', result);
} else if (type === '[object Array]') {
_arrayToPath(item, path + '[' + index + ']', result);
}
});
}
function tag(name, pure) {
return function (target) {
target.pure = pure;
define(name, target);
};
}
/**
* Clones the given VNode, optionally adding attributes/props and replacing its children.
* @param {VNode} vnode The virtual DOM element to clone
* @param {Object} props Attributes/props to add when cloning
* @param {VNode} rest Any additional arguments will be used as replacement children.
*/
function cloneElement(vnode, props) {
return h(vnode.nodeName, extend(extend({}, vnode.attributes), props), arguments.length > 2 ? [].slice.call(arguments, 2) : vnode.children);
}
function getHost(ele) {
var p = ele.parentNode;
while (p) {
if (p.host) {
return p.host;
} else if (p.shadowRoot && p.shadowRoot.host) {
return p.shadowRoot.host;
} else {
p = p.parentNode;
}
}
}
function rpx(str) {
return str.replace(/([1-9]\d*|0)(\.\d*)*rpx/g, function (a, b) {
return window.innerWidth * Number(b) / 750 + 'px';
});
}
function _classCallCheck$2(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn$2(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits$2(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var ModelView = function (_WeElement) {
_inherits$2(ModelView, _WeElement);
function ModelView() {
_classCallCheck$2(this, ModelView);
return _possibleConstructorReturn$2(this, _WeElement.apply(this, arguments));
}
ModelView.prototype.beforeInstall = function beforeInstall() {
this.data = this.vm.data;
};
ModelView.prototype.observed = function observed() {
this.vm.data = this.data;
};
return ModelView;
}(WeElement);
ModelView.observe = true;
ModelView.mergeUpdate = true;
var Component = WeElement;
var defineElement = define;
var omi = {
tag: tag,
WeElement: WeElement,
Component: Component,
render: render,
h: h,
createElement: h,
options: options,
define: define,
observe: observe,
cloneElement: cloneElement,
getHost: getHost,
rpx: rpx,
tick: tick,
nextTick: nextTick,
ModelView: ModelView,
defineElement: defineElement
};
options.root.Omi = omi;
options.root.Omi.version = '5.0.16';
if (typeof module != 'undefined') module.exports = omi;else self.Omi = omi;
}());
//# sourceMappingURL=omi.dev.js.map
|
"use strict";
const trendStore = require("../../lib/trendStore");
const sampleTrends = require("../../lib/sampleTrends.json");
module.exports = {
/**
* The sample trends for the "DEMO" account
*
* @type {object[]}
*/
sampleTrends,
/**
* Creates multiple new test records, and updates the source objects
* with any new or changed fields (such as auto-assigned IDs)
*
* @param {string} user - The current user's ID
* @param {Trend[]} trends - The trends to create
* @returns {Promise<Trend[]>} - Resolves with the updated source objects
*/
create (user, trends) {
return Promise.all(trends.map(trend => {
return trendStore.create(user, trend)
.then(updatedTrend => Object.assign(trend, updatedTrend.toResource()));
}));
},
};
|
//objects assignment; file holding faunctional code
var message = '';
var student;
var search;
function print(message) {
var outputDiv = document.getElementById('output');
outputDiv.innerHTML = message;
}
function getStudentReport( student ) {
var report = '<h2>Student: ' + student.name + '</h2>';
report += '<p>Track: ' + student.track + '</p>';
report += '<p>Points: ' + student.points + '</p>';
report += '<p>Achievements: ' + student.achievements + '</p>';
return report;
}
while (true) {
search = prompt('Search student records: type a name [Jody] (or type "quit" to end)');
if (search === null || search.toLowerCase() === 'quit') {
break;
}
for (var i = 0; i < students.length; i += 1) {
student = students[i];
if ( student.name === search ) {
message = getStudentReport( student );
print(message);
}
}
}
|
import styled from "styled-components";
// Used for wrapping a page component
export const Screen = styled.div`
background-color: var(--primary);
background-image: ${({ image }) => (image ? `url(${image})` : "none")};
background-size: cover;
background-position: center;
width: 100%;
min-height: 100vh;
display: flex;
flex-direction: column;
`;
// Used for providing space between components
export const Space = styled.div`
height: 0px;
width: 8px;
`;
// Used for providing space between components
export const SpacerXSmall = styled.div`
height: 8px;
width: 8px;
`;
// Used for providing space between components
export const SpacerSmall = styled.div`
height: 16px;
width: 16px;
`;
// Used for providing space between components
export const SpacerMedium = styled.div`
height: 24px;
width: 24px;
`;
// Used for providing space between components
export const SpacerLarge = styled.div`
height: 32px;
width: 32px;
`;
// Used for providing a wrapper around a component
export const Container = styled.div`
display: flex;
flex: ${({ flex }) => (flex ? flex : 0)};
flex-direction: ${({ fd }) => (fd ? fd : "column")};
justify-content: ${({ jc }) => (jc ? jc : "flex-start")};
align-items: ${({ ai }) => (ai ? ai : "flex-start")};
background-color: ${({ test }) => (test ? "pink" : "none")};
width: 100%;
background-image: ${({ image }) => (image ? `url(${image})` : "none")};
background-size: cover;
background-position: center;
`;
export const Container1 = styled.div`
padding: 10px;
margin: 10px;
display: flex;
`;
export const Container2 = styled.div`
padding: 0px 10px;
margin: 0;
display: flex;
`;
export const TextTitle = styled.p`
color: var(--primary-text);
font-size: 22px;
font-weight: 500;
line-height: 1.6;
`;
export const TextTitleButton = styled.p`
color: var(--primary-text);
font-size: 16px;
font-weight: 500;
line-height: 1.6;
`;
export const TextSubTitle = styled.p`
color: var(--primary-text);
font-size: 18px;
line-height: 1.6;
`;
export const TextDescription = styled.p`
color: var(--primary-text);
font-size: 16px;
line-height: 1;
margin:0;
padding:0;
border:0;
`;
export const TextDescription1 = styled.p`
color: var(--primary-text);
font-size: 20px;
line-height: 2;
`;
export const StyledClickable = styled.div`
:active {
opacity: 0.6;
}
`;
export const form = styled.p`
color: var(--primary-text);
font-size: 50px;
font-weight: 50;
width:75%:
padding:5px;
margin: 0p;
box-sizing: border-box;
border:none;
border-radius: 10px
`;
export const StyledButton = styled.p`
`;
|
/**
* Copyright 2012-2017, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
module.exports = require('../src/traces/histogram');
|
module.exports = {
root: true,
env: {
node: true
},
parser: '@typescript-eslint/parser',
parserOptions: {
project: [
'./tsconfig.json',
'./tsconfig.test.json'
]
},
ignorePatterns: [
'.eslintrc.js',
'jest.config.js'
],
plugins: [
'@typescript-eslint',
'jest'
],
extends: [
'airbnb-typescript/base',
'plugin:jest/recommended'
],
rules: {
'@typescript-eslint/semi': ['warn', 'never'],
'class-methods-use-this': 0,
'import/no-dynamic-require': 0,
'import/prefer-default-export': 0,
'max-len': 0,
'no-multi-assign': 0,
'no-param-reassign': 0
}
}
|
module.exports = {
preset: "ts-jest",
testEnvironment: "jsdom",
roots: ["<rootDir>"],
modulePaths: ["<rootDir>"],
moduleNameMapper: {
"filebridge-client": "<rootDir>/packages/filebridge-client/src",
},
};
|
var classAdobeXMPCommon_1_1IConfigurationManager__v1 =
[
[ "~IConfigurationManager_v1", "classAdobeXMPCommon_1_1IConfigurationManager__v1.html#aab2f368cf6883a6cd92fe688a95516b5", null ],
[ "DisableMultiThreading", "classAdobeXMPCommon_1_1IConfigurationManager__v1.html#acf69fdd4ec5c1eb47b6a41b052372504", null ],
[ "IsMultiThreaded", "classAdobeXMPCommon_1_1IConfigurationManager__v1.html#acbdb00613df7f5498a7fe264f8cd950d", null ],
[ "RegisterErrorNotifier", "classAdobeXMPCommon_1_1IConfigurationManager__v1.html#af078935e322f611a884061977d015d1d", null ],
[ "RegisterMemoryAllocator", "classAdobeXMPCommon_1_1IConfigurationManager__v1.html#a4886e0ac409969583acccbe344489a85", null ],
[ "REQ_FRIEND_CLASS_DECLARATION", "classAdobeXMPCommon_1_1IConfigurationManager__v1.html#ad857109e294bdff85685fa0974020645", null ]
];
|
// entry-server.js
import { createApp } from './app'
export default context => {
// 因为有可能会是异步路由钩子函数或组件,所以我们将返回一个 Promise,
// 以便服务器能够等待所有的内容在渲染前,
// 就已经准备就绪。
return new Promise((resolve, reject) => {
const { app, router } = createApp()
// 设置服务器端 router 的位置
router.push(context.url)
// 等到 router 将可能的异步组件和钩子函数解析完
router.onReady(() => {
const matchedComponents = router.getMatchedComponents()
// 匹配不到的路由,执行 reject 函数,并返回 404
if (!matchedComponents.length) {
return reject({ code: 404 })
}
// Promise 应该 resolve 应用程序实例,以便它可以渲染
resolve(app)
}, reject)
})
}
|
'use strict';
/**
* Module dependencies
*/
// Node.js core.
const path = require('path');
const { exec, execSync } = require('child_process');
// Public node modules.
const _ = require('lodash');
const {green, cyan} = require('chalk');
const fs = require('fs-extra');
const npm = require('enpeem');
const ora = require('ora');
const shell = require('shelljs');
// Logger.
const { packageManager } = require('strapi-utils');
/**
* Runs after this generator has finished
*
* @param {Object} scope
* @param {Function} cb
*/
/* eslint-disable no-console */
/* eslint-disable prefer-template */
module.exports = (scope, cb) => {
console.log(`The app has been connected to the database ${green('successfully')}!`);
console.log();
console.log('🏗 Application generation:');
let loader = ora('Copy dashboard').start();
const packageJSON = require(path.resolve(scope.rootPath, 'package.json'));
// const strapiRootPath = path.resolve(scope.strapiRoot, '..');
process.chdir(scope.rootPath);
// Copy the default files.
fs.copySync(path.resolve(__dirname, '..', 'files'), path.resolve(scope.rootPath));
loader.succeed();
let availableDependencies = [];
const dependencies = _.get(packageJSON, 'dependencies');
const strapiDependencies = Object.keys(dependencies).filter(key => key.indexOf('strapi') !== -1);
const othersDependencies = Object.keys(dependencies).filter(key => key.indexOf('strapi') === -1);
// Add this check to know if we are in development mode so the creation is faster.
const isStrapiInstalledWithNPM = packageManager.isStrapiInstalledWithNPM();
const globalRootPath = execSync(packageManager.commands('root -g'));
// Verify if the dependencies are available into the global
_.forEach(strapiDependencies, (key) => {
try {
const depPath = isStrapiInstalledWithNPM ? path.resolve(_.trim(globalRootPath.toString()), key) : path.resolve(_.trim(globalRootPath.toString()), `node_modules/${key}`);
fs.accessSync(depPath, fs.constants.R_OK | fs.constants.F_OK);
availableDependencies.push({
key,
global: true,
path: depPath
});
} catch (e) {
othersDependencies.push(key);
}
});
if (!_.isEmpty(othersDependencies)) {
if (isStrapiInstalledWithNPM) {
npm.install({
dir: scope.rootPath,
dependencies: othersDependencies,
loglevel: 'silent',
production: true,
'cache-min': 999999999
}, err => {
if (err) {
console.log();
console.log('⚠️ You should run `npm install` into your application before starting it.');
console.log();
console.log('⚠️ Some dependencies could not be installed:');
_.forEach(othersDependencies, value => console.log('• ' + value));
console.log();
return cb();
}
pluginsInstallation();
});
} else {
const alphaDependencies = othersDependencies.map(dep => {
if (_.includes(dep, 'strapi') && !_.includes(dep, '@alpha')) { // We need this for yarn
return `${dep}@alpha`;
}
return dep;
}).join(' ');
const data = shell.exec(`yarn --cwd ${scope.rootPath} add ${alphaDependencies} --production`, { silent: true });
if (data.stderr && data.code !== 0) {
cb();
}
pluginsInstallation();
}
} else {
pluginsInstallation();
}
// Install default plugins and link dependencies.
function pluginsInstallation() {
const strapiBin = path.join(scope.strapiRoot, scope.strapiPackageJSON.bin.strapi);
// Define the list of default plugins.
const defaultPlugins = [{
name: 'settings-manager',
core: true
}, {
name: 'content-type-builder',
core: true
}, {
name: 'content-manager',
core: true
}, {
name: 'users-permissions',
core: true
}, {
name: 'email',
core: true
},{
name: 'upload',
core: true
}];
let installPlugin = new Promise(resolve => {
return resolve();
});
// Install each plugin.
defaultPlugins.forEach(defaultPlugin => {
installPlugin = installPlugin.then(() => {
return new Promise(resolve => {
loader = ora(`Install plugin ${cyan(defaultPlugin.name)}.`).start();
exec(`node ${strapiBin} install ${defaultPlugin.name} ${scope.developerMode && defaultPlugin.core ? '--dev' : ''}`, (err) => {
if (err) {
loader.warn(`An error occurred during ${defaultPlugin.name} plugin installation.`);
console.log(err);
return resolve();
}
loader.succeed();
return resolve();
});
});
});
});
installPlugin
.then(() => {
// Link dependencies.
availableDependencies.forEach(dependency => {
loader = ora(`Link ${cyan(dependency.key)} dependency to the project.`).start();
if (dependency.global) {
try {
fs.accessSync(dependency.path, fs.constants.R_OK | fs.constants.F_OK);
fs.symlinkSync(dependency.path, path.resolve(scope.rootPath, 'node_modules', dependency.key), 'dir');
} catch (e) {
// Silent.
}
} else {
try {
fs.accessSync(path.resolve(scope.strapiRoot, 'node_modules', dependency.key), fs.constants.R_OK | fs.constants.F_OK);
fs.symlinkSync(path.resolve(scope.strapiRoot, 'node_modules', dependency.key), path.resolve(scope.rootPath, 'node_modules', dependency.key), 'dir');
} catch (e) {
// Silent.
}
}
loader.succeed();
});
console.log();
console.log(`👌 Your new application ${green(scope.name)} is ready at ${cyan(scope.rootPath)}.`);
console.log();
console.log('⚡️ change directory:');
console.log(`$ ${green(`cd ${scope.name}`)}`);
console.log();
console.log('⚡️ start application:');
console.log(`$ ${green('strapi start')}`);
cb();
});
}
};
|
/* globals Vue, Vuetify, firebase */
const gAuthProvider = new firebase.auth.GoogleAuthProvider()
const admins = [
'Kpz3afszjBR0qwZYUrKURRJx2cm2', // Dylan
'g0G3A7FxieN333lZ2RKclkmv9Uw1' // Svante
]
firebase.firestore().enablePersistence()
const dateFormatter = new Intl.DateTimeFormat()
new Vue({
el: '#app',
vuetify: new Vuetify({
theme: {
themes: {
light: {
primary: '#fe3500',
secondary: '#ffc107',
accent: '#ffeb3b',
error: '#fe3500',
warning: '#ff9800',
info: '#3f51b5',
success: '#4caf50'
}
}
}
}),
data: () => ({
authDialog: 'unchecked',
uid: null,
drawer: false,
discipline: 'sr',
tab: null,
trick: null,
search: '',
tricks: {
sr: [],
dd: [],
wh: []
},
loaded: {
sr: false,
dd: false,
wh: false
},
types: [],
saving: false,
valid: false,
reqRule: [v => !!v || 'Required'],
error: false,
newPrereqId: null
}),
computed: {
levelArrays () {
const out = {}
for (const trick of this.tricks[this.discipline]) {
if (!Object.prototype.hasOwnProperty.call(out, trick.level)) out[trick.level] = []
out[trick.level].push(trick)
}
return out
},
tricksWithoutCurrent () {
return this.tricks[this.discipline].filter(trick => trick.id !== this.trick.id)
}
},
created () {
firebase.auth().onAuthStateChanged(user => {
if (user) {
if (admins.includes(user.uid)) {
this.authDialog = 'authed'
this.uid = user.uid
this.load()
} else {
this.uid = null
this.authDialog = 'notadmin'
}
} else {
this.authDialog = 'unchecked'
this.uid = null
}
})
},
methods: {
login () {
firebase.auth().signInWithPopup(gAuthProvider)
},
logout () {
firebase.auth().signOut()
},
changeDiscipline (discipline) {
this.discipline = discipline
this.load()
},
getTrick (id) {
return this.tricks[this.discipline].find(trick => trick.id === id)
},
load () {
const discipline = `${this.discipline}`
firebase.firestore().collection('tricks' + discipline.toUpperCase()).get().then(qSnap => {
this.loaded[discipline] = true
qSnap.forEach(dSnap => {
const trickIdx = this.tricks[discipline].findIndex(trick => trick.id === dSnap.id)
if (trickIdx !== -1) {
this.tricks[discipline].splice(trickIdx, 1, {
id: dSnap.id,
...dSnap.data()
})
} else {
this.tricks[discipline].push({
id: dSnap.id,
...dSnap.data()
})
}
})
})
firebase.firestore().collection('i18n').doc('en').collection('tricktypes').doc('translated').get().then(dSnap => {
const keys = Object.keys(dSnap.data())
this.$set(this, 'types', keys)
})
},
edit (trick) {
if (!trick.videos) this.$set(trick, 'videos', {})
if (!trick.levels) this.$set(trick, 'levels', {})
if (!trick.levels.ijru) this.$set(trick.levels, 'ijru', {})
if (!trick.levels.ijru.verified) this.$set(trick.levels.ijru, 'verified', {})
this.$set(this, 'trick', trick)
},
close () {
this.$set(this, 'trick', null)
this.$set(this, 'newPrereqId', null)
},
save () {
const discipline = `${this.discipline}`
const { id, ...trick } = this.trick
this.$refs.form.validate()
if (!this.valid || !trick.name || !trick.level || !trick.type) {
this.error = 'From is missing required fields'
return
}
this.saving = true
if (!id || !trick.createdAt) trick.createdAt = firebase.firestore.FieldValue.serverTimestamp()
trick.updatedAt = firebase.firestore.FieldValue.serverTimestamp()
const baseRef = firebase.firestore().collection('tricks' + discipline.toUpperCase())
const promise = id
? baseRef.doc(id).set(trick, { merge: true })
: baseRef.add(trick)
promise.then(dSnap => {
this.saving = false
if (!dSnap) return this.close()
const trickIdx = this.tricks[discipline].findIndex(trick => trick.id === dSnap.id)
if (trickIdx !== -1) {
this.tricks[discipline].splice(trickIdx, 1, {
id: dSnap.id,
...trick
})
} else {
this.tricks[discipline].push({
id: dSnap.id,
...trick
})
}
this.close()
})
.catch(err => {
this.error = err.message
})
},
generateSlug () {
this.$set(this.trick, 'slug', this.trick.name.toLocaleLowerCase().replace(/[^a-z]/g, '-').replace(/-{2,}/g, '-'))
},
newAlternativeName () {
if (!this.trick.alternativeNames) this.$set(this.trick, 'alternativeNames', [])
this.trick.alternativeNames.push('')
},
removeAlternativeName (idx) {
this.trick.alternativeNames.splice(idx, 1)
},
setAlternativeName (idx, name) {
this.trick.alternativeNames.splice(idx, 1, name)
},
addPrereq (newPrereqId) {
console.log(newPrereqId)
if (!this.trick.prerequisites) this.$set(this.trick, 'prerequisites', [])
const discipline = `${this.discipline}`
this.trick.prerequisites.push({
id: newPrereqId,
ref: firebase.firestore().collection('tricks' + discipline.toUpperCase()).doc(newPrereqId)
})
this.newPrereqId = null
},
removePrereq (idx) {
this.trick.prerequisites.splice(idx, 1)
},
verifyTrick (trick, vLevel, verified) {
this.$set(trick.levels.ijru.verified, 'date', firebase.firestore.Timestamp.now())
this.$set(trick.levels.ijru.verified, 'vLevel', vLevel)
this.$set(trick.levels.ijru.verified, 'verified', verified)
this.$set(trick.levels.ijru.verified, 'verifier', this.uid)
}
},
filters: {
timestamp (value) {
if (!value) return ''
if (!(value instanceof firebase.firestore.Timestamp)) return value
const date = dateFormatter.format(value.toDate())
return date
}
}
})
|
(window["webpackJsonp"] = window["webpackJsonp"] || []).push([[72],{
/***/ "./node_modules/babel-loader/lib/index.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/src/components/timeline/VxTimeline.vue?vue&type=script&lang=js&":
/*!**********************************************************************************************************************************************************************************!*\
!*** ./node_modules/babel-loader/lib??ref--4-0!./node_modules/vue-loader/lib??vue-loader-options!./resources/js/src/components/timeline/VxTimeline.vue?vue&type=script&lang=js& ***!
\**********************************************************************************************************************************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
/* harmony default export */ __webpack_exports__["default"] = ({
name: 'vx-timeline',
props: {
data: {
type: Array,
required: true
}
}
});
/***/ }),
/***/ "./node_modules/babel-loader/lib/index.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/src/views/DashboardAnalytics.vue?vue&type=script&lang=js&":
/*!****************************************************************************************************************************************************************************!*\
!*** ./node_modules/babel-loader/lib??ref--4-0!./node_modules/vue-loader/lib??vue-loader-options!./resources/js/src/views/DashboardAnalytics.vue?vue&type=script&lang=js& ***!
\****************************************************************************************************************************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var vue_apexcharts__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! vue-apexcharts */ "./node_modules/vue-apexcharts/dist/vue-apexcharts.js");
/* harmony import */ var vue_apexcharts__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(vue_apexcharts__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _components_statistics_cards_StatisticsCardLine_vue__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @/components/statistics-cards/StatisticsCardLine.vue */ "./resources/js/src/components/statistics-cards/StatisticsCardLine.vue");
/* harmony import */ var _ui_elements_card_analyticsData_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./ui-elements/card/analyticsData.js */ "./resources/js/src/views/ui-elements/card/analyticsData.js");
/* harmony import */ var _components_ChangeTimeDurationDropdown_vue__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @/components/ChangeTimeDurationDropdown.vue */ "./resources/js/src/components/ChangeTimeDurationDropdown.vue");
/* harmony import */ var _components_timeline_VxTimeline__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @/components/timeline/VxTimeline */ "./resources/js/src/components/timeline/VxTimeline.vue");
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
/* harmony default export */ __webpack_exports__["default"] = ({
data: function data() {
return {
checkpointReward: {},
subscribersGained: {},
ordersRecevied: {},
salesBarSession: {},
supportTracker: {},
productsOrder: {},
salesRadar: {},
timelineData: [{
color: 'primary',
icon: 'PlusIcon',
title: 'Client Meeting',
desc: 'Bonbon macaroon jelly beans gummi bears jelly lollipop apple',
time: '25 mins Ago'
}, {
color: 'warning',
icon: 'MailIcon',
title: 'Email Newsletter',
desc: 'Cupcake gummi bears soufflé caramels candy',
time: '15 Days Ago'
}, {
color: 'danger',
icon: 'UsersIcon',
title: 'Plan Webinar',
desc: 'Candy ice cream cake. Halvah gummi bears',
time: '20 days ago'
}, {
color: 'success',
icon: 'LayoutIcon',
title: 'Launch Website',
desc: 'Candy ice cream cake. Halvah gummi bears Cupcake gummi bears soufflé caramels candy.',
time: '25 days ago'
}, {
color: 'primary',
icon: 'TvIcon',
title: 'Marketing',
desc: 'Candy ice cream cake. Halvah gummi bears Cupcake gummi bears.',
time: '28 days ago'
}],
analyticsData: _ui_elements_card_analyticsData_js__WEBPACK_IMPORTED_MODULE_2__["default"],
dispatchedOrders: []
};
},
components: {
VueApexCharts: vue_apexcharts__WEBPACK_IMPORTED_MODULE_0___default.a,
StatisticsCardLine: _components_statistics_cards_StatisticsCardLine_vue__WEBPACK_IMPORTED_MODULE_1__["default"],
ChangeTimeDurationDropdown: _components_ChangeTimeDurationDropdown_vue__WEBPACK_IMPORTED_MODULE_3__["default"],
VxTimeline: _components_timeline_VxTimeline__WEBPACK_IMPORTED_MODULE_4__["default"]
},
created: function created() {
var _this = this;
// User Reward Card
this.$http.get('/api/user/checkpoint-reward').then(function (response) {
_this.checkpointReward = response.data;
}).catch(function (error) {
console.log(error);
}); // Subscribers gained - Statistics
this.$http.get('/api/card/card-statistics/subscribers').then(function (response) {
_this.subscribersGained = response.data;
}).catch(function (error) {
console.log(error);
}); // Orders - Statistics
this.$http.get('/api/card/card-statistics/orders').then(function (response) {
_this.ordersRecevied = response.data;
}).catch(function (error) {
console.log(error);
}); // Sales bar - Analytics
this.$http.get('/api/card/card-analytics/sales/bar').then(function (response) {
_this.salesBarSession = response.data;
}).catch(function (error) {
console.log(error);
}); // Support Tracker
this.$http.get('/api/card/card-analytics/support-tracker').then(function (response) {
_this.supportTracker = response.data;
}).catch(function (error) {
console.log(error);
}); // Products Order
this.$http.get('/api/card/card-analytics/products-orders').then(function (response) {
_this.productsOrder = response.data;
}).catch(function (error) {
console.log(error);
}); // Sales Radar
this.$http.get('/api/card/card-analytics/sales/radar').then(function (response) {
_this.salesRadar = response.data;
}).catch(function (error) {
console.log(error);
}); // Dispatched Orders
this.$http.get('/api/table/dispatched-orders').then(function (response) {
_this.dispatchedOrders = response.data;
}).catch(function (error) {
console.log(error);
});
}
});
/***/ }),
/***/ "./node_modules/css-loader/index.js!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/lib/index.js?!./node_modules/sass-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/src/components/timeline/VxTimeline.vue?vue&type=style&index=0&lang=scss&":
/*!*********************************************************************************************************************************************************************************************************************************************************************************************************************************!*\
!*** ./node_modules/css-loader!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/lib??ref--8-2!./node_modules/sass-loader/dist/cjs.js??ref--8-3!./node_modules/vue-loader/lib??vue-loader-options!./resources/js/src/components/timeline/VxTimeline.vue?vue&type=style&index=0&lang=scss& ***!
\*********************************************************************************************************************************************************************************************************************************************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
exports = module.exports = __webpack_require__(/*! ../../../../../node_modules/css-loader/lib/css-base.js */ "./node_modules/css-loader/lib/css-base.js")(false);
// imports
// module
exports.push([module.i, "/*=========================================================================================\n File Name: vxTimeline.scss\n Description: Styles for vx-timeline component\n ----------------------------------------------------------------------------------------\n Item Name: Vuexy - Vuejs, HTML & Laravel Admin Dashboard Template\n Author: Pixinvent\n Author URL: http://www.themeforest.net/user/pixinvent\n==========================================================================================*/\n\n/*=========================================================================================\n File Name: _variables.scss\n Description: partial- SCSS varibales\n ----------------------------------------------------------------------------------------\n Item Name: Vuexy - Vuejs, HTML & Laravel Admin Dashboard Template\n Author: Pixinvent\n Author URL: http://www.themeforest.net/user/pixinvent\n==========================================================================================*/\n\n/*========================================================\n SPACING\n=========================================================*/\n\n/*========================================================\n COLORS\n=========================================================*/\n\n/*========================================================\n TYPOGRAPHY\n=========================================================*/\n\n/*========================================================\n TYPOGRAPHY\n=========================================================*/\n\n/*========================================================\n DARK THEME\n=========================================================*/\n[dir=ltr] .vx-timeline {\n margin-left: 1.5rem;\n padding-left: 40px;\n border-left: 2px solid #E5E8EB;\n}\n[dir=rtl] .vx-timeline {\n margin-right: 1.5rem;\n padding-right: 40px;\n border-right: 2px solid #E5E8EB;\n}\n[dir] .theme-dark .vx-timeline {\n border-color: #414561;\n}\n.vx-timeline li {\n position: relative;\n}\n[dir] .vx-timeline li {\n margin-bottom: 20px;\n}\n.vx-timeline li .timeline-icon {\n position: absolute;\n top: 0;\n}\n[dir] .vx-timeline li .timeline-icon {\n border-radius: 50%;\n padding: 0.75rem;\n padding-bottom: 0.4rem;\n}\n[dir=ltr] .vx-timeline li .timeline-icon {\n left: -4.3rem;\n}\n[dir=rtl] .vx-timeline li .timeline-icon {\n right: -4.3rem;\n}\n.vx-timeline li .activity-desc {\n font-size: 0.9rem;\n}\n.vx-timeline li .activity-e-time {\n font-size: 0.8rem;\n}", ""]);
// exports
/***/ }),
/***/ "./node_modules/css-loader/index.js!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/lib/index.js?!./node_modules/sass-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/src/views/DashboardAnalytics.vue?vue&type=style&index=0&lang=scss&":
/*!***************************************************************************************************************************************************************************************************************************************************************************************************************************!*\
!*** ./node_modules/css-loader!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/lib??ref--8-2!./node_modules/sass-loader/dist/cjs.js??ref--8-3!./node_modules/vue-loader/lib??vue-loader-options!./resources/js/src/views/DashboardAnalytics.vue?vue&type=style&index=0&lang=scss& ***!
\***************************************************************************************************************************************************************************************************************************************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
exports = module.exports = __webpack_require__(/*! ../../../../node_modules/css-loader/lib/css-base.js */ "./node_modules/css-loader/lib/css-base.js")(false);
// imports
// module
exports.push([module.i, "#dashboard-analytics .greet-user {\n position: relative;\n}\n#dashboard-analytics .greet-user .decore-left {\n position: absolute;\n left: 0;\n top: 0;\n}\n#dashboard-analytics .greet-user .decore-right {\n position: absolute;\n right: 0;\n top: 0;\n}\n@media (max-width: 576px) {\n#dashboard-analytics .decore-left, #dashboard-analytics .decore-right {\n width: 140px;\n}\n}", ""]);
// exports
/***/ }),
/***/ "./node_modules/style-loader/index.js!./node_modules/css-loader/index.js!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/lib/index.js?!./node_modules/sass-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/src/components/timeline/VxTimeline.vue?vue&type=style&index=0&lang=scss&":
/*!*************************************************************************************************************************************************************************************************************************************************************************************************************************************************************!*\
!*** ./node_modules/style-loader!./node_modules/css-loader!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/lib??ref--8-2!./node_modules/sass-loader/dist/cjs.js??ref--8-3!./node_modules/vue-loader/lib??vue-loader-options!./resources/js/src/components/timeline/VxTimeline.vue?vue&type=style&index=0&lang=scss& ***!
\*************************************************************************************************************************************************************************************************************************************************************************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var content = __webpack_require__(/*! !../../../../../node_modules/css-loader!../../../../../node_modules/vue-loader/lib/loaders/stylePostLoader.js!../../../../../node_modules/postcss-loader/lib??ref--8-2!../../../../../node_modules/sass-loader/dist/cjs.js??ref--8-3!../../../../../node_modules/vue-loader/lib??vue-loader-options!./VxTimeline.vue?vue&type=style&index=0&lang=scss& */ "./node_modules/css-loader/index.js!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/lib/index.js?!./node_modules/sass-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/src/components/timeline/VxTimeline.vue?vue&type=style&index=0&lang=scss&");
if(typeof content === 'string') content = [[module.i, content, '']];
var transform;
var insertInto;
var options = {"hmr":true}
options.transform = transform
options.insertInto = undefined;
var update = __webpack_require__(/*! ../../../../../node_modules/style-loader/lib/addStyles.js */ "./node_modules/style-loader/lib/addStyles.js")(content, options);
if(content.locals) module.exports = content.locals;
if(false) {}
/***/ }),
/***/ "./node_modules/style-loader/index.js!./node_modules/css-loader/index.js!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/lib/index.js?!./node_modules/sass-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/src/views/DashboardAnalytics.vue?vue&type=style&index=0&lang=scss&":
/*!*******************************************************************************************************************************************************************************************************************************************************************************************************************************************************!*\
!*** ./node_modules/style-loader!./node_modules/css-loader!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/lib??ref--8-2!./node_modules/sass-loader/dist/cjs.js??ref--8-3!./node_modules/vue-loader/lib??vue-loader-options!./resources/js/src/views/DashboardAnalytics.vue?vue&type=style&index=0&lang=scss& ***!
\*******************************************************************************************************************************************************************************************************************************************************************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var content = __webpack_require__(/*! !../../../../node_modules/css-loader!../../../../node_modules/vue-loader/lib/loaders/stylePostLoader.js!../../../../node_modules/postcss-loader/lib??ref--8-2!../../../../node_modules/sass-loader/dist/cjs.js??ref--8-3!../../../../node_modules/vue-loader/lib??vue-loader-options!./DashboardAnalytics.vue?vue&type=style&index=0&lang=scss& */ "./node_modules/css-loader/index.js!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/lib/index.js?!./node_modules/sass-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/src/views/DashboardAnalytics.vue?vue&type=style&index=0&lang=scss&");
if(typeof content === 'string') content = [[module.i, content, '']];
var transform;
var insertInto;
var options = {"hmr":true}
options.transform = transform
options.insertInto = undefined;
var update = __webpack_require__(/*! ../../../../node_modules/style-loader/lib/addStyles.js */ "./node_modules/style-loader/lib/addStyles.js")(content, options);
if(content.locals) module.exports = content.locals;
if(false) {}
/***/ }),
/***/ "./node_modules/vue-loader/lib/loaders/templateLoader.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/src/components/timeline/VxTimeline.vue?vue&type=template&id=0a954b3e&":
/*!**************************************************************************************************************************************************************************************************************************!*\
!*** ./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/vue-loader/lib??vue-loader-options!./resources/js/src/components/timeline/VxTimeline.vue?vue&type=template&id=0a954b3e& ***!
\**************************************************************************************************************************************************************************************************************************/
/*! exports provided: render, staticRenderFns */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "render", function() { return render; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "staticRenderFns", function() { return staticRenderFns; });
var render = function() {
var _vm = this
var _h = _vm.$createElement
var _c = _vm._self._c || _h
return _c(
"ul",
{ staticClass: "vx-timeline" },
_vm._l(_vm.data, function(item) {
return _c("li", { key: item.title }, [
_c(
"div",
{ staticClass: "timeline-icon", class: "bg-" + item.color },
[
_c("feather-icon", {
attrs: {
icon: item.icon,
svgClasses: "text-white stroke-current w-5 h-5"
}
})
],
1
),
_vm._v(" "),
_c("div", { staticClass: "timeline-info" }, [
_c("p", { staticClass: "font-semibold" }, [
_vm._v(_vm._s(item.title))
]),
_vm._v(" "),
_c("span", { staticClass: "activity-desc" }, [
_vm._v(_vm._s(item.desc))
])
]),
_vm._v(" "),
_c("small", { staticClass: "text-grey activity-e-time" }, [
_vm._v(_vm._s(item.time))
])
])
}),
0
)
}
var staticRenderFns = []
render._withStripped = true
/***/ }),
/***/ "./node_modules/vue-loader/lib/loaders/templateLoader.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/src/views/DashboardAnalytics.vue?vue&type=template&id=596e52fc&":
/*!********************************************************************************************************************************************************************************************************************!*\
!*** ./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/vue-loader/lib??vue-loader-options!./resources/js/src/views/DashboardAnalytics.vue?vue&type=template&id=596e52fc& ***!
\********************************************************************************************************************************************************************************************************************/
/*! exports provided: render, staticRenderFns */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "render", function() { return render; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "staticRenderFns", function() { return staticRenderFns; });
var render = function() {
var _vm = this
var _h = _vm.$createElement
var _c = _vm._self._c || _h
return _c("div", { attrs: { id: "dashboard-analytics" } }, [
_c("div", { staticClass: "vx-row" }, [
_c(
"div",
{ staticClass: "vx-col w-full lg:w-1/2 mb-base" },
[
_c(
"vx-card",
{
staticClass: "text-center bg-primary-gradient greet-user",
attrs: { slot: "no-body" },
slot: "no-body"
},
[
_c("img", {
staticClass: "decore-left",
attrs: {
src: __webpack_require__(/*! @assets/images/elements/decore-left.png */ "./resources/assets/images/elements/decore-left.png"),
alt: "Decore Left",
width: "200"
}
}),
_vm._v(" "),
_c("img", {
staticClass: "decore-right",
attrs: {
src: __webpack_require__(/*! @assets/images/elements/decore-right.png */ "./resources/assets/images/elements/decore-right.png"),
alt: "Decore Right",
width: "175"
}
}),
_vm._v(" "),
_c("feather-icon", {
staticClass:
"p-6 mb-8 bg-primary inline-flex rounded-full text-white shadow",
attrs: { icon: "AwardIcon", svgClasses: "h-8 w-8" }
}),
_vm._v(" "),
_c("h1", { staticClass: "mb-6 text-white" }, [
_vm._v(
"Congratulations " +
_vm._s(_vm.checkpointReward.userName) +
","
)
]),
_vm._v(" "),
_c(
"p",
{
staticClass:
"xl:w-3/4 lg:w-4/5 md:w-2/3 w-4/5 mx-auto text-white"
},
[
_vm._v("You have done "),
_c("strong", [_vm._v(_vm._s(_vm.checkpointReward.progress))]),
_vm._v(
" more sales today. Check your new badge in your profile."
)
]
)
],
1
)
],
1
),
_vm._v(" "),
_c(
"div",
{
staticClass:
"vx-col w-full sm:w-1/2 md:w-1/2 lg:w-1/4 xl:w-1/4 mb-base"
},
[
_c("statistics-card-line", {
attrs: {
icon: "UsersIcon",
statistic: "92.6k",
statisticTitle: "Subscribers Gained",
chartData: _vm.subscribersGained.series,
type: "area"
}
})
],
1
),
_vm._v(" "),
_c(
"div",
{
staticClass:
"vx-col w-full sm:w-1/2 md:w-1/2 lg:w-1/4 xl:w-1/4 mb-base"
},
[
_c("statistics-card-line", {
attrs: {
icon: "ShoppingBagIcon",
statistic: "97.5K",
statisticTitle: "Orders Received",
chartData: _vm.ordersRecevied.series,
color: "warning",
type: "area"
}
})
],
1
)
]),
_vm._v(" "),
_c("div", { staticClass: "vx-row" }, [
_c(
"div",
{ staticClass: "vx-col w-full md:w-1/2 mb-base" },
[
_c(
"vx-card",
[
_c(
"div",
{
staticClass:
"vx-row flex-col-reverse md:flex-col-reverse sm:flex-row lg:flex-row"
},
[
_vm.salesBarSession.analyticsData
? _c(
"div",
{
staticClass:
"vx-col w-full md:w-full sm:w-1/2 lg:w-1/2 xl:w-1/2 flex flex-col justify-between"
},
[
_c("div", [
_c("h2", { staticClass: "mb-1 font-bold" }, [
_vm._v(
_vm._s(
_vm._f("k_formatter")(
_vm.salesBarSession.analyticsData.session
)
)
)
]),
_vm._v(" "),
_c("span", { staticClass: "font-medium" }, [
_vm._v("Avg Sessions")
]),
_vm._v(" "),
_c(
"p",
{ staticClass: "mt-2 text-xl font-medium" },
[
_c(
"span",
{
class:
_vm.salesBarSession.analyticsData
.comparison.result >= 0
? "text-success"
: "text-danger"
},
[
_vm.salesBarSession.analyticsData.comparison
.result > 0
? _c("span", [_vm._v("+")])
: _vm._e(),
_vm._v(" "),
_c("span", [
_vm._v(
_vm._s(
_vm.salesBarSession.analyticsData
.comparison.result
)
)
])
]
),
_vm._v(" "),
_c("span", [_vm._v(" vs ")]),
_vm._v(" "),
_c("span", [
_vm._v(
_vm._s(
_vm.salesBarSession.analyticsData
.comparison.str
)
)
])
]
)
]),
_vm._v(" "),
_c(
"vs-button",
{
staticClass: "shadow-md w-full lg:mt-0 mt-4",
attrs: {
"icon-pack": "feather",
icon: "icon-chevrons-right",
"icon-after": ""
}
},
[_vm._v("View Details")]
)
],
1
)
: _vm._e(),
_vm._v(" "),
_c(
"div",
{
staticClass:
"vx-col w-full md:w-full sm:w-1/2 lg:w-1/2 xl:w-1/2 flex flex-col lg:mb-0 md:mb-base sm:mb-0 mb-base"
},
[
_c("change-time-duration-dropdown", {
staticClass: "self-end"
}),
_vm._v(" "),
_vm.salesBarSession.series
? _c("vue-apex-charts", {
attrs: {
type: "bar",
height: "200",
options: _vm.analyticsData.salesBar.chartOptions,
series: _vm.salesBarSession.series
}
})
: _vm._e()
],
1
)
]
),
_vm._v(" "),
_c("vs-divider", { staticClass: "my-6" }),
_vm._v(" "),
_c("div", { staticClass: "vx-row" }, [
_c(
"div",
{ staticClass: "vx-col w-1/2 mb-3" },
[
_c("p", [_vm._v("Goal: $100000")]),
_vm._v(" "),
_c("vs-progress", {
staticClass: "block mt-1",
attrs: { percent: 50, color: "primary" }
})
],
1
),
_vm._v(" "),
_c(
"div",
{ staticClass: "vx-col w-1/2 mb-3" },
[
_c("p", [_vm._v("Users: 100K")]),
_vm._v(" "),
_c("vs-progress", {
staticClass: "block mt-1",
attrs: { percent: 60, color: "warning" }
})
],
1
),
_vm._v(" "),
_c(
"div",
{ staticClass: "vx-col w-1/2 mb-3" },
[
_c("p", [_vm._v("Retention: 90%")]),
_vm._v(" "),
_c("vs-progress", {
staticClass: "block mt-1",
attrs: { percent: 70, color: "danger" }
})
],
1
),
_vm._v(" "),
_c(
"div",
{ staticClass: "vx-col w-1/2 mb-3" },
[
_c("p", [_vm._v("Duration: 1yr")]),
_vm._v(" "),
_c("vs-progress", {
staticClass: "block mt-1",
attrs: { percent: 90, color: "success" }
})
],
1
)
])
],
1
)
],
1
),
_vm._v(" "),
_c(
"div",
{ staticClass: "vx-col w-full md:w-1/2 lg:w-1/2 xl:w-1/2 mb-base" },
[
_c(
"vx-card",
{ attrs: { title: "Support Tracker" } },
[
_c(
"template",
{ slot: "actions" },
[_c("change-time-duration-dropdown")],
1
),
_vm._v(" "),
_vm.supportTracker.analyticsData
? _c("div", { attrs: { slot: "no-body" }, slot: "no-body" }, [
_c("div", { staticClass: "vx-row text-center" }, [
_c(
"div",
{
staticClass:
"vx-col w-full lg:w-1/5 md:w-full sm:w-1/5 flex flex-col justify-between mb-4 lg:order-first md:order-last sm:order-first order-last"
},
[
_c(
"div",
{
staticClass:
"lg:ml-6 lg:mt-6 md:mt-0 md:ml-0 sm:ml-6 sm:mt-6"
},
[
_c("h1", { staticClass: "font-bold text-5xl" }, [
_vm._v(
_vm._s(
_vm.supportTracker.analyticsData.openTickets
)
)
]),
_vm._v(" "),
_c("small", [_vm._v("Tickets")])
]
)
]
),
_vm._v(" "),
_c(
"div",
{
staticClass:
"vx-col w-full lg:w-4/5 md:w-full sm:w-4/5 justify-center mx-auto lg:mt-0 md:mt-6 sm:mt-0 mt-6"
},
[
_c("vue-apex-charts", {
attrs: {
type: "radialBar",
height: "385",
options:
_vm.analyticsData.supportTrackerRadialBar
.chartOptions,
series: _vm.supportTracker.series
}
})
],
1
)
]),
_vm._v(" "),
_c(
"div",
{
staticClass:
"flex flex-row justify-between px-8 pb-4 mt-4"
},
_vm._l(_vm.supportTracker.analyticsData.meta, function(
val,
key
) {
return _c(
"p",
{ key: key, staticClass: "text-center" },
[
_c("span", { staticClass: "block" }, [
_vm._v(_vm._s(key))
]),
_vm._v(" "),
_c(
"span",
{ staticClass: "text-2xl font-semibold" },
[_vm._v(_vm._s(val))]
)
]
)
}),
0
)
])
: _vm._e()
],
2
)
],
1
)
]),
_vm._v(" "),
_c("div", { staticClass: "vx-row" }, [
_c(
"div",
{ staticClass: "vx-col w-full lg:w-1/3 mb-base" },
[
_c(
"vx-card",
{ attrs: { title: "Product Orders" } },
[
_c(
"template",
{ slot: "actions" },
[_c("change-time-duration-dropdown")],
1
),
_vm._v(" "),
_c(
"div",
{ attrs: { slot: "no-body" }, slot: "no-body" },
[
_c("vue-apex-charts", {
attrs: {
type: "radialBar",
height: "420",
options:
_vm.analyticsData.productOrdersRadialBar.chartOptions,
series: _vm.productsOrder.series
}
})
],
1
),
_vm._v(" "),
_c(
"ul",
_vm._l(_vm.productsOrder.analyticsData, function(orderData) {
return _c(
"li",
{
key: orderData.orderType,
staticClass: "flex mb-3 justify-between"
},
[
_c("span", { staticClass: "flex items-center" }, [
_c("span", {
staticClass:
"inline-block h-4 w-4 rounded-full mr-2 bg-white border-3 border-solid",
class: "border-" + orderData.color
}),
_vm._v(" "),
_c("span", { staticClass: "font-semibold" }, [
_vm._v(_vm._s(orderData.orderType))
])
]),
_vm._v(" "),
_c("span", [_vm._v(_vm._s(orderData.counts))])
]
)
}),
0
)
],
2
)
],
1
),
_vm._v(" "),
_c(
"div",
{ staticClass: "vx-col w-full lg:w-1/3 mb-base" },
[
_c(
"vx-card",
{ attrs: { title: "Sales Stats", subtitle: "Last 6 Months" } },
[
_c(
"template",
{ slot: "actions" },
[
_c("feather-icon", {
attrs: {
icon: "MoreVerticalIcon",
svgClasses: "w-6 h-6 text-grey"
}
})
],
1
),
_vm._v(" "),
_c("div", { staticClass: "flex" }, [
_c("span", { staticClass: "flex items-center" }, [
_c("div", {
staticClass: "h-3 w-3 rounded-full mr-1 bg-primary"
}),
_c("span", [_vm._v("Sales")])
]),
_vm._v(" "),
_c("span", { staticClass: "flex items-center ml-4" }, [
_c("div", {
staticClass: "h-3 w-3 rounded-full mr-1 bg-success"
}),
_c("span", [_vm._v("Visits")])
])
]),
_vm._v(" "),
_c(
"div",
{ attrs: { slot: "no-body-bottom" }, slot: "no-body-bottom" },
[
_c("vue-apex-charts", {
attrs: {
type: "radar",
height: "385",
options: _vm.analyticsData.statisticsRadar.chartOptions,
series: _vm.salesRadar.series
}
})
],
1
)
],
2
)
],
1
),
_vm._v(" "),
_c(
"div",
{ staticClass: "vx-col w-full lg:w-1/3 mb-base" },
[
_c(
"vx-card",
{ attrs: { title: "Activity Timeline" } },
[_c("vx-timeline", { attrs: { data: _vm.timelineData } })],
1
)
],
1
)
]),
_vm._v(" "),
_c("div", { staticClass: "vx-row" }, [
_c(
"div",
{ staticClass: "vx-col w-full" },
[
_c("vx-card", { attrs: { title: "Dispatched Orders" } }, [
_c(
"div",
{
staticClass: "mt-4",
attrs: { slot: "no-body" },
slot: "no-body"
},
[
_c(
"vs-table",
{
staticClass: "table-dark-inverted",
attrs: { data: _vm.dispatchedOrders },
scopedSlots: _vm._u([
{
key: "default",
fn: function(ref) {
var data = ref.data
return _vm._l(data, function(tr, indextr) {
return _c(
"vs-tr",
{ key: indextr },
[
_c(
"vs-td",
{ attrs: { data: data[indextr].orderNo } },
[
_c("span", [
_vm._v(
"#" + _vm._s(data[indextr].orderNo)
)
])
]
),
_vm._v(" "),
_c(
"vs-td",
{ attrs: { data: data[indextr].status } },
[
_c(
"span",
{
staticClass:
"flex items-center px-2 py-1 rounded"
},
[
_c("div", {
staticClass:
"h-3 w-3 rounded-full mr-2",
class:
"bg-" + data[indextr].statusColor
}),
_vm._v(_vm._s(data[indextr].status))
]
)
]
),
_vm._v(" "),
_c(
"vs-td",
{ attrs: { data: data[indextr].orderNo } },
[
_c(
"ul",
{ staticClass: "users-liked user-list" },
_vm._l(data[indextr].usersLiked, function(
user,
userIndex
) {
return _c(
"li",
{ key: userIndex },
[
_c(
"vx-tooltip",
{
attrs: {
text: user.name,
position: "bottom"
}
},
[
_c("vs-avatar", {
staticClass:
"border-2 border-white border-solid -m-1",
attrs: {
src: user.img,
size: "30px"
}
})
],
1
)
],
1
)
}),
0
)
]
),
_vm._v(" "),
_c(
"vs-td",
{ attrs: { data: data[indextr].orderNo } },
[
_c("span", [
_vm._v(_vm._s(data[indextr].location))
])
]
),
_vm._v(" "),
_c(
"vs-td",
{ attrs: { data: data[indextr].orderNo } },
[
_c("span", [
_vm._v(_vm._s(data[indextr].distance))
]),
_vm._v(" "),
_c("vs-progress", {
attrs: {
percent: data[indextr].distPercent,
color: data[indextr].statusColor
}
})
],
1
),
_vm._v(" "),
_c(
"vs-td",
{ attrs: { data: data[indextr].orderNo } },
[
_c("span", [
_vm._v(_vm._s(data[indextr].startDate))
])
]
),
_vm._v(" "),
_c(
"vs-td",
{ attrs: { data: data[indextr].orderNo } },
[
_c("span", [
_vm._v(_vm._s(data[indextr].estDelDate))
])
]
)
],
1
)
})
}
}
])
},
[
_c(
"template",
{ slot: "thead" },
[
_c("vs-th", [_vm._v("ORDER NO.")]),
_vm._v(" "),
_c("vs-th", [_vm._v("STATUS")]),
_vm._v(" "),
_c("vs-th", [_vm._v("OPERATORS")]),
_vm._v(" "),
_c("vs-th", [_vm._v("LOCATION")]),
_vm._v(" "),
_c("vs-th", [_vm._v("DISTANCE")]),
_vm._v(" "),
_c("vs-th", [_vm._v("START DATE")]),
_vm._v(" "),
_c("vs-th", [_vm._v("EST DELIVERY DATE")])
],
1
)
],
2
)
],
1
)
])
],
1
)
])
])
}
var staticRenderFns = []
render._withStripped = true
/***/ }),
/***/ "./resources/assets/images/elements/decore-left.png":
/*!**********************************************************!*\
!*** ./resources/assets/images/elements/decore-left.png ***!
\**********************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
module.exports = "/images/decore-left.png?2d9d23e097d9118c0aa4cc074b6c5b22";
/***/ }),
/***/ "./resources/assets/images/elements/decore-right.png":
/*!***********************************************************!*\
!*** ./resources/assets/images/elements/decore-right.png ***!
\***********************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
module.exports = "/images/decore-right.png?da0ab5cda39e974268cbe4da64f597b6";
/***/ }),
/***/ "./resources/js/src/components/timeline/VxTimeline.vue":
/*!*************************************************************!*\
!*** ./resources/js/src/components/timeline/VxTimeline.vue ***!
\*************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _VxTimeline_vue_vue_type_template_id_0a954b3e___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./VxTimeline.vue?vue&type=template&id=0a954b3e& */ "./resources/js/src/components/timeline/VxTimeline.vue?vue&type=template&id=0a954b3e&");
/* harmony import */ var _VxTimeline_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./VxTimeline.vue?vue&type=script&lang=js& */ "./resources/js/src/components/timeline/VxTimeline.vue?vue&type=script&lang=js&");
/* empty/unused harmony star reexport *//* harmony import */ var _VxTimeline_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./VxTimeline.vue?vue&type=style&index=0&lang=scss& */ "./resources/js/src/components/timeline/VxTimeline.vue?vue&type=style&index=0&lang=scss&");
/* harmony import */ var _node_modules_vue_loader_lib_runtime_componentNormalizer_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../../../../node_modules/vue-loader/lib/runtime/componentNormalizer.js */ "./node_modules/vue-loader/lib/runtime/componentNormalizer.js");
/* normalize component */
var component = Object(_node_modules_vue_loader_lib_runtime_componentNormalizer_js__WEBPACK_IMPORTED_MODULE_3__["default"])(
_VxTimeline_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__["default"],
_VxTimeline_vue_vue_type_template_id_0a954b3e___WEBPACK_IMPORTED_MODULE_0__["render"],
_VxTimeline_vue_vue_type_template_id_0a954b3e___WEBPACK_IMPORTED_MODULE_0__["staticRenderFns"],
false,
null,
null,
null
)
/* hot reload */
if (false) { var api; }
component.options.__file = "resources/js/src/components/timeline/VxTimeline.vue"
/* harmony default export */ __webpack_exports__["default"] = (component.exports);
/***/ }),
/***/ "./resources/js/src/components/timeline/VxTimeline.vue?vue&type=script&lang=js&":
/*!**************************************************************************************!*\
!*** ./resources/js/src/components/timeline/VxTimeline.vue?vue&type=script&lang=js& ***!
\**************************************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _node_modules_babel_loader_lib_index_js_ref_4_0_node_modules_vue_loader_lib_index_js_vue_loader_options_VxTimeline_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!../../../../../node_modules/babel-loader/lib??ref--4-0!../../../../../node_modules/vue-loader/lib??vue-loader-options!./VxTimeline.vue?vue&type=script&lang=js& */ "./node_modules/babel-loader/lib/index.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/src/components/timeline/VxTimeline.vue?vue&type=script&lang=js&");
/* empty/unused harmony star reexport */ /* harmony default export */ __webpack_exports__["default"] = (_node_modules_babel_loader_lib_index_js_ref_4_0_node_modules_vue_loader_lib_index_js_vue_loader_options_VxTimeline_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__["default"]);
/***/ }),
/***/ "./resources/js/src/components/timeline/VxTimeline.vue?vue&type=style&index=0&lang=scss&":
/*!***********************************************************************************************!*\
!*** ./resources/js/src/components/timeline/VxTimeline.vue?vue&type=style&index=0&lang=scss& ***!
\***********************************************************************************************/
/*! no static exports found */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _node_modules_style_loader_index_js_node_modules_css_loader_index_js_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_lib_index_js_ref_8_2_node_modules_sass_loader_dist_cjs_js_ref_8_3_node_modules_vue_loader_lib_index_js_vue_loader_options_VxTimeline_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!../../../../../node_modules/style-loader!../../../../../node_modules/css-loader!../../../../../node_modules/vue-loader/lib/loaders/stylePostLoader.js!../../../../../node_modules/postcss-loader/lib??ref--8-2!../../../../../node_modules/sass-loader/dist/cjs.js??ref--8-3!../../../../../node_modules/vue-loader/lib??vue-loader-options!./VxTimeline.vue?vue&type=style&index=0&lang=scss& */ "./node_modules/style-loader/index.js!./node_modules/css-loader/index.js!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/lib/index.js?!./node_modules/sass-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/src/components/timeline/VxTimeline.vue?vue&type=style&index=0&lang=scss&");
/* harmony import */ var _node_modules_style_loader_index_js_node_modules_css_loader_index_js_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_lib_index_js_ref_8_2_node_modules_sass_loader_dist_cjs_js_ref_8_3_node_modules_vue_loader_lib_index_js_vue_loader_options_VxTimeline_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_index_js_node_modules_css_loader_index_js_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_lib_index_js_ref_8_2_node_modules_sass_loader_dist_cjs_js_ref_8_3_node_modules_vue_loader_lib_index_js_vue_loader_options_VxTimeline_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0__);
/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _node_modules_style_loader_index_js_node_modules_css_loader_index_js_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_lib_index_js_ref_8_2_node_modules_sass_loader_dist_cjs_js_ref_8_3_node_modules_vue_loader_lib_index_js_vue_loader_options_VxTimeline_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0__) if(__WEBPACK_IMPORT_KEY__ !== 'default') (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _node_modules_style_loader_index_js_node_modules_css_loader_index_js_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_lib_index_js_ref_8_2_node_modules_sass_loader_dist_cjs_js_ref_8_3_node_modules_vue_loader_lib_index_js_vue_loader_options_VxTimeline_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0__[key]; }) }(__WEBPACK_IMPORT_KEY__));
/* harmony default export */ __webpack_exports__["default"] = (_node_modules_style_loader_index_js_node_modules_css_loader_index_js_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_lib_index_js_ref_8_2_node_modules_sass_loader_dist_cjs_js_ref_8_3_node_modules_vue_loader_lib_index_js_vue_loader_options_VxTimeline_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0___default.a);
/***/ }),
/***/ "./resources/js/src/components/timeline/VxTimeline.vue?vue&type=template&id=0a954b3e&":
/*!********************************************************************************************!*\
!*** ./resources/js/src/components/timeline/VxTimeline.vue?vue&type=template&id=0a954b3e& ***!
\********************************************************************************************/
/*! exports provided: render, staticRenderFns */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_vue_loader_lib_index_js_vue_loader_options_VxTimeline_vue_vue_type_template_id_0a954b3e___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!../../../../../node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!../../../../../node_modules/vue-loader/lib??vue-loader-options!./VxTimeline.vue?vue&type=template&id=0a954b3e& */ "./node_modules/vue-loader/lib/loaders/templateLoader.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/src/components/timeline/VxTimeline.vue?vue&type=template&id=0a954b3e&");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "render", function() { return _node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_vue_loader_lib_index_js_vue_loader_options_VxTimeline_vue_vue_type_template_id_0a954b3e___WEBPACK_IMPORTED_MODULE_0__["render"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "staticRenderFns", function() { return _node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_vue_loader_lib_index_js_vue_loader_options_VxTimeline_vue_vue_type_template_id_0a954b3e___WEBPACK_IMPORTED_MODULE_0__["staticRenderFns"]; });
/***/ }),
/***/ "./resources/js/src/views/DashboardAnalytics.vue":
/*!*******************************************************!*\
!*** ./resources/js/src/views/DashboardAnalytics.vue ***!
\*******************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _DashboardAnalytics_vue_vue_type_template_id_596e52fc___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./DashboardAnalytics.vue?vue&type=template&id=596e52fc& */ "./resources/js/src/views/DashboardAnalytics.vue?vue&type=template&id=596e52fc&");
/* harmony import */ var _DashboardAnalytics_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./DashboardAnalytics.vue?vue&type=script&lang=js& */ "./resources/js/src/views/DashboardAnalytics.vue?vue&type=script&lang=js&");
/* empty/unused harmony star reexport *//* harmony import */ var _DashboardAnalytics_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./DashboardAnalytics.vue?vue&type=style&index=0&lang=scss& */ "./resources/js/src/views/DashboardAnalytics.vue?vue&type=style&index=0&lang=scss&");
/* harmony import */ var _node_modules_vue_loader_lib_runtime_componentNormalizer_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../../../node_modules/vue-loader/lib/runtime/componentNormalizer.js */ "./node_modules/vue-loader/lib/runtime/componentNormalizer.js");
/* normalize component */
var component = Object(_node_modules_vue_loader_lib_runtime_componentNormalizer_js__WEBPACK_IMPORTED_MODULE_3__["default"])(
_DashboardAnalytics_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__["default"],
_DashboardAnalytics_vue_vue_type_template_id_596e52fc___WEBPACK_IMPORTED_MODULE_0__["render"],
_DashboardAnalytics_vue_vue_type_template_id_596e52fc___WEBPACK_IMPORTED_MODULE_0__["staticRenderFns"],
false,
null,
null,
null
)
/* hot reload */
if (false) { var api; }
component.options.__file = "resources/js/src/views/DashboardAnalytics.vue"
/* harmony default export */ __webpack_exports__["default"] = (component.exports);
/***/ }),
/***/ "./resources/js/src/views/DashboardAnalytics.vue?vue&type=script&lang=js&":
/*!********************************************************************************!*\
!*** ./resources/js/src/views/DashboardAnalytics.vue?vue&type=script&lang=js& ***!
\********************************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _node_modules_babel_loader_lib_index_js_ref_4_0_node_modules_vue_loader_lib_index_js_vue_loader_options_DashboardAnalytics_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!../../../../node_modules/babel-loader/lib??ref--4-0!../../../../node_modules/vue-loader/lib??vue-loader-options!./DashboardAnalytics.vue?vue&type=script&lang=js& */ "./node_modules/babel-loader/lib/index.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/src/views/DashboardAnalytics.vue?vue&type=script&lang=js&");
/* empty/unused harmony star reexport */ /* harmony default export */ __webpack_exports__["default"] = (_node_modules_babel_loader_lib_index_js_ref_4_0_node_modules_vue_loader_lib_index_js_vue_loader_options_DashboardAnalytics_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__["default"]);
/***/ }),
/***/ "./resources/js/src/views/DashboardAnalytics.vue?vue&type=style&index=0&lang=scss&":
/*!*****************************************************************************************!*\
!*** ./resources/js/src/views/DashboardAnalytics.vue?vue&type=style&index=0&lang=scss& ***!
\*****************************************************************************************/
/*! no static exports found */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _node_modules_style_loader_index_js_node_modules_css_loader_index_js_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_lib_index_js_ref_8_2_node_modules_sass_loader_dist_cjs_js_ref_8_3_node_modules_vue_loader_lib_index_js_vue_loader_options_DashboardAnalytics_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!../../../../node_modules/style-loader!../../../../node_modules/css-loader!../../../../node_modules/vue-loader/lib/loaders/stylePostLoader.js!../../../../node_modules/postcss-loader/lib??ref--8-2!../../../../node_modules/sass-loader/dist/cjs.js??ref--8-3!../../../../node_modules/vue-loader/lib??vue-loader-options!./DashboardAnalytics.vue?vue&type=style&index=0&lang=scss& */ "./node_modules/style-loader/index.js!./node_modules/css-loader/index.js!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/lib/index.js?!./node_modules/sass-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/src/views/DashboardAnalytics.vue?vue&type=style&index=0&lang=scss&");
/* harmony import */ var _node_modules_style_loader_index_js_node_modules_css_loader_index_js_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_lib_index_js_ref_8_2_node_modules_sass_loader_dist_cjs_js_ref_8_3_node_modules_vue_loader_lib_index_js_vue_loader_options_DashboardAnalytics_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_index_js_node_modules_css_loader_index_js_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_lib_index_js_ref_8_2_node_modules_sass_loader_dist_cjs_js_ref_8_3_node_modules_vue_loader_lib_index_js_vue_loader_options_DashboardAnalytics_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0__);
/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _node_modules_style_loader_index_js_node_modules_css_loader_index_js_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_lib_index_js_ref_8_2_node_modules_sass_loader_dist_cjs_js_ref_8_3_node_modules_vue_loader_lib_index_js_vue_loader_options_DashboardAnalytics_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0__) if(__WEBPACK_IMPORT_KEY__ !== 'default') (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _node_modules_style_loader_index_js_node_modules_css_loader_index_js_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_lib_index_js_ref_8_2_node_modules_sass_loader_dist_cjs_js_ref_8_3_node_modules_vue_loader_lib_index_js_vue_loader_options_DashboardAnalytics_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0__[key]; }) }(__WEBPACK_IMPORT_KEY__));
/* harmony default export */ __webpack_exports__["default"] = (_node_modules_style_loader_index_js_node_modules_css_loader_index_js_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_lib_index_js_ref_8_2_node_modules_sass_loader_dist_cjs_js_ref_8_3_node_modules_vue_loader_lib_index_js_vue_loader_options_DashboardAnalytics_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0___default.a);
/***/ }),
/***/ "./resources/js/src/views/DashboardAnalytics.vue?vue&type=template&id=596e52fc&":
/*!**************************************************************************************!*\
!*** ./resources/js/src/views/DashboardAnalytics.vue?vue&type=template&id=596e52fc& ***!
\**************************************************************************************/
/*! exports provided: render, staticRenderFns */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_vue_loader_lib_index_js_vue_loader_options_DashboardAnalytics_vue_vue_type_template_id_596e52fc___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!../../../../node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!../../../../node_modules/vue-loader/lib??vue-loader-options!./DashboardAnalytics.vue?vue&type=template&id=596e52fc& */ "./node_modules/vue-loader/lib/loaders/templateLoader.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/src/views/DashboardAnalytics.vue?vue&type=template&id=596e52fc&");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "render", function() { return _node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_vue_loader_lib_index_js_vue_loader_options_DashboardAnalytics_vue_vue_type_template_id_596e52fc___WEBPACK_IMPORTED_MODULE_0__["render"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "staticRenderFns", function() { return _node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_vue_loader_lib_index_js_vue_loader_options_DashboardAnalytics_vue_vue_type_template_id_596e52fc___WEBPACK_IMPORTED_MODULE_0__["staticRenderFns"]; });
/***/ })
}]);
|
import Api from 'app/api';
import ApiConstants from '../ApiConstants';
export default function registerUser(username, password, email, phone, address, city, country, name, nid, bio, firstName, lastName, profileType) {
const payload = {
username: username,
password: password,
email: email,
phone: phone,
address: address,
city: city,
country: country,
name: name,
nid: nid,
bio: bio,
first_name: firstName,
last_name: lastName,
profile_type: profileType,
};
return Api(
ApiConstants.SIGNUP,
payload,
'post',
null
);
}
|
export default function() {
const store = this.riotx.get();
const maxSize = 5;
this.names = store.getter('endpoints.namesFiltered', maxSize);
// `tag`はriotの予約後なので_を付けとく。
this._tags = store.getter('endpoints.tagsFiltered', maxSize);
this.isEmpty = (!this.names.length && !this._tags.length);
this.listen('application', () => {
this.names = store.getter('endpoints.namesFiltered', maxSize);
this._tags = store.getter('endpoints.tagsFiltered', maxSize);
this.isEmpty = (!this.names.length && !this._tags.length);
this.update();
});
this.handleMouseDown = e => {
// input要素のblurイベント発火を抑制するため。
e.stopPropagation();
e.preventDefault();
};
this.handleItemTap = e => {
const text = e.item.value || '';
Promise
.resolve()
.then(() => store.action('application.updateEndpointFilterText', text))
.catch(err => store.action('modals.add', 'viron-error', {
error: err
}));
};
}
|
import React from 'react';
import { connect } from 'react-redux';
import cx from 'classnames';
import './styles.css';
import UI from './UI';
import Item from './Item';
import Activity from './Activity';
import Vendor from './Vendor';
import { Checklist, Record, Node } from './Maps';
import CollectionsBadge from './CollectionsBadge';
class Tooltip extends React.Component {
state = {
hash: false,
table: false,
data: {}
};
ref_tooltip = React.createRef();
touchPosition = {
x: 0,
y: 0
};
mousePosition = {
x: 0,
y: 0
};
rAF = null;
helper_tooltipPositionUpdate = () => {
if (this.ref_tooltip.current) {
this.ref_tooltip.current.style.transform = `translate(${this.mousePosition.x}px, ${this.mousePosition.y}px)`;
}
window.requestAnimationFrame(this.helper_tooltipPositionUpdate);
};
helper_windowMouseMove = e => {
let x = 0;
let y = 0;
let offset = 0;
let tooltipWidth = 440;
let tooltipHeight = this.state.hash ? this.ref_tooltip.current.clientHeight : 0;
let scrollbarAllowance = 24;
x = e.clientX;
y = e.clientY - (tooltipHeight >= 320 ? 140 : 0);
if (x + tooltipWidth + scrollbarAllowance > (window.innerWidth / 3) * 2 + tooltipWidth) {
x = x - tooltipWidth - scrollbarAllowance - offset;
} else {
x = x + scrollbarAllowance + offset;
}
if (y + tooltipHeight + scrollbarAllowance > window.innerHeight) {
y = window.innerHeight - tooltipHeight - scrollbarAllowance;
}
y = y < scrollbarAllowance ? scrollbarAllowance : y;
if (this.state.hash) {
this.mousePosition = {
x,
y
};
}
};
helper_targetMouseEnter = e => {
if (e.currentTarget.dataset.hash) {
this.setState({
hash: e.currentTarget.dataset.hash,
table: e.currentTarget.dataset.table,
type: e.currentTarget.dataset.type,
data: {
...e.currentTarget.dataset
}
});
this.helper_windowMouseMove(e);
}
};
helper_targetMouseLeave = e => {
window.cancelAnimationFrame(this.rAF);
this.resetState();
};
helper_targetTouchStart = e => {
this.touchPosition = {
x: e.changedTouches[0].clientX,
y: e.changedTouches[0].clientY
};
};
helper_targetTouchMove = e => {};
helper_targetTouchEnd = e => {
const drag = e && e.changedTouches && e.changedTouches.length ? !(e.changedTouches[0].clientX - this.touchPosition.x === 0 && e.changedTouches[0].clientY - this.touchPosition.y === 0) : false;
if (!drag) {
if (e.currentTarget.dataset.hash) {
this.setState({
hash: e.currentTarget.dataset.hash,
table: e.currentTarget.dataset.table,
type: e.currentTarget.dataset.type,
data: {
...e.currentTarget.dataset
}
});
}
}
};
helper_tooltipTouchStart = e => {
this.touchPosition = {
x: e.changedTouches[0].clientX,
y: e.changedTouches[0].clientY
};
};
helper_tooltipTouchMove = e => {};
helper_tooltipTouchEnd = e => {
e.preventDefault();
const drag = e && e.changedTouches && e.changedTouches.length ? !(e.changedTouches[0].clientX - this.touchPosition.x === 0 && e.changedTouches[0].clientY - this.touchPosition.y === 0) : false;
if (!drag) {
this.resetState();
}
};
resetState = () => {
this.setState({
hash: false,
table: false,
data: {}
});
this.touchPosition = {
x: 0,
y: 0
};
this.mousePosition = {
x: 0,
y: 0
};
};
bind_TooltipItem = reset => {
if (reset) {
this.resetState();
}
const targets = document.querySelectorAll('.tooltip');
targets.forEach(target => {
target.addEventListener('touchstart', this.helper_targetTouchStart);
target.addEventListener('touchmove', this.helper_targetTouchMove);
target.addEventListener('touchend', this.helper_targetTouchEnd);
target.addEventListener('mouseenter', this.helper_targetMouseEnter);
target.addEventListener('mouseleave', this.helper_targetMouseLeave);
});
};
bind_Tooltip = () => {
this.ref_tooltip.current.addEventListener('touchstart', this.helper_tooltipTouchStart);
this.ref_tooltip.current.addEventListener('touchmove', this.helper_tooltipTouchMove);
this.ref_tooltip.current.addEventListener('touchend', this.helper_tooltipTouchEnd);
};
componentDidUpdate(p) {
if (this.props.tooltips.bindTime !== p.tooltips.bindTime) {
this.bind_TooltipItem();
}
if (this.props.location && p.location.pathname !== this.props.location.pathname) {
// console.log('location change');
this.bind_TooltipItem(true);
}
if (this.props.member.updated !== p.member.updated) {
this.bind_TooltipItem();
}
if (this.state.hash) {
this.bind_Tooltip();
}
}
componentDidMount() {
window.addEventListener('mousemove', this.helper_windowMouseMove);
this.rAF = window.requestAnimationFrame(this.helper_tooltipPositionUpdate);
}
componentWillUnmount() {
window.removeEventListener('mousemove', this.helper_windowMouseMove);
window.cancelAnimationFrame(this.rAF);
}
render() {
let Tooltip = Item;
if (this.state.hash) {
if (this.state.table === 'DestinyActivityDefinition') Tooltip = Activity;
if (this.state.table === 'DestinyVendorDefinition') Tooltip = Vendor;
if (this.state.table === 'DestinyChecklistDefinition') Tooltip = Checklist;
if (this.state.table === 'DestinyRecordDefinition') Tooltip = Record;
if (this.state.type === 'maps') Tooltip = Node;
if (this.state.type === 'activity') Tooltip = Activity;
if (this.state.type === 'checklist') Tooltip = Checklist;
if (this.state.type === 'record') Tooltip = Record;
if (this.state.type === 'vendor') Tooltip = Vendor;
if (this.state.type === 'collections-badge') Tooltip = CollectionsBadge;
if (['braytech', 'ui', 'modifier', 'stat'].includes(this.state.type)) Tooltip = UI;
}
return (
<div ref={this.ref_tooltip} id='tooltip' className={cx({ visible: this.state.hash })}>
{this.state.hash ? <Tooltip {...this.state.data} /> : null}
</div>
);
}
}
function mapStateToProps(state, ownProps) {
return {
member: state.member,
tooltips: state.tooltips
};
}
export default connect(mapStateToProps)(Tooltip);
|
module.exports = {
interval: 60000, // Feed check interval, in miliseconds
userAgent: 'Mozilla/5.0 (Linux x86_64; rv:76.0) Gecko/20100101 Firefox/76.0', // Experimental: User agent string to bypass possible fetching limits on GitHub
/**
* Provide your GitHub token below to bypass the rate limit
* and to get notified from private repositories
*/
githubToken: null,
notifications: {
pushbullet: {
enabled: false,
accessToken: 'PUSHBULLET_TOKEN',
},
pushover: {
enabled: false,
config: {
user: 'PUSHOVER_USER',
token: 'PUSHOVER_TOKEN',
},
},
email: {
enabled: true,
config: { // Nodemailer configuration
host: 'smtp.service.com',
port: 465,
secure: true,
auth: {
user: 'smtp@user.com',
pass: 'password',
},
},
mailOptions: {
from: '"AlertHub" <smtp@user.com>', // from field, can be pure e-mail or "Name" <e-mail> format
to: 'your@email.com', // Your e-mail, can add more e-mails by commas
subjectPrefix: 'New GitHub Release', // Subject prefix
},
},
},
rss: {
enabled: true,
port: 3444,
title: 'AlertHub RSS', // Feed Title
description: 'My Awesome GitHub Release Aggregator', // Feed Description
includeFromEachRepository: 10, // How many releases/items will be fetched from each repository
count: 50, // How many elements will be there in the feed
siteUrl: 'https://github.com/Ardakilic/alerthub', // Site url shown on the feed
feedUrl: null, // Fills: <atom:link href="feedurl" rel="self" type="application/rss+xml"/>
logLevel: 'info', // debug, info, warn, err, off
},
repositories: {
github: {
releases: [
'Ardakilic/alerthub', // can be resolved as https://github.com/Ardakilic/alerthub
'expressjs/express',
'Unitech/pm2',
'facebook/react',
],
tags: [
],
commits: {
'laravel/laravel': ['*'], // All commits of https://github.com/Laravel/laravel regardless of the branch
'acikkaynak/acikkaynak': ['master'], // only commits at master branch of https://github.com/acikkaynak/acikkaynak
'acikkaynak/acikkaynak-website': ['master', 'development'], // master and development branches of https://github.com/acikkaynak/acikkaynak-website
},
issues: {
'denoland/deno': { // The below will be converted to GitHub API querystring parameters, feel free to edit accordingly
state: 'all', // all, open, closed
labels: '', // leave blank for all labels, or add comma for multiple labels
},
},
},
gitlab: {
// releases: [], // Gitlab doesn't support this yet. Use tags instead for the time being
tags: [
'gitlab-org/gitlab-foss', // Can be resolved as https://gitlab.com/gitlab-org/gitlab-foss/
],
commits: {
'gitlab-org/gitlab-foss': ['master'], // resolves as https://gitlab.com/gitlab-org/gitlab-foss/-/commits/master . You can follow multiple branches this way.
},
},
},
extras: [
// direct rss links from other sources if you want to watch with this tool
],
};
|
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(['exports', '../createIcon'], factory);
} else if (typeof exports !== "undefined") {
factory(exports, require('../createIcon'));
} else {
var mod = {
exports: {}
};
factory(mod.exports, global.createIcon);
global.imagesIcon = mod.exports;
}
})(this, function (exports, _createIcon) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createIcon2 = _interopRequireDefault(_createIcon);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
var ImagesIcon = (0, _createIcon2.default)({
name: 'ImagesIcon',
height: 512,
width: 576,
svgPath: 'M480 416v16c0 26.51-21.49 48-48 48H48c-26.51 0-48-21.49-48-48V176c0-26.51 21.49-48 48-48h16v208c0 44.112 35.888 80 80 80h336zm96-80V80c0-26.51-21.49-48-48-48H144c-26.51 0-48 21.49-48 48v256c0 26.51 21.49 48 48 48h384c26.51 0 48-21.49 48-48zM256 128c0 26.51-21.49 48-48 48s-48-21.49-48-48 21.49-48 48-48 48 21.49 48 48zm-96 144l55.515-55.515c4.686-4.686 12.284-4.686 16.971 0L272 256l135.515-135.515c4.686-4.686 12.284-4.686 16.971 0L512 208v112H160v-48z',
yOffset: '',
xOffset: '',
transform: ''
}); /* This file is generated by createIcons.js any changes will be lost. */
exports.default = ImagesIcon;
});
|
/*
* Copyright (C) 2019 Intel Corporation
* SPDX-License-Identifier: MIT
*/
/* global
require:true
*/
const JSZip = require('jszip');
onmessage = (e) => {
const zip = new JSZip();
if (e.data) {
const { start, end, block } = e.data;
zip.loadAsync(block).then((_zip) => {
let index = start;
_zip.forEach((relativePath) => {
const fileIndex = index++;
if (fileIndex <= end) {
_zip.file(relativePath).async('blob').then((fileData) => {
createImageBitmap(fileData).then((img) => {
postMessage({
fileName: relativePath,
index: fileIndex,
data: img,
});
});
});
}
});
});
}
};
|
/*
@licstart The following is the entire license notice for the JavaScript code in this file.
The MIT License (MIT)
Copyright (C) 1997-2020 by Dimitri van Heesch
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.
@licend The above is the entire license notice for the JavaScript code in this file
*/
var menudata={children:[
{text:"Main Page",url:"index.html"},
{text:"Classes",url:"annotated.html",children:[
{text:"Class List",url:"annotated.html"},
{text:"Class Index",url:"classes.html"},
{text:"Class Hierarchy",url:"hierarchy.html"},
{text:"Class Members",url:"functions.html",children:[
{text:"All",url:"functions.html"},
{text:"Functions",url:"functions_func.html"},
{text:"Variables",url:"functions_vars.html"}]}]},
{text:"Files",url:"files.html",children:[
{text:"File List",url:"files.html"}]}]}
|
module.exports = {
env: {
browser: true,
},
extends: 'airbnb',
parser: 'babel-eslint',
parserOptions: {
"ecmaVersion": 6,
"ecmaFeatures": {
"jsx": true
}
},
rules: {
//"class-methods-use-this": ["error", { "exceptMethods": ["render"] }],
//react组件推荐写法
"react/prefer-stateless-function": 0,
//拖尾逗号
"comma-dangle": 0,
//箭头函数函数体
"arrow-body-style": [2,'always']
},
plugins: [
'jsx-a11y',
'react',
],
};
|
const createExcludeRegex = require("../lib/to-abstract-base-template-utils/oc-webpack/lib/configurator/createExcludeRegex");
test("should create a regex that match against any node module set aside given ones", () => {
const regex = createExcludeRegex([
"ot-oc-template-react-email-compiler/utils",
"@ot-react-ui/timeslots",
"underscore"
]);
expect(regex).toBeInstanceOf(RegExp);
expect(regex.test("node_modules/lodash")).toBe(true);
expect(regex.test("node_modules/ot-oc-template-react-email-compiler")).toBe(
true
);
expect(regex.test("node_modules/@ot-react-ui/dtp")).toBe(true);
expect(
regex.test("node_modules/ot-oc-template-react-email-compiler/utils")
).toBe(false);
expect(regex.test("node_modules/underscore")).toBe(false);
expect(regex.test("node_modules/@ot-react-ui/timeslots")).toBe(false);
});
|
(function()
{
/**
* Download from following URL as TSV and convert using https://jgraph.github.io/drawio-tools/tools/convert.html:
* https://docs.google.com/spreadsheets/d/1sAL1zn-UtmJtKPH4cLApGjRX-TRSJa5dYdfZ9NKYfRs
* Maps package and stencil names to additional tags.
*/
Sidebar.prototype.tagIndex = '5V1dV+M6sv01rDvngax0oLvveYQEaGaAziE0PW8sxVYSDbblI9uk6V9/VVWS7ST+kB0zL3etbmIn3ltlfZRKUqkU/rpRLN6MmFJym5yM/8QL/Xnw7yLceXQ03fA3JaOTyfjCQCKZehvu66tErCMW6J9E1M4jlJcFTJWIPP1VIKK1ixj/zML4VBRiTMaf9HOKx8G7/lwy71V/ZJEv8Vv8cKea9KW646tU41nk678/4tK7SZVu5FpC9oz/TDPVnkEPJlsn4wVma1lEnVemGByy6q+M+SXkSmaQ6Vv27gJeBDzyOQDMu1ma5FVEEVBEtuokgQhdyZ62Uv/9qWWoYPRltgx4A3U970/hc6BnIuD+kdI+KbGTcelGce6ec4evOBl/k0r8llGKtWBTvulF98xVKjzEvxWXDVS/M8VHF57Hk0TDpzpxJQGScC9TIoX3euXvVV/UcWWpDFkqsCYyfaM/1ly36vGfgVhv0oiasyfh7ypgyaaBaKHl5/nThqb5VeAvZEigXx8k0AolJJUkVjo7jGBOHFOm29Se3FZin6VsyRL42V+2U90z9crTOGAeIEK8Q1UCnMlGxk4CLWb/gsflKt0y/MLnbzyQccgjaIivAjgTT/Gtr4Quf9cXXWRLjRKxyRwvkBko75hHnjisPzUkP/kyESnHtwoAtQ7kkrehL7UyzUAtLrh6E5g7Nnn9iYo2SWW8ZVr1QYsTIW8gE+ll5kHWQlXGdr/Qug1Zl/RDe2O4FL+fWPBaiJSUZGoDT6HRYT3DN9Gdgy4agY3Q59gj+iIOdAOB/MmYYlHKqYp5PMLaFHMVirSSG2XYySnnZrGHNW19JdaZoiYxGV8LbGq+9DKsT0APT3Sk1ldzXaZszQvOpfzlkndUYodytAPDOEuxuocyEqlUmM+Jbm6HevkAq0sAW8+MB9BmQJs+8HQr1Wup3G2zL6uCetJZjXKofV7J+FLnUUWtxZyLTYa20FzpV1GxEgnVdxH4JOgyS0QECr4F3z3nEUHWUQfUjUi/ZUv7tjqTGaCkl0q6Wou0Ef9tdhslUBAn9Xq4GshZkG6gTmx0m8EqvuGoYzb4iwMYdDnVMcpbS2QM3TYB3mM0Sp71/0fuSVPf7lmki1d10DN3LE6x0/CKut+GuddVgGpRyFCtc/sZYS/Cm9FySdUj3sgIPlOZeZvWNAm1o0uTXH81UO3zZEEqQDkwD5q37t+zdAOqNe/RS/aJ6Tdi5purBt73xV930PiLapT8HTTXqz2Kh7JloQ26bIlVOtAl6dIY9uBPMhbeCdgtu/ZLJeEe1XdduTSPrpc6v9+TlIf64jakMpeQ9RumQFVr3YiV3vcb+eZyy9Viw4Ogl1p+nM2xmofSyNSdYgHjnSzA6m26fu+wTKtwYM30S1LXTkxPsYp0qp+nbu8yg271r4xnWM3/hoseBI+8qttygmLlSfLhZtmsS7CZUd1Kds295iT2m4dTh7aH0qLgF2QqGo5qVVdLtHiPvIp2mdDXinvvXtBgGhLRI4/1sJs09z5TqY6sRCNVqlU+2qxPDNuRuxm20MqLmqNOO3CqHRqxEGEclC3jNtATkMOLhFZpOynrH5FAc3UlcKRsbJHvy/9wD8iylUSFJHhrrfmRYBPaZCGDZ2Mu6QXolr3prFf16OdvsxOjqyqUVPXzVEngw+g2Qrur8WehCxWnqu71sE9gv/QWnrSalK00WglxllLFX+VXVaxv1TMae7yFcRrlV2059PNiNr2+wdxh60gmKamJ7trRDvIm4xsecYXqxI7z6sQ5pICWKDHp6jFiEyjpgtLioL1lU6MmSu3VHZm0QtcI1RVNeCPPjIeKHnuZLamxJzHnNIzdyIzsV2+DJm+Y22ZVlPINS35AxuFl1Bo4nQ5IJ7PIfxyW8xzGplLgaG9BGginPqsrUhn55RCZiLoxbRn4v4dAbkYubdBLFkWoRfXYs24CvPz8lGzpNZchT1XDzN8OSEkcF8ZBhnP+1cq2jJgddJORxMmOmMX7w5A96HXzILoS882Mr/IBWqAHTcjxejheKQPvJRo3kWNuP0g0msMlzn6upFoK36/o6A6R34t5fG0RKMGiNdXSwyFVJX4R6mwE9Y+GsodSb1gcv7cCTRUWmCEx1rI2SAbsPvY2+m9QmTl7mCeBdrAdKeMnTGC24X4ylMvU3qWtzY2Yf5/QdB+kwyKPB1i9agqkwEqZJqm+HLULWY27rx0Q72mUWoass8VjGOIQHihN0cRKenQVagMsqEtZ40YXPq4geB2yGWCXNjHdvWUBLwzZJqO0hL+TVEJ2va5urbACZWbCVYXEuLKywZep5bhnERlBRuANDHRa5c1HgwZlFJY2kWnipFFzIUE+znKy+EtINIQLcbvWDo8tdUmlOANNl1A7/85EXGmvHeBG00tYB81LS0AuLBVnVATUY8Ryv9DreSbjX5/Gw7BN6qTSVmRHniapOrKd1UqFa33dmLRcn4eiO68TzJgwXYga5OrAdj+l/P+s/3w5u4BXnkOdFpGwo5wOb+7Cf+7CX/0GtfRfzjCN8YfJX05g2BeQMAv9mxwCtgIWyOwr5L/o7pR+6SJ3Fe/5QLwwr4C6BIv1fKyzpToXHJTbLiG8/GQotrMJyTgA31zp7sYz07uavDfhI0+ET93fNFPKrlqZnmkCBaS85u7Qkeu8E9ciU7jYt/Oin4Cirkdwp8G3qlPh7jTYKupVrjsR5kytjqzkeYIFXRodnI/DcJL3VsvKmexWjgEoQCsdT/N5gLf5grrxeJ6vHTm4gO6UlxdM9fCJr5VdTooZGIdRDXwVSKniAK23gL3Xr/TsPT66RK06s+5MS1xeX2UqEqZDcGRYCDPKrMfWwKV89WhCtCt0umFC9cHJWKCO87lZ93ND0Yx1Ilesax5NH5/A6H4+Kc+ulmZcK+SoYJnx5BWnwRUNUOzoqJMouyS0VN6PSOkRm10jTnAgsGXKVzQTWkNVwXMVcD3cwHzgiccCc+0iwrV+eIB8vYYrzXPHQmiE1ZMQ1dCqZe8YRowhM391K5bkoGWFgTnpJC0cvypov69W1PHZKu61VvUKlrlgOFehv8dRqYiSVFVPrFeh9R+a6FKwUKF/2DYN5EtABZqrc/t6ZBF2b+Aky+I4EDDf0hE76YPlKyXWsFCNdaYrfEHqwDPaoVMBPZl25/OkuXfYh1AuGViPJI2HzBH4syPx50fiP/fFS0ErkVp1KFpUCxjqH1AdWqWlSspDr9t9mp8sRe05lZKcAbbwhWfvXCT5uaMGgh6KpJLW1xfoBw3LaFijA7pLbA/dLBaAHq0vExEoc+vIsCVvS8dsgKfzHs2zF5UcNegfdc9XQw7LtzEBEfnVuw5qsk9o/ZpU+TG0Qy5lmqJsZZKl/bKVR1cmoRI9kMKywhvIGYGrFIq+bi/73BQ0hZ97urenL6JXo5mqakobbtIVV66p/w8gNxay1cYALkHB9QnaBuTxx//OCudewXQalev3OcXoIopkah29PmH7C415oHVru0dODdPkGKapDAJyVt7oUe06YBVuotXIfZ+gJPdtaYfWuto0odAH8LSEDeELJ+eFgmTOYjMjHzutTu3jF0WpG5cTsOdrF/oO4OA7ZEqfB4GIEzsLWN3o6/CT3nipaAhKotcVWg06C0PjypdFnnW8zKDa16wc7zM8ads4WfHympGqW4QkbMBZ9BJqM5HWi99YkIFBog0Hzio7lkrk6FpEIqHNUzdS+rD2lUqc/dJZEPYVaHSDy8bczBP5mZ0nMo6LJDO2Kt7crnZYv2dpIkqO4Lj+UwiaZGA0N9XXHbZnPaKg7UVm+cmsVbpgLwQqTBDlK2QRjYqU9WGg36q1rR4EKSmgVoQS93g0qWbzMLnj/zKeThc2Ny9xdcxvW89tJ4FBZ+TrYS822IEJJ+OfG7MBproKdaU+lm6ha0k6VD5Wkg2Rn63EH5QRvWjn4LGOw95S7TY+lo3TH5bgr0x4r7qHlmhA5xdL8inC2+X+qnIjibHk+hEt7HPJHmiPr5FDKwqa25qJBIaLoGOvda+c0H4n10rRyKPrgymjDoVVMM5x8qynOBbcSwY9gDZTfidm4q9hNigH6Zq7EjwAgaEWn4CdRLdtSHCS1yLr+oE6voukO1CwEDCn2jNsm2CDCNlvtAe2HK3BYr8H2yZ1uJHuZl7so7STbMGZwqkd6+yc2C8a0q/ngU2T1/pvyFPmk83Tn/jK+AeZjy7QxdUCkrSe3NbTqNgL40jzsEOzt6u1D9tkTG81GT/skQ2ayLenp/lHp2H3zgzG+tdOZtsNHX1oJuNi99VAhH9Z9NF0P6/LNDBfboa6fZhgGdkTPhmqg3Eaf+zelGaa70Uruxfjpw7m7dWUBlIMPOJLqqEnlbYw7m/rCMN8W4EIq3yU28lRr/00O6EP07B7pPtJPgO3BzSObqMkNTPyh4nQVpli6C+Kh7umeGXIdYrzyrTE4a54V+7GdziaNakWdy8rutDfP+5Q6uGXHqZnFasiznRQXfSQERvNwMTfZtcLB/4N88lR1Bd6tC6Wmg+3UpO1nNAGReekn+dT/fCb2QYDbrLizeyyPyxWZ8bSBMBkfKP5KJTH8MncwhpdhJEJPjKZR2kWM4anfp4/4AqMtort1M9HJXJkDjXvCa99fDR7j1goZ+Ci5eNlH6zuA1JT24fiScpErMTelfGWWtwxQgHFjjzCtuJuPPlabFdZTK9hY7OU1LD5pjsLmKV+V7LRWsksxq1hcNHhDR5nYFYqnRg0I1Y7DGhmMD12qaM7njEng52y6I//yONAG9BDsy/0hb98H4T2Hv7Q9t5BMyMPDTB4Nn9XzMNV9SGpaZMwKq/cRu6MBdc0PRqMupDoGiLfYQUGNXqIoSzglobh11Ll0aDyYCql7wahxgrlvX5sEk9cZ8huDzRQKtakbzDk+1FCGCwTPmIQ6tuLe/08bRLHSBvMs1uV8of6M2tpff8UM/Pjklg8LY7ij2R0alrmSxLrke4KNjZKlWGvuIKL9jaT+K844epjeCsbzgtnkPNwXuM/X3fC4BwyjB44eY2kUW1gqzKElvowWzyKevTim5hHprYrSXGfbPU290OwgmbZRoHEXmVmBwR7emHQ9K589FG7k96B/hk0nQWuRNKy6Ee92NUl1NrCPFkWodFqXT7dWLX8EYuTjUw/LIFnGWQh/wD6BXjF5f1UsZTtMB/UxgsRVUy8uA9OYDJGlyEbZyNpS1HacBx90z06HU8knhzZ+GJAVIo1Vl/L92CjS6WtHnxx8r5FZ4xmPbZPYWNQQGbmEnRmuZ+BSxs5k2zBqQJpskiklWy1PIuQ4XrcZbGXdyOzpNmGIhLrhZhgucX6peINVyxIRreX0Gvda5tspRgFQCo8FlPjIwyemeTOGHtHJCIiCLF1sTgfj3fTib1jX+DJSDoQaa0feE+++5K/Z4mSnEGL3N11JS8SdE9HeEraqGfFD0fVEJwXKwldJ25PbrDKdG6T+y0F1RlOcDth5Q1LnHvED0S48Kx/2FCEsd33NxRhFplVkqLAB2obiywGV+ucayDaPEbVTg7QOnlfSrsfbDAhf+w3rmPInvWoA13OtB5XbLiyp9hIlxATesgqVVuZanqbKm6MJh1Y9lBCLL9k9Gl8cwW+HVN5dYJRLrKWiYZmurNPX2FH4z9mJNcfpaWJPKJ1YKpu6aZ3cv+m5HAb00cnVoSnzXdi39v8OjrjroXiW7JZiggXhh5ecLu4/2OIdA7Ih+C08S2Hz/Mi1Fqe56VEdMY8L6Zn4/H4j64J+gKCZEl0trLXXWAjGMsGJWQg26I8EcMmW9IrrmlhBZrg+JIlHLZJUsDSTda8UlJHNIXvj2Y5Dm0N7+NY9pee1o2LUIfB7vYSCPXf0b/4OxT2bsD8RsTjfKH/6Z9VXOcwfICpjK3rhMzX9DytZOyWPLfXrWCUPg9NPwImrq4cFDp2bgze3FOyVbYDpm9SprndbD67s+TRiPMDD27nJfk83rKrqZ7X5xQq0q9YDHNhWMhV5/fLowhZv+42gEJbG6qJssvEbZBSVOXSZTsKYuja+uiYEEIglnuoh940Z5eYnsnancUvHRghyGUuRsN2kzpsWYZVmcuVBAd9W77MgSF8cWI9JZs5sAeipm0DrrRhtrqDCGj+YStWogZxgwj9oEfBAkdsCZHMvHQ0uwCj1xdrQQeRMG1SSzqzI4JDRSpiZTWQ8TCDQIm6wsMEi66wv1qClVex6HKgZJe6zcRte5SqGO6zX6dWll1JmiVrIz2g68ZgQnab6IEXIcRmwh3ZYRxAHN5hGCfHMT5dGKlkiVuP1WAvj64TsOvFLGDWJOJAP/lY+rOPooctUXaFcG5CMCa1a0AHPB6LmSeMTZjfdEePpjmWiipzbiI1JJMhSCDb6SkZvNPUfwVnB0LYx541RzxuJ/k8hFT3ptWjI2OJC8b3RVLQnYF/CSf9GYYUlJRr45LCdn5cmnOM+J+nGctEOKfpC22h0DCFPGOcUCZPT0PubViEX01O6XyqRR4tbFvn7ONCdyczP8nnzoqrvnzzLNmUx3kP0PNFsKof4FFvGGqlYWNjR/bvu+xaITXs0W3mplMCaGSq9dDgslfw95VecO/809fRxfT0YkqMuRWRmxYdiWa1RIXZ4s43G5IMY9p07mxL6Mn4UtAY33ZVfdkuC2NpZQ2orngTjbcXfnaxl7EVNqU7WUX1OZLvoBYVfDWmbgulWK24yneHH1cVriJPvce4Kh95HZSwgX8Tx5T8neyLftHFIDycVUHfSFbhqFqHRluMTCF73Rk7urVIY0gLE+jEreOr5DkbiOfzMTy0c16rX25fTSgzM38k16QXl41tRaVVG+mqHQ9Kj2tRjO4N49KlY/vbrXN4V1f3WuAjOGZmozND0lk84L9yZ3zmzFEzTpQwu8YD2B2viUbXWWKDSOkmchQHFhbnzo2qkgRHQ8tEBty9dVYSnR8lzW0QZLBgZ46HuswCmA8R9ltgtcHh8HNJD3RKA4PMUdZbLlFOtrvUhnEyICPSHGYAsR3mR598eOA4RDUx91qTOIbeVNIBkpDJiqcJlB1dnsAJOg2hOSqwoxkt5cC8PixAfV9cX8Gqx8PJzjAM7N5oP9h+T2rYzFYabfWizslupwMJu8s4qIywhoDnZ+gK/DqkqPM94mMlfji1sFJxfTppGJD3YpwMzng2OOP54IyfB2f8cgzjvK6saydCejFOBmc8G5zxfHDGz4MzfunPCEXQt3+YDK4TahiP0Ak1jEfohBrGI3RCDeMROqGG8QidMBlcJ9QwHqETahiP0Ak1jEfohBrGI3RCDWMfnSDjVL6Y+cxIeMnoK67frkNzxEEetjrhb7XHe/VlzX35Z/NSCj73REj+FIdndDml9mfNO0Si1lGgL+nuK5gEjn+Du6vZ3iiMhyK1J7EeLjJ0IJ0MTApUp8xL0fUFY+1PIThD4lH4kcAc0ZZ7fsEUO87W7k3yOaX2XX9x6sksJg8y+L2461euSImrmyKhGTR4ZOeLfsTzjUylzdYYbqqzuZbvRY8OMSAUjkF3l2M7rL3GgfcSMN/nCg7P1gX0PUvjzEbVbDt124lo0ptoAFl6SwF7LF4S3QbMsrY0LjilL47hGt08fS+aQ3tDMPNvaYbHaMjVCm4278rUQudkb2+mtp+2Z3RgWoYf/YJS812Jv/v7mYQmH57QA7rd3d5cFu+VZMFuaksRSzpcr7Lp9ktr8l9M6+y/mNb5x6Y1f5j/18prJ60PLq+dtD64vHbS+uDyAhVlI6M799fdE5h8YAK31gsPt6BVaZt6RsUp69DTk3fr9ROx1h3yS5LHHaarfvARrtguLAODtUQzBeyZU8d6kM5KpOZkDlwuH5J18iGsZwOxPmOw7TcZpG2xuxs4cH33aI5Jd5J0A/u0wKZ8oZC56GjUdHaNAwVZp8aD2xqnlQ7dlXy5uknqlI8rfmfa4p+V00n/cZ2kaqGdDEA7r5a267C7hbLPjMiWvXFYo0Y/ZnPdiBUy+ToCJYpL0l6tk/j+06MLbE6e4m3OCmUMBlbBmIwYySAVIUXwCUXkNy1blzguKWaN4jE6VDljtma3rNJVX2ak5eHgFEcCGB0nG3TrWcrDQ+wrQdSQmIkm0+0tpXzFpGTTidwVMBCtiEwAsXob3RfLWCX4ypxyl0oZVL1mDXTKAh75Jk66e3WYbjBMgC8SL0vqzqOpBO7WH5vDDkAZ6haFYTV80TxG3EGhkULjQpwqMUeO68F4KirOKKgkwXBn/2FvzDVZc9pEc2C+SiA3Pgq6yskW3VGGFYeCeDJ2blwWhh1SQRGzpMmTZIdgizN+NtQNGoLctdpe2WPnJ+N/XIVx+o67L/O4wYoztyZe5jFhh4EpiyoZ6kje0SLH+OEmmkWxpN90tkyJ4zpgyWbHhcM19WsZkH6Ras0i8du55AloXNdaztzYgSmjVSMTb53tH+BUg7xhGZYONOBme6EMCujYxrX+rN3BeYD6xunkoQ3XlnTdTqBDlETN0hSK5ABzV3IzOXRyoYOyyjWjlS7C4Gzl2KFuctjgTfkpR62bf3bRrzgai5lv1GzlwbDVWPlKbkk35kykmnDxNfh7Eyk+b73cNsoi+HsbRY71qHcpDnlyBic7MhgeB3Q5TsmbJMsckqeTLbVSk+tI5EHclWjjK84IzRcv3ASRtGEiPyEv+h/61AUTSdPlpplatvIkMKP6LPiW06Ed6OhY1wfKmLYftpG+gY7Fc4RyhcXwxBznF3yQ2LXoERXmbJgl6LsIFIGoOEPugOC7tnWi/CywOxNXSxuzuPakZB7BoTLnqxhxGxNtsOAVRmUdSnF0fvb2MtDBzKimE2/MA2mNB7qTEI8873ZXiid0El/MsdYrniqHt38sni8oclZHCnqsvxCLcqZV5+t+fnro/r7m5ryWStYNhRnMYvM+Tnm60EOFmFThlPqfZeZcvRe6EzZntaWkS0wsOJ8spTa4HjHk+6Ibt48fQlPMCVXtlFkLkvG2iMbZYpnXMBwMWHzFas7yPYRn2FSxmTraXlU05nQ71NwNh5Uc4uTB2MANp7Sh5+EmdN03vFN026Vw7ud/xJ2r5Q8KdgOHyTIb+oN5bt1bHpGwXf/vNj8HUrMgLTPqDioiQ1eBf7KAoiFR2zLDcwecuIa+t7TluwWGYR+m9rzA4ghBJ5iZsdwJqknTOi4mHXJ0HtARirSFPaHPBXL1KyZjxYJaSwJh5izfLind6Vpr9KPN18QcHuVG8GizwuetHvkllLGJuoi6sGeG/eObVOI3NJkAhoY154U58DxDm/F6suBsH7TdDa8wy2tA3fQ6YlC9NOXTGgF0TuGI+bD1SyTEX3M0aAXOM1NHtJU7n0ZywCkYmwWjBz30PNV21NvJzuSeO0EfLBzLSaFI8HQybXkJbo+4tZ/tLMW0krl0QcGMLniY2CkXc+kC1c9lJPUyS1OcetH6+4SiDIMPmf4dGpT+0lgaIX3TQmvUXIL7tS5MjYlzg7gjwTfSQF3xN9z0aDhTy1PUXKarOmnpnCoJzWDUmgLFgLBZGF0hcDmELWGhtiVWVYyHIcbCnNNabPDKOwolTaRtHq1FxLnabcBlpslwVCMGezrNyo69hvxMhe7NKq2yCuzowiK1zpsqmSSnl5yFGAIM7kBRVJ1H68B2DYvgp5cBwwNf58z3A5yua4hje1NQxjHTqlC3Bed2VIAx6JNYZTRNUNy1A2UYw6GIJmxFftcFSGvDF8JELCgYOq0S75NO7UvgzpwS72R8qv8/ZWop8DTbmR5fknemaluT2kvj5fRFJLLje6ss2UCcubWuqSZOMX53Uj4XDH+0nxTziHBunKMpfIOWCGTtjU0KwgfbJPYIawXWuUKzqHiBn+9NQxjAUFssWiW8m2z0WSihRldm5Q/ElaZpXEz/6FMhmihnSOm+CF/mw3DTbBjZdrj6CLXi3E5041VrkdJWbsdN3SXA6E78nQk8jJVwWuBLIXHTLNl9S9Ec04PI8pHWKvfRbYEEcvuS8CixfoyRS1PbcJa+8F+wBL2m181vTnDqPM0v3FlG1+IX+QKnipndmk/ZksMe4W/ANBlflVJJs2W7StlP4oAHehqJJ3NiUn8MSXwN4xO/eAtQGNcsGjSN/bzqTf4DMn7D4rLAvbO91851AIa6CmB9wgvHx0e30ekd9TiPUo9cwMH+3uBFFLT571cSLcAO8roTkUFVIjoWj5N7XieKjDzA4dPtYd3b+jiPZCB+xaTSDirhaBFZnWFuWhNLdP3Sb/diemM6EMb2ms3QNzgeGsc+dOUKGM1ktsSZMgjAqTjuIn5idqksZYIGnp6A8MItr205EY/N+dkKcxzX0bLo3kLK9I8hiEr5BNFrh+KEfgwopR5JhgOTPkq5+gBK/QFjy4GFftODSX9ILqqJg5X/TGjj1R8yV3cYSdoPqRDXLMCAGUNSBtJGzhgsO/Y4jyg+xbxXE4/UhoiespQF77gOa0e7eWi0s/FkrD9WNG0CW882fBvwlNxvvFfyzRgorU/HptUVBG6zdODOGk83i2jQkJ/09x4uccbM/F6NH7EINuHhNEZktuOlMlO0SkxXYfnHZpoRBlaYybU5t2wpfL9lQyThV1L6NUm34kZThkF9C91FPjq0dLTEeyeea4Zle02yhLzFiaaEfORJyjLFIrtJa9XA0Uow6UZAnjseLcPmbjwh94VHlsZGJvFhyLlaFp2fuFnzDo/N8PQNxE4Sv5tiJNcw3WJ05d/Mzi2K0n03poX0KACac1zyGqKn2QyqF6wS7MV+zr3Ffc5W5pn9sNl7vLq9ZZrziinM8xgi12CwVt16W+ucAf8z04VDZ2xY+BrLXtdGBSPi9wrCaqp7RnE87+gFdANgfrM75R4c7dvjxeDKy9T7IFTkqpPoAXYQiJZlrB3kA4/TjEKfHyvEPMjQ8/9oogUz+xaPZ4rkdhWwV3hy27QQUIXFY31wI1PasqxWgZv0xJ31xJ13xv3QajQbpCI/82OJnMLpHwJG11x3p1i4shPunlAdMbY+mDQ74SadcT/xlUw/yfthJ12wCVtxPGJgw35XmVR1CLBmupkxBU53VCE5e4Jdu6a1N/jU1l1rz5B4AuZARroHljjTAMIHFadYVUBjqegcRrgofTqgIKykRANWm7VhSMLHsnbdtYLhX+yd4fYTuTUr3ZK8TFkk6wIn7BA84rk3y4CZBY38HByV/9CefZZqa1Lfl8YJ/XyCfkewgYfsgze+EV67KWnwCyZouIcpJvqubXp6Dx4JM7UHUTRkQsZPvlpZHKKVgpsUaIrDDQU11B6PcKoPHFdt7I03bXa7mAqW41X3yDo3lSmmJL/vwBFhASlaZ0jsXfm6MfThLpmtsXarWZdaWwJP3MEp9za1p9FUGY8NLHuHwdEZkWHpAMndYxfT4lC6Wk739fkD6OMCDguCJSBoA4IClZL1lcDRBKiPmgie8rc3xdFw+kwjeHIM+OwY8Pkx4M9dwLDLEephqUG/cXOaBJxi241gdIG+4kXW43VXMcosk0FYzgZhOR+E5fMgLF8GYfnan+USwwljIWfLACtK/kQvqslwVGfDUZ0PQTVlefBuPZhz8PpuYJkMwnI2CMv5kSxwXGOqMvSUXAmcQrK3XWhuFO41mYyfKrRZTYG1ki5oNfaSB2hC6bslXXbkMUtOTIXkCwSfOD/vaNHt0ykmoqEaniUbpOlZskEanyYLB3zLcLiXhOpJgh1RuSzNZBias2Fozoeh+TwMzZdhaL52pzEGUM0iQB1kRM61k/HD1QkeK5NuTjntucUb3rj/tprpZ8605QWTue7CtACZEpkVMuFND5kWP3MmIwfedJDpkq3XNBgIMnvlDFVLdMVZ0HaSDRPKa4knt0sAoRsm4wvsLhYye9Oj0RIfhHRISpdp4+kRO8y0lcR7L3nwnGCMOLdFAsNyFfA3490RiFWHF8OdweQFbLdrOSJxvmjOlJkv6jLjZBjmZqunZ7Og8kSzaixkPM4YUa53yfEfsR6TCvKKsRd7//4P';
/**
* To update this, go to https://test.draw.io/?dev=1&test=1&drawdev=1&demo=1&createindex=1 and
* copy the output of searchFileData from the browser console to the variable below.
*/
Sidebar.prototype.searchIndexData = '7Z1rU+M40Kh/zVbN+wEq98vHkHDbJUxeHGDrfFEpjkh0cKwc2R6G/fVHchKGKMwuRo7Usr21xQyBzUaPW62+qfuP9tkf3bM/Go0ofg2I+POP5kB+t8Rr8kdztPq54Hi9PMWcs5fodCD/QCP2Ev7RPFvGq0D8Sl389QfhMfVxcINnJJiwiMaUiV8ZzVgcs9W7XxgEdCF/ELO1eDWKOXsmj3QeL8VrjbdXhixgXLzyR6NZS/8RP5EfrTEUX182H7Jb23y73Hzb726+pfO3NWw+89t/F9DZBz/qjuRPsxK4IU+xdQK7JS/3gZghcEcXy5IjuF9bX7+lTXBGwjjdAyglYR2DIgZGMaQboeIgdgNMCL2mGQhDHAQsicXhmMwCAoRF245+2LH43wTPgZCwtDV2JMDsjo4iET1DHJbkB2chEAj9zh6EjiGzYUi5nwSYQ6GwvyU6fTMU/kxW6xO6FQVUt49hXxj6VjA0yoohtSJxOIejIVUQHYMgvCXma3Q+X5A5uiJQD09T+vKWxf5SkPDEOnDwtlns49iXkKYhHJU1tfG1dmIBBMW+MJgKQbzXFEBA2FES4JRD14py8AISzgkHHJUxJhBbEtMXhh7xawVDwhAfmqAppgEcdWHHB/NiTtdwINiJX3vil2gkKIA+Sk2JxJRTqIZVx1B4Zk9XoivG6T8sjHFgn4clkdjj8bBdlnUaavDOkGt6j6YJB2pfmQpgbhnI1DdMEJ2GURCA7Mzdyg07o1sQkPJ/dknAieAZ3hk+jXx2OktoMKfhIjo94zj0l+j70xP1yT6NNaNhTPj5DxLG0fa1OY6EDSa+kWt5okHwfo3NTk8s54PVP6X/fEjqi8jx9jufyI8oXmBJHNBQ/E/DkPjx9gOqsNv1fRO2fQA7xfMh6/QnZztuWszPw3lZgLf2gLcPjQAjwC9JSDj10e7dio69v2971Zu2uDOxqnAlSy7Kgr5eU9zkQ5vPCPrx6L7oqDv7/lbv0N8yQtpb4SAQ8h2JDxxFRYe+82F2Gr1lB/qUBMRnq1UiPjq6YklU+KO0Xts/S3uWFMsheTQZVvDNwL8PqViWWOtr4Yk3m/uK5rA08ojEhYCvpYBHabnHWhiP6yXhOIhOr8/GaIxp+MTxqvA6RynJ/CDk/x/PYLjj+EejJkiKr5NfLPN/LjSkaOC1Uke70A+mtb85PogagHowU/aSrq3Yz2Q/oNU9DGiBeSY3eL1ZaaEfiOIFd+pwH8gY+4I+i5aFfyb9/WeS2X0w+Eyoz9l6ycLCH/O9/0zVgXkoxXc1uj1nbK7JEA3m4igRjuAQ83nRn0xH8QFBbxN0x+SP/BI8F5d2DKfblRX6ifT382xNwKe852OxksI/EeWIz575NPhE1gQ/F/+JtPdd+D7kPZKE6JHx5yjGGyLFfjK99r6PAtiR9xLx3e7HhX8uyo45vPUH5rlM8SwgcdEfiHLMtwEbXlPCVzRUy2KL90g6yiMBfKrcF9+XVzYIZI/xgc4JE278Snxb9MfS2S/R+aAsG8xjeSQzdCaLPIt/vCsFwZBDw2UyhuFlGkNBJAh2z2XF5klAotN67fIcXQzZedGfiBqG/IL2eiP49kzGG4o5Po9mvdtC30YkehaL/R80DJIoDRS//XrRn1N3/5RpfmHnGHlOf8vndBEwxqun9FZTCu0pyf+LLKP2XmjsL9Hmf1D0Z9PraFsEJp7NBeXkRdYAe4T/oD7ZPh2xqV688f8U/SEpcczeFyLLJh7S/rMp/EOpO6HVvFdx2qxKdNqo4RmgttsD5XGCg91p8+t/ir49eEN5mbHwaq2ldFbLXH6c75OaizPGjxn/ZQmchwuxCPRtiP0lQaPtzwv/XNSivsw2wY6U3lPYvcvJMMBRhC7ojBM0XMpccvD2MIr+LNRTJnNCJq9nITjQWRKTeWnQK5FlW9vghon1zEvCXKkzameuJ86HuQw+LjhL1qURdjUGmTkhrwN+mcw2xtECx8LNe5WRxtoZjsgUXSWzoqNXjttWZu9OMPpl/1xuEebyGIby9TI8A+Wec3an4XjPYNdYYfumJXsS3cyn7vGeRLUPbNIfD7yy7IG2YgVlNvqP9xQ2nRhKsBMAn8rbG+o4KM1+0G1xdLxn8TC5LctTUPzhlrWzYSW+ntbbjeLfQe/rHsdj8eWrhDvdWk3m2ygpfMcdpd4je6hHh3O3XathHqFv3Xa9WfjgsnqTzKhID3yfRBGaSKqFB71/xSL7BTEt0MPC14hpZ0n0+HpF56vIb/bmRFp8R+PC89UNtWvx9Qao3S6+AddWenFkDqtrQY6ojyacyTOv+BkMJWjywZzXo8rzHarXSmMv9xTWmR1yLdbTQdH51mu61/70AI9Rs1d85azcUcp+YV8L8kPhLTi7FvLfk6LzVV1po3zPzrzCm8iqGt61HzREmBP8LIeFn7GfRSetNNs0q4rPOJ0vCl+v3tVNomghnnrCPi5BxF5t52tUkIcyNzvGIV6Ursy/aTSOPMTF57sfuWgajVwIvsKN5mmDPRou0OYSS9GRW02NDEeja3QhvhSdsl3felj8wHJ/35bLXr2kxVf+NQ3FFR2zcim0ZdSe22AeFj4Qp10Wrw/5PqTxKzr/ueYlGH2ktgqwwDttPFN0ztr9F7U4y1nSfowG/v9LKC++q6IOrTYap9vBHu4+cqFRd3Qv5euilteGpxyH0RPjq7R71a9bxNPzwld3KaPrDIu6dzIe3BU+raIWxpj1X7zxSeEJq+2/zAbxvHs08go/WbRe2+9FmP2ChRbk+7PCFyiqAxXNVtCNSFyKi9OKx5K9G7AWZBafzFnhS5mb+4yNxkVHk2nR8SpGW/aLPVp8vZtB4UOiSqcjs7W2I9lmaszmxc9wt22q4sfRGF3QoAROttKTKPswKB3OMkWF7mi4KDrlerNjUS1fcJY2QJuXp4BcGS5rVkmnXT6Enh6s1wHFoV94Za342Gavtu56qpRGtq1ejrjC4XxJgsIPSVTqyc2WzFxN0tnsRWes1NeZtfGuULPRLDzhusVj8HpYeF9QCWZkn2Gvx7fwwftuzSZf+UlDEiMv5kQOeio67Xptv07U7CWU6+8e8m7Oig5Z7bxjNFVyXfh7VIor0jV6y+d6Mi38jL6DklujZRmC8APa1WaU5HaE1eYO1xOBe7VKQrGaEmQA1UCd4SNwgkbeTdEZd21eJb6eFv4IVPWF0fjQn2ffR0UH3FAawRi1Mf4ihW9O2doX4LrRSyeCb+ErxpXrw9knw+sAvhncopgh8UfRMasFzEYNtxu6WMYvRH5Fg8KfeXa9khsWLjjBcvTXpPCliOpMNqPKYzwofDFtbz913TAqyeNh4fm2bd7gGZ/X68W/zqrdXVwLMZnTMoQqFCOuZ9QLGRMimzmsA1z86paWzXjFmETLyn47OmSxelQvQQ9b7ZlAWphpSNHD4O+iQ27rjpvRgsxmNCAlylkrCT+jBcxjr/DunnKhxGyR1vi+8MpCyYaYjdaP/y68/Kpd240G4W4Hw/JUgfcUx9qoCXdbDSk5Ll9hIuOwDNUWysUzs/qCxBELS9CQUrkOZdRCFpBfGH/elg+tSPHHRylnoFkb7pb8TKJSdPGzrKAl5oacW3KBZ/JC1PnPmITz4mtsu01AN9zbJRBvCJy7JeCsXNrpGE2wfvdjEhSdsJI6MesTfr/16mUYl6Z2wDaan/q+TteBBivhfD/R4h+Cyn1Vs27LjnbaLHHNeOENaqVRlNl7aZPBCNWLTliZSmc2rC8JNwpPeD/QYbZIYyI8b3Tty9UVm7JSy2zWmJucFT59ojTDMJvQngyRx57iF8wLH9xXSrrMTgkVnB/onLCiQ1ZLa43mAiejwk+A2Pkgu4slNaNW8mRc/MvBjX3Chg1jzmLms60fEpShCFQxL8yOqJv8fVF0vmr3cKNBjDsck1VS+HmhVodZ3pE1wSXo86kIstnpt3L0H0HeC439ZXn69Km6w6xcTzzxb9ERW22N4RH+gwpRLjpk5cKU2eqBLeS05wtnZctMmQ3KeSRGU7Yuw4zyet3meeh5hfcElXiR2aF0nneDpoSvaFgGH1Dtvmw0xOxNC9+xT6lrNtsK2Ct+vyI1hG9WfktyT0oZ5Gy2NtF7KH4eymYQY0oC4ssufeIDlyKrumu5ZSVRImnLAc6kBHd66k1FORutw5iKpRdelq1eUJtOUAlavih5P7ORuE1RHJYrLzblTt+iiTHlif9cdMIH2tjsuZdwTgpf2lnv7NfFmb3GOn0oOt9206II35/d9euFr7y3e1HnfnyJPMJp8RMjljlX6b2j8n3ASVD4085qWOihdONIzHoeD5NbmTeVn5hXiZBjw/YKr46tCvPjoGrwclS+117hx/X19gH3jQkwm5NVhHA4R+slC0l0OsSzgKSD3FdFh66UtDSzlyin9P5o1AQ/8XWSEsznKZAgQOn7Ff0hNLUnNB/tIVzg4lcbNTq6lsnR8F8xFq/LsAXUCujsyv9oz+B6Ug4tpBg4X4iXHO0RbNvmDnxZm45K+kB6oB5IGWyj/T4SjeylZUfjn77VyVMJDudaB+zBUAolBPhgvrsoh4+mzBz6QjX80R6BbLBQDvtUewJGTs9gTdg6IKeDcM7ZgoQsidCE8KgEVYX7BSzZL/tOUnJfRz7GPnpkK1x80vt2T72W2fDRRx2WA7Vq3tTbmQNwuqwnQ9lrufig9+2YeitzlEcX9F0ShjRclIF2bz9x3c9cRqTL2qOxnIBWDiWiXAHuZ44TaNOOhVFTEtFu7Bvj2ceL5wa7FLJtDzeXbTF4dCrMn9K1A85e93m3oaXBeTAdo827VLCNwJ7ixa7rSzm4a7eL0ud+xhme+ziKS4JcbTOeObOtj1z2JhGfGe16lZQSvA0dc0kXeEbjnY7ZqZxS8rch+NeDUTlh2xD26wlKbx4vWfhaTurZm2fnQN0bXpeEtnqdJXszUX3c+2UY5eDeV6azWVDkt8PzksAGoMhvSfwUsJeyAFcG02QOHeoD342n2TVsLAt5ZcpV5usE+uRLAtq+Ttm8A7oO0VlCAxm8LTp0pcHgW2sEC9QfabxEHg2oz8KtL1p0+kpHlex9SvXhV9EW08DXuDS468qFmezzx3LgHTMux2SVg7hSfJX9rr8+8Omoyg8Zg/3AKuVtEPcj/kECEi7isqTiAPidj5QL5qWJY6kJicw1nV8nHhE/4TR+PR3KXhcUXQjyLzgo/LiAltK+JXO+2duC02Iuv0Vv71Rw5KqUZ9YreSAvi3w3lJaSmVVKHrAvcUyeCVkXX4MrI4GzX1PPBXeC+bzwpBWLMHNsNg/S19+98pyUSm+dzLer8gB+w4rfo1bp75m9nXUeoG9J/ML4c2mMkpaiuDOHY/OAPrn+uzTqRPUurUj5Nv1QGuZKNZBZZ4f/SEs9U1/nPqRPlMzRZDsFIs0sF988VGacfMUaTynq8JdTTkKxILnOqJzcs98M1+c+EjrGjxl/LQlyJb/5FU9IF/kFDUhUCtg5RLHygF0S0VZof8VW1KV9xaLCd9ZWr4N/xUTU5Xw9mT6URKpzMMh1aY+pz9kLmZVDaUMA/v2qJNIN4ITcvMOm1q0c+Uxl2FL2+tkcoMtGlJz9LIvZrcSxvpJc00bOnuIXzAk6w5Fw8cvBXenHlD11nwN32XQC8zkqg3EIQZ9vqwvLIeBKCKWXuQJLH/h9SOOy6PG2km2zED7Z1BfKeGE57HEAQcLHx8eSyHdnvx+W0Uj4Rm9vMxFp3Oo8XNDi90fVno6zPfF0mAcsKXxpSr2nNIysZVcl2qRHNHomcVx4oW7rTpDUR30xRLs3KThsJWTVym4E6sOmM+FaDpdYfM4ASSlHXjKLXqO4+E3G9Z2eHPCL43KIZ+KzFt7HVFSLDdx3JEgT9ViIOo7xDEeF1zGKZZj9qo8+9an4IRpwjotf9mZfozySGRoGSVSCeLhdwzC9Vk82fSUvZHvDXfO383gpPKlS3Lrv6Hb08LYUdR9AOZoc6IdUcsA9DHAUoRZqlwS6cg88e6vxXKArHT23DSbr9eL3ae5D0DFv/Msh8rpztfNAvu+ZXuAZp35J+B80PrQi85ckJClz9hSXw5xRskTZ+03mgf1afOIgoJvvkRfj4l/RUrMX2bNzeXD3Rrcl0S9t5bKnFd43+JVw1EB3ZMViUhLyqmb/Qnw9N/TNkjAH4aSOL/9GvVqthsZJENNoz4wv+gPQbgyfywOQ3E92ZuSmdrQc+JVZWXasmhR/kOqdUil81ZWyJ/tbg3JEpOYpOnb1nLWj9Cdnf5dEzFWLMnuWKQ/cnInXVys8C8qiXkBEhMt8mloiTle/ztOScFc0jJWD9FcoDE0uH9H4clh47B0A5+gD5XGCA3RTInkHEYPf1KxXCVYL0MsBHEY87JHx5wVnybqifnzqL9smxKcDmVINcdFhK50V39owfB72rm2zDuxLId7hHE0JX9EQF741lzLCrL77sVnod3hOGZqyl+LX4jW7ipRnbr+QB3APp7nT4l/TUMeBtDIHdXPFLS8OFP7UVHRK9qKMPJA/0pMLKocKF5229rC4fGhv36PgsBXtnf36aJ6w0Rmn8xJc/tpvLZK9L3GuzG/YpoUlGqzXAcVh8VNEfd2O57nyn3IcRmvGC38LTG3TZQf7zeAWyZpezoKg+Mb5gb+fOa71Jegc+8+neO2fDiZD5K0wj9H9xEP1Wq120pS1MA8D1Ljfhx8oPDhdLON3Cw/Ik/w2WmOfhoub9LtRva0+IvFR5uzl4+f19lQOMHX2MTUPwyJySR9Skj8Qy8yDT3uLpg0YzQfGrwk03XZKpg6YTP3QE8ufzEadDeVXVO/X2rKgieIAydph8Wvxtk/Yb2dLuwxsuNNUOsgadSdZZdVIubBq1VPxEngqZJ9C1ujX3BQvC1ux0a+7yeqDiNvxWTmqtqywalesPsmq2W+0K1afZdWqWH2SVbdTa4Ln0jFvHwguLfBcPrgmYIBLBzyXj/L3BsD0wYNp1g8j2McHU4evYRofpFOODabXbNU2ofxNWP/ku3DgQnlgbScRilX/LtQPiZ2FU2vgDVC73Wuf/I0Gc7yO6Q/yNrbRBWQWHN6BdyejunXwW9GCg7tl0wDPxp7cNMRWq+j8jg58U9GCCb1lA99c7B32VjDDxgHDqN4/vCZoAk5fHFVwqVjSNAJKBy6UesvOPurX6jW4VBotS7LSl78OlUqnfVjsfWwqAsD8rStfs9aEJDRK2ap5OEPMhffJ0UT8gMS/Sp1QQ+1eCEmMLOjh34JqA+Zkwaf6LacOZIGyYAoOcYyD1yhGLXG8f3yJExIhK1vujVCjJ8zm/S7OIfm45SckaFb23xu0VgXtS9AqQL8H1GnXmifn8BC1lPmrFrWVQNRyAJGFJOJ7RB0HENU/aIdnklEfPKFGw3yY6B2hutBFgOH0zScX3+AoXm+jhp4YR1cTQLjUe+Dmc9S/o9VspLRGJAjg8vpgJJktXq0afF5Wgisf4qrXHMAFSLzqlfLKQqtZSdeHvK7nJIx3Y7XTutCPZuGW3NG7nnio1RYKyiNhJD8wVDYW4lHb8iw08H15LXh7RxUuIgvic0t+JpHMcNfQrjHg225zoD7LGrGG8B2mu0E65z9jEs5BVwdY49RotKYTdHlesfoEq2ZjMhGbsaL1SVrTcUXrs7Ravcn/VrQ+T6vSWp9j1azVO/DCnnDoVPmpf6PTaVV0fkunXcnO7+m0BZ1Jhef3ePqdKVwuVqIBOy738OXGGp+OvHoEnY61XdWRV0ig07FQS7Gh05XNtuq1Ey9gu6olOXM4imgEl5aNq7bvcfUcw9W1iqvlFi0bF9zf0eq7RatRM1++8/3WQ/V2s9beHyY6TKKYrQjf5Q4mAY6fGF/BhWfhTNyyExp/eIO877fn032IFbR/hTYeIG90BR1Zb39olYXC+w2xVru1kbGTQ2ic/aCRQCMbMcAjeCh05svMNgw7H89MhomtoTTabdTNFwRNlq+RbBz8q2lF6x55MeNY7akOScAsOACHoD5Ua4XqNmsQW5E6OxvE1gKMzcImvR96qC2LGcF7AhasDAmn02j17ie7pJ/sTMj9XTN4qKgsaK0NqjSO6hQqC5pKoho2GmjcRJvJznDpWBIkQadW4fkXPC0X6FjbWi0nhMcank6F51/wtNxQPdbwSOlpgMdjwZJ+HJyftOsNuEwsnFaSSadicsik24LLxIJqkUy6zVbVNe4QSreCsg/l4Rw1+oC3jxWVIqC0KyiHUDoVlEMo3XalaT+iUqnaQyq9SlYUKmT2Qbt65NW7NbicbGia33BqQuYESJ46FafT5fr0aoKEA9m+/NX67n2nBECENHtJXE2+iifl4b1GMVkhPx37ex76AYsSDrgcIWsyLyc8XUfw1FtWxCfqtN3gkzW893U81+ETDekZDufoYnQHXe00zMnNhLMbcVQJfXzTadT8bUR4I05g+RhUy+/5dCo+/8qn14bKp9m1zmd0U+/U0GUPDhRd7yIXKM1GjVRUDqh0KiofUllXVA6o9IDLSlYvMy8qsGXFEpV2ReWAShv4wWwBinfTaNYiUFR61nWtgNKGDcWcpOxaCg43lcHoIiA/T+o18e8IDh0bbhGdrU6vz8aoXq/Vag8DdD/xAAHRnF4uFqZBpF2rnTQa8Klk3UV6VLrtFrph/mYvRSwgaIxDvIBclpdV9+oBuhfKBcdogkPyi9FfNK74pHyaDuiZrPPJtYB0HACSNfKtBWT+U3jOcFkYVbdCKuTBDBhH1pyaLo62TKZdPcAFYlR5CCDddiUeWxo/m8LjQeMCFd9p4mg3KxzvcVTS8R5HR0pHEy4OoyftFgdg6TCNA/hmMY2jD/iUNcyiC3lytXEW7UqJ/sLRE1rj7zZcHEY92Z/NfoXj+ZSJrwE5vSUxx9tC2r+bJ40zePd5NQPw39OFagIaTprysvxgOhzsqo6hYVKs1nrG1qK5YepWmP4T07Rfg01J9YGyTk7OD1OtgvMhnG2RpNTZcNFktXPyIbPG3EfT1kkdvOhY5rM77NGYzZMAUK0tiDP/jVPxepzkwufvljzroaOxssX+7vxCU22ufUKbbXUuWwKuOY0IGrdcOOWz5kxyp9R2gVK9ZQNTddb/G5nqlP8PQvDP96zp67zItMCTyVp9qEsmCbcue8eZ+8OGNbJCaHdXfzdt/fznmsuRKRtlhBqtNarX0OXsHBBCy3ppn+C2Spr+Q+aolZL6DcsK4AHAKqL973hSN+Wth2clR4egRjjGQyLN8O39/5m8/78dmdXsAGKlWbaSA6udWqrXpJLaMuo21hWkDyD97+jufUeJSxyTF/wKr6uEfWK7SHfjBHDhi2kLfY8LoMtkAOxzJzIjFveR4HIDF4zpMIkEs5nYhRrycpmwhgac49eK0DtC/+fCe6PUrTcKVGiWN5wmZDiG00QCzgXlBE3roC/LmFfFKZW/G3VYVBogqLSAUYEhKy3Q94ks6ZW/W52SU1nT+Sle0BiL4yc6HWz/Jv5jcSBRztWg15pRGck4/0HCONq+tiPjp0EO8YKwEWM5PfFGQTljccxW735hsP0vY7ZW+aloejUlkHOIZr35+wEZ8fpuXVEObNC3QegvGf+fiswBmSFnUXRyRvCqonNIZ0QjHyqX5uGxZIyLbKxATjYB5QmezwMClVLLovRcpt0nINOxubeuSCA/PVQ0HziVxtBcr9YkCAjYA8smmwlnsOD0FR+q2bAHZ5rwGQ3BqhtjR9Z6jTmOkwiRgKzkqk/HOFwyNc9pDYz0d/fI1LLtqN36/mjUzrcrzAOSx/xnEktXYtueTawU3bJ//gEDrrnPLePpfixsyXrNeIzOpEdHYiCo6qqIQUJ1QxZAMDXaIHfiltMdDaGAUnVWI5syPzIo75lyODvPvnaXC+T0KVmQ6HT49nep2kfEx2ltyzfP5+QlDRyxgM6RtxR2FRTToX6gvjIx/LXkvNAJh4UulshbEzIHA0kVtGxK/hiQJoQ/MSG9BJo8AUSViM8Lxo0BuOHe9BNYoQLIjKSHh3AGIcUuAe4+YTCsVtX2+zdCAK0Ci3LEVmnhPeMROkE0YqdnAXshaeLtAodQAWUUo1+LFMbntfc9B0y/3lOiesB+kqzQJFmtK2T/jQx9e5NZOKFy4MRGVPwexwswGU3gvM7/L/FjONlx4LQmNIpZWMH6FCwZvqpQfQ4Vk0ktcT7CSd+AJxZj/lrB+hSs1JeuWH2KlcyisorVjhVP41QRWnAazoVCPx1uXgEK6IMSzH/js12dgHO5XV9+hIT1zuCqc1CgrjCoaAxkVNerNfbjCtUnUP2JwZ55oDhtjM8K1X+gSt9qiHZvi8bYF69BqY2BiG1MgyDN4CSBWBH9p7IaMsGqzsWvUauOyM9Qq/T+Zzk90BnHcoUVqh2qOafiHU5H8g+gUDJe/kiXkj0x+B6EvBmT0Hnat+sMcJ2QBTDb+KZwiH+QV8YFngCsgjbM51Xakt/FquUxtv12uMSr2Sa7LDPwT/L1aqNJXlcEx+k432QFF0i2IJ0ekE0cXAhIskIbdSyEZpqsZoEUpEpBbzF5a45fKxw7HGmQ+5e8yGqxX9+N2Q8pOzvNU3ZkT4TMJbOL9M9d5glN8QzO1c56raWjgjZL+zoaeS2PcbkOHKDNm4EBo6WbjwAGfRsTsV5AufGmwqhtH9F2jz1g4dVDwWRZlDYnGKj7eCoRQ4JD41jsnuj0TJg48/TsAsKjpXU8XWzXpQGEE/wcLzlLFksgSJo9rT2jjWQY4NVa+OMXAQ4XRHgOyTqAc6uuradR9OkwASeM0hZCMIgoW6hnHEglH+9wiF2zIrI7JongiAgsKOjbiMTCdpELOxG2DHsqir2SO6jzn+tALK3i9B+cZKu7kzsS0SjGIdwwKSxMaRij2om/RSesn/m7xh5AyDS0HIjcuIyS1epV0PkBJm7Ra9sFkwhBCaCwsOxWXbEIjMetsMjWi0sfxXW4uS4EBIdCw7RgXMul+UupQ2QweBNG//YrLAHl/LEdl/iY03fhem7+eh0ioXB8SCUWtpG9wal4bHhw+kR9giay92jFJGVyR+aJD8Zi6do15e6SdZxwAmnP2A5UeCR4OhGKRBavhQt0RwKCI7JJqgBBdJi3bBlmRAMSwtlEdVWnGJcZ8VWc0BvHCAgUu66QF3NMQzASYjlAvqMB63KbZSgPYm1ASNj2lR8oeZGHzWWAowgIE800db5M0LcbOaEEUPmHrejkUpZykp8bv5DL3Fs4J2EERtP2dJSKrFOVHTzflqeNZ8QS6TtP6JqgtAr27b2B8Orr7LL8eZ0HxI859VNYYCBpGnj5Y7qgP2VjRXmsC7WEpsmMRDDlS9VT2Y62/MldYcrXNATHqf+f8xHNYoK0/YDp9P19Jm1qGmy2IFTjAII0vSd2QcNQ6K+K2ReZ/bFpYAkVnfXj8YBdwDbRNPEDsDf8oAlcGrSvYH0OlremvDDdPg3g2rNcoWKzLWTpDkQ4nKMLLquonDDwMw6oy5/aHZkJgwwMH9Wwb9qlk/YGT2VKbj1FpFAdCLTOvkxla5VgGlqjgpYdWrOC9iG0TSZvImPOINV9H9YRubG7YKJST8Z+pulb+bOaLml4ckGDFTr/gdeMA7pApDfkNn9U9ycf6CwgrIBFCu+RJ39r7lIQ2jSzFf0pUV2HJzc0JGh7T3osX4VCqK/lMaZL0ebixVh8blhc9DxpPS5/hQQDasrQtYhC/NcyfjfBMZQ70o2ODRzrZLWOTof4B41fQU3kaTT3NWwmW0cu5MssyNuwnRQIGB9W2S6drjUiYBzUxh6Rrj0iULxPazIi23iA0h9aZQI6JC5xhLZj4WCg6DYsyYQk8W7yGwwaB2WAxg6WS4I5pC3S7u5HE+qmQFwxTv9hYbxVnkBw1NvKFPi6MSBFuk+pw2FCuLzGH4gPDASFGs3tm0KRzmqCtD1Uy6JjngQYu1N1TsztEC+ZrYSbR9MaYDjCUa/tA+lmur+lB0TIBWAS9Z6xjSK7ucKZRNLfb/mWLQ+mgwHedOF+f19bGDtEHrafFRKMutLspd4ytUHQCZrT8L3vDgWJXkx4i6Q2ur7VAvM2M7nC8h7Lue+nEuOjR8YrNvts0ts1bIUXIYFjtAOBI/39ish7Ilevc46ToBKUfSw39P8ldI7+JFCuDwPhckd8uubMT0vtKzR7aDYZ/80g+grNezRpvKBCskMiB1sLzbIJoHzbqBqo9fFfxPOVidbv8WzQvPMLKj4f8HlzDyo6H9CRxl4F5gMwlcb5LZrNmn6k3crWAfbJihSm0XPOpDhbyCyyhLWpVaowfYBpz2DeGocVqA9ApTZiReY0Imuclu1Hp5d8UwPo7V76Q46dJHEcvB9FCYOYXnX/2wqzx5Hf8dqMl36Hq0KzQ7MvQvQJbOMPu3SEy/HqB4D65wGjowSXK0r/RinaXHWYcGkC0Fj+rAKWEZhUV48EjAUOjNuE8BUOxYLRON2RFaYPMckuoAmnSJiYyUyYTBWmDzGJfVYh+ggRC+icPtG0D1jAIgImdAKNjpyNULF5xyadDLvbU6UHI16TjusK+0sakuj0/GfMk3SqMLC4SF2nYYS3WaZw/8fbheZJClaYBByoCQkC4Zn8I18ENHBCjScBACVjt+A2HlRMd0yIFRijCB6m7Xui7Tuib7/uE1XQPg1tVxtcIdsi+yE2Hwmi0zMMpdZImRyUrd3Pw2Y5OhjQt2vvOxT5sAyDcxLI+NCIJ1BqgJXb7xnTRvkiASUqeo00tMEk4fN2Mk569+IsXQkUNprJRl04AorwKWKCpjh8hoJEkZeuUdUylIZLOllKbKWUivhzKCxlwqEWdnZNi8xvAaFvZ4yBiUSrnLLNFTg2p0oLfRLVDVmA7SBdr9lRTuhbGnpNBwVsKvrSv17iCFC3bcVEzDZ6SBfVdjBTdcAdgJHmIeMI2mAvrbaXulAuGPfJ/GTE8VMsyLC0yGoKqGmQcme5n+nOsjadhIfYh3KTXclhWEHRgMnC8LmdttYSnz6AIhrN/ZZBZoMSksYVC+A09OzaDNFc4eBpMxZx29pz84ZA0BzYcd1MYxt04VyHckY86PNmv12IWRfzT+w/C5tt7ojoZGquo8vmr5D5zycsiSGFPtt1i5oGUjtppZlKr2cYhNwtdwQDal6n5gkydZfRJSJrktBZEjwjTxDBCyh2it7sa10qaV474fQfoWFBq9aGWXN2wtkaDRbb4mMYSKwqFFiapGXTnH27eQUpjmQ1vr2pbxxxCubwtcxjc8Igb70kHMpBYzc+sAvlgz5kzLo2gNSHVX0qOcDOFmbrv50Pj7dsxRmOwFxDVDtEWgJTFW/8O5o7xp6ggulb5pJOqYQmO/sxk7pZH3DHSHxyOFeaDo5mC0fSFok0WyCfTj0LaEZUfkDYisYuFik1jhxVDQukLnAQEWBgFCu4Xm9Y4BKwTYsgyFvLvJ+kgAGvks0CApQsrLf2lXCmiVa5gECPNF6iCfafAbWmtUplM3wCWji72dlnYjTrLltBoG9nBFJTPyXfYR5Hau9WPFIe8k9pzz09CRdAwBlRvCJitWBKatVkqlGV8otPau9uzDh5KHsJf8I+QdfhnMpeh3DuFCvGXc8mr/NwU6N9xtPqFjAy1bHpQf2G0aYnVOpGyeHs4kyHQsvqtcff0NoiOtnVkW3Kp8AQa8AjBulKieqANow6oL8BdAdpywEUIO+ZcjgqHKQITZeyQV0grIIoCUBZBTAEiq3AZPj6+2Xz2UYw5wXkIgmCk2kyIwfn2ZBROG0xGjajYjtWEwrmeAchOx5ZUQdkp25adiLx2aJTHFKhiKPTMznwvP7fMJ5oEAxZIING4n/UrKX/iNejmLNnsvtJyNLZpl8EdQD8QK6UeaWHR1q6uA9ppT8ZbFaty6vhCC81n/zBQOijAxsR4o6A9RQr4LCy1gwvVwRsF2z6fezp+LzYAn0PhfcmtKyj1A5rp45PLfE/UXIIgtZbO4XdCXmYHzg6rgvhxqArHPvCf3l1hJsiZR8Uhxwd218kDD9T4wuRV//wBt/ReY0Ziz5RJQ4Dl2KLWRCvW4aE9o/cBGbDtvDIZ+apg6B1UMRlwdb3AhY7Y1Ps9wLpWbApvBA/O6q9rGzGGM8+0ySj4rXhNSXz+Ss6+9TAdhDMOv/ZnudozJ4Ym8vun46Q0pauC7Her2Ia4jB6uwsQEFfMiW7LJjP29EQc1V2dzEejDqkRp6GsP0SPOHYpEGZTuhRmDUeYdTsWmV3gKEbpG7gBS9mUH1RhHROW+IKm3J0YmELrg2thR6T1V0ifnNH1+0GculFdf0eiGCcch7Ezel5tjmdUZ73j5YqOV8pE6rXMUcIvAlsSHMRLH3NyOgjEZwtxOpV+TObUp6Ez21NxiTIHDa/eMGgyDIXsLUlEsSvklPPSHrkoolEqezeyGXco7TTvVfztE33nQJDs6ZppeZE845iGjkADI35DzOdUrHnhTBpOiW1kNnRzJEeQF+OnJzTgxBm91wWyW4c4XiKxOle47YvdR11ITIGTv+BK2qmrWwCUF7URwU+uMOuDYcZXOHbqcFDQZa7Pyw0dFSuLnQl+q/EQa+bI+aujrpdVZOjRoWK9pmYWLy9uF3hFg1c04dgX63BG7HRTe7nhozyK0YA6GiC3B+6ShEQswNGjwd5+3bwPOp8nm/vvjvKzJnfifbg7gfR6TTknMgeG8+XWcISbKm6Zi7tzw8aiNY1x4IzEwdmoO3KuyFxPN+mVF7nr1SoJ6T/p8eDM+QrF278On4iwhFkSoRGNCHa1ct4mwbUQPfExXQEHJXNzLT5gGMkcmAyqu0IPjtil+evAteR1tw4E4F90HhJXQpxgqN0koTt3hRRo1pzYMV6tmPiZK8l9MEou1W1ppxvxQddyfgN3BaFyk8haoHiH8IbOOHbn2i00CbwjPuNzZzQfHHxhvGk1GDhzCVC7aj83eHfXjiADE3+6JQl3KXUNRtZuk5hTlwLsutcC8wL3PfRdEjgwJ8P3JEYTpwIn7Q4QkZssMV9h3xWRazeBiNxk+RqlxpxsoInXrvBTXQlrcndHFlSs3Kk8LJRgpydeQDc4XCSfmpUNAp7a+K5nLRvrMZ+KfesR/oP67tTXQUnyeAlfuNNy66BpjTVu09HIEWZg/Igpc6fbz8EI58z3XPOidh+IYzViSehMXZ2yRa3ZJI9LQgJ/iSlHA18cDRGdBcSZ6pPdhX2gGBuOYrSm/T7G2HQEo9p6w6w0hjhOZGE75s4cINrBlNt0zV+H9Weypu7kxHq6lwB0cY3xWmzHG3cuhfVsC9gYc2e8LeusCPcTZ7ysXdt/e5uRORNF0j4YdVndknWcOFPipW2O6eKaBEnMHIHV0Y2O68Ly5B+u7ER1pKLxneiF7OUpcKdFr/W96CWhM+64dlI5D1iuON0gYLniWls3TiWsVgXrc7CmURLiFXUFl5IfNo7rnuMwccVN7LQsq60H4hAs3Tt+X4a1JmwdkNMzPHt1xnxQ3MR6rZEV1yRdtSYuVwyIrm7yQ5fWcInDRdp5MXaqpkU316vNjYViwYnvEDM1kGpc1i7ICjszp0S7B7surbE7rNSWFW/fm6Tljovd1I1H5AHLlROyqRt31oaVrFauJDTUJuzGYU3InIgVU+zMoagbTNUl5i3Zi0PjXNR6WPPKawvMFf2lBnKM+0OeWG0QOFMgoVa+Zr81rAvsPqQR+ekILjUCbdzwesRiKcJ/vGNs5YwWU9zuL/S0zhWbK7qsp1vMr08tkOO8HMHVtm2NPbKVQ25RS7vRfD68XNmNLWviFeEnEr+enlG2xP9g7krBfr2m+JKZJ2h46cK/TmyIE4cChtrZbW1cS7JKL6s+Erx2FlvmU1IX2wUOgo1t4T+7kmXTbracBzSWxMhbksCdcnLrW/SC4wV1JlDd1a2+18V1hcN5QNAjjZdOdXzU7SKnzY0uluiBBTFeuHOzrWX7INij5oxZqxuRzZWaM8V1ugVQutT+ImSNRs5c/dC+h6XL69aV4nzrJsYtC0+uWUj/SW1aPKdOFaoo4y4zx2f16aHzMHZmXwKQNuStmENRRuvu5q+cLxpyFkUOodMtstZF55o2eyvn/PJsGl1iXkDX6MqlqGNXO6ytzSxmnKA7YdbG6H7tjPvUte0IKNxccaAsajWfktAnp2JFjGNBzxmrQxvZZuUazMZ4ERJX2oB2dS+Q5MCL+sLY8NnalRia9qUbfWa3iR8Q7E6xmX5QIzdkrip/C1L2SMP5SrBwhJg6qN0ksTXjcXQ6WK2XNCbYobSTbumBl65cAxn3l+5081RFLLse08R1hiMyw85syba2EtPlRUPmJ0GJGj9pE2PCI3/BwbMrwHSvd+UALEY3OAl9Rzv9tTNXsusiG+LV2qGrEor12jWuxba8HDVd21Z4PVF3ijJsWxWS14K71LFZ8SezR6+1iYXMnfoVNXeZvVw2F1yu6C/1FnTLvAJLuy7f0CdX4ojaLfu1iQV0NXMoYamdHdflJRO8aCh0fsxfkfdMZU2Go/rsC8nLY9BzRb2psmfe/H/1A4e2qnJ4Ghe2EeUxOqPOdOlU5csCsB8OiZd2NkmXFnsJl4KEc4eAImbGjVoVnKP637xCO/9JuE+jSp99ktcF5eSFMVec84POItnrpLSBRUuXVNnBkLjsxcU5EXNGhym1eHXj2n9HbELdSfbadtIlMzQMCA4dss/2Ja1jfGtessCVCT/q+Afjtqxk5Y5oabcV0ccVzlmAHcGlPTpaF9cVFvr+MqBzd0RMYdbpGGdGn505H7Wn1+QAyyHRUoKwxg/GK8ZlMZT/jKYcU1dKoqxH/q99grbGa4Xs88i8Zxw7hGzftPjKXSVdZsK0YBx5L3S1coibbRvjTxLLeKKjuIybF3/hV+xMpaJtNXZDnwj6UxyYzlxPOgiMGWc2ZjHjM1ni6UowUREz88Urv5A13ETWNK7GJtQPqe9ayzLbVRhbalMs59I7uj07xp3MPWqO7lDzFYx3OFwQvhuu5I602S4tVrg5I2+6s+K0uTH/GTlW1Kg9aSkfaHJIgkvjvOzv0XSsxCzALgW2bZdN3bEXaeO6gks5P+vGcSWhQ0lftWON+S354Agp1Zw1XkzsYRqgM4d2onaXAm1gIY0xf0UjKl6JcODaxFDbroAnPppwoB4oeUkhOcJNe0CaPrdkhpFbxdmKrBnPcXqERPjFTVpt4wEhjwRP6DJJCzSqpHAmck5HHo0nN2UymMxkpwx3dFnHtnfuPVP0Z7JaO8JrV9Bij1dA5g7Jl3pPzngSRfAia6n5HVNmfdvKbIWDjQvlVhsb+7cmvDANAvG5s8Jm3tAQyFZs5s6kIdUFML89BTGh0hhx5yhQu0GYl7KEO3QPQG1hZh7XtkjPnbTmvq2xa8togVjDFWJKVVDmYdw5EHNnQ+p3+tekNSVhSJ3pWWnbqKhCPRlgybi1I6x2sX1rLvijUylx7flB2rTEB4vSZhgVsk8iW+KApKkkh6DZbuos+9JHbln41uWMsTm6xPGScIeoWSuMiom/PB04VPOvuyWnYsEanBz1gvqZvSAdTkO8Ihy7KlPZ20TlwMpRucoej9BiRYIATZabFbpAq6Vr1mvRYqsVdrXRtVnFLlCtE4cSabqjM7RYceZMYtumTJ3/X+K7UjGnRpkzVxpqgZK2ujuDBNX4stHNlzZIdGjeg26bLB1WY2dDpV2j1vqEvbhz8tUtnnxy9DVzBZRSoZq5RkkLlOe5gslmOGFKArKW3owznnJrP071hXRhPrxc8ZabupWo+eBqOoJLmdH81l7ZNK+WK7zqILRX2xFcVnfjvXfmCKaWbjm4DqYHOicMbYKijvBSbIiW0TPxEW+ac4+xL/50xS/s6jad+CoyjsM0T5heAz1tocclEWrMGe9HCdNkPx731q8PcED5DLuSZFWH3fWz+0T541sH2CH7X20flj1OcSyCrngE9dq+C9XOHmo9FkJXvIS+dlLtWARd8Rv0o2jHIuiKK6HdNetoBDuuENzfxV/x9Y+FsOsIQvVaYCt74UreCFezRCD0XfFDtFtU5g4w9JeMu2MP6tYtHomfK9ag9pyqI/FzxhTUrTY+Ej9nDEHtQqKc+Z1R/9V3KCADzQzc8nPnANFtqncsgM6cINp5/iMBdPQIaWfPoR0JoDNniAIQjA50JpawfwhnbyaXO8AkcvUAAXACC3iOHh4N+4eHgOfowdHM3JPpGPBcOTR6+xHorxSS5UxviB0KuyidmqwrPQnPFaWnRk3tb1xJz1WtB0L0XNF62o0jjwHvhvnOzBVU6l+slx/IFt9zMkdXdLF8wa+OYFSb1lnfwxeEc1fgKTLYsR4vkFfCYp64s4mVE8R63veC8eeAPjlz/1A5RKwXEF1id8IFHe3a5iPAc8Vy1q/aPQI8ZwxnaFVrEp4rhjM8yeMsCedIeVs3YKoWjPWc2xXmM7lwF+llb2KfOz0SUJ+t3eleogZgOtYDMG65bx1oRRt/ErJ2xgJUs23WhS+l54oJqN/8JGd6N2LrxkuWRA7VvEDbv+8YuiKHbWgG4ZitydxVEbR/CWmDzxXpA1exMWYx42nVi5sEO9YzIRMs1oGD4BV5yWxF+EKI4yMn7kRVldSIdaCyWRIWUonSXuluUuxb39iez5hD+JRqXvv4CI7RGQlcie33oF3MFADRRF6KcwQguAtd3pK66xtbjwym9JyxCqGVok5x6Ir5osYE29bDqlP8kzoCD5zVMmUvaOBOQFXhZ78iQbyfH7t0DVhpX2vd+dgBdPTosF/YJufMhc7IXxua2bzB54r0dXSnsh4HnzOVHdDusG7weS4XJYCQwZUzClB13CBYMCtn9J96gxXABk78Z3eErw9O+CQ+R6WvBUDzSXzOnL5K9137zm+Kz5XKSnC3WDf4nLm7r9ygtp5I3+BzpQlgF1zINMXnSgNA9eiwfvLeh0RAQncMOzp20H7C6IEsqexe4tSdOAWilfjfDxKcDjinP2Q7/ItA1rRFjvA7mHvyFQ9ErF8LHHtB5zhyJVOu3oL7it2SA7Hbc1d45XDS5sFL7PGlI8h2MmUb2aMjvPKoa86Bl+fMlgTCiyXVlsyIrNqSmXg9EnfsCqW1knG74gwvFnjhTL2dYoYZN1zP3KlxUkXrK16SJis+Ixx5S3cGuO/r+6+1idNjRnASvyIPB+6kUjvWoTH2jAbhXNoWAg91S+aUM9O4SpNNue7Ep8OuTC9XujN8bZSLJrJoSV29JvGlWgc9XAzHaLh053aTWh78pcmHesgSzknov6Lzn/4Sh+4YaIqsGbdnh0kkFuBKJFa10b6STdbCNWIvYRRjyl0lZlzARpyGz2nMnyXi0KSumGk7X8neqTnaJkumLHHm6GxYPjrPA/JDXmt1hFdHNc2M+wLnkfjUDhFTL1J/paIjH2BIngWuUFNOAfP78o3avTOOpmKamd+aCWeOsOopVxSMB7LPf1JnQthKAMO4RXYlzFc/cQVXu2f7iLxiMXEl1qOW+tiBha7DJ8ZXTl1wUZquGz8hr1crKl6ukGVA9kvK3LmNYTvl+x5awxFobdvVUXIIhzPx624Od/U0aUVxml+SIR9HK437X7njrUVtnEQkWblCK4eeFlq0bhmaYC4Di64Qs51V2uJy5qTs5jAGJxdgrpyS1k2LiSSDvj8J8198QmeLyixsTYfOyTzam+vBEpIlPpwjuLq2I2OytMeZZKUiW8ZtMM+p1K7tOzZTKryiGI2xv6TOtKDsWY8nbrFNEu4vceQKN+t7c5qEoTNxWOsJkfu1W2Uqii7Tk6726P8D';
/**
* Overrides gear image URL.
*/
Sidebar.prototype.gearImage = GRAPH_IMAGE_PATH + '/clipart/Gear_128x128.png';
/**
* Aliases for IDs in the libs parameter.
*/
Sidebar.prototype.libAliases = {'aws2': 'aws3', 'gcp' : 'gcp2'};
/**
*
*/
Sidebar.prototype.defaultEntries = 'general;uml;er;bpmn;flowchart;basic;arrows2';
/**
* Library definitions
*/
Sidebar.prototype.signs = ['Animals', 'Food', 'Healthcare', 'Nature', 'People', 'Safety', 'Science', 'Sports', 'Tech', 'Transportation', 'Travel'];
Sidebar.prototype.ibm = ['Analytics', 'Applications', 'Blockchain', 'Data', 'DevOps', 'Infrastructure', 'Management', 'Miscellaneous', 'Security', 'Social', 'Users', 'VPC', 'Boxes', 'Connectors'];
Sidebar.prototype.allied_telesis = ['Buildings', 'Computer and Terminals', 'Media Converters', 'Security', 'Storage', 'Switch', 'Wireless'];
Sidebar.prototype.gcp = ['Cards', 'Big Data', 'Compute', 'Developer Tools', 'Extras', 'Identity and Security', 'Machine Learning', 'Management Tools', 'Networking', 'Storage Databases'];
Sidebar.prototype.gcp2 = ['Paths', 'Zones', 'Service Cards', 'Compute', 'API Management', 'Security', 'Data Analytics', 'Data Transfer', 'Cloud AI', 'Internet of Things', 'Databases', 'Storage', 'Management Tools', 'Networking', 'Developer Tools', 'Expanded Product Cards', 'User Device Cards', 'Product Cards', 'General Icons', 'Icons AI Machine Learning', 'Icons Compute', 'Icons Data Analytics', 'Icons Management Tools', 'Icons Networking', 'Icons Developer Tools', 'Icons API Management', 'Icons Internet of Things', 'Icons Databases', 'Icons Storage', 'Icons Security', 'Icons Migration', 'Icons Hybrid and Multi Cloud'];
Sidebar.prototype.rack = ['General', 'APC', 'Cisco', 'Dell', 'F5', 'HP', 'HPE Aruba Gateways Controllers', 'HPE Aruba Security', 'HPE Aruba Switches', 'IBM', 'Oracle'];
Sidebar.prototype.pids = ['Agitators', 'Apparatus Elements', 'Centrifuges', 'Compressors', 'Compressors ISO', 'Crushers Grinding',
'Driers', 'Engines', 'Feeders', 'Filters', 'Fittings', 'Flow Sensors', 'Heat Exchangers', 'Instruments', 'Misc',
'Mixers', 'Piping', 'Pumps', 'Pumps DIN', 'Pumps ISO', 'Separators', 'Shaping Machines', 'Valves', 'Vessels'];
Sidebar.prototype.cisco = ['Buildings', 'Computers and Peripherals', 'Controllers and Modules', 'Directors', 'Hubs and Gateways', 'Misc',
'Modems and Phones', 'People', 'Routers', 'Security', 'Servers', 'Storage', 'Switches', 'Wireless'];
Sidebar.prototype.cisco19 = ['LAN Switching', 'Routing WAN', 'Network Management', 'Data Center', 'Wireless LAN', 'Collaboration', 'Security Clouds Connectors', 'Endpoint Client Device Icons', 'DNA SD Access', 'SD WAN Viptela', 'ETA Stealthwatch', 'SAFE'];
Sidebar.prototype.cisco_safe = ['Architecture', 'Business Icons', 'Capability', 'Design', 'IoT Things Icons', 'People Places Things Icons', 'Security Icons', 'Technology Icons', 'Threat'];
Sidebar.prototype.sysml = ['Model Elements', 'Blocks', 'Ports and Flows', 'Constraint Blocks', 'Activities', 'Interactions', 'State Machines',
'Use Cases', 'Allocations', 'Requirements', 'Profiles', 'Stereotypes'];
Sidebar.prototype.eip = ['Message Construction', 'Message Routing', 'Message Transformation', 'Messaging Channels', 'Messaging Endpoints',
'Messaging Systems', 'System Management'];
Sidebar.prototype.gmdl = ['Bottom Navigation', 'Bottom Sheets', 'Buttons', 'Cards', 'Chips', 'Dialogs', 'Dividers', 'Grid Lists', 'Icons', 'Lists', 'Menus', 'Misc', 'Pickers',
'Selection Controls', 'Sliders', 'Steppers', 'Tabs', 'Text Fields'];
Sidebar.prototype.aws2 = ['Analytics', 'Application Services', 'Compute', 'Database', 'Developer Tools', 'Enterprise Applications', 'Game Development', 'General', 'Internet of Things',
'Management Tools', 'Mobile Services', 'Networking', 'On-Demand Workforce', 'SDKs', 'Security and Identity', 'Storage and Content Delivery', 'Groups'];
Sidebar.prototype.aws3 = ['Analytics', 'Application Services', 'Artificial Intelligence', 'Business Productivity', 'Compute', 'Contact Center', 'Database', 'Desktop and App Streaming', 'Developer Tools',
'Game Development', 'General', 'Groups', 'Internet of Things',
'Management Tools', 'Messaging', 'Migration', 'Mobile Services', 'Networking and Content Delivery', 'On Demand Workforce', 'SDKs', 'Security Identity and Compliance', 'Storage'];
Sidebar.prototype.aws4b = ['Arrows', 'General Resources', 'Illustrations', 'Groups Light', 'Groups Dark', 'Analytics', 'Application Integration', 'AR VR', 'Cost Management', 'Business Productivity', 'Compute', 'Customer Engagement',
'Database', 'Desktop App Streaming', 'Developer Tools', 'Game Development', 'Internet of Things', 'IoT Things', 'IoT Resources', 'Machine Learning', 'Management Tools',
'Media Services', 'Migration', 'Mobile Services', 'Network Content Delivery', 'Security Identity Compliance', 'Storage'];
Sidebar.prototype.aws4 = ['Arrows', 'General Resources', 'Illustrations', 'Groups', 'Analytics', 'Application Integration', 'AR VR', 'Cost Management', 'Blockchain',
'Business Applications', 'EC2 Instance Types', 'Compute', 'Containers', 'Customer Enablement', 'Customer Engagement',
'Database', 'End User Computing', 'Developer Tools', 'Game Tech', 'Internet of Things', 'IoT Things', 'IoT Resources', 'Machine Learning', 'Management Governance',
'Media Services', 'Migration Transfer', 'Mobile', 'Network Content Delivery', 'Quantum Technologies', 'Robotics', 'Satellite', 'Security Identity Compliance', 'Storage'];
Sidebar.prototype.office = ['Clouds', 'Communications', 'Concepts', 'Databases', 'Devices', 'Security', 'Servers', 'Services', 'Sites', 'Users'];
Sidebar.prototype.veeam = ['Data Center', 'Misc', 'Software', 'Storage', 'UsersStatus', 'VASComponents', 'Backup Replication', 'Products', 'VMs and Tape', '2D', '3D'];
Sidebar.prototype.veeam2 = ['Auxiliary', 'Data Center', 'Features', 'General', 'Products and Components', 'Software', 'States', 'Storage', '3D'];
Sidebar.prototype.archimate3 = ['Application', 'Business', 'Composite', 'Implementation and Migration', 'Motivation', 'Physical', 'Relationships', 'Strategy', 'Technology'];
Sidebar.prototype.electrical = ['LogicGates', 'Resistors', 'Capacitors', 'Inductors', 'SwitchesRelays', 'Diodes', 'Sources', 'Transistors', 'Misc', 'Audio', 'PlcLadder', 'Abstract', 'Optical', 'VacuumTubes', 'Waveforms', 'Instruments', 'RotMech', 'Transmission'];
/**
* Description of custom libraries, see https://www.diagrams.net/doc/faq/configure-diagram-editor
*/
Sidebar.prototype.customEntries = null;
/**
* Array of strings for the built-in libraries to be enabled in the more shapes dialog. Null means all,
* empty array means none, possible keys are listed for the libs parameter at
*
* https://www.diagrams.net/doc/faq/supported-url-parameters
*/
Sidebar.prototype.enabledLibraries = null;
/**
* Maximum number of custom libraries to preload into the search index.
*/
Sidebar.prototype.maxPreloadCount = 20;
/**
*
*/
Sidebar.prototype.configuration = [{id: 'general', libs: ['general', 'misc', 'advanced']},
{id: 'uml'}, {id: 'uml25'}, {id: 'search'}, {id: 'er'},
{id: 'azure2', prefix: 'azure2', libs: ['AI Machine Learning', 'Analytics', 'App Services', 'Azure Stack', 'Azure VMware Solution', 'Blockchain', 'Compute', 'Containers', 'CXP', 'Databases', 'DevOps', 'General', 'Identity', 'Integration', 'Internet of Things', 'Intune', 'IoT', 'Management Governance', 'Migrate', 'Mixed Reality', 'Monitor', 'Networking', 'Other', 'Preview', 'Security', 'Storage', 'Web']},
{id: 'ios', prefix: 'ios', libs: [''/*prefix is library*/, '7icons', '7ui']},
{id: 'android', prefix: 'android', libs: [''/*prefix is library*/]}, {id: 'aws3d'},
{id: 'flowchart'}, {id: 'basic'}, {id: 'infographic'}, {id: 'arrows'}, {id: 'arrows2'}, {id: 'lean_mapping'}, {id: 'citrix'}, {id: 'azure'}, {id: 'network'}, {id: 'vvd'},
{id: 'sitemap'}, {id:'c4'}, {id: 'dfd'}, {id: 'threatModeling'}, {id : 'kubernetes'}, {id : 'cisco19', prefix: 'cisco19', libs: Sidebar.prototype.cisco19},
{id: 'mscae', prefix: 'mscae', libs: ['Companies', 'EnterpriseFlat', 'IntuneFlat', 'OMSFlat', 'System CenterFlat', 'AI and ML Service', 'Analytics Service', 'Compute Service', 'Compute Service VM', 'Container Service', 'Databases Service', 'DevOps Service', 'General Service', 'Identity Service', 'Integration Service', 'Internet of Things Service', 'Intune Service', 'Management and Governance Service', 'Management and Governance Service Media', 'Migrate Service', 'Mixed Reality Service', 'Mobile Service', 'Networking Service', 'Other Category Service', 'Security Service', 'Storage Service', 'Web Service']},
{id: 'active_directory'},
{id: 'bpmn2', prefix: 'bpmn2', libs: ['General', 'Tasks', 'Choreographies', 'Events', 'Gateways']},
{id: 'clipart', prefix: null, libs: ['computer', 'finance', 'clipart', 'networking', 'people', 'telco']},
{id: 'ibm', prefix: 'ibm', libs: Sidebar.prototype.ibm},
{id: 'allied_telesis', prefix: 'allied_telesis', libs: Sidebar.prototype.allied_telesis},
{id: 'cumulus', libs: ['cumulus']},
{id: 'eip', prefix: 'eip', libs: Sidebar.prototype.eip},
{id: 'mockups', prefix: 'mockup', libs: ['Buttons', 'Containers', 'Forms', 'Graphics', 'Markup', 'Misc', 'Navigation', 'Text']},
{id: 'pid2', prefix: 'pid2', libs: ['Agitators', 'Apparatus Elements', 'Centrifuges', 'Compressors', 'Compressors ISO', 'Crushers Grinding',
'Driers', 'Engines', 'Feeders', 'Filters', 'Fittings', 'Flow Sensors', 'Heat Exchangers', 'Instruments', 'Misc',
'Mixers', 'Piping', 'Pumps', 'Pumps DIN', 'Pumps ISO', 'Separators', 'Shaping Machines', 'Valves', 'Vessels']},
{id: 'signs', prefix: 'signs', libs: Sidebar.prototype.signs},
{id: 'gcp', prefix: 'gcp', libs: Sidebar.prototype.gcp},
{id: 'gcp2', prefix: 'gcp2', libs: Sidebar.prototype.gcp2},
// {id: 'gcp19', prefix: 'gcp19', libs: Sidebar.prototype.gcp2},
{id: 'rack', prefix: 'rack', libs: Sidebar.prototype.rack},
{id: 'electrical', prefix: 'electrical', libs: Sidebar.prototype.electrical},
{id: 'aws2', prefix: 'aws2', libs: Sidebar.prototype.aws2},
{id: 'aws3', prefix: 'aws3', libs: Sidebar.prototype.aws3},
{id: 'aws4b', prefix: 'aws4b', libs: Sidebar.prototype.aws4b},
{id: 'aws4', prefix: 'aws4', libs: Sidebar.prototype.aws4},
{id: 'pid', prefix: 'pid', libs: Sidebar.prototype.pids},
{id: 'cisco', prefix: 'cisco', libs: Sidebar.prototype.cisco},
{id: 'cisco_safe', prefix: 'cisco_safe', libs: Sidebar.prototype.cisco_safe},
{id: 'office', prefix: 'office', libs: Sidebar.prototype.office},
{id: 'veeam', prefix: 'veeam', libs: Sidebar.prototype.veeam},
{id: 'veeam2', prefix: 'veeam2', libs: Sidebar.prototype.veeam2},
{id: 'cabinets', libs: ['cabinets']},
{id: 'floorplan', libs: ['floorplan']},
{id: 'bootstrap', libs: ['bootstrap']},
{id: 'atlassian', libs: ['atlassian']},
{id: 'fluid_power', libs: ['fluid_power']},
{id: 'gmdl', prefix: 'gmdl', libs: Sidebar.prototype.gmdl},
{id: 'archimate3', prefix: 'archimate3', libs: Sidebar.prototype.archimate3},
{id: 'archimate', libs: ['archimate']},
{id: 'webicons', libs: ['webicons', 'weblogos']},
{id: 'sysml', prefix: 'sysml', libs: Sidebar.prototype.sysml}];
/**
* Adds hint for quick tutorial video for certain search terms.
*/
var siderbarInsertSearchHint = Sidebar.prototype.insertSearchHint;
Sidebar.prototype.insertSearchHint = function(div, searchTerm, count, page, results, len, more, terms)
{
if (terms != null && page == 1)
{
var hintText = null;
// Adds hint for text inserts
if (mxUtils.indexOf(terms, 'text') >= 0)
{
hintText = 'Double click anywhere in the diagram to insert text.';
}
else
{
// Checks if any of the following keywords are in the search terms
var words = ['line', 'lines', 'arrow', 'arrows', 'connect', 'connection', 'connections',
'connector', 'connectors', 'curve', 'curves', 'link', 'links', 'directed',
'directional', 'bidirectional'];
for (var i = 0; i < words.length; i++)
{
if (mxUtils.indexOf(terms, words[i]) >= 0)
{
hintText = 'Need help with connections?';
break;
}
}
}
if (hintText != null && !this.hideSearchHint)
{
var link = document.createElement('a');
link.setAttribute('href', 'https://youtu.be/Z0D96ZikMkc');
link.setAttribute('target', '_blank');
link.className = 'geTitle';
link.style.cssText = 'background-color:#ffd350;border-radius:6px;color:black;' +
'border:1px solid black !important;text-align:center;white-space:normal;' +
'padding:6px 0px 6px 0px !important;margin:4px 4px 8px 2px;font-size:12px;';
mxUtils.write(link, hintText);
// Adds close button
var img = document.createElement('img');
img.setAttribute('src', Dialog.prototype.closeImage);
img.setAttribute('title', mxResources.get('hide'));
img.className = 'geDialogClose';
img.style.position = 'relative';
img.style.cursor = 'default';
img.style.top = '1px';
img.style.right = '0px';
mxEvent.addListener(img, 'click', mxUtils.bind(this, function(evt)
{
link.parentNode.removeChild(link);
this.hideSearchHint = true;
mxEvent.consume(evt);
}));
link.appendChild(img);
div.appendChild(link);
// Shows hint only once
this.hideSearchHint = true;
}
}
siderbarInsertSearchHint.apply(this, arguments);
};
/**
* Toggle palette.
*/
Sidebar.prototype.togglePalettes = function(prefix, ids)
{
this.showPalettes(prefix, ids);
};
/**
* Toggle palette.
*/
Sidebar.prototype.togglePalette = function(id)
{
this.showPalette(id);
};
/**
* Shows or hides palettes.
*/
Sidebar.prototype.showPalettes = function(prefix, ids, visible)
{
for (var i = 0; i < ids.length; i++)
{
this.showPalette(prefix + ids[i], visible);
}
};
/**
* Shows or hides a palette.
*/
Sidebar.prototype.showPalette = function(id, visible)
{
var elts = this.palettes[id];
if (elts != null)
{
var vis = (visible != null) ? ((visible) ? 'block' : 'none') : (elts[0].style.display == 'none') ? 'block' : 'none';
for (var i = 0; i < elts.length; i++)
{
elts[i].style.display = vis;
}
}
return elts;
};
/**
*
*/
Sidebar.prototype.getConfigurationById = function(id)
{
for (var i = 0; i < this.configuration.length; i++)
{
if (this.configuration[i].id == id)
{
return this.configuration[i];
}
}
if (this.customEntries != null)
{
for (var i = 0; i < this.customEntries.length; i++)
{
var section = this.customEntries[i];
for (var j = 0; j < section.entries.length; j++)
{
var entry = section.entries[j];
if (entry.id == id)
{
return {id: entry.id, libs: entry.libs};
}
}
}
}
return null;
};
/**
*
*/
Sidebar.prototype.isEntryVisible = function(key)
{
var config = this.getConfigurationById(key);
if (config != null)
{
var id = (config.libs != null) ? ((config.prefix || '') + config.libs[0]) : key;
var elts = this.palettes[id];
if (elts != null)
{
return elts[0].style.display != 'none';
}
}
if (this.customEntries != null)
{
for (var i = 0; i < this.customEntries.length; i++)
{
var section = this.customEntries[i];
for (var j = 0; j < section.entries.length; j++)
{
var entry = section.entries[j];
if (entry.id == key)
{
if (entry.libs != null && entry.libs.length > 0)
{
var elts = this.palettes[entry.id + '.0'];
if (elts != null)
{
return elts[0].style.display != 'none';
}
}
break;
}
}
}
}
return false;
};
/**
*
*/
Sidebar.prototype.showEntries = function(entries, remember, force)
{
var all = [];
if (remember)
{
mxSettings.setLibraries(entries);
mxSettings.save();
}
if (entries != null && (force || entries.length > 0))
{
all.push(entries);
}
else
{
var done = false;
if (urlParams['libs'] != null && urlParams['libs'].length > 0)
{
all.push(decodeURIComponent(urlParams['libs']));
done = this.editorUi.getServiceName() == 'draw.io';
}
// Libs parameter overrides configuration for online app so that
// links can be created to show just the specifies libraries
if (!done)
{
if (mxSettings != null && mxSettings.settings != null)
{
all.push(mxSettings.getLibraries());
}
else
{
all.push(this.defaultEntries);
}
}
}
// Merges array of semicolon separated strings into a single array
var temp = all.join(';').split(';');
// Resolves aliases and creates lookup
var visible = {};
for (var i = 0; i < temp.length; i++)
{
visible[this.libAliases[temp[i]] || temp[i]] = true;
}
for (var i = 0; i < this.configuration.length; i++)
{
// Search has separate switch in Extras menu
if (this.configuration[i].id != 'search')
{
this.showPalettes(this.configuration[i].prefix || '',
this.configuration[i].libs || [this.configuration[i].id],
visible[this.configuration[i].id] == true);
}
}
if (this.customEntries != null)
{
for (var i = 0; i < this.customEntries.length; i++)
{
var section = this.customEntries[i];
for (var j = 0; j < section.entries.length; j++)
{
var entry = section.entries[j];
if (entry.libs != null && entry.libs.length > 0)
{
var libs = [];
for (var k = 0; k < entry.libs.length; k++)
{
libs.push(entry.id + '.' + k);
}
this.showPalettes('', libs, visible[entry.id]);
}
}
}
}
};
/**
* Overrides the sidebar init.
*/
Sidebar.prototype.init = function()
{
// Defines all entries for the sidebar. This is used in the MoreShapes dialog. Create screenshots using the savesidebar URL parameter and
// http://www.alderg.com/merge.html for creating a vertical stack of PNG images if multiple sidebars are part of an entry.
this.entries = [{title: mxResources.get('standard'),
entries: [{title: mxResources.get('general'), id: 'general', image: IMAGE_PATH + '/sidebar-general.png'},
{title: mxResources.get('basic'), id: 'basic', image: IMAGE_PATH + '/sidebar-basic.png'},
{title: mxResources.get('arrows'), id: 'arrows2', image: IMAGE_PATH + '/sidebar-arrows2.png'},
{title: mxResources.get('clipart'), id: 'clipart', image: IMAGE_PATH + '/sidebar-clipart.png'},
{title: mxResources.get('flowchart'), id: 'flowchart', image: IMAGE_PATH + '/sidebar-flowchart.png'}]},
{title: mxResources.get('software'),
entries: [{title: 'Active Directory', id: 'active_directory', image: IMAGE_PATH + '/sidebar-active_directory.png'},
{title: mxResources.get('android'), id: 'android', image: IMAGE_PATH + '/sidebar-android.png'},
{title: 'Atlassian', id: 'atlassian', image: IMAGE_PATH + '/sidebar-atlassian.png'},
{title: mxResources.get('bootstrap'), id: 'bootstrap', image: IMAGE_PATH + '/sidebar-bootstrap.png'},
{title: 'C4', id: 'c4', image: IMAGE_PATH + '/sidebar-c4.png'},
{title: 'Data Flow Diagram', id: 'dfd', image: IMAGE_PATH + '/sidebar-dfd.png'},
{title: mxResources.get('entityRelation'), id: 'er', image: IMAGE_PATH + '/sidebar-er.png'},
{title: mxResources.get('ios'), id: 'ios', image: IMAGE_PATH + '/sidebar-ios.png'},
{title: mxResources.get('mockups'), id: 'mockups', image: IMAGE_PATH + '/sidebar-mockups.png'},
{title: 'Sitemap', id: 'sitemap', image: IMAGE_PATH + '/sidebar-sitemap.png'},
{title: mxResources.get('uml') + ' 2.5', id: 'uml25', image: IMAGE_PATH + '/sidebar-uml25.png'},
{title: mxResources.get('uml'), id: 'uml', image: IMAGE_PATH + '/sidebar-uml.png'}]},
{title: mxResources.get('networking'),
entries: [{title: 'Allied Telesis', id: 'allied_telesis', image: IMAGE_PATH + '/sidebar-allied_telesis.png'},
{title: 'AWS17', id: 'aws3', image: IMAGE_PATH + '/sidebar-aws3.png'},
{title: 'AWS18', id: 'aws4b', image: IMAGE_PATH + '/sidebar-aws4b.png'},
{title: 'AWS19', id: 'aws4', image: IMAGE_PATH + '/sidebar-aws4.png'},
// TODO: Add isometric containers
{title: mxResources.get('aws3d'), id: 'aws3d', image: IMAGE_PATH + '/sidebar-aws3d.png'},
{title: mxResources.get('azure'), id: 'azure2', image: IMAGE_PATH + '/sidebar-azure.png'},
{title: 'Cloud & Enterprise', id: 'mscae', image: IMAGE_PATH + '/sidebar-mscae.png'},
{title: mxResources.get('cisco'), id: 'cisco', image: IMAGE_PATH + '/sidebar-cisco.png'},
{title: 'Cisco19', id: 'cisco19', image: IMAGE_PATH + '/sidebar-cisco19.png'},
{title: 'Cisco Safe', id: 'cisco_safe', image: IMAGE_PATH + '/sidebar-cisco_safe.png'},
{title: 'Cumulus', id: 'cumulus', image: IMAGE_PATH + '/sidebar-cumulus.png'},
{title: 'Citrix', id: 'citrix', image: IMAGE_PATH + '/sidebar-citrix.png'},
{title: 'Google Cloud Platform', id: 'gcp2', image: IMAGE_PATH + '/sidebar-gcp2.png'},
{title: 'IBM', id: 'ibm', image: IMAGE_PATH + '/sidebar-ibm.png'},
{title: 'Kubernetes', id: 'kubernetes', image: IMAGE_PATH + '/sidebar-kubernetes.png'},
{title: 'Network', id: 'network', image: IMAGE_PATH + '/sidebar-network.png'},
{title: 'Office', id: 'office', image: IMAGE_PATH + '/sidebar-office.png'},
{title: mxResources.get('rack'), id: 'rack', image: IMAGE_PATH + '/sidebar-rack.png'},
{title: 'Veeam', id: 'veeam2', image: IMAGE_PATH + '/sidebar-veeam.png'},
{title: 'VMware', id: 'vvd', image: IMAGE_PATH + '/sidebar-vvd.png'}]},
{title: mxResources.get('business'),
entries: [{title: 'ArchiMate 3.0', id: 'archimate3', image: IMAGE_PATH + '/sidebar-archimate3.png'},
{title: mxResources.get('archiMate21'), id: 'archimate', image: IMAGE_PATH + '/sidebar-archimate.png'},
{title: mxResources.get('bpmn') + ' 2.0', id: 'bpmn2', image: IMAGE_PATH + '/sidebar-bpmn.png'},
{title: mxResources.get('sysml'), id: 'sysml', image: IMAGE_PATH + '/sidebar-sysml.png'},
{title: 'Value Stream Mapping', id: 'lean_mapping', image: IMAGE_PATH + '/sidebar-leanmapping.png'}]},
{title: mxResources.get('other'),
entries: [{title: mxResources.get('cabinets'), id: 'cabinets', image: IMAGE_PATH + '/sidebar-cabinets.png'},
{title: 'Infographic', id: 'infographic', image: IMAGE_PATH + '/sidebar-infographic.png'},
{title: mxResources.get('eip'), id: 'eip', image: IMAGE_PATH + '/sidebar-eip.png'},
{title: mxResources.get('electrical'), id: 'electrical', image: IMAGE_PATH + '/sidebar-electrical.png'},
{title: mxResources.get('floorplans'), id: 'floorplan', image: IMAGE_PATH + '/sidebar-floorplans.png'},
{title: 'Fluid Power (ISO 1219)', id: 'fluid_power', image: IMAGE_PATH + '/sidebar-fluid_power.png'},
{title: mxResources.get('gmdl'), id: 'gmdl', image: IMAGE_PATH + '/sidebar-gmdl.png'},
{title: mxResources.get('procEng'), id: 'pid', image: IMAGE_PATH + '/sidebar-pid.png'},
{title: 'Threat Modeling', id: 'threatModeling', image: IMAGE_PATH + '/sidebar-threatmodeling.png'},
{title: 'Web Icons', id: 'webicons', image: IMAGE_PATH + '/sidebar-webIcons.png'},
{title: mxResources.get('signs'), id: 'signs', image: IMAGE_PATH + '/sidebar-signs.png'}]}];
// Uses search.xml index file instead (faster load times)
this.addStencilsToIndex = false;
// Contains additional tags for shapes
this.shapetags = {};
// Adds tags from compressed text file for improved searches
if (this.tagIndex != null)
{
this.addTagIndex(Graph.decompress(this.tagIndex));
this.tagIndex = null;
}
this.initPalettes();
}
/**
* Overridden to add image export via servlet
*/
if (urlParams['savesidebar'] == '1')
{
Sidebar.prototype.addFoldingHandler = function(title, content, funct)
{
var initialized = false;
// Avoids mixed content warning in IE6-8
if (!mxClient.IS_IE || document.documentMode >= 8)
{
title.style.backgroundImage = (content.style.display == 'none') ?
'url(\'' + this.collapsedImage + '\')' : 'url(\'' + this.expandedImage + '\')';
}
title.style.backgroundRepeat = 'no-repeat';
title.style.backgroundPosition = '0% 50%';
var btn = document.createElement('button');
btn.style.marginLeft = '4px';
mxUtils.write(btn, 'Save');
mxEvent.addListener(title, 'click', mxUtils.bind(this, function(evt)
{
if (mxEvent.getSource(evt).nodeName == 'BUTTON')
{
var title2 = title.cloneNode(true);
title2.style.backgroundImage = '';
title2.style.textDecoration = 'none';
title2.style.fontWeight = 'bold';
title2.style.fontSize = '14px';
title2.style.color = 'rgb(80, 80, 80)';
title2.style.width = '456px';
title2.style.backgroundColor = '#ffffff';
title2.style.paddingLeft = '6px';
var btn2 = title2.getElementsByTagName('button')[0];
btn2.parentNode.removeChild(btn2);
var clone = content.cloneNode(true);
clone.style.backgroundColor = '#ffffff';
clone.style.borderColor = 'transparent';
clone.style.width = '456px';
var parser = new DOMParser();
var doc = parser.parseFromString('<body style="background:#ffffff;font-family:Helvetica,Arial;">' +
title2.outerHTML + clone.outerHTML + '</body>', 'text/html');
this.editorUi.editor.convertImages(doc.documentElement, mxUtils.bind(this, function(body)
{
var html = '<!DOCTYPE html><html><head><link rel="stylesheet" type="text/css" ' +
'href="https://www.draw.io/styles/grapheditor.css"></head>' +
mxUtils.getXml(body) + '</html>';
clone.style.position = 'absolute';
window.document.body.appendChild(clone);
var h = clone.clientHeight + 18;
clone.parentNode.removeChild(clone);
this.editorUi.confirm('Image data created', mxUtils.bind(this, function()
{
new mxXmlRequest(EXPORT_URL, 'w=456&h=' + h + '&html=' + encodeURIComponent(
Graph.compress(html))).simulate(document, '_blank');
}), null, mxResources.get('save'), mxResources.get('cancel'));
}));
return;
}
if (content.style.display == 'none')
{
if (!initialized)
{
initialized = true;
if (funct != null)
{
if (btn.parentNode != null)
{
btn.parentNode.removeChild(btn);
}
// Wait cursor does not show up on Mac
title.style.cursor = 'wait';
var prev = title.innerHTML;
title.innerHTML = mxResources.get('loading') + '...';
window.setTimeout(function()
{
funct(content);
title.style.cursor = '';
title.innerHTML = prev;
title.appendChild(btn);
}, 0);
}
else
{
title.appendChild(btn);
}
}
else
{
title.appendChild(btn);
}
title.style.backgroundImage = 'url(\'' + this.expandedImage + '\')';
content.style.display = 'block';
}
else
{
title.style.backgroundImage = 'url(\'' + this.collapsedImage + '\')';
content.style.display = 'none';
if (btn.parentNode != null)
{
btn.parentNode.removeChild(btn);
}
}
mxEvent.consume(evt);
}));
};
};
/**
* Overridden to use shapetags to improve search results.
*/
Sidebar.prototype.extractShapeStyle = function(style)
{
if (style != null && style.substring(0, 6) == 'shape=')
{
var semi = style.indexOf(';');
if (semi < 0)
{
semi = style.length;
}
return style.substring(6, semi);
}
return null;
};
/**
* Overridden to use shapetags to improve search results.
*/
var sidebarGetTagsForStencil = Sidebar.prototype.getTagsForStencil;
Sidebar.prototype.getTagsForStencil = function(pkg, stc, moreTags)
{
var tags = sidebarGetTagsForStencil.apply(this, arguments);
// Adds tags from tags file
if (this.shapetags != null)
{
pkg = pkg.toLowerCase();
stc = stc.toLowerCase();
if (this.shapetags[pkg] != null)
{
tags.push(this.shapetags[pkg]);
}
stc = pkg + '.' + stc;
if (this.shapetags[stc] != null)
{
tags.push(this.shapetags[stc]);
}
}
return tags;
};
/**
* Overrides the sidebar init.
*/
Sidebar.prototype.addTagIndex = function(text)
{
var lines = text.split('\n');
for (var i = 0; i < lines.length; i++)
{
if (lines[i] != null)
{
var tags = lines[i].split('\t');
if (tags.length > 1)
{
var key = tags[0].toLowerCase().replace(' ', '_');
var value = mxUtils.trim(tags.slice(1, tags.length).join(' ').toLowerCase());
if (value.length > 0)
{
this.shapetags[key] = value;
}
}
}
}
};
/**
* Adds shape search UI.
*/
Sidebar.prototype.showPopupMenuForEntry = function(elt, libs, evt)
{
if (libs != null && libs.length > 0)
{
var offset = mxUtils.getOffset(elt);
this.editorUi.showPopupMenu(mxUtils.bind(this, function(menu, parent)
{
menu.addItem(mxResources.get('openLibrary'), null, mxUtils.bind(this, function()
{
for (var i = 0; i < libs.length; i++)
{
(mxUtils.bind(this, function(lib)
{
var config = this.getConfigurationById(lib.id);
if (config != null)
{
this.showPalettes(config.prefix || '', config.libs || [config.id], true);
var elts = this.showPalette(libs[i].lib || libs[i].id, true);
if (elts != null && elts.length > 1 && elts[1].firstChild != null &&
(elts[1].firstChild.firstChild == null ||
elts[1].firstChild.style.display == 'none'))
{
elts[0].click();
}
window.setTimeout(function()
{
elts[1].scrollIntoView(true);
}, 0);
mxEvent.consume(evt);
}
}))(libs[i]);
}
}));
}), offset.x, offset.y + elt.offsetHeight, evt);
}
};
/**
* Overrides the sidebar init.
*/
Sidebar.prototype.addSearchIndex = function(shapes)
{
if (shapes != null)
{
for (var i = 0; i < shapes.length; i++)
{
if (shapes[i].style != null)
{
var style = shapes[i].style;
var shapeStyle = this.extractShapeStyle(style);
if (shapeStyle != null)
{
var lastDot = shapeStyle.lastIndexOf('.');
if (lastDot > 0)
{
var pkg = shapeStyle.substring(0, lastDot);
var stc = shapeStyle.substring(lastDot + 1, shapeStyle.length);
var tags = this.getTagsForStencil(pkg, stc, shapes[i].tags);
// TODO: Use shapetags for programmatic stencils
if (tags != null)
{
// Converts stencil name to lowercase
var semi = style.indexOf(';');
style = 'shape=' + pkg + '.' + stc.toLowerCase() + ';' +
((semi < 0) ? '' : style.substring(semi + 1));
this.setCurrentSearchEntryLibrary(shapes[i].id, shapes[i].lib);
this.createVertexTemplateEntry(style, parseInt(shapes[i].w),
parseInt(shapes[i].h), '', stc.replace(/_/g, ' '),
null, null, this.filterTags(tags.join(' ')));
this.setCurrentSearchEntryLibrary();
}
}
}
}
}
}
};
/**
* Overrides the sidebar init.
*/
Sidebar.prototype.initPalettes = function()
{
var imgDir = GRAPH_IMAGE_PATH;
var dir = STENCIL_PATH;
var signs = this.signs;
var gcp = this.gcp;
var rack = this.rack;
var pids = this.pids;
var cisco = this.cisco;
var cisco19 = this.cisco19;
var cisco_safe = this.cisco_safe;
var sysml = this.sysml;
var eip = this.eip;
var gmdl = this.gmdl;
var office = this.office;
var veeam = this.veeam;
var veeam2 = this.veeam2;
var archimate3 = this.archimate3;
var electrical = this.electrical;
if (urlParams['createindex'] == '1')
{
this.createdSearchIndex = [];
}
this.addSearchPalette(true);
// Adds custom sections first
if (this.customEntries != null)
{
var preloadCount = 0;
for (var i = 0; i < this.customEntries.length; i++)
{
var section = this.customEntries[i];
for (var j = 0; j < section.entries.length; j++)
{
var entry = section.entries[j];
for (var k = 0; k < entry.libs.length; k++)
{
(mxUtils.bind(this, function(lib)
{
var data = null;
var error = null;
var content = null;
var title = null;
var showError = mxUtils.bind(this, function(err, c)
{
var div = document.createElement('span');
div.style.paddingBottom = '6px';
div.style.paddingTop = '6px';
div.style.fontSize = '11px';
mxUtils.write(div, err);
c.innerHTML = '<img align="top" src="' + mxGraph.prototype.warningImage.src + '"/> ';
c.appendChild(div);
});
var barrier = mxUtils.bind(this, function()
{
if (content != null && title != null)
{
if (error != null)
{
content.style.display = 'block';
title.innerHTML = '';
mxUtils.write(title, this.editorUi.getResource(lib.title));
showError(error, content);
}
else if (data != null)
{
this.editorUi.addLibraryEntries(data, content);
content.style.display = 'block';
title.innerHTML = '';
mxUtils.write(title, this.editorUi.getResource(lib.title));
}
else
{
content.style.display = 'none';
title.innerHTML = '';
mxUtils.write(title, mxResources.get('loading') + '...');
}
}
});
if (lib.data == null && lib.url != null && (!lib.preload && preloadCount >= this.maxPreloadCount))
{
this.addPalette(entry.id + '.' + k, this.editorUi.getResource(lib.title),
false, mxUtils.bind(this, function(content, title)
{
var dataLoaded = mxUtils.bind(this, function(images)
{
this.setCurrentSearchEntryLibrary(entry.id, entry.id + '.' + k);
this.addEntries(images);
this.setCurrentSearchEntryLibrary();
this.editorUi.addLibraryEntries(images, content);
});
content.style.display = 'none';
title.innerHTML = '';
mxUtils.write(title, mxResources.get('loading') + '...');
var url = lib.url;
if (!this.editorUi.editor.isCorsEnabledForUrl(url))
{
url = PROXY_URL + '?url=' + encodeURIComponent(url);
}
this.editorUi.editor.loadUrl(url, mxUtils.bind(this, function(data)
{
content.style.display = 'block';
title.innerHTML = '';
mxUtils.write(title, this.editorUi.getResource(lib.title));
try
{
var doc = mxUtils.parseXml(data);
if (doc.documentElement.nodeName == 'mxlibrary')
{
var images = JSON.parse(mxUtils.getTextContent(doc.documentElement));
dataLoaded(images);
}
else
{
showError(mxResources.get('notALibraryFile'), content);
}
}
catch (e)
{
showError(mxResources.get('error') + ': ' + e.message, content);
}
}));
}));
}
else
{
this.addPalette(entry.id + '.' + k, this.editorUi.getResource(lib.title),
false, mxUtils.bind(this, function(c, t)
{
content = c;
title = t;
barrier();
}));
if (lib.data != null)
{
this.setCurrentSearchEntryLibrary(entry.id, entry.id + '.' + k);
this.addEntries(lib.data);
this.setCurrentSearchEntryLibrary();
data = lib.data;
barrier();
}
else if (lib.url != null)
{
preloadCount++;
var url = lib.url;
if (!this.editorUi.editor.isCorsEnabledForUrl(url))
{
url = PROXY_URL + '?url=' + encodeURIComponent(url);
}
this.editorUi.editor.loadUrl(url, mxUtils.bind(this, function(temp)
{
try
{
var doc = mxUtils.parseXml(temp);
if (doc.documentElement.nodeName == 'mxlibrary')
{
data = JSON.parse(mxUtils.getTextContent(doc.documentElement));
this.addEntries(data);
barrier();
}
else
{
error = mxResources.get('notALibraryFile');
barrier();
}
}
catch (e)
{
error = mxResources.get('error') + ': ' + e.message;
barrier();
}
}), mxUtils.bind(this, function(e)
{
error = (e != null && e.message != null) ? e.message : e;
barrier();
}));
}
else
{
error = mxResources.get('invalidInput');
barrier();
}
}
}))(entry.libs[k]);
}
}
}
}
this.addGeneralPalette(this.customEntries == null);
this.addMiscPalette(false);
this.addAdvancedPalette(false);
this.addBasicPalette();
this.addStencilPalette('arrows', mxResources.get('arrows'), dir + '/arrows.xml',
';html=1;' + mxConstants.STYLE_VERTICAL_LABEL_POSITION + '=bottom;' + mxConstants.STYLE_VERTICAL_ALIGN + '=top;' + mxConstants.STYLE_STROKEWIDTH + '=2;strokeColor=#000000;',
null, null, null, null, null, 'arrows');
this.addArrows2Palette();
this.setCurrentSearchEntryLibrary('clipart', 'computer');
this.addImagePalette('computer', 'Clipart / Computer', imgDir
+ '/lib/clip_art/computers/', '_128x128.png', ['Antivirus',
'Data_Filtering', 'Database', 'Database_Add', 'Database_Minus',
'Database_Move_Stack', 'Database_Remove', 'Fujitsu_Tablet',
'Harddrive', 'IBM_Tablet', 'iMac', 'iPad', 'Laptop', 'MacBook',
'Mainframe', 'Monitor', 'Monitor_Tower',
'Monitor_Tower_Behind', 'Netbook', 'Network', 'Network_2',
'Printer', 'Printer_Commercial', 'Secure_System', 'Server',
'Server_Rack', 'Server_Rack_Empty', 'Server_Rack_Partial',
'Server_Tower', 'Software', 'Stylus', 'Touch', 'USB_Hub',
'Virtual_Application', 'Virtual_Machine', 'Virus',
'Workstation' ], [ 'Antivirus', 'Data Filtering', 'Database',
'Database Add', 'Database Minus', 'Database Move Stack',
'Database Remove', 'Fujitsu Tablet', 'Harddrive', 'IBMTablet',
'iMac', 'iPad', 'Laptop', 'MacBook', 'Mainframe', 'Monitor',
'Monitor Tower', 'Monitor Tower Behind', 'Netbook', 'Network',
'Network 2', 'Printer', 'Printer Commercial', 'Secure System',
'Server', 'Server Rack', 'Server Rack Empty', 'Server Rack Partial',
'Server Tower', 'Software', 'Stylus', 'Touch', 'USB Hub',
'Virtual Application', 'Virtual Machine', 'Virus', 'Workstation']);
this.setCurrentSearchEntryLibrary('clipart', 'finance');
this.addImagePalette('finance', 'Clipart / Finance', imgDir
+ '/lib/clip_art/finance/', '_128x128.png', [ 'Arrow_Down',
'Arrow_Up', 'Coins', 'Credit_Card', 'Dollar', 'Graph',
'Pie_Chart', 'Piggy_Bank', 'Safe', 'Shopping_Cart',
'Stock_Down', 'Stock_Up'], ['Arrow_Down', 'Arrow Up',
'Coins', 'Credit Card', 'Dollar', 'Graph', 'Pie Chart',
'Piggy Bank', 'Safe', 'Shopping Basket', 'Stock Down', 'Stock Up']);
this.setCurrentSearchEntryLibrary('clipart', 'clipart');
this.addImagePalette('clipart', 'Clipart / Various', imgDir
+ '/lib/clip_art/general/', '_128x128.png', [ 'Battery_0',
'Battery_100', 'Battery_50', 'Battery_75', 'Battery_allstates',
'Bluetooth', 'Earth_globe', 'Empty_Folder', 'Full_Folder',
'Gear', 'Keys', 'Lock', 'Mouse_Pointer', 'Plug', 'Ships_Wheel',
'Star', 'Tire' ], [ 'Battery 0%', 'Battery 100%', 'Battery 50%',
'Battery 75%', 'Battery', 'Bluetooth', 'Globe',
'Empty Folder', 'Full Folder', 'Gear', 'Keys', 'Lock', 'Mousepointer',
'Plug', 'Ships Wheel', 'Star', 'Tire']);
this.setCurrentSearchEntryLibrary('clipart', 'networking');
this.addImagePalette('networking', 'Clipart / Networking', imgDir
+ '/lib/clip_art/networking/', '_128x128.png', ['Bridge',
'Certificate', 'Certificate_Off', 'Cloud', 'Cloud_Computer',
'Cloud_Computer_Private', 'Cloud_Rack', 'Cloud_Rack_Private',
'Cloud_Server', 'Cloud_Server_Private', 'Cloud_Storage',
'Concentrator', 'Email', 'Firewall_02', 'Firewall',
'Firewall-page1', 'Ip_Camera', 'Modem',
'power_distribution_unit', 'Print_Server',
'Print_Server_Wireless', 'Repeater', 'Router', 'Router_Icon',
'Switch', 'UPS', 'Wireless_Router', 'Wireless_Router_N'],
['Bridge', 'Certificate', 'Certificate Off', 'Cloud', 'Cloud Computer',
'Cloud Computer Private', 'Cloud Rack', 'Cloud Rack Private',
'Cloud Server', 'Cloud Server Private', 'Cloud Storage',
'Concentrator', 'Email', 'Firewall 1', 'Firewall 2',
'Firewall', 'Camera', 'Modem',
'Power Distribution Unit', 'Print Server',
'Print Server Wireless', 'Repeater', 'Router', 'Router Icon',
'Switch', 'UPS', 'Wireless Router', 'Wireless Router N'],
{'Wireless_Router': 'wireless router switch wap wifi access point wlan',
'Wireless_Router_N': 'wireless router switch wap wifi access point wlan',
'Router': 'router switch',
'Router_Icon': 'router switch'});
this.setCurrentSearchEntryLibrary('clipart', 'people');
this.addImagePalette('people', 'Clipart / People', imgDir
+ '/lib/clip_art/people/', '_128x128.png', ['Suit_Man',
'Suit_Man_Black', 'Suit_Man_Blue', 'Suit_Man_Green',
'Suit_Man_Green_Black', 'Suit_Woman', 'Suit_Woman_Black',
'Suit_Woman_Blue', 'Suit_Woman_Green',
'Suit_Woman_Green_Black', 'Construction_Worker_Man',
'Construction_Worker_Man_Black', 'Construction_Worker_Woman',
'Construction_Worker_Woman_Black', 'Doctor_Man',
'Doctor_Man_Black', 'Doctor_Woman', 'Doctor_Woman_Black',
'Farmer_Man', 'Farmer_Man_Black', 'Farmer_Woman',
'Farmer_Woman_Black', 'Nurse_Man', 'Nurse_Man_Black',
'Nurse_Woman',
'Nurse_Woman_Black',
'Military_Officer', 'Military_Officer_Black',
'Military_Officer_Woman', 'Military_Officer_Woman_Black',
'Pilot_Man', 'Pilot_Man_Black', 'Pilot_Woman',
'Pilot_Woman_Black', 'Scientist_Man', 'Scientist_Man_Black',
'Scientist_Woman', 'Scientist_Woman_Black', 'Security_Man',
'Security_Man_Black', 'Security_Woman', 'Security_Woman_Black',
'Tech_Man', 'Tech_Man_Black',
'Telesales_Man', 'Telesales_Man_Black', 'Telesales_Woman',
'Telesales_Woman_Black', 'Waiter', 'Waiter_Black',
'Waiter_Woman', 'Waiter_Woman_Black', 'Worker_Black',
'Worker_Man', 'Worker_Woman', 'Worker_Woman_Black']);
this.setCurrentSearchEntryLibrary('clipart', 'telco');
this.addImagePalette('telco', 'Clipart / Telecommunication', imgDir
+ '/lib/clip_art/telecommunication/', '_128x128.png', [
'BlackBerry', 'Cellphone', 'HTC_smartphone', 'iPhone',
'Palm_Treo', 'Signal_tower_off', 'Signal_tower_on' ],
['BlackBerry', 'Cellphone', 'HTC smartphone', 'iPhone',
'Palm Treo', 'Signaltower off', 'Signaltower on']);
this.setCurrentSearchEntryLibrary();
this.addFlowchartPalette();
this.addActiveDirectoryPalette();
this.addAndroidPalette();
this.addAtlassianPalette();
this.addBootstrapPalette();
this.addDFDPalette();
this.addErPalette();
this.addIos7Palette();
this.addIosPalette();
this.addKubernetesPalette();
this.addMockupPalette();
this.addSitemapPalette();
this.addUml25Palette();
this.addUmlPalette(false);
this.addAlliedTelesisPalette();
this.addAWS3Palette();
this.addAWS4bPalette();
this.addAWS4Palette();
this.addAWS3DPalette();
this.addAzurePalette();
this.addAzure2Palette();
this.addMSCAEPalette();
this.addC4Palette();
this.addCiscoPalette(cisco, dir);
this.addCisco19Palette();
this.addCiscoSafePalette();
this.addCumulusPalette();
this.addCitrixPalette();
this.addGCP2Palette();
this.addIBMPalette();
this.addNetworkPalette();
this.addOfficePalette();
this.addRackPalette(rack, dir);
this.addVeeamPalette();
this.addVeeam2Palette();
this.addVVDPalette();
this.addArchimate3Palette();
this.addArchiMatePalette();
this.addBpmn2Palette();
this.addSysMLPalette(sysml, dir);
this.addLeanMappingPalette();
this.addCabinetsPalette();
this.addInfographicPalette();
this.addEipPalette();
this.addElectricalPalette();
this.addFloorplanPalette();
this.addFluidPowerPalette();
this.addGMDLPalette();
this.addPidPalette(pids, dir);
this.addThreatModelingPalette();
this.addWebIconsPalette();
this.addWebLogosPalette();
this.addSignsPalette(signs, dir);
// LATER: Check if conflicts with restore libs after loading file
this.showEntries();
if (this.createdSearchIndex != null)
{
console.log('searchFileData', Graph.compress(JSON.stringify(this.createdSearchIndex)));
}
};
/**
* Overridden to manually create search index for stencil files which are not pre-loaded
* and no entries are created programmatically.
*/
if (urlParams['createindex'] == '1')
{
var sidebarAddStencilPalette = Sidebar.prototype.addStencilPalette;
Sidebar.prototype.addStencilPalette = function(id, title, stencilFile, style, ignore, onInit, scale, tags, customFns, groupId)
{
sidebarAddStencilPalette.apply(this, arguments);
scale = (scale != null) ? scale : 1;
// Used for creating index
mxStencilRegistry.loadStencilSet(stencilFile, mxUtils.bind(this, function(packageName, stencilName, displayName, w, h)
{
if (this.createdSearchIndex != null && ignore == null || mxUtils.indexOf(ignore, stencilName) < 0)
{
var entry = {style: 'shape=' + packageName + stencilName + style,
w: Math.round(w * scale), h: Math.round(h * scale)};
var tmpTags = (tags != null) ? tags[stencilName] : null;
if (tmpTags != null)
{
entry.tags = tmpTags;
}
if (groupId != null)
{
entry.id = groupId;
entry.lib = id;
}
this.createdSearchIndex.push(entry);
}
}), true);
};
}
/**
* Extracs icons from the search result.
*/
Sidebar.prototype.extractIconsFromResponse = function(res, results)
{
for (var i = 0; i < res.icons.length; i++)
{
var sizes = res.icons[i].raster_sizes;
var index = sizes.length - 1;
while (index > 0 && sizes[index].size > 128)
{
index--;
}
var size = sizes[index].size;
var url = sizes[index].formats[0].preview_url;
if (size != null && url != null)
{
(mxUtils.bind(this, function(s, u)
{
results.push(mxUtils.bind(this, function()
{
return this.createVertexTemplate('shape=image;html=1;verticalAlign=top;' +
'verticalLabelPosition=bottom;labelBackgroundColor=#ffffff;imageAspect=0;' +
'aspect=fixed;image=' + u, s, s, '');
}));
}))(size, url);
}
}
};
/**
* Adds server icon results to local search results
*/
var sidebarSearchEntries = Sidebar.prototype.searchEntries;
Sidebar.prototype.searchEntries = function(searchTerms, count, page, success, error)
{
var succ = success;
// Lazy-load indices
if (this.searchIndexData != null)
{
this.addSearchIndex(JSON.parse(Graph.decompress(this.searchIndexData)));
this.searchFileData = null;
}
// Logs search terms for improving search results
if (!this.editorUi.isOffline() && page == 0)
{
EditorUi.logEvent({category: 'Shape', action: 'search', label: searchTerms});
}
if (ICONSEARCH_PATH != null)
{
success = mxUtils.bind(this, function(results, len, more, terms)
{
if (!this.editorUi.isOffline() && results.length <= count / 4)
{
var pg = page - Math.ceil((len - count / 4) / count);
mxUtils.get(ICONSEARCH_PATH + '?q=' + encodeURIComponent(searchTerms) +
'&p=' + pg + '&c=' + count, mxUtils.bind(this, function(req)
{
try
{
if (req.getStatus() >= 200 && req.getStatus() <= 299)
{
// Ignore without error if no response
if (req.getText() != null && req.getText().length > 0)
{
try
{
var res = JSON.parse(req.getText());
if (res == null || res.icons == null)
{
succ(results, len, false, terms);
this.editorUi.handleError(res);
}
else
{
this.extractIconsFromResponse(res, results);
succ(results, (page - 1) * count + results.length, res.icons.length == count, terms);
}
}
catch (e)
{
succ(results, len, false, terms);
this.editorUi.handleError(e);
}
}
else
{
succ(results, len, false, terms);
}
}
else
{
succ(results, len, false, terms);
this.editorUi.handleError({message: mxResources.get('unknownError')});
}
}
catch (e)
{
succ(results, len, false, terms);
this.editorUi.handleError(e);
}
},
function()
{
succ(results, len, false, terms);
}));
}
else
{
succ(results, len, more || !this.editorUi.isOffline(), terms);
}
});
}
sidebarSearchEntries.apply(this, arguments);
};
/**
* Adds a click handler for inserting the cell as target for dangling edge.
*/
var sidebarItemClicked = Sidebar.prototype.itemClicked;
Sidebar.prototype.itemClicked = function(cells, ds, evt)
{
var graph = this.editorUi.editor.graph;
var handled = false;
if (cells != null && graph.getSelectionCount() == 1 && graph.getModel().isVertex(cells[0]))
{
var target = graph.cloneCell(cells[0]);
// Inserts cell as target of selected edge if not connected
if (graph.getModel().isEdge(graph.getSelectionCell()) && graph.getModel().getTerminal(graph.getSelectionCell(), false) == null &&
graph.getModel().isVertex(target))
{
graph.getModel().beginUpdate();
try
{
var edgeState = graph.view.getState(graph.getSelectionCell());
if (edgeState != null)
{
var tr = graph.view.translate;
var s = graph.view.scale;
var pt = edgeState.absolutePoints[edgeState.absolutePoints.length - 1];
target.geometry.x = pt.x / s - tr.x - target.geometry.width / 2;
target.geometry.y = pt.y / s - tr.y - target.geometry.height / 2;
}
graph.addCell(target);
graph.getModel().setTerminal(graph.getSelectionCell(), target, false);
if (evt == null || !mxEvent.isShiftDown(evt))
{
graph.fireEvent(new mxEventObject('cellsInserted', 'cells', [target]));
}
}
catch (e)
{
this.editorUi.handleError(e);
}
finally
{
graph.getModel().endUpdate();
}
graph.scrollCellToVisible(target);
graph.setSelectionCell(target);
handled = true;
}
}
if (!handled)
{
sidebarItemClicked.apply(this, arguments);
}
};
})();
|
module.exports = {
//---------------------------------------------------------------------
// Action Name
//
// This is the name of the action displayed in the editor.
//---------------------------------------------------------------------
name: "Control Variable",
//---------------------------------------------------------------------
// Action Section
//
// This is the section the action will fall into.
//---------------------------------------------------------------------
section: "Other Stuff",
//---------------------------------------------------------------------
// Action Subtitle
//
// This function generates the subtitle displayed next to the name.
//---------------------------------------------------------------------
subtitle: function(data) {
const storage = ['', 'Temp Variable', 'Server Variable', 'Global Variable'];
return `${storage[parseInt(data.storage)]} (${data.varName}) ${data.changeType === "1" ? "+=" : "="} ${data.value}`;
},
//---------------------------------------------------------------------
// Action Storage Function
//
// Stores the relevant variable info for the editor.
//---------------------------------------------------------------------
variableStorage: function(data, varType) {
const type = parseInt(data.storage);
if(type !== varType) return;
return ([data.varName, 'Unknown Type']);
},
//---------------------------------------------------------------------
// Action Fields
//
// These are the fields for the action. These fields are customized
// by creating elements with corresponding IDs in the HTML. These
// are also the names of the fields stored in the action's JSON data.
//---------------------------------------------------------------------
fields: ["storage", "varName", "changeType", "value"],
//---------------------------------------------------------------------
// Command HTML
//
// This function returns a string containing the HTML used for
// editting actions.
//
// The "isEvent" parameter will be true if this action is being used
// for an event. Due to their nature, events lack certain information,
// so edit the HTML to reflect this.
//
// The "data" parameter stores constants for select elements to use.
// Each is an array: index 0 for commands, index 1 for events.
// The names are: sendTargets, members, roles, channels,
// messages, servers, variables
//---------------------------------------------------------------------
html: function(isEvent, data) {
return `
<div>
<div style="float: left; width: 35%;">
Store In:<br>
<select id="storage" class="round">
${data.variables[1]}
</select>
</div>
<div id="varNameContainer" style="float: right; width: 60%;">
Variable Name:<br>
<input id="varName" class="round" type="text">
</div>
</div><br><br><br>
<div style="padding-top: 8px;">
<div style="float: left; width: 45%;">
Control Type:<br>
<select id="changeType" class="round">
<option value="0" selected>Set Value</option>
<option value="1">Add Value</option>
</select>
</div>
<div style="float: right; width: 50%;">
Value:<br>
<input id="value" class="round" type="text" name="is-eval"><br>
</div>
</div>`
},
//---------------------------------------------------------------------
// Action Editor Init Code
//
// When the HTML is first applied to the action editor, this code
// is also run. This helps add modifications or setup reactionary
// functions for the DOM elements.
//---------------------------------------------------------------------
init: function() {
},
//---------------------------------------------------------------------
// Action Bot Function
//
// This is the function for the action within the Bot's Action class.
// Keep in mind event calls won't have access to the "msg" parameter,
// so be sure to provide checks for variable existance.
//---------------------------------------------------------------------
action: function(cache) {
const data = cache.actions[cache.index];
const type = parseInt(data.storage);
const varName = this.evalMessage(data.varName, cache);
const storage = this.getVariable(type, varName, cache);
const isAdd = Boolean(data.changeType === "1");
let val = this.evalMessage(data.value, cache);
try {
val = this.eval(val, cache);
} catch(e) {
this.displayError(data, cache, e);
}
if(val !== undefined) {
if(isAdd) {
let result;
if(storage === undefined) {
result = val;
} else {
result = storage + val;
}
this.storeValue(result, type, varName, cache);
} else {
this.storeValue(val, type, varName, cache);
}
}
this.callNextAction(cache);
},
//---------------------------------------------------------------------
// Action Bot Mod
//
// Upon initialization of the bot, this code is run. Using the bot's
// DBM namespace, one can add/modify existing functions if necessary.
// In order to reduce conflictions between mods, be sure to alias
// functions you wish to overwrite.
//---------------------------------------------------------------------
mod: function(DBM) {
}
}; // End of module
|
const express = require('express');
const router = express.Router()
router.use((req, res, next) => {
if (req.method === 'POST') {
console.log(JSON.stringify(req.session.data, null, 2))
}
next()
})
// Query
router.post('/legacy/sprint49d/query', function(req, res) {
if (req.body['query'] === 'eligibility') {
res.redirect('date-of-birth');
} else {
res.redirect('/legacy/sprint49d/find');
}
});
// FIND SOMEONE AND SECURITY -------------------------------------------------
// Find someone to find result
router.post('/legacy/sprint49d/find', function(req, res) {
if (req.body['nino'] === 'XX987654X') {
res.redirect('/legacy/sprint49d/find-2');
} else if (req.body['nino'] === 'xx987654x') {
res.redirect('/legacy/sprint49d/find-2');
} else {
res.redirect('/legacy/sprint49d/find-1');
}
});
// Find result to security
router.post('/legacy/sprint49d/find-1', (req, res) => {
res.redirect('/legacy/sprint49d/security')
});
// Find result to security
router.post('/legacy/sprint49d/find-2', (req, res) => {
res.redirect('/legacy/sprint49d/security-2')
});
router.post('/legacy/sprint49d/security', (req, res) => {
res.redirect('/legacy/sprint49d/overview-returned')
});
router.post('/legacy/sprint49d/security-2', (req, res) => {
res.redirect('/legacy/sprint49d/overview-2')
});
// THIS IS WHAT YOU NEED TO CHANGE BACK!!!!!! ---------------------------
//-------------------------------------------------------------------------
//
router.post('/legacy/sprint49d/contact-preferences', (req, res) => {
res.redirect('/legacy/sprint49d/overview')
});
// CONTACT CHANGES -----------------------------------------------------------
// Correspondence address to address found
router.post('/legacy/sprint49d/correspondence-address', (req, res) => {
res.redirect('/legacy/sprint49d/correspondence-address-1')
});
// Correspondence address to address found
router.post('/legacy/sprint49d/correspondence-address-1', function(req, res) {
if (req.body['correspondence-address-change'] === 'no address found') {
res.redirect('correspondence-address-search');
} else {
res.redirect('contact');
}
});
router.post('/legacy/sprint49d/correspondence-address-search', (req, res) => {
res.redirect('/legacy/sprint49d/correspondence-address-search-result')
});
router.post('/legacy/sprint49d/correspondence-address-search-result', (req, res) => {
res.redirect('/legacy/sprint49d/contact')
});
// Home phone number change back to contact
router.post('/legacy/sprint49d/homephone', (req, res) => {
res.redirect('/legacy/sprint49d/contact')
});
// Home phone number removal
router.post('/legacy/sprint49d/homephone-remove', function(req, res) {
if (req.body['homephone-remove'] === 'Yes') {
res.redirect('contact');
} else {
res.redirect('homephone');
}
});
// Work phone number change back to contact
router.post('/legacy/sprint49d/workphone', (req, res) => {
res.redirect('/legacy/sprint49d/contact')
});
// Work phone number removal
router.post('/legacy/sprint49d/workphone-remove', function(req, res) {
if (req.body['workphone-remove'] === 'Yes') {
res.redirect('contact');
} else {
res.redirect('workphone');
}
});
// Mobile phone number change back to contact
router.post('/legacy/sprint49d/mobilephone', (req, res) => {
res.redirect('/legacy/sprint49d/contact')
});
// Mobile phone number removal
router.post('/legacy/sprint49d/mobilephone-remove', function(req, res) {
if (req.body['mobilephone-remove'] === 'yes') {
res.redirect('contact');
} else {
res.redirect('mobilephone');
}
});
// Email address change back to contact
router.post('/legacy/sprint49d/email', (req, res) => {
res.redirect('/legacy/sprint49d/contact')
});
// Email removal
router.post('/legacy/sprint49d/email-remove', function(req, res) {
if (req.body['email-remove'] === 'yes') {
res.redirect('contact');
} else {
res.redirect('email');
}
});
// Contact preference change back to contact
router.post('/legacy/sprint49d/contact-preferences', (req, res) => {
res.redirect('/legacy/sprint49d/contact')
});
// Address -------------------------------------------------------------------
router.post('/legacy/sprint49d/address', function(req, res) {
if (req.body['postcode'] === 'NE2 1YL') {
res.redirect('address-no-result');
} else if (req.body['postcode'] === "NE65 0AP") {
res.redirect('address-carehome');
} else {
res.redirect('address-1');
}
});
// Address select, yes or search address
router.post('/legacy/sprint49d/address-1', function(req, res) {
if (req.body['address-change'] === '27 Kent Street, Amble, NE65 0LZ') {
res.redirect('move-date');
} else {
res.redirect('address-search');
}
});
// Care home address select, yes or search address
router.post('/legacy/sprint49d/address-carehome', function(req, res) {
if (req.body['address-change'] === 'Dolphin View Care Home, Harbour Road, Amble, NE65 0AP') {
res.redirect('carehome-move-date');
} else {
res.redirect('address-search');
}
});
// Address search
router.post('/legacy/sprint49d/address-search', function(req, res) {
if (req.body['address-search-postcode'] === 'NE2 1YL') {
res.redirect('address-search-no-result');
} else {
res.redirect('address-search-result');
}
});
// Address search select, yes or search address
router.post('/legacy/sprint49d/address-search-result', function(req, res) {
if (req.body['address-search-change'] === '27 Kent Street, Amble, NE65 0LZ') {
res.redirect('move-date');
} else {
res.redirect('TBC');
}
});
// Move date
router.post('/legacy/sprint49d/move-date', (req, res) => {
res.redirect('/legacy/sprint49d/living-with')
});
// Care home move date
router.post('/legacy/sprint49d/carehome-move-date', (req, res) => {
res.redirect('/legacy/sprint49d/declaration')
});
router.post('/legacy/sprint49d/homephone-address', function(req, res) {
if (req.body["homephone-address"] === "Yes") {
res.redirect('homephone-address-change');
}
else if (req.session.data["movemonth"] === "08") {
res.redirect('living-with-q-week');
} else if (req.session.data["movemonth"] === "07") {
res.redirect('living-with-q-week');
} else if (req.session.data["movemonth"] === "7") {
res.redirect('living-with-q-week');
} else {
res.redirect('poa');
}
});
router.post('/legacy/sprint49d/homephone-address-change', function(req, res) {
if (req.session.data["movemonth"] === "08") {
res.redirect('living-with-q-week');
} else if (req.session.data["movemonth"] === "07") {
res.redirect('living-with-q-week');
} else if (req.session.data["movemonth"] === "7") {
res.redirect('living-with-q-week');
} else {
res.redirect('poa');
}
});
// Living with anyone at address change
router.post('/legacy/sprint49d/living-with', function(req, res) {
if (req.body['living-with'] === 'Lives with someone else who gets Winter Fuel Payment') {
res.redirect('living-with-age');
} else {
res.redirect('living-with-date');
}
});
router.post('/legacy/sprint49d/living-with-date', (req, res) => {
res.redirect('/legacy/sprint49d/homephone-address')
});
// Living with anyone at address change
router.post('/legacy/sprint49d/living-with-q-week', function(req, res) {
if (req.body['living-with-q-week'] === 'Lives with someone else who gets Winter Fuel Payment') {
res.redirect('living-with-age-q-week');
} else {
res.redirect('living-with-date');
}
});
// Power of attourney
router.post('/legacy/sprint49d/poa', function(req, res) {
if (req.body['poa'] === 'Yes') {
res.redirect('poa-people');
} else {
res.redirect('declaration');
}
});
router.post('/legacy/sprint49d/poa-people', (req, res) => {
res.redirect('/legacy/sprint49d/declaration')
});
// Declaration
router.post('/legacy/sprint49d/declaration', function(req, res) {
if (req.session.data["movemonth"] === "08") {
res.redirect('make-payment');
} else if (req.session.data["movemonth"] === "8") {
res.redirect('make-payment');
} else if (req.session.data["movemonth"] === "07") {
res.redirect('over-payment');
} else if (req.session.data["movemonth"] === "7") {
res.redirect('over-payment');
} else if (req.session.data["movemonth"] === "10") {
res.redirect('over-payment');
} else if (req.session.data["movemonth"] === "05") {
res.redirect('over-payment-2');
} else if (req.session.data["movemonth"] === "5") {
res.redirect('over-payment-2');
} else {
res.redirect('overview-changed');
}
});
// Overpayment recoverable?
router.post('/legacy/sprint49d/over-payment', (req, res) => {
res.redirect('/legacy/sprint49d/overview-changed')
})
;
// Overpayment recoverable?
router.post('/legacy/sprint49d/over-payment-2', (req, res) => {
res.redirect('/legacy/sprint49d/overview-changed')
})
;
// Check to payments
router.post('/legacy/sprint49d/recoverable-payment', (req, res) => {
res.redirect('/legacy/sprint49d/overview-recoverable')
});
// Check to payments
router.post('/legacy/sprint49d/check', (req, res) => {
res.redirect('/legacy/sprint49d/make-payment')
});
// Make payment to contact
router.post('/legacy/sprint49d/make-payment', (req, res) => {
res.redirect('/legacy/sprint49d/overview-topup-1')
});
// Living with age back to contact
router.post('/legacy/sprint49d/living-with-age', (req, res) => {
res.redirect('/legacy/sprint49d/living-with-date')
});
// Living with age back to contact
router.post('/legacy/sprint49d/living-with-age-q-week', (req, res) => {
res.redirect('/legacy/sprint49d/poa')
});
// PAYMENT CHANGES -----------------------------------------------------------
// Bank details change to bank confirm
router.post('/legacy/sprint49d/bankdetails', (req, res) => {
res.redirect('/legacy/sprint49d/confirm-bank')
});
// Bank confirm to payment
router.post('/legacy/sprint49d/confirm-bank', function(req, res) {
if (req.body['bank-name'] === 'Yes') {
res.redirect('payment');
} else {
res.redirect('bankdetails');
}
});
// Bank type to input
router.post('/legacy/sprint49d/reissue-bank-type', function(req, res) {
if (req.body['bank-account-type'] === 'uk') {
res.redirect('reissue-bank-uk');
} else {
res.redirect('reissue-bank-ig');
}
});
// Bank details to reissue
router.post('/legacy/sprint49d/reissue-bank-uk', (req, res) => {
res.redirect('/legacy/sprint49d/reissue-payment-uk')
});
router.post('/legacy/sprint49d/reissue-bank-ig', (req, res) => {
res.redirect('/legacy/sprint49d/reissue-payment-ig')
});
// Reissue payment to payment with confirmation and updated
router.post('/legacy/sprint49d/reissue-payment-uk', (req, res) => {
res.redirect('/legacy/sprint49d/payment-reissued-1')
});
router.post('/legacy/sprint49d/reissue-payment-ig', (req, res) => {
res.redirect('/legacy/sprint49d/payment-reissued-1')
});
// RETURNED PAYMENTS ---------------------------------------------------------
router.post('/legacy/sprint49d/change-payment-status', function(req, res) {
if (req.body['returned'] === 'yes') {
res.redirect('payment-returned-1');
} else {
res.redirect('payment');
}
});
// STOP PAYMENTS - OPTED OUT ---------------------------------------------------------
router.post('/legacy/sprint49d/stop-payments', function(req, res) {
if (req.body['stop-payments'] === 'yes') {
res.redirect('payment-opted-out');
} else {
res.redirect('payment');
}
});
// START PAYMENTS - OPTED IN ---------------------------------------------------------
router.post('/legacy/sprint49d/start-payments', function(req, res) {
if (req.body['start-payments'] === 'yes') {
res.redirect('payment-opted-in');
} else {
res.redirect('payment-opted-out');
}
});
module.exports = router;
|
import React, { Component } from "react";
import Fade from "react-reveal";
import Grid from '@material-ui/core/Grid';
import TextField from '@material-ui/core/TextField';
import Typography from '@material-ui/core/Typography';
import Button from '@material-ui/core/Button';
import Paper from '@material-ui/core/Paper';
import { makeStyles } from '@material-ui/core/styles';
import AvailabilityRadioButtons from "./AvailabilityRadioButtons";
import PositionRadioButtons from "./PositionRadioButtons";
class About extends Component {
constructor(props) {
super(props);
this.state = {
applyButtonPressed: false
}
}
missingInputWarning = () => {
if(this.state.applyButtonPressed && (this.props.mainState().firstName === "" || this.props.mainState().lastName === "" || this.props.mainState().fromEmail === "" || this.props.mainState().phoneNumber === "" || this.props.mainState().startDate === "")) {
return (
<div style={{marginTop: "1rem", marginBottom: "1rem", fontSize: 18, textAlign: 'left', color: "black"}}>
Failed to submit job application. Please fill in every field then try again.
</div>
)
}
}
render() {
if (!this.props.data) return null;
const profilepic = "images/" + this.props.data.careerImage;
const useStyles = makeStyles((theme) => ({
finish: {
padding: theme.spacing(.75),
width: '100%',
height: '100%',
maxWidth: '100%',
maxHeight: '100%',
backgroundColor: "#07080fdc",
borderRadius: "10%",
fontWeight: "700",
},
largeRadioButton: {
"& svg": {
width: "1em",
height: "1em"
}
}
}));
function handleSubmit(e){
e.preventDefault();
}
return (
<section id="careers">
<Fade duration={1000}>
<div className="row">
<div className="three columns">
<img
className="profile-pic"
src={profilepic}
alt="Career"
/>
</div>
<div className="nine columns main-col">
<h2 class="form-headers">Complete the form below to apply for a position with us</h2>
<Grid container direction="row" justifyContent="center">
<Grid item xs={12}>
<div style={{display: 'flex', justifyContent:'center', alignItems:'center', flexDirection:'column'}}>
<form id="input-box" noValidate autoComplete="off" onSubmit={handleSubmit}>
<TextField onChange={(event) => {
this.props.onChangeFirstName(event.target.value)
}} id="outlined-basic" style={{textAlign: 'left', backgroundColor: "white"}} label={<Typography id="typography">First name</Typography>} variant="outlined" inputProps={{min: 0, style: { textAlign: 'left', paddingTop: 30, fontSize: 20}}} />
</form>
<form id="input-box" noValidate autoComplete="off" onSubmit={handleSubmit}>
<TextField onChange={(event) => {
this.props.onChangeLastName(event.target.value)
}} id="outlined-basic" style={{textAlign: 'left', backgroundColor: "white"}} label={<Typography id="typography">Last name</Typography>} variant="outlined" inputProps={{min: 0, style: { textAlign: 'left', paddingTop: 30, fontSize: 20}}} />
</form>
<form id="input-box" noValidate autoComplete="off" onSubmit={handleSubmit}>
<TextField onChange={(event) => {
this.props.onChangeEmail(event.target.value)
}} id="outlined-basic" style={{textAlign: 'left', backgroundColor: "white"}} label={<Typography id="typography">Email</Typography>} variant="outlined" inputProps={{min: 0, style: { textAlign: 'left', paddingTop: 30, fontSize: 20}}} />
</form>
<form id="input-box" noValidate autoComplete="off" onSubmit={handleSubmit}>
<TextField onChange={(event) => {
this.props.onChangePhoneNumber(event.target.value)
}} id="outlined-basic" style={{textAlign: 'left', backgroundColor: "white"}} label={<Typography id="typography">Phone number</Typography>} variant="outlined" inputProps={{min: 0, style: { textAlign: 'left', paddingTop: 30, fontSize: 20}}} />
</form>
<form id="input-box" noValidate autoComplete="off" onSubmit={handleSubmit}>
<TextField onChange={(event) => {
this.props.onChangeStartDate(event.target.value)
}} id="outlined-basic" style={{textAlign: 'left', backgroundColor: "white"}} label={<Typography id="typography">When can you start? (MM/DD/YYYY)</Typography>} variant="outlined" inputProps={{min: 0, style: { textAlign: 'left', paddingTop: 30, fontSize: 20}}} />
</form>
</div>
</Grid>
</Grid>
<h2 class="form-headers">Position</h2>
<PositionRadioButtons onChangePosition={this.props.onChangePosition}/>
<h2 class="form-headers">Availability</h2>
<AvailabilityRadioButtons onChangeAvailability={this.props.onChangeAvailability}/>
{this.missingInputWarning()}
<Button style={{textTransform: 'none', float: 'right'}} onClick={() => {
this.setState({
applyButtonPressed: true
});
if(this.props.mainState().firstName !== "" && this.props.mainState().lastName !== "" && this.props.mainState().fromEmail !== "" && this.props.mainState().phoneNumber !== "" && this.props.mainState().startDate !== "") {
this.props.submitJobApplication();
}}}>
<Paper style={{fontSize: 25, color: 'white', backgroundColor: "#25274D", padding: .75, borderRadius: "7%", fontWeight: "700"}}>   Apply   </Paper>
</Button>
</div>
</div>
</Fade>
</section>
);
}
}
export default About;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.