code stringlengths 2 1.05M |
|---|
import createGetFormValues from '../getFormValues';
import plain from '../../structure/plain';
import plainExpectations from '../../structure/plain/expectations';
import immutable from '../../structure/immutable';
import immutableExpectations from '../../structure/immutable/expectations';
import addExpectations from '../../__tests__/addExpectations';
var describeGetFormValues = function describeGetFormValues(name, structure, expect) {
var getFormValues = createGetFormValues(structure);
var fromJS = structure.fromJS;
var getIn = structure.getIn;
describe(name, function () {
it('should return a function', function () {
expect(getFormValues('foo')).toBeA('function');
});
it('should get the form values from state', function () {
expect(getFormValues('foo')(fromJS({
form: {
foo: {
values: {
dog: 'Snoopy',
cat: 'Garfield'
}
}
}
}))).toEqualMap({
dog: 'Snoopy',
cat: 'Garfield'
});
});
it('should use getFormState if provided', function () {
expect(getFormValues('foo', function (state) {
return getIn(state, 'someOtherSlice');
})(fromJS({
someOtherSlice: {
foo: {
values: {
dog: 'Snoopy',
cat: 'Garfield'
}
}
}
}))).toEqualMap({
dog: 'Snoopy',
cat: 'Garfield'
});
});
});
};
describeGetFormValues('getFormValues.plain', plain, addExpectations(plainExpectations));
describeGetFormValues('getFormValues.immutable', immutable, addExpectations(immutableExpectations)); |
import context from 'context-utils';
export default function getContextOptions(viewName) {
if (context && context.uikit && context.uikit[viewName])
return context.uikit[viewName];
return {};
}
|
module.exports = require('mori');
|
'use strict';
/**
* Module dependencies
*/
var lotesPolicy = require('../policies/lotes.server.policy'),
lotes = require('../controllers/lotes.server.controller');
module.exports = function(app) {
// Lotes Routes
app.route('/api/lotes')
.get(lotes.list)
.post(lotes.create);
app.route('/api/lotes/:loteId')
.get(lotes.read)
.put(lotes.update)
.delete(lotes.delete);
app.route('/api/getfilterLote')
.get(lotes.getfilterLote);
// Finish by binding the Lote middleware
app.param('loteId', lotes.loteByID);
};
|
// Copyright (c) 2014 The Chromebleed Contributors. All rights reserved.
/*
Grays out or [whatever the opposite of graying out is called] the option
field.
*/
function ghost(isDeactivated) {
options.style.color = isDeactivated ? 'graytext' : 'black';
// The label color.
}
window.addEventListener('load', function() {
// Initialize the option controls.
options.isActivated.checked = JSON.parse(localStorage.isActivated);
options.isShowingAll.checked = JSON.parse(localStorage.isShowingAll);
options.isShowOnGoogle.checked = JSON.parse(localStorage.isShowOnGoogle);
if (!options.isActivated.checked) {
ghost(true);
}
// Set the display activation
options.isActivated.onchange = function() {
localStorage.isActivated = options.isActivated.checked;
ghost(!options.isActivated.checked);
console.log("isActivated:" + options.isActivated.checked);
//Visual icon for on Activated.
var icon_name = (options.isActivated.checked?"logo-ok48.png":"logo-off48.png")
var title = (options.isActivated.checked?"Notificatons Active!":"Notificatons Off!")
//also change the 'heartbleed' icon at top right of browser
chrome.browserAction.setIcon({path: icon_name});
//add tooltip with title
chrome.browserAction.setTitle({title: title});
};
// Set the showing of domains that seem Ok
options.isShowingAll.onchange = function() {
localStorage.isShowingAll = options.isShowingAll.checked;
console.log("isShowingAll:" + options.isShowingAll.checked);
};
// Set whether showing on Google search page
options.isShowOnGoogle.onchange = function() {
localStorage.isShowOnGoogle = options.isShowOnGoogle.checked;
console.log("isShowOnGoogle:" + options.isShowOnGoogle.checked);
};
// Clear cached sites on click
options.clearCachedSites.onclick = function() {
resetCachedSites();
resetCachedBleedSites();
alert('Cached Sites Cleared!');
//console.log(" Cached Sites after clear:" + JSON.stringify(cachedSites) + JSON.stringify(cachedBleedSites));
};
//Set the version
var name = chrome.app.getDetails().name;
var nameversion = name + ' (' + chrome.app.getDetails().version + ')';
document.getElementById("runningversion").innerHTML = nameversion;
document.getElementById("runningname").innerHTML = name;
}); |
/* eslint-env mocha */
'use strict'
const hat = require('hat')
const { getDescribe, getIt, expect } = require('../utils/mocha')
/** @typedef { import("ipfsd-ctl/src/factory") } Factory */
/**
* @param {Factory} common
* @param {Object} options
*/
module.exports = (common, options) => {
const describe = getDescribe(options)
const it = getIt(options)
describe('.key.gen', () => {
const keyTypes = [
{ type: 'rsa', size: 2048 }
]
let ipfs
before(async () => {
ipfs = (await common.spawn()).api
})
after(() => common.clean())
keyTypes.forEach((kt) => {
it(`should generate a new ${kt.type} key`, async function () {
this.timeout(20 * 1000)
const name = hat()
const key = await ipfs.key.gen(name, kt)
expect(key).to.exist()
expect(key).to.have.property('name', name)
expect(key).to.have.property('id')
})
})
})
}
|
/**
* Created by mark on 12/26/13.
*/
define([
'jquery',
'backbone',
'underscore',
'views/gauges/TemperatureFGaugeView',
'models/arduino-home/gauges/DhtGaugeIndoorModel'
],
function(
$,
Backbone,
_,
TemperatureFGaugeView,
DhtGaugeIndoorModel
) {
'use strict';
return TemperatureFGaugeView.extend({
initialize: function() {
this.model = new DhtGaugeIndoorModel();
this.render();
this.bindEvents();
},
render: function() {
this.renderGauge({
title: 'Indoor Temperature'
});
return this;
}
});
}
); |
// @flow
const { createReporter } = require(`yurnalist`)
const { get } = require(`lodash`)
const path = require(`path`)
const ProgressBar = require(`progress`)
const chalk = require(`chalk`)
const calcElapsedTime = require(`../../../util/calc-elapsed-time`)
const VERBOSE = process.env.gatsby_log_level === `verbose`
const reporter = createReporter({ emoji: true, verbose: VERBOSE })
/**
* Reporter module.
* @module reporter
*/
module.exports = {
/**
* Toggle verbosity.
* @param {boolean} [isVerbose=true]
*/
setVerbose(isVerbose = true) {
reporter.isVerbose = !!isVerbose
},
/**
* Turn off colors in error output.
*/
setColors() {},
success: reporter.success.bind(reporter),
error: details => {
const origError = get(details, `error.message`, null)
let locString = details.filePath
? path.relative(process.cwd(), details.filePath)
: null
if (locString) {
const lineNumber = get(details, `location.start.line`, null)
if (lineNumber) {
locString += `:${lineNumber}`
const columnNumber = get(details, `location.start.column`, null)
if (columnNumber) {
locString += `:${columnNumber}`
}
}
}
const text = `${details.id ? chalk.red(`#${details.id} `) : ``}${
details.type ? `${chalk.red(details.type)} ` : ``
}${origError ? origError : ``}\n\n${details.text}${
locString ? `\n\nFile: ${chalk.blue(locString)}` : ``
}${
details.docsUrl
? `\n\nSee our docs page for more info on this error: ${
details.docsUrl
}`
: ``
}`
reporter.error(text)
},
verbose: reporter.verbose.bind(reporter),
info: reporter.info.bind(reporter),
warn: reporter.warn.bind(reporter),
log: reporter.log.bind(reporter),
createActivity: activity => {
let start
if (activity.type === `spinner`) {
const spinner = reporter.activity()
let status
return {
update: newState => {
if (newState.startTime) {
start = newState.startTime
spinner.tick(activity.id)
}
if (newState.status) {
status = newState.status
spinner.tick(`${activity.id} — ${newState.status}`)
}
},
done: () => {
const str = status
? `${activity.id} — ${calcElapsedTime(start)} — ${status}`
: `${activity.id} — ${calcElapsedTime(start)}`
reporter.success(str)
spinner.end()
},
}
}
if (activity.type === `progress`) {
const bar = new ProgressBar(
` [:bar] :current/:total :elapsed s :percent ${activity.id}`,
{
total: 0,
width: 30,
clear: true,
}
)
return {
update: newState => {
if (newState.startTime) {
start = newState.startTime
}
if (newState.total) {
bar.total = newState.total
}
if (newState.current) {
bar.tick()
}
},
done: () => {
reporter.success(
`${activity.id} — ${bar.curr}/${bar.total} - ${calcElapsedTime(
start
)} s`
)
},
}
}
return {
update: () => {},
done: () => {},
}
},
}
|
/**
Copyright (c) 2007 Bill Orcutt (http://lilyapp.org, http://publicbeta.cx)
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.
*/
/**
* Construct a new modulo object
* @class
* @constructor
* @extends LilyObjectBase
*/
function $modulo(args)
{
var thisPtr=this;
this.inlet1=new this.inletClass("inlet1",this,"dividend");
this.inlet2=new this.inletClass("inlet2",this,"divisor");
this.outlet1=new this.outletClass("outlet1",this,"remainder");
var value=(+args)||1;
this.inlet1["num"]=function(msg) {
thisPtr.outlet1.doOutlet(msg%value);
}
this.inlet2["num"]=function(val) {
if(!isNaN(+val))
value=(+val);
}
return this;
}
var $moduloMetaData = {
textName:"%",
htmlName:"%",
objectCategory:"Math",
objectSummary:"Take the modulo of a number.",
objectArguments:"Modulo [1]"
} |
import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path d="M17 11h2v2h-2v2h2v2h-2v2h4V5h-9v1.4l5 3.57V11zm0-4h2v2h-2V7z" opacity=".3" /><path d="M10 3v1.97l.96.69L12 6.4V5h9v14h-4v2h6V3z" /><path d="M3 12v7h2v-5h6v5h2v-7L8 8.5z" opacity=".3" /><path d="M17 7h2v2h-2zm0 4h2v2h-2zm0 4h2v2h-2zM1 11v10h6v-5h2v5h6V11L8 6l-7 5zm12 8h-2v-5H5v5H3v-7l5-3.5 5 3.5v7z" /></React.Fragment>
, 'MapsHomeWorkTwoTone');
|
/**
* Economy
* Gold Server - http://gold.psim.us/
*
* Deals with economy commands, mostly.
* Functions for a lot of this can be found in: ./chat-plugins/goldusers.js
*
* @license MIT license
*/
'use strict';
const fs = require('fs');
let prices;
exports.commands = {
shop: function (target, room, user) {
if (!this.runBroadcast()) return;
if (room.id === 'lobby' && this.broadcasting) {
return this.sendReplyBox('<center>Click <button name="send" value="/shop" style="background-color: black; font-color: white;" title="Enter the Shop!"><font color="white"><b>here</button></b></font> to enter our shop!');
} else {
updatePrices();
let topStyle = 'background: linear-gradient(10deg, #FFF8B5, #eadf7c, #FFF8B5); color: black; border: 1px solid #635b00; padding: 2px; border-radius: 5px;';
let top = '<center><h3><b><u>Gold Bucks Shop</u></b></h3><table style="' + topStyle + '" border="1" cellspacing ="2" cellpadding="3"><tr><th>Item</th><th>Description</th><th>Cost</th></tr>';
let bottom = '</table><br /><b>Prices in the shop go up and down automatically depending on the amount of bucks the average user has at that given time.</b><br />To buy an item from the shop, click the respective button for said item.<br>Do /getbucks to learn more about how to obtain bucks. </center>';
return this.sendReply('|raw|' +
top +
shopTable("Symbol", "Buys a custom symbol to go infront of name and puts you towards the top of userlist (lasts 2 hrs from logout)", prices['symbol']) +
// shopTable("Declare", "Advertisement declare for a room on the server from an Administrator / Leader.", prices['declare']) +
shopTable("Fix", "Ability to modify a custom avatar, trainer card, or userlist icon.", prices['fix']) +
shopTable("Custom", "Buys a custom avatar to be applied to your name (you supply)", prices['custom']) +
shopTable("Animated", "Buys an animated avatar to be applied to your name (you supply)", prices['animated']) +
shopTable("Room", "Buys a public unofficial chat room - will be deleted if inactive. Must have a valid purpose; staff can reject making these.", prices['room']) +
shopTable("Musicbox", "A command that lists / links up to 8 of your favorite songs", prices['musicbox']) +
shopTable("Trainer", "Gives you a custom command - you provide the HTML and command name.", prices['trainer']) +
shopTable("Mystery Box", "Gives you a special surprise gift when you open it! (Could be good or bad!)", prices['pack']) +
shopTable("Emote", "A custom chat emoticon such as \"Kappa\" - must be 30x30", prices['emote']) +
shopTable("Color", "This gives your username a custom color on the userlist and in all rooms (existing at time of purchase)", prices['color']) +
shopTable("Icon", "This gives your username a custom userlist icon on our regular client - MUST be a Pokemon and has to be 32x32.", prices['icon']) +
shopTable("VIP Status", "Gives you the ability to change your custom symbol, avatar, custom color, and userlist icon as much as you wish, and it is also displayed in your profile.", prices['vip']) +
bottom
);
}
},
buy: function (target, room, user) {
updatePrices();
if (!target) return this.errorReply("You need to pick an item! Type /buy [item] to buy something.");
let parts = target.split(',');
let output = '';
let price;
function link(link, formatted) {
return '<a href="' + link + '" target="_blank">' + formatted + '</a>';
}
function moneyCheck(price) {
if (Gold.readMoney(user.userid) < price) return false;
if (Gold.readMoney(user.userid) >= price) return true;
}
function alertStaff(message, staffRoom) {
Gold.pmUpperStaff('/raw ' + message, '~Server', false);
if (staffRoom) {
Rooms.get('staff').add('|raw|<b>' + message + '</b>');
Rooms.get('staff').update();
}
}
function processPurchase(price, item, desc) {
if (!desc) desc = '';
if (Gold.readMoney(user.userid) < price) return false; // this should never happen
Gold.updateMoney(user.userid, -price);
logTransaction(user.name + ' has purchased a(n) ' + item + '. ' + desc);
}
switch (toId(parts[0])) {
case 'symbol':
price = prices['symbol'];
if (Gold.hasVip(user.userid)) return this.errorReply("You are a VIP user - you do not need to buy custom symbols from the shop. Use /customsymbol to change your symbol.");
if (!moneyCheck(price)) return this.errorReply("You do not have enough bucks for this item at this time, sorry.");
processPurchase(price, parts[0]);
this.sendReply("You have purchased a custom symbol. You will have this until you log off for more than an hour.");
this.sendReply("Use /customsymbol [symbol] to change your symbol now!");
user.canCustomSymbol = true;
break;
case 'custom':
case 'avatar':
case 'customavatar':
price = prices['custom'];
if (Gold.hasVip(user.userid)) return this.errorReply("You are a VIP user - you do not need to buy avatars from the shop. Use /customavatar to change your avatar.");
if (!moneyCheck(price)) return this.errorReply("You do not have enough bucks for this item at this time, sorry.");
if (!parts[1]) return this.errorReply("Usage: /buy avatar, [link to avatar]. Must be a PNG or JPG.");
let filepaths = ['.png', '.jpg'];
if (!~filepaths.indexOf(parts[1].substr(-4))) return this.errorReply("Your image for a regular custom avatar must be either a PNG or JPG. (If it is a valid file type, it will end in one of these)");
processPurchase(price, parts[0], 'Image: ' + parts[1]);
if (Config.customavatars[user.userid]) output = ' | <button name="send" value="/sca delete, ' + user.userid + '" target="_blank" title="Click this to remove current avatar.">Click2Remove</button>';
alertStaff(Gold.nameColor(user.name, true) + ' has purchased a custom avatar. Image: ' + link(parts[1].replace(' ', ''), 'desired avatar'), true);
alertStaff('<center><img src="' + parts[1] + '" width="80" height="80"><br /><button name="send" value="/sca set, ' + toId(user.name) + ', ' + parts[1] + '" target="_blank" title="Click this to set the above custom avatar.">Click2Set</button> ' + output + '</center>', false);
this.sendReply("You have bought a custom avatar from the shop. The staff have been notified and will set it ASAP.");
break;
case 'color':
case 'customcolor':
price = prices['color'];
if (Gold.hasVip(user.userid)) price = 0;
if (!moneyCheck(price)) return this.errorReply("You do not have enough bucks for this item at this time, sorry.");
if (!parts[1]) return this.errorReply("Usage: /buy color, [hex code OR name of an alt you want the color of]");
if (parts[1].length > 20) return this.errorReply("This is not a valid color, try again.");
processPurchase(price, parts[0], parts[1]);
alertStaff(Gold.nameColor(user.name, true) + ' has purchased a custom color. Color: ' + parts[1], true);
this.sendReply("You have purchased a custom color: " + parts[1] + " from the shop. Please screen capture this in case the staff do not get this message.");
break;
case 'emote':
case 'emoticon':
price = prices['emote'];
if (!moneyCheck(price)) return this.errorReply("You do not have enough bucks for this item at this time, sorry.");
if (!parts[1] || !parts[2]) return this.errorReply("Usage: /buy emote, [emote code], [image for the emote]");
let emoteFilepaths = ['.png', '.jpg', '.gif'];
if (!~emoteFilepaths.indexOf(parts[2].substr(-4))) return this.errorReply("Emoticons must be in one of the following formats: PNG, JPG, or GIF.");
if (Gold.emoticons.chatEmotes[parts[1].replace(' ', '')]) return this.errorReply("An emoticon with this trigger word already exists on this server.");
processPurchase(price, parts[0], 'Emote: ' + parts[1] + ' Link: ' + parts[2]);
alertStaff(Gold.nameColor(user.name, true) + " has purchased a custom emote. Emote \"" + parts[1].trim() + "\": " + link(parts[2].replace(' ', ''), 'desired emote'), true);
alertStaff('<center><img title=' + parts[1] + ' src=' + parts[2] + '><br /><button name="send" value="/emote add, ' + parts[1] + ', ' + parts[2] + '" target="_blank" title="Click to add the emoticon above.">Click2Add</button></center>', false);
this.sendReply("You have bought a custom emoticon from the shop. The staff have been notified and will add it ASAP.");
break;
case 'animated':
price = prices['animated'];
if (Gold.hasVip(user.userid)) return this.errorReply("You are a VIP user - you do not need to buy animated avatars from the shop. Use /customavatar to change your avatar.");
if (!moneyCheck(price)) return this.errorReply("You do not have enough bucks for this item at this time, sorry.");
if (!parts[1]) return this.errorReply("Usage: /buy animated, [link to avatar]. Must be a GIF.");
if (parts[1].split('.').pop() !== 'gif') return this.errorReply("Your animated avatar must be a GIF. (If it's a GIF, the link will end in .gif)");
processPurchase(price, parts[0], 'Image: ' + parts[1]);
if (Config.customavatars[user.userid]) output = ' | <button name="send" value="/sca delete, ' + user.userid + '" target="_blank" title="Click this to remove current avatar.">Click2Remove</button>';
alertStaff(Gold.nameColor(user.name, true) + ' has purchased a custom animated avatar. Image: ' + link(parts[1].replace(' ', ''), 'desired avatar'), true);
alertStaff('<center><img src="' + parts[1] + '" width="80" height="80"><br /><button name="send" value="/sca set, ' + toId(user.name) + ', ' + parts[1] + '" target="_blank" title="Click this to set the above custom avatar.">Click2Set</button> ' + output + '</center>', false);
this.sendReply("You have purchased a custom animated avatar. The staff have been notified and will add it ASAP.");
break;
case 'room':
case 'chatroom':
price = prices['room'];
if (!moneyCheck(price)) return this.errorReply("You do not have enough bucks for this item at this time, sorry.");
if (!parts[1]) return this.errorReply("Usage: /buy room, [room name]");
let bannedRoomNames = [',', '|', '[', '-'];
if (~bannedRoomNames.indexOf(parts[1])) return this.errorReply("This room name is not valid, try again.");
processPurchase(price, parts[0], 'Room name: ' + parts[1]);
alertStaff(Gold.nameColor(user.name, true) + ' has purchased a chat room. Room name: ' + parts[1], true);
this.sendReply("You have purchased a room. The staff have been notified and it will be created shortly as long as it meets our basic rules.");
break;
case 'trainer':
case 'trainercard':
price = prices['trainer'];
if (!moneyCheck(price)) return this.errorReply("You do not have enough bucks for this item at this time, sorry.");
processPurchase(price, parts[0]);
alertStaff(Gold.nameColor(user.name, true) + ' has purchased a trainer card.', true);
this.sendReply("|html|You have purchased a trainer card. Please use <a href=http://goldservers.info/site/trainercard.html>this</a> to make your trainer card and then PM a leader or administrator the HTML with the command name you want it to have.");
break;
case 'mb':
case 'musicbox':
price = prices['musicbox'];
if (!moneyCheck(price)) return this.errorReply("You do not have enough bucks for this item at this time, sorry.");
if (!Gold.createMusicBox(user)) return this.errorReply("You already have a music box! There's no need to buy another.");
processPurchase(price, parts[0]);
alertStaff(Gold.nameColor(user.name, true) + ' has purchased a music box.', true);
Gold.createMusicBox(user); // give the user a music box
this.parse('/' + toId(parts[0]) + ' help');
this.sendReply("You have purchased a music box. You may have a maximum of 8 songs in it.");
break;
case 'fix':
price = prices['fix'];
if (Gold.hasVip(user.userid)) price = 0;
if (!moneyCheck(price)) return this.errorReply("You do not have enough bucks for this item at this time, sorry.");
processPurchase(price, parts[0]);
alertStaff(Gold.nameColor(user.name, true) + ' has purchased a fix from the shop.', true);
user.canFixItem = true;
this.sendReply("You have purchased a fix from the shop. You can use this to alter your trainer card, music box, or custom chat emoticon. PM a leader or administrator to proceed.");
break;
/*
case 'ad':
case 'declare':
price = prices['declare'];
if (Gold.hasVip(user.userid)) price = 0;
if (!moneyCheck(price)) return this.errorReply("You do not have enough bucks for this item at this time, sorry.");
processPurchase(price, parts[0]);
alertStaff(Gold.nameColor(user.name, true) + ' has purchased the ability to declare from the shop.', true);
this.sendReply("You have purchased an advertisement declare from the shop. Please prepare an advertisement for your room; a leader or administrator will soon be PMing you to proceed.");
break;
*/
case 'userlisticon':
case 'icon':
price = prices['icon'];
if (Gold.hasVip(user.userid)) price = 0;
if (!moneyCheck(price)) return this.errorReply("You do not have enough bucks for this item at this time, sorry.");
if (!parts[1] || parts[1].length < 3) return this.errorReply("Usage: /buy icon, [32x32 icon image]");
let iconFilepaths = ['.png', '.jpg', '.gif'];
if (!~iconFilepaths.indexOf(parts[1].substr(-4))) return this.errorReply("Your image for a custom userlist icon must be a PNG, JPG, or GIF.");
processPurchase(price, parts[0], 'Image: ' + parts[1]);
alertStaff(Gold.nameColor(user.name, true) + ' has purchased a custom userlist icon. Image: ' + link(parts[1].replace(' ', ''), 'desired icon'), true);
alertStaff('<center><button name="send" value="/icon ' + user.userid + ', ' + parts[1] + '" target="_blank" title="Click this to set the above custom userlist icon.">Click2Set</button></center>', false);
this.sendReply("You have purchased a custom userlist icon. The staff have been notified and this will be added ASAP.");
break;
case 'vip':
case 'vipstatus':
price = prices['vip'];
if (!moneyCheck(price)) return this.errorReply("You do not have enough bucks for this item at this time, sorry.");
processPurchase(price, parts[0]);
Gold.modifyBadge(user.userid, 'vip', 'GIVE');
alertStaff(Gold.nameColor(user.name, true) + " has purchased VIP Status from the shop and they have recieved it automatically from the server.", true);
break;
case 'mysterybox':
case 'pack':
case 'magicpack':
price = prices['pack'];
if (!moneyCheck(price)) return this.errorReply("You do not have enough bucks for this item at this time, sorry.");
if (room.id !== 'lobby') return this.errorReply("You must buy this item in the Lobby!");
processPurchase(price, parts[0]);
let randomNumber = Math.floor((Math.random() * 100) + 1);
let prize = '';
let goodBad = '';
let opts;
if (randomNumber < 70) {
goodBad = 'bad';
opts = ['nothing', 'rick rolled', 'meme avatar', 'kick from Lobby', '2 minute mute'];
prize = opts[Math.floor(Math.random() * opts.length)];
} else if (randomNumber > 70) {
goodBad = 'good';
opts = ['100 bucks', '125 bucks', 'a custom symbol', 'a custom userlist icon', 'ability to get Dubtrack VIP', 'ability to set the PotD', 'custom color', 'the cost of the mystery box back', 'ability to have a leader/admin broadcast an image to Lobby', 'a kind, warm hearted thank you'];
prize = opts[Math.floor(Math.random() * opts.length)];
}
switch (prize) {
// good
case '100 bucks':
Gold.updateMoney(user.userid, 100);
break;
case '125 bucks':
Gold.updateMoney(user.userid, 125);
break;
case 'the cost of the mystery box back':
Gold.updateMoney(user.userid, prices['pack']);
break;
case 'ability to get Dubtrack VIP':
case 'ability to have a leader/admin broadcast an image to Lobby':
case 'custom color':
case 'ability to set the PotD':
alertStaff(Gold.nameColor(user.name, true) + " has won an " + prize + ". Please PM them to proceed with giving them this.", true);
break;
case 'a custom symbol':
user.canCustomSymbol = true;
this.sendReply("Do /customsymbol [symbol] to set a FREE custom symbol! (Do /rs to reset your custom symbol when you want to remove it later.)");
break;
case 'a kind, warm hearted thank you':
this.sendReply("THANK U 8D!");
break;
case 'a custom userlist icon':
this.sendReply("PM a leader or administrator to claim this prize!");
break;
// bad
case 'nothing':
break;
case 'meme avatar':
opts = ['notpawn.png', 'notpawn2.png'];
user.avatar = opts[Math.floor(Math.random() * opts.length)];
break;
case 'kick from Lobby':
try {
user.leaveRoom('lobby');
user.popup("You have been kicked from the Lobby by the Mystery Box!");
} catch (e) {}
break;
case '2 minute mute':
try {
Rooms('lobby').mute(user, 2 * 60 * 1000, false);
} catch (e) {}
break;
case 'rick rolled':
Rooms('lobby').add("|raw|<blink>" +
"Never gonna give you up<br />" +
"Never gonna let you down<br />" +
"Never gonna run around and desert you<br />" +
"Never gonna make you cry<br />" +
"Never gonna say goodbye<br />" +
"Never gonna tell a lie and hurt you</blink>").update();
break;
default:
this.sendReply("Oh oh... this shouldn't of happened. Please message an Administrator and take a screencap of this. (Problem with mysterybox)");
break;
}
Rooms('lobby').add("|raw|" + Gold.nameColor(user.name, true) + " has bought a Magic Pack from the shop! " + (goodBad === 'good' ? "They have won a(n) <b>" + prize + "</b>!" : "Oh no! They got a " + prize + " from their pack :(")).update();
break;
default:
this.errorReply("Shop item not found. Check spelling?");
}
},
awardbucks: 'givebucks',
gb: 'givebucks',
givebucks: function (target, room, user) {
if (!user.can('pban')) return this.errorReply("You do not have enough authority to do this.");
let parts = target.split(',');
if (!parts[1]) return this.errorReply("Usage: /givebucks [user], [amount]");
for (let u in parts) parts[u] = parts[u].trim();
let targetUser = parts[0];
if (targetUser.length < 1 || toId(targetUser).length > 18) return this.errorReply("Usernames cannot be this length.");
let amount = Math.round(Number(toId(parts[1])));
//checks
if (isNaN(amount)) return this.errorReply("The amount you give must be a number.");
if (amount < 1) return this.errorReply("You can't give less than one buck.");
if (amount > 1000) return this.errorReply("You cannot give more than 1,000 bucks at once.");
//give the bucks
Gold.updateMoney(toId(targetUser), amount);
//send replies
let amountLbl = amount + " Gold buck" + Gold.pluralFormat(amount, 's');
logTransaction(user.name + " has given " + amountLbl + " to " + targetUser + ".");
this.sendReply("You have given " + amountLbl + " to " + targetUser + ".");
if (Users(targetUser)) Users(targetUser).popup("|modal|" + user.name + " has given " + amountLbl + " to you.");
},
takebucks: 'removebucks',
removebucks: function (target, room, user) {
if (!user.can('pban')) return this.errorReply("You do not have enough authority to do this.");
let parts = target.split(',');
if (!parts[1]) return this.errorReply("Usage: /removebucks [user], [amount]");
for (let u in parts) parts[u] = parts[u].trim();
let targetUser = parts[0];
if (targetUser.length < 1 || toId(targetUser).length > 18) return this.errorReply("Usernames cannot be this length.");
let amount = Math.round(Number(toId(parts[1])));
if (amount > Gold.readMoney(targetUser)) return this.errorReply("You cannot remove more bucks than the user has.");
//checks
if (isNaN(amount)) return this.errorReply("The amount you remove must be a number.");
if (amount < 1) return this.errorReply("You can't remove less than one buck.");
if (amount > 1000) return this.errorReply("You cannot remove more than 1,000 bucks at once.");
//take the bucks
Gold.updateMoney(toId(targetUser), -amount);
//send replies
let amountLbl = amount + " Gold buck" + Gold.pluralFormat(amount, 's');
logTransaction(user.name + " has removed " + amountLbl + " from " + targetUser + ".");
this.sendReply("You have removed " + amountLbl + " from " + targetUser + ".");
if (Users(targetUser)) Users(targetUser).popup("|modal|" + user.name + " has removed " + amountLbl + " from you.");
},
tb: 'transferbucks',
transferbucks: function (target, room, user) {
let parts = target.split(',');
if (!parts[1]) return this.errorReply("Usage: /transferbucks [user], [amount]");
for (let u in parts) parts[u] = parts[u].trim();
let targetUser = parts[0];
if (targetUser.length < 1 || toId(targetUser).length > 18) return this.errorReply("Usernames cannot be this length.");
let amount = Math.round(Number(parts[1]));
//checks
if (isNaN(amount)) return this.errorReply("The amount you transfer must be a number.");
if (amount < 1) return this.errorReply("Cannot be less than 1.");
if (toId(targetUser) === user.userid) return this.errorReply("You cannot transfer bucks to yourself.");
if (Gold.readMoney(user.userid) < amount) return this.errorReply("You cannot transfer more than you have.");
//finally, transfer the bucks
Gold.updateMoney(user.userid, Number(-amount));
Gold.updateMoney(targetUser, Number(amount));
//log the transaction
let amountLbl = amount + " Gold buck" + Gold.pluralFormat(amount, 's');
logTransaction(user.name + " has transfered " + amountLbl + " to " + targetUser);
//send return messages
this.sendReply("You have transfered " + amountLbl + " to " + targetUser + ".");
let targetUserConnected = Users(parts[0]);
if (targetUserConnected) {
targetUserConnected.popup("|modal|" + user.name + " has transferred " + amountLbl + " to you.");
targetUserConnected.sendTo(room, "|raw|<b>" + Gold.nameColor(user.name, false) + " has transferred " + amountLbl + " to you.</b>");
}
},
'!atm': true,
balance: 'atm',
wallet: 'atm',
satchel: 'atm',
fannypack: 'atm',
purse: 'atm',
bag: 'atm',
bank: 'atm',
atm: function (target, room, user) {
if (!this.runBroadcast()) return;
if (!target) target = user.name;
let output = "<u>Gold Wallet:</u><br />", bucks = Gold.readMoney(target);
output += Gold.nameColor(target, true) + ' ' + (bucks === 0 ? "does not have any Gold bucks." : "has " + bucks + " Gold buck" + Gold.pluralFormat(bucks, 's') + ".");
return this.sendReplyBox(output);
},
'!richestuser': true,
whosgotthemoneyz: 'richestuser',
richestusers: 'richestuser',
richestuser: function (target, room, user) {
if (!this.runBroadcast()) return;
let number = (target && !~target.indexOf('.') && target > 1 && !isNaN(target) ? Number(target) : 10);
if (this.broadcasting && number > 10) number = 10; // limit to 10 when broadcasting
return this.sendReplyBox(Gold.richestUsers(number));
},
moneylog: function (target, room, user) {
if (!this.can('hotpatch')) return false;
if (!target) return this.errorReply("Usage: /moneylog [number] to view the last x lines OR /moneylog [text] to search for text.");
let word = false;
if (isNaN(Number(target))) word = true;
let lines = fs.readFileSync('logs/transactions.log', 'utf8').split('\n').reverse();
let output = '';
let count = 0;
let regex = new RegExp(target.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), "gi");
if (word) {
output += 'Displaying last 50 lines containing "' + target + '":\n';
for (let line in lines) {
if (count >= 50) break;
if (!~lines[line].search(regex)) continue;
output += lines[line] + '\n';
count++;
}
} else {
if (target > 100) target = 100;
output = lines.slice(0, (lines.length > target ? target : lines.length));
output.unshift("Displaying the last " + (lines.length > target ? target : lines.length) + " lines:");
output = output.join('\n');
}
user.popup(output);
},
cs: 'customsymbol',
customsymbol: function (target, room, user) {
if (!user.canCustomSymbol && !Gold.hasVip(user.userid)) return this.errorReply("You don't have the permission to use this command.");
if (user.hasCustomSymbol) return this.errorReply("You currently have a custom symbol, use /resetsymbol if you would like to use this command again.");
if (!this.canTalk()) return;
if (!target || target.length > 1) return this.errorReply("/customsymbol [symbol] - changes your symbol (usergroup) to the specified symbol. The symbol can only be one character");
if (~target.indexOf('\u202e')) return this.errorReply("nono riperino");
let bannedSymbols = /[ +<>$%‽!★@&~#*卐|A-z0-9]/;
if (target.match(bannedSymbols)) return this.errorReply("That symbol is banned.");
user.getIdentity = function (roomid) {
if (this.locked) return '‽' + this.name;
if (roomid) {
let room = Rooms(roomid);
if (room.isMuted(this)) return '!' + this.name;
if (room && room.auth) {
if (room.auth[this.userid]) return room.auth[this.userid] + this.name;
if (room.isPrivate === true) return ' ' + this.name;
}
}
return target + this.name;
};
user.updateIdentity();
user.canCustomSymbol = false;
user.hasCustomSymbol = true;
return this.sendReply("Your symbol has been set.");
},
rs: 'resetsymbol',
resetsymbol: function (target, room, user) {
if (!user.hasCustomSymbol) return this.errorReply("You don't have a custom symbol!");
user.hasCustomSymbol = false;
delete user.getIdentity;
user.updateIdentity();
this.sendReply('Your symbol has been reset.');
},
'!economy': true,
economy: function (target, room, user) {
if (!this.runBroadcast()) return;
let econ = Gold.moneyCirculating();
return this.sendReplyBox("<b>Total bucks in economy:</b> " + econ[0] + "<br /><b>The average user has:</b> " + econ[1] + " bucks.<br />At least " + econ[2] + " users have 1 buck.");
},
};
// local functions
function logTransaction(message) {
if (!message) return false;
fs.appendFile('logs/transactions.log', '[' + new Date().toUTCString() + '] ' + message + '\n');
}
function updatePrices() {
let avg = Gold.moneyCirculating()[1];
prices = {
'symbol': Math.round(avg * 0.035),
// 'declare': Math.round(avg * 0.19),
'fix': Math.round(avg * 0.2),
'custom': Math.round(avg * 0.55),
'animated': Math.round(avg * 0.65),
'room': Math.round(avg * 0.53),
'musicbox': Math.round(avg * 0.4),
'trainer': Math.round(avg * 0.4),
'emote': Math.round(avg * 2.5),
'color': Math.round(avg * 4.5),
'icon': Math.round(avg * 4.5),
'pack': Math.round(avg * 1),
'vip': Math.round(avg * 25),
};
}
function shopTable(item, desc, price) {
let buttonStyle = 'border-radius: 5px; background: linear-gradient(-30deg, #fff493, #e8d95a, #fff493); color: black; text-shadow: 0px 0px 5px #d6b600; border-bottom: 2px solid #635b00; border-right: 2px solid #968900; width: 100%;';
let descStyle = 'border-radius: 5px; border: 1px solid #635b00; background: #fff8b5; color: black;';
let priceStyle = 'border-radius: 5px; border: 1px solid #635b00; background: #fff8b5; color: black; font-weight: bold; text-align: center;';
return '<tr><td style="' + descStyle + '"><button title="Click this button to buy a(n) ' + item + ' from the shop." style="' + buttonStyle + '" name="send" value="/buy ' + item + '">' + item + '</button></td><td style="' + descStyle + '">' + desc + '</td><td style="' + priceStyle + '">' + price + '</td></tr>';
}
|
'use strict';
import detailModule from './detail/detail';
export default {
init(){
var that = this;
$(document).on('pageBeforeInit', (e) => {
that.pageBeforeInit(e.detail.page);
});
},
pageBeforeInit(page){
switch (page.name) {
case 'detail':
detailModule.init(page);
break;
default:
break;
}
}
}; |
#!/usr/bin/env node
require("./proof")(1, function (parse, equal) {
try {
parse("b8z<0x0A,a>")
} catch (e) {
equal(e.message, "invalid terminator at character 10", "parse bad terminator");
}
});
|
/*
THIS IS JUST A SCRATCH FILE FOR TESTING AND DEBUGGING.
Working with JS in PG is still a little raw, so easier to play using node and move across.
*/
// var json = '{"uuid":"ba596c94-9e50-11e1-a50e-70cd60fffe0e","integer":10,"string":"Blick","date":"2012-05-11T15:42:15+10:00","boolean":true,"numeric":99.9,"object":{"string":"Ullrich","array":[3428,7389,5166,5823,3566,6086,3087,7690,6374,4531,6019,9722,8793,6732,5264,9618,5843,6714,5160,4065,2102,4972,2778,6110,4357,4385,1296,7981,607,3104,4992,8207,7517,1932,8097,2626,5196,425,8803,4778,7814,5337,9467,200,3542,4001,5930,4646,7304,4033,4838,7539,648,7016,6377,7957,7411,4023,7105,3676,9195,2337,8259,9166,9972,4740,7705,5368,5815,2592,5569,4842,6577,3805,1473,8585,9371,8732,9491,3819,7517,3437,6342,3397,8603,5324,676,7922,813,9850,8032,9324,733,5436,2971,9878,1648,6248,2109,1422]}}';
function test(ret) {
var ret = ret.boolean;
// console.log(ret);
// console.log(ret == true);
if (ret === true || ret === false) {
console.log("bool:"+ret);
} else {
console.log("null!");
}
// if (ret != true || ret != false) {
// console.log("null!");
// } else {
// console.log("bool:"+ret);
// }
}
test(JSON.parse('{"boolean":true}'));
test(JSON.parse('{"boolean":false}'));
test(JSON.parse('{"boolean":1}'));
test(JSON.parse('{"boolean":0}'));
test(JSON.parse('{"boolean":"true"}'));
test(JSON.parse('{"boolean":"false"}'));
test(JSON.parse('{"boolean":"100"}'));
// var data ='{"count":[99], "date":"2012-05-08T15:42:15+10:00", "object": {"test":[10]}}';
// var value = '99';
// // var value = '99';
// // var key = "object.vtha"
// var key = "date"
// var data = JSON.parse(data);
// var value = JSON.parse(value);
// var keys = key.split('.')
// var len = keys.length;
// var ret = data;
// // var ret = JSON.parse(data);
// for (var i=0; i<len; ++i) {
// if (ret != null) ret = ret[keys[i]];
// }
// //ret = Date.parse(ret)
// //if (isNaN(ret)) ret = null;
// ret = new Date(ret)
// if (isNaN(ret.getTime())) ret = null;
// console.log(ret);
// for (var i=0; i<len; ++i) {
// if (field) field = field[keys[i]];
// }
// if (field) {
// var idx = field.indexOf(value);
// console.log(idx);
// if (idx != -1) {
// field = field.slice(idx,1);
// console.log(field);
// }
// }
// for (var i=0; i<len; ++i) {
// last_field = field;
// if (field) field = field[keys[i]];
// }
// if (field) {
// field.push(value)
// } else {
// if (! (value instanceof Array)) {
// value = [value];
// }
// last_field[keys.pop()]= value;
// }
// for (var i=0; i<len; ++i) {
// last_field = field;
// if (field) field = field[keys[i]];
// }
// // if (field == null) field = last_field;
// console.log(last_field)
// console.log(field)
// field.push(value)
// if (field && field.indexOf(value) == -1) {
// field.push(value)
// } else {
// if (! (value instanceof Array)) {
// value = [value];
// }
// last_field[keys.pop()]= value;
// }
// console.log(data)
|
/*
Leaflet, a JavaScript library for mobile-friendly interactive maps. http://leafletjs.com
(c) 2010-2013, Vladimir Agafonkin
(c) 2010-2011, CloudMade
*/
! function(t, e, i) {
var n = t.L,
o = {};
o.version = "0.7.3", "object" == typeof module && "object" == typeof module.exports ? module.exports = o : "function" == typeof define && define.amd && define(o), o.noConflict = function() {
return t.L = n, this
}, t.L = o, o.Util = {
extend: function(t) {
var e, i, n, o, s = Array.prototype.slice.call(arguments, 1);
for (i = 0, n = s.length; n > i; i++) {
o = s[i] || {};
for (e in o) o.hasOwnProperty(e) && (t[e] = o[e])
}
return t
},
bind: function(t, e) {
var i = arguments.length > 2 ? Array.prototype.slice.call(arguments, 2) : null;
return function() {
return t.apply(e, i || arguments)
}
},
stamp: function() {
var t = 0,
e = "_leaflet_id";
return function(i) {
return i[e] = i[e] || ++t, i[e]
}
}(),
invokeEach: function(t, e, i) {
var n, o;
if ("object" == typeof t) {
o = Array.prototype.slice.call(arguments, 3);
for (n in t) e.apply(i, [n, t[n]].concat(o));
return !0
}
return !1
},
limitExecByInterval: function(t, e, i) {
var n, o;
return function s() {
var a = arguments;
return n ? void(o = !0) : (n = !0, setTimeout(function() {
n = !1, o && (s.apply(i, a), o = !1)
}, e), void t.apply(i, a))
}
},
falseFn: function() {
return !1
},
formatNum: function(t, e) {
var i = Math.pow(10, e || 5);
return Math.round(t * i) / i
},
trim: function(t) {
return t.trim ? t.trim() : t.replace(/^\s+|\s+$/g, "")
},
splitWords: function(t) {
return o.Util.trim(t).split(/\s+/)
},
setOptions: function(t, e) {
return t.options = o.extend({}, t.options, e), t.options
},
getParamString: function(t, e, i) {
var n = [];
for (var o in t) n.push(encodeURIComponent(i ? o.toUpperCase() : o) + "=" + encodeURIComponent(t[o]));
return (e && -1 !== e.indexOf("?") ? "&" : "?") + n.join("&")
},
template: function(t, e) {
return t.replace(/\{ *([\w_]+) *\}/g, function(t, n) {
var o = e[n];
if (o === i) throw new Error("No value provided for variable " + t);
return "function" == typeof o && (o = o(e)), o
})
},
isArray: Array.isArray || function(t) {
return "[object Array]" === Object.prototype.toString.call(t)
},
emptyImageUrl: "data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs="
},
function() {
function e(e) {
var i, n, o = ["webkit", "moz", "o", "ms"];
for (i = 0; i < o.length && !n; i++) n = t[o[i] + e];
return n
}
function i(e) {
var i = +new Date,
o = Math.max(0, 16 - (i - n));
return n = i + o, t.setTimeout(e, o)
}
var n = 0,
s = t.requestAnimationFrame || e("RequestAnimationFrame") || i,
a = t.cancelAnimationFrame || e("CancelAnimationFrame") || e("CancelRequestAnimationFrame") || function(e) {
t.clearTimeout(e)
};
o.Util.requestAnimFrame = function(e, n, a, r) {
return e = o.bind(e, n), a && s === i ? void e() : s.call(t, e, r)
}, o.Util.cancelAnimFrame = function(e) {
e && a.call(t, e)
}
}(), o.extend = o.Util.extend, o.bind = o.Util.bind, o.stamp = o.Util.stamp, o.setOptions = o.Util.setOptions, o.Class = function() {}, o.Class.extend = function(t) {
var e = function() {
this.initialize && this.initialize.apply(this, arguments), this._initHooks && this.callInitHooks()
}, i = function() {};
i.prototype = this.prototype;
var n = new i;
n.constructor = e, e.prototype = n;
for (var s in this) this.hasOwnProperty(s) && "prototype" !== s && (e[s] = this[s]);
t.statics && (o.extend(e, t.statics), delete t.statics), t.includes && (o.Util.extend.apply(null, [n].concat(t.includes)), delete t.includes), t.options && n.options && (t.options = o.extend({}, n.options, t.options)), o.extend(n, t), n._initHooks = [];
var a = this;
return e.__super__ = a.prototype, n.callInitHooks = function() {
if (!this._initHooksCalled) {
a.prototype.callInitHooks && a.prototype.callInitHooks.call(this), this._initHooksCalled = !0;
for (var t = 0, e = n._initHooks.length; e > t; t++) n._initHooks[t].call(this)
}
}, e
}, o.Class.include = function(t) {
o.extend(this.prototype, t)
}, o.Class.mergeOptions = function(t) {
o.extend(this.prototype.options, t)
}, o.Class.addInitHook = function(t) {
var e = Array.prototype.slice.call(arguments, 1),
i = "function" == typeof t ? t : function() {
this[t].apply(this, e)
};
this.prototype._initHooks = this.prototype._initHooks || [], this.prototype._initHooks.push(i)
};
var s = "_leaflet_events";
o.Mixin = {}, o.Mixin.Events = {
addEventListener: function(t, e, i) {
if (o.Util.invokeEach(t, this.addEventListener, this, e, i)) return this;
var n, a, r, h, l, u, c, d = this[s] = this[s] || {}, p = i && i !== this && o.stamp(i);
for (t = o.Util.splitWords(t), n = 0, a = t.length; a > n; n++) r = {
action: e,
context: i || this
}, h = t[n], p ? (l = h + "_idx", u = l + "_len", c = d[l] = d[l] || {}, c[p] || (c[p] = [], d[u] = (d[u] || 0) + 1), c[p].push(r)) : (d[h] = d[h] || [], d[h].push(r));
return this
},
hasEventListeners: function(t) {
var e = this[s];
return !!e && (t in e && e[t].length > 0 || t + "_idx" in e && e[t + "_idx_len"] > 0)
},
removeEventListener: function(t, e, i) {
if (!this[s]) return this;
if (!t) return this.clearAllEventListeners();
if (o.Util.invokeEach(t, this.removeEventListener, this, e, i)) return this;
var n, a, r, h, l, u, c, d, p, _ = this[s],
m = i && i !== this && o.stamp(i);
for (t = o.Util.splitWords(t), n = 0, a = t.length; a > n; n++)
if (r = t[n], u = r + "_idx", c = u + "_len", d = _[u], e) {
if (h = m && d ? d[m] : _[r]) {
for (l = h.length - 1; l >= 0; l--) h[l].action !== e || i && h[l].context !== i || (p = h.splice(l, 1), p[0].action = o.Util.falseFn);
i && d && 0 === h.length && (delete d[m], _[c]--)
}
} else delete _[r], delete _[u], delete _[c];
return this
},
clearAllEventListeners: function() {
return delete this[s], this
},
fireEvent: function(t, e) {
if (!this.hasEventListeners(t)) return this;
var i, n, a, r, h, l = o.Util.extend({}, e, {
type: t,
target: this
}),
u = this[s];
if (u[t])
for (i = u[t].slice(), n = 0, a = i.length; a > n; n++) i[n].action.call(i[n].context, l);
r = u[t + "_idx"];
for (h in r)
if (i = r[h].slice())
for (n = 0, a = i.length; a > n; n++) i[n].action.call(i[n].context, l);
return this
},
addOneTimeEventListener: function(t, e, i) {
if (o.Util.invokeEach(t, this.addOneTimeEventListener, this, e, i)) return this;
var n = o.bind(function() {
this.removeEventListener(t, e, i).removeEventListener(t, n, i)
}, this);
return this.addEventListener(t, e, i).addEventListener(t, n, i)
}
}, o.Mixin.Events.on = o.Mixin.Events.addEventListener, o.Mixin.Events.off = o.Mixin.Events.removeEventListener, o.Mixin.Events.once = o.Mixin.Events.addOneTimeEventListener, o.Mixin.Events.fire = o.Mixin.Events.fireEvent,
function() {
var n = "ActiveXObject" in t,
s = n && !e.addEventListener,
a = navigator.userAgent.toLowerCase(),
r = -1 !== a.indexOf("webkit"),
h = -1 !== a.indexOf("chrome"),
l = -1 !== a.indexOf("phantom"),
u = -1 !== a.indexOf("android"),
c = -1 !== a.search("android [23]"),
d = -1 !== a.indexOf("gecko"),
p = typeof orientation != i + "",
_ = t.navigator && t.navigator.msPointerEnabled && t.navigator.msMaxTouchPoints && !t.PointerEvent,
m = t.PointerEvent && t.navigator.pointerEnabled && t.navigator.maxTouchPoints || _,
f = "devicePixelRatio" in t && t.devicePixelRatio > 1 || "matchMedia" in t && t.matchMedia("(min-resolution:144dpi)") && t.matchMedia("(min-resolution:144dpi)").matches,
g = e.documentElement,
v = n && "transition" in g.style,
y = "WebKitCSSMatrix" in t && "m11" in new t.WebKitCSSMatrix && !c,
P = "MozPerspective" in g.style,
L = "OTransition" in g.style,
x = !t.L_DISABLE_3D && (v || y || P || L) && !l,
w = !t.L_NO_TOUCH && !l && function() {
var t = "ontouchstart";
if (m || t in g) return !0;
var i = e.createElement("div"),
n = !1;
return i.setAttribute ? (i.setAttribute(t, "return;"), "function" == typeof i[t] && (n = !0), i.removeAttribute(t), i = null, n) : !1
}();
o.Browser = {
ie: n,
ielt9: s,
webkit: r,
gecko: d && !r && !t.opera && !n,
android: u,
android23: c,
chrome: h,
ie3d: v,
webkit3d: y,
gecko3d: P,
opera3d: L,
any3d: x,
mobile: p,
mobileWebkit: p && r,
mobileWebkit3d: p && y,
mobileOpera: p && t.opera,
touch: w,
msPointer: _,
pointer: m,
retina: f
}
}(), o.Point = function(t, e, i) {
this.x = i ? Math.round(t) : t, this.y = i ? Math.round(e) : e
}, o.Point.prototype = {
clone: function() {
return new o.Point(this.x, this.y)
},
add: function(t) {
return this.clone()._add(o.point(t))
},
_add: function(t) {
return this.x += t.x, this.y += t.y, this
},
subtract: function(t) {
return this.clone()._subtract(o.point(t))
},
_subtract: function(t) {
return this.x -= t.x, this.y -= t.y, this
},
divideBy: function(t) {
return this.clone()._divideBy(t)
},
_divideBy: function(t) {
return this.x /= t, this.y /= t, this
},
multiplyBy: function(t) {
return this.clone()._multiplyBy(t)
},
_multiplyBy: function(t) {
return this.x *= t, this.y *= t, this
},
round: function() {
return this.clone()._round()
},
_round: function() {
return this.x = Math.round(this.x), this.y = Math.round(this.y), this
},
floor: function() {
return this.clone()._floor()
},
_floor: function() {
return this.x = Math.floor(this.x), this.y = Math.floor(this.y), this
},
distanceTo: function(t) {
t = o.point(t);
var e = t.x - this.x,
i = t.y - this.y;
return Math.sqrt(e * e + i * i)
},
equals: function(t) {
return t = o.point(t), t.x === this.x && t.y === this.y
},
contains: function(t) {
return t = o.point(t), Math.abs(t.x) <= Math.abs(this.x) && Math.abs(t.y) <= Math.abs(this.y)
},
toString: function() {
return "Point(" + o.Util.formatNum(this.x) + ", " + o.Util.formatNum(this.y) + ")"
}
}, o.point = function(t, e, n) {
return t instanceof o.Point ? t : o.Util.isArray(t) ? new o.Point(t[0], t[1]) : t === i || null === t ? t : new o.Point(t, e, n)
}, o.Bounds = function(t, e) {
if (t)
for (var i = e ? [t, e] : t, n = 0, o = i.length; o > n; n++) this.extend(i[n])
}, o.Bounds.prototype = {
extend: function(t) {
return t = o.point(t), this.min || this.max ? (this.min.x = Math.min(t.x, this.min.x), this.max.x = Math.max(t.x, this.max.x), this.min.y = Math.min(t.y, this.min.y), this.max.y = Math.max(t.y, this.max.y)) : (this.min = t.clone(), this.max = t.clone()), this
},
getCenter: function(t) {
return new o.Point((this.min.x + this.max.x) / 2, (this.min.y + this.max.y) / 2, t)
},
getBottomLeft: function() {
return new o.Point(this.min.x, this.max.y)
},
getTopRight: function() {
return new o.Point(this.max.x, this.min.y)
},
getSize: function() {
return this.max.subtract(this.min)
},
contains: function(t) {
var e, i;
return t = "number" == typeof t[0] || t instanceof o.Point ? o.point(t) : o.bounds(t), t instanceof o.Bounds ? (e = t.min, i = t.max) : e = i = t, e.x >= this.min.x && i.x <= this.max.x && e.y >= this.min.y && i.y <= this.max.y
},
intersects: function(t) {
t = o.bounds(t);
var e = this.min,
i = this.max,
n = t.min,
s = t.max,
a = s.x >= e.x && n.x <= i.x,
r = s.y >= e.y && n.y <= i.y;
return a && r
},
isValid: function() {
return !(!this.min || !this.max)
}
}, o.bounds = function(t, e) {
return !t || t instanceof o.Bounds ? t : new o.Bounds(t, e)
}, o.Transformation = function(t, e, i, n) {
this._a = t, this._b = e, this._c = i, this._d = n
}, o.Transformation.prototype = {
transform: function(t, e) {
return this._transform(t.clone(), e)
},
_transform: function(t, e) {
return e = e || 1, t.x = e * (this._a * t.x + this._b), t.y = e * (this._c * t.y + this._d), t
},
untransform: function(t, e) {
return e = e || 1, new o.Point((t.x / e - this._b) / this._a, (t.y / e - this._d) / this._c)
}
}, o.DomUtil = {
get: function(t) {
return "string" == typeof t ? e.getElementById(t) : t
},
getStyle: function(t, i) {
var n = t.style[i];
if (!n && t.currentStyle && (n = t.currentStyle[i]), (!n || "auto" === n) && e.defaultView) {
var o = e.defaultView.getComputedStyle(t, null);
n = o ? o[i] : null
}
return "auto" === n ? null : n
},
getViewportOffset: function(t) {
var i, n = 0,
s = 0,
a = t,
r = e.body,
h = e.documentElement;
do {
if (n += a.offsetTop || 0, s += a.offsetLeft || 0, n += parseInt(o.DomUtil.getStyle(a, "borderTopWidth"), 10) || 0, s += parseInt(o.DomUtil.getStyle(a, "borderLeftWidth"), 10) || 0, i = o.DomUtil.getStyle(a, "position"), a.offsetParent === r && "absolute" === i) break;
if ("fixed" === i) {
n += r.scrollTop || h.scrollTop || 0, s += r.scrollLeft || h.scrollLeft || 0;
break
}
if ("relative" === i && !a.offsetLeft) {
var l = o.DomUtil.getStyle(a, "width"),
u = o.DomUtil.getStyle(a, "max-width"),
c = a.getBoundingClientRect();
("none" !== l || "none" !== u) && (s += c.left + a.clientLeft), n += c.top + (r.scrollTop || h.scrollTop || 0);
break
}
a = a.offsetParent
} while (a);
a = t;
do {
if (a === r) break;
n -= a.scrollTop || 0, s -= a.scrollLeft || 0, a = a.parentNode
} while (a);
return new o.Point(s, n)
},
documentIsLtr: function() {
return o.DomUtil._docIsLtrCached || (o.DomUtil._docIsLtrCached = !0, o.DomUtil._docIsLtr = "ltr" === o.DomUtil.getStyle(e.body, "direction")), o.DomUtil._docIsLtr
},
create: function(t, i, n) {
var o = e.createElement(t);
return o.className = i, n && n.appendChild(o), o
},
hasClass: function(t, e) {
if (t.classList !== i) return t.classList.contains(e);
var n = o.DomUtil._getClass(t);
return n.length > 0 && new RegExp("(^|\\s)" + e + "(\\s|$)").test(n)
},
addClass: function(t, e) {
if (t.classList !== i)
for (var n = o.Util.splitWords(e), s = 0, a = n.length; a > s; s++) t.classList.add(n[s]);
else if (!o.DomUtil.hasClass(t, e)) {
var r = o.DomUtil._getClass(t);
o.DomUtil._setClass(t, (r ? r + " " : "") + e)
}
},
removeClass: function(t, e) {
t.classList !== i ? t.classList.remove(e) : o.DomUtil._setClass(t, o.Util.trim((" " + o.DomUtil._getClass(t) + " ").replace(" " + e + " ", " ")))
},
_setClass: function(t, e) {
t.className.baseVal === i ? t.className = e : t.className.baseVal = e
},
_getClass: function(t) {
return t.className.baseVal === i ? t.className : t.className.baseVal
},
setOpacity: function(t, e) {
if ("opacity" in t.style) t.style.opacity = e;
else if ("filter" in t.style) {
var i = !1,
n = "DXImageTransform.Microsoft.Alpha";
try {
i = t.filters.item(n)
} catch (o) {
if (1 === e) return
}
e = Math.round(100 * e), i ? (i.Enabled = 100 !== e, i.Opacity = e) : t.style.filter += " progid:" + n + "(opacity=" + e + ")"
}
},
testProp: function(t) {
for (var i = e.documentElement.style, n = 0; n < t.length; n++)
if (t[n] in i) return t[n];
return !1
},
getTranslateString: function(t) {
var e = o.Browser.webkit3d,
i = "translate" + (e ? "3d" : "") + "(",
n = (e ? ",0" : "") + ")";
return i + t.x + "px," + t.y + "px" + n
},
getScaleString: function(t, e) {
var i = o.DomUtil.getTranslateString(e.add(e.multiplyBy(-1 * t))),
n = " scale(" + t + ") ";
return i + n
},
setPosition: function(t, e, i) {
t._leaflet_pos = e, !i && o.Browser.any3d ? t.style[o.DomUtil.TRANSFORM] = o.DomUtil.getTranslateString(e) : (t.style.left = e.x + "px", t.style.top = e.y + "px")
},
getPosition: function(t) {
return t._leaflet_pos
}
}, o.DomUtil.TRANSFORM = o.DomUtil.testProp(["transform", "WebkitTransform", "OTransform", "MozTransform", "msTransform"]), o.DomUtil.TRANSITION = o.DomUtil.testProp(["webkitTransition", "transition", "OTransition", "MozTransition", "msTransition"]), o.DomUtil.TRANSITION_END = "webkitTransition" === o.DomUtil.TRANSITION || "OTransition" === o.DomUtil.TRANSITION ? o.DomUtil.TRANSITION + "End" : "transitionend",
function() {
if ("onselectstart" in e) o.extend(o.DomUtil, {
disableTextSelection: function() {
o.DomEvent.on(t, "selectstart", o.DomEvent.preventDefault)
},
enableTextSelection: function() {
o.DomEvent.off(t, "selectstart", o.DomEvent.preventDefault)
}
});
else {
var i = o.DomUtil.testProp(["userSelect", "WebkitUserSelect", "OUserSelect", "MozUserSelect", "msUserSelect"]);
o.extend(o.DomUtil, {
disableTextSelection: function() {
if (i) {
var t = e.documentElement.style;
this._userSelect = t[i], t[i] = "none"
}
},
enableTextSelection: function() {
i && (e.documentElement.style[i] = this._userSelect, delete this._userSelect)
}
})
}
o.extend(o.DomUtil, {
disableImageDrag: function() {
o.DomEvent.on(t, "dragstart", o.DomEvent.preventDefault)
},
enableImageDrag: function() {
o.DomEvent.off(t, "dragstart", o.DomEvent.preventDefault)
}
})
}(), o.LatLng = function(t, e, n) {
if (t = parseFloat(t), e = parseFloat(e), isNaN(t) || isNaN(e)) throw new Error("Invalid LatLng object: (" + t + ", " + e + ")");
this.lat = t, this.lng = e, n !== i && (this.alt = parseFloat(n))
}, o.extend(o.LatLng, {
DEG_TO_RAD: Math.PI / 180,
RAD_TO_DEG: 180 / Math.PI,
MAX_MARGIN: 1e-9
}), o.LatLng.prototype = {
equals: function(t) {
if (!t) return !1;
t = o.latLng(t);
var e = Math.max(Math.abs(this.lat - t.lat), Math.abs(this.lng - t.lng));
return e <= o.LatLng.MAX_MARGIN
},
toString: function(t) {
return "LatLng(" + o.Util.formatNum(this.lat, t) + ", " + o.Util.formatNum(this.lng, t) + ")"
},
distanceTo: function(t) {
t = o.latLng(t);
var e = 6378137,
i = o.LatLng.DEG_TO_RAD,
n = (t.lat - this.lat) * i,
s = (t.lng - this.lng) * i,
a = this.lat * i,
r = t.lat * i,
h = Math.sin(n / 2),
l = Math.sin(s / 2),
u = h * h + l * l * Math.cos(a) * Math.cos(r);
return 2 * e * Math.atan2(Math.sqrt(u), Math.sqrt(1 - u))
},
wrap: function(t, e) {
var i = this.lng;
return t = t || -180, e = e || 180, i = (i + e) % (e - t) + (t > i || i === e ? e : t), new o.LatLng(this.lat, i)
}
}, o.latLng = function(t, e) {
return t instanceof o.LatLng ? t : o.Util.isArray(t) ? "number" == typeof t[0] || "string" == typeof t[0] ? new o.LatLng(t[0], t[1], t[2]) : null : t === i || null === t ? t : "object" == typeof t && "lat" in t ? new o.LatLng(t.lat, "lng" in t ? t.lng : t.lon) : e === i ? null : new o.LatLng(t, e)
}, o.LatLngBounds = function(t, e) {
if (t)
for (var i = e ? [t, e] : t, n = 0, o = i.length; o > n; n++) this.extend(i[n])
}, o.LatLngBounds.prototype = {
extend: function(t) {
if (!t) return this;
var e = o.latLng(t);
return t = null !== e ? e : o.latLngBounds(t), t instanceof o.LatLng ? this._southWest || this._northEast ? (this._southWest.lat = Math.min(t.lat, this._southWest.lat), this._southWest.lng = Math.min(t.lng, this._southWest.lng), this._northEast.lat = Math.max(t.lat, this._northEast.lat), this._northEast.lng = Math.max(t.lng, this._northEast.lng)) : (this._southWest = new o.LatLng(t.lat, t.lng), this._northEast = new o.LatLng(t.lat, t.lng)) : t instanceof o.LatLngBounds && (this.extend(t._southWest), this.extend(t._northEast)), this
},
pad: function(t) {
var e = this._southWest,
i = this._northEast,
n = Math.abs(e.lat - i.lat) * t,
s = Math.abs(e.lng - i.lng) * t;
return new o.LatLngBounds(new o.LatLng(e.lat - n, e.lng - s), new o.LatLng(i.lat + n, i.lng + s))
},
getCenter: function() {
return new o.LatLng((this._southWest.lat + this._northEast.lat) / 2, (this._southWest.lng + this._northEast.lng) / 2)
},
getSouthWest: function() {
return this._southWest
},
getNorthEast: function() {
return this._northEast
},
getNorthWest: function() {
return new o.LatLng(this.getNorth(), this.getWest())
},
getSouthEast: function() {
return new o.LatLng(this.getSouth(), this.getEast())
},
getWest: function() {
return this._southWest.lng
},
getSouth: function() {
return this._southWest.lat
},
getEast: function() {
return this._northEast.lng
},
getNorth: function() {
return this._northEast.lat
},
contains: function(t) {
t = "number" == typeof t[0] || t instanceof o.LatLng ? o.latLng(t) : o.latLngBounds(t);
var e, i, n = this._southWest,
s = this._northEast;
return t instanceof o.LatLngBounds ? (e = t.getSouthWest(), i = t.getNorthEast()) : e = i = t, e.lat >= n.lat && i.lat <= s.lat && e.lng >= n.lng && i.lng <= s.lng
},
intersects: function(t) {
t = o.latLngBounds(t);
var e = this._southWest,
i = this._northEast,
n = t.getSouthWest(),
s = t.getNorthEast(),
a = s.lat >= e.lat && n.lat <= i.lat,
r = s.lng >= e.lng && n.lng <= i.lng;
return a && r
},
toBBoxString: function() {
return [this.getWest(), this.getSouth(), this.getEast(), this.getNorth()].join(",")
},
equals: function(t) {
return t ? (t = o.latLngBounds(t), this._southWest.equals(t.getSouthWest()) && this._northEast.equals(t.getNorthEast())) : !1
},
isValid: function() {
return !(!this._southWest || !this._northEast)
}
}, o.latLngBounds = function(t, e) {
return !t || t instanceof o.LatLngBounds ? t : new o.LatLngBounds(t, e)
}, o.Projection = {}, o.Projection.SphericalMercator = {
MAX_LATITUDE: 85.0511287798,
project: function(t) {
var e = o.LatLng.DEG_TO_RAD,
i = this.MAX_LATITUDE,
n = Math.max(Math.min(i, t.lat), -i),
s = t.lng * e,
a = n * e;
return a = Math.log(Math.tan(Math.PI / 4 + a / 2)), new o.Point(s, a)
},
unproject: function(t) {
var e = o.LatLng.RAD_TO_DEG,
i = t.x * e,
n = (2 * Math.atan(Math.exp(t.y)) - Math.PI / 2) * e;
return new o.LatLng(n, i)
}
}, o.Projection.LonLat = {
project: function(t) {
return new o.Point(t.lng, t.lat)
},
unproject: function(t) {
return new o.LatLng(t.y, t.x)
}
}, o.CRS = {
latLngToPoint: function(t, e) {
var i = this.projection.project(t),
n = this.scale(e);
return this.transformation._transform(i, n)
},
pointToLatLng: function(t, e) {
var i = this.scale(e),
n = this.transformation.untransform(t, i);
return this.projection.unproject(n)
},
project: function(t) {
return this.projection.project(t)
},
scale: function(t) {
return 256 * Math.pow(2, t)
},
getSize: function(t) {
var e = this.scale(t);
return o.point(e, e)
}
}, o.CRS.Simple = o.extend({}, o.CRS, {
projection: o.Projection.LonLat,
transformation: new o.Transformation(1, 0, -1, 0),
scale: function(t) {
return Math.pow(2, t)
}
}), o.CRS.EPSG3857 = o.extend({}, o.CRS, {
code: "EPSG:3857",
projection: o.Projection.SphericalMercator,
transformation: new o.Transformation(.5 / Math.PI, .5, -.5 / Math.PI, .5),
project: function(t) {
var e = this.projection.project(t),
i = 6378137;
return e.multiplyBy(i)
}
}), o.CRS.EPSG900913 = o.extend({}, o.CRS.EPSG3857, {
code: "EPSG:900913"
}), o.CRS.EPSG4326 = o.extend({}, o.CRS, {
code: "EPSG:4326",
projection: o.Projection.LonLat,
transformation: new o.Transformation(1 / 360, .5, -1 / 360, .5)
}), o.Map = o.Class.extend({
includes: o.Mixin.Events,
options: {
crs: o.CRS.EPSG3857,
fadeAnimation: o.DomUtil.TRANSITION && !o.Browser.android23,
trackResize: !0,
markerZoomAnimation: o.DomUtil.TRANSITION && o.Browser.any3d
},
initialize: function(t, e) {
e = o.setOptions(this, e), this._initContainer(t), this._initLayout(), this._onResize = o.bind(this._onResize, this), this._initEvents(), e.maxBounds && this.setMaxBounds(e.maxBounds), e.center && e.zoom !== i && this.setView(o.latLng(e.center), e.zoom, {
reset: !0
}), this._handlers = [], this._layers = {}, this._zoomBoundLayers = {}, this._tileLayersNum = 0, this.callInitHooks(), this._addLayers(e.layers)
},
setView: function(t, e) {
return e = e === i ? this.getZoom() : e, this._resetView(o.latLng(t), this._limitZoom(e)), this
},
setZoom: function(t, e) {
return this._loaded ? this.setView(this.getCenter(), t, {
zoom: e
}) : (this._zoom = this._limitZoom(t), this)
},
zoomIn: function(t, e) {
return this.setZoom(this._zoom + (t || 1), e)
},
zoomOut: function(t, e) {
return this.setZoom(this._zoom - (t || 1), e)
},
setZoomAround: function(t, e, i) {
var n = this.getZoomScale(e),
s = this.getSize().divideBy(2),
a = t instanceof o.Point ? t : this.latLngToContainerPoint(t),
r = a.subtract(s).multiplyBy(1 - 1 / n),
h = this.containerPointToLatLng(s.add(r));
return this.setView(h, e, {
zoom: i
})
},
fitBounds: function(t, e) {
e = e || {}, t = t.getBounds ? t.getBounds() : o.latLngBounds(t);
var i = o.point(e.paddingTopLeft || e.padding || [0, 0]),
n = o.point(e.paddingBottomRight || e.padding || [0, 0]),
s = this.getBoundsZoom(t, !1, i.add(n)),
a = n.subtract(i).divideBy(2),
r = this.project(t.getSouthWest(), s),
h = this.project(t.getNorthEast(), s),
l = this.unproject(r.add(h).divideBy(2).add(a), s);
return s = e && e.maxZoom ? Math.min(e.maxZoom, s) : s, this.setView(l, s, e)
},
fitWorld: function(t) {
return this.fitBounds([
[-90, -180],
[90, 180]
], t)
},
panTo: function(t, e) {
return this.setView(t, this._zoom, {
pan: e
})
},
panBy: function(t) {
return this.fire("movestart"), this._rawPanBy(o.point(t)), this.fire("move"), this.fire("moveend")
},
setMaxBounds: function(t) {
return t = o.latLngBounds(t), this.options.maxBounds = t, t ? (this._loaded && this._panInsideMaxBounds(), this.on("moveend", this._panInsideMaxBounds, this)) : this.off("moveend", this._panInsideMaxBounds, this)
},
panInsideBounds: function(t, e) {
var i = this.getCenter(),
n = this._limitCenter(i, this._zoom, t);
return i.equals(n) ? this : this.panTo(n, e)
},
addLayer: function(t) {
var e = o.stamp(t);
return this._layers[e] ? this : (this._layers[e] = t, !t.options || isNaN(t.options.maxZoom) && isNaN(t.options.minZoom) || (this._zoomBoundLayers[e] = t, this._updateZoomLevels()), this.options.zoomAnimation && o.TileLayer && t instanceof o.TileLayer && (this._tileLayersNum++, this._tileLayersToLoad++, t.on("load", this._onTileLayerLoad, this)), this._loaded && this._layerAdd(t), this)
},
removeLayer: function(t) {
var e = o.stamp(t);
return this._layers[e] ? (this._loaded && t.onRemove(this), delete this._layers[e], this._loaded && this.fire("layerremove", {
layer: t
}), this._zoomBoundLayers[e] && (delete this._zoomBoundLayers[e], this._updateZoomLevels()), this.options.zoomAnimation && o.TileLayer && t instanceof o.TileLayer && (this._tileLayersNum--, this._tileLayersToLoad--, t.off("load", this._onTileLayerLoad, this)), this) : this
},
hasLayer: function(t) {
return t ? o.stamp(t) in this._layers : !1
},
eachLayer: function(t, e) {
for (var i in this._layers) t.call(e, this._layers[i]);
return this
},
invalidateSize: function(t) {
if (!this._loaded) return this;
t = o.extend({
animate: !1,
pan: !0
}, t === !0 ? {
animate: !0
} : t);
var e = this.getSize();
this._sizeChanged = !0, this._initialCenter = null;
var i = this.getSize(),
n = e.divideBy(2).round(),
s = i.divideBy(2).round(),
a = n.subtract(s);
return a.x || a.y ? (t.animate && t.pan ? this.panBy(a) : (t.pan && this._rawPanBy(a), this.fire("move"), t.debounceMoveend ? (clearTimeout(this._sizeTimer), this._sizeTimer = setTimeout(o.bind(this.fire, this, "moveend"), 200)) : this.fire("moveend")), this.fire("resize", {
oldSize: e,
newSize: i
})) : this
},
addHandler: function(t, e) {
if (!e) return this;
var i = this[t] = new e(this);
return this._handlers.push(i), this.options[t] && i.enable(), this
},
remove: function() {
this._loaded && this.fire("unload"), this._initEvents("off");
try {
delete this._container._leaflet
} catch (t) {
this._container._leaflet = i
}
return this._clearPanes(), this._clearControlPos && this._clearControlPos(), this._clearHandlers(), this
},
getCenter: function() {
return this._checkIfLoaded(), this._initialCenter && !this._moved() ? this._initialCenter : this.layerPointToLatLng(this._getCenterLayerPoint())
},
getZoom: function() {
return this._zoom
},
getBounds: function() {
var t = this.getPixelBounds(),
e = this.unproject(t.getBottomLeft()),
i = this.unproject(t.getTopRight());
return new o.LatLngBounds(e, i)
},
getMinZoom: function() {
return this.options.minZoom === i ? this._layersMinZoom === i ? 0 : this._layersMinZoom : this.options.minZoom
},
getMaxZoom: function() {
return this.options.maxZoom === i ? this._layersMaxZoom === i ? 1 / 0 : this._layersMaxZoom : this.options.maxZoom
},
getBoundsZoom: function(t, e, i) {
t = o.latLngBounds(t);
var n, s = this.getMinZoom() - (e ? 1 : 0),
a = this.getMaxZoom(),
r = this.getSize(),
h = t.getNorthWest(),
l = t.getSouthEast(),
u = !0;
i = o.point(i || [0, 0]);
do s++, n = this.project(l, s).subtract(this.project(h, s)).add(i), u = e ? n.x < r.x || n.y < r.y : r.contains(n); while (u && a >= s);
return u && e ? null : e ? s : s - 1
},
getSize: function() {
return (!this._size || this._sizeChanged) && (this._size = new o.Point(this._container.clientWidth, this._container.clientHeight), this._sizeChanged = !1), this._size.clone()
},
getPixelBounds: function() {
var t = this._getTopLeftPoint();
return new o.Bounds(t, t.add(this.getSize()))
},
getPixelOrigin: function() {
return this._checkIfLoaded(), this._initialTopLeftPoint
},
getPanes: function() {
return this._panes
},
getContainer: function() {
return this._container
},
getZoomScale: function(t) {
var e = this.options.crs;
return e.scale(t) / e.scale(this._zoom)
},
getScaleZoom: function(t) {
return this._zoom + Math.log(t) / Math.LN2
},
project: function(t, e) {
return e = e === i ? this._zoom : e, this.options.crs.latLngToPoint(o.latLng(t), e)
},
unproject: function(t, e) {
return e = e === i ? this._zoom : e, this.options.crs.pointToLatLng(o.point(t), e)
},
layerPointToLatLng: function(t) {
var e = o.point(t).add(this.getPixelOrigin());
return this.unproject(e)
},
latLngToLayerPoint: function(t) {
var e = this.project(o.latLng(t))._round();
return e._subtract(this.getPixelOrigin())
},
containerPointToLayerPoint: function(t) {
return o.point(t).subtract(this._getMapPanePos())
},
layerPointToContainerPoint: function(t) {
return o.point(t).add(this._getMapPanePos())
},
containerPointToLatLng: function(t) {
var e = this.containerPointToLayerPoint(o.point(t));
return this.layerPointToLatLng(e)
},
latLngToContainerPoint: function(t) {
return this.layerPointToContainerPoint(this.latLngToLayerPoint(o.latLng(t)))
},
mouseEventToContainerPoint: function(t) {
return o.DomEvent.getMousePosition(t, this._container)
},
mouseEventToLayerPoint: function(t) {
return this.containerPointToLayerPoint(this.mouseEventToContainerPoint(t))
},
mouseEventToLatLng: function(t) {
return this.layerPointToLatLng(this.mouseEventToLayerPoint(t))
},
_initContainer: function(t) {
var e = this._container = o.DomUtil.get(t);
if (!e) throw new Error("Map container not found.");
if (e._leaflet) throw new Error("Map container is already initialized.");
e._leaflet = !0
},
_initLayout: function() {
var t = this._container;
o.DomUtil.addClass(t, "leaflet-container" + (o.Browser.touch ? " leaflet-touch" : "") + (o.Browser.retina ? " leaflet-retina" : "") + (o.Browser.ielt9 ? " leaflet-oldie" : "") + (this.options.fadeAnimation ? " leaflet-fade-anim" : ""));
var e = o.DomUtil.getStyle(t, "position");
"absolute" !== e && "relative" !== e && "fixed" !== e && (t.style.position = "relative"), this._initPanes(), this._initControlPos && this._initControlPos()
},
_initPanes: function() {
var t = this._panes = {};
this._mapPane = t.mapPane = this._createPane("leaflet-map-pane", this._container), this._tilePane = t.tilePane = this._createPane("leaflet-tile-pane", this._mapPane), t.objectsPane = this._createPane("leaflet-objects-pane", this._mapPane), t.shadowPane = this._createPane("leaflet-shadow-pane"), t.overlayPane = this._createPane("leaflet-overlay-pane"), t.markerPane = this._createPane("leaflet-marker-pane"), t.popupPane = this._createPane("leaflet-popup-pane");
var e = " leaflet-zoom-hide";
this.options.markerZoomAnimation || (o.DomUtil.addClass(t.markerPane, e), o.DomUtil.addClass(t.shadowPane, e), o.DomUtil.addClass(t.popupPane, e))
},
_createPane: function(t, e) {
return o.DomUtil.create("div", t, e || this._panes.objectsPane)
},
_clearPanes: function() {
this._container.removeChild(this._mapPane)
},
_addLayers: function(t) {
t = t ? o.Util.isArray(t) ? t : [t] : [];
for (var e = 0, i = t.length; i > e; e++) this.addLayer(t[e])
},
_resetView: function(t, e, i, n) {
var s = this._zoom !== e;
n || (this.fire("movestart"), s && this.fire("zoomstart")), this._zoom = e, this._initialCenter = t, this._initialTopLeftPoint = this._getNewTopLeftPoint(t), i ? this._initialTopLeftPoint._add(this._getMapPanePos()) : o.DomUtil.setPosition(this._mapPane, new o.Point(0, 0)), this._tileLayersToLoad = this._tileLayersNum;
var a = !this._loaded;
this._loaded = !0, this.fire("viewreset", {
hard: !i
}), a && (this.fire("load"), this.eachLayer(this._layerAdd, this)), this.fire("move"), (s || n) && this.fire("zoomend"), this.fire("moveend", {
hard: !i
})
},
_rawPanBy: function(t) {
o.DomUtil.setPosition(this._mapPane, this._getMapPanePos().subtract(t))
},
_getZoomSpan: function() {
return this.getMaxZoom() - this.getMinZoom()
},
_updateZoomLevels: function() {
var t, e = 1 / 0,
n = -1 / 0,
o = this._getZoomSpan();
for (t in this._zoomBoundLayers) {
var s = this._zoomBoundLayers[t];
isNaN(s.options.minZoom) || (e = Math.min(e, s.options.minZoom)), isNaN(s.options.maxZoom) || (n = Math.max(n, s.options.maxZoom))
}
t === i ? this._layersMaxZoom = this._layersMinZoom = i : (this._layersMaxZoom = n, this._layersMinZoom = e), o !== this._getZoomSpan() && this.fire("zoomlevelschange")
},
_panInsideMaxBounds: function() {
this.panInsideBounds(this.options.maxBounds)
},
_checkIfLoaded: function() {
if (!this._loaded) throw new Error("Set map center and zoom first.")
},
_initEvents: function(e) {
if (o.DomEvent) {
e = e || "on", o.DomEvent[e](this._container, "click", this._onMouseClick, this);
var i, n, s = ["dblclick", "mousedown", "mouseup", "mouseenter", "mouseleave", "mousemove", "contextmenu"];
for (i = 0, n = s.length; n > i; i++) o.DomEvent[e](this._container, s[i], this._fireMouseEvent, this);
this.options.trackResize && o.DomEvent[e](t, "resize", this._onResize, this)
}
},
_onResize: function() {
o.Util.cancelAnimFrame(this._resizeRequest), this._resizeRequest = o.Util.requestAnimFrame(function() {
this.invalidateSize({
debounceMoveend: !0
})
}, this, !1, this._container)
},
_onMouseClick: function(t) {
!this._loaded || !t._simulated && (this.dragging && this.dragging.moved() || this.boxZoom && this.boxZoom.moved()) || o.DomEvent._skipped(t) || (this.fire("preclick"), this._fireMouseEvent(t))
},
_fireMouseEvent: function(t) {
if (this._loaded && !o.DomEvent._skipped(t)) {
var e = t.type;
if (e = "mouseenter" === e ? "mouseover" : "mouseleave" === e ? "mouseout" : e, this.hasEventListeners(e)) {
"contextmenu" === e && o.DomEvent.preventDefault(t);
var i = this.mouseEventToContainerPoint(t),
n = this.containerPointToLayerPoint(i),
s = this.layerPointToLatLng(n);
this.fire(e, {
latlng: s,
layerPoint: n,
containerPoint: i,
originalEvent: t
})
}
}
},
_onTileLayerLoad: function() {
this._tileLayersToLoad--, this._tileLayersNum && !this._tileLayersToLoad && this.fire("tilelayersload")
},
_clearHandlers: function() {
for (var t = 0, e = this._handlers.length; e > t; t++) this._handlers[t].disable()
},
whenReady: function(t, e) {
return this._loaded ? t.call(e || this, this) : this.on("load", t, e), this
},
_layerAdd: function(t) {
t.onAdd(this), this.fire("layeradd", {
layer: t
})
},
_getMapPanePos: function() {
return o.DomUtil.getPosition(this._mapPane)
},
_moved: function() {
var t = this._getMapPanePos();
return t && !t.equals([0, 0])
},
_getTopLeftPoint: function() {
return this.getPixelOrigin().subtract(this._getMapPanePos())
},
_getNewTopLeftPoint: function(t, e) {
var i = this.getSize()._divideBy(2);
return this.project(t, e)._subtract(i)._round()
},
_latLngToNewLayerPoint: function(t, e, i) {
var n = this._getNewTopLeftPoint(i, e).add(this._getMapPanePos());
return this.project(t, e)._subtract(n)
},
_getCenterLayerPoint: function() {
return this.containerPointToLayerPoint(this.getSize()._divideBy(2))
},
_getCenterOffset: function(t) {
return this.latLngToLayerPoint(t).subtract(this._getCenterLayerPoint())
},
_limitCenter: function(t, e, i) {
if (!i) return t;
var n = this.project(t, e),
s = this.getSize().divideBy(2),
a = new o.Bounds(n.subtract(s), n.add(s)),
r = this._getBoundsOffset(a, i, e);
return this.unproject(n.add(r), e)
},
_limitOffset: function(t, e) {
if (!e) return t;
var i = this.getPixelBounds(),
n = new o.Bounds(i.min.add(t), i.max.add(t));
return t.add(this._getBoundsOffset(n, e))
},
_getBoundsOffset: function(t, e, i) {
var n = this.project(e.getNorthWest(), i).subtract(t.min),
s = this.project(e.getSouthEast(), i).subtract(t.max),
a = this._rebound(n.x, -s.x),
r = this._rebound(n.y, -s.y);
return new o.Point(a, r)
},
_rebound: function(t, e) {
return t + e > 0 ? Math.round(t - e) / 2 : Math.max(0, Math.ceil(t)) - Math.max(0, Math.floor(e))
},
_limitZoom: function(t) {
var e = this.getMinZoom(),
i = this.getMaxZoom();
return Math.max(e, Math.min(i, t))
}
}), o.map = function(t, e) {
return new o.Map(t, e)
}, o.Projection.Mercator = {
MAX_LATITUDE: 85.0840591556,
R_MINOR: 6356752.314245179,
R_MAJOR: 6378137,
project: function(t) {
var e = o.LatLng.DEG_TO_RAD,
i = this.MAX_LATITUDE,
n = Math.max(Math.min(i, t.lat), -i),
s = this.R_MAJOR,
a = this.R_MINOR,
r = t.lng * e * s,
h = n * e,
l = a / s,
u = Math.sqrt(1 - l * l),
c = u * Math.sin(h);
c = Math.pow((1 - c) / (1 + c), .5 * u);
var d = Math.tan(.5 * (.5 * Math.PI - h)) / c;
return h = -s * Math.log(d), new o.Point(r, h)
},
unproject: function(t) {
for (var e, i = o.LatLng.RAD_TO_DEG, n = this.R_MAJOR, s = this.R_MINOR, a = t.x * i / n, r = s / n, h = Math.sqrt(1 - r * r), l = Math.exp(-t.y / n), u = Math.PI / 2 - 2 * Math.atan(l), c = 15, d = 1e-7, p = c, _ = .1; Math.abs(_) > d && --p > 0;) e = h * Math.sin(u), _ = Math.PI / 2 - 2 * Math.atan(l * Math.pow((1 - e) / (1 + e), .5 * h)) - u, u += _;
return new o.LatLng(u * i, a)
}
}, o.CRS.EPSG3395 = o.extend({}, o.CRS, {
code: "EPSG:3395",
projection: o.Projection.Mercator,
transformation: function() {
var t = o.Projection.Mercator,
e = t.R_MAJOR,
i = .5 / (Math.PI * e);
return new o.Transformation(i, .5, -i, .5)
}()
}), o.TileLayer = o.Class.extend({
includes: o.Mixin.Events,
options: {
minZoom: 0,
maxZoom: 18,
tileSize: 256,
subdomains: "abc",
errorTileUrl: "",
attribution: "",
zoomOffset: 0,
opacity: 1,
unloadInvisibleTiles: o.Browser.mobile,
updateWhenIdle: o.Browser.mobile
},
initialize: function(t, e) {
e = o.setOptions(this, e), e.detectRetina && o.Browser.retina && e.maxZoom > 0 && (e.tileSize = Math.floor(e.tileSize / 2), e.zoomOffset++, e.minZoom > 0 && e.minZoom--, this.options.maxZoom--), e.bounds && (e.bounds = o.latLngBounds(e.bounds)), this._url = t;
var i = this.options.subdomains;
"string" == typeof i && (this.options.subdomains = i.split(""))
},
onAdd: function(t) {
this._map = t, this._animated = t._zoomAnimated, this._initContainer(), t.on({
viewreset: this._reset,
moveend: this._update
}, this), this._animated && t.on({
zoomanim: this._animateZoom,
zoomend: this._endZoomAnim
}, this), this.options.updateWhenIdle || (this._limitedUpdate = o.Util.limitExecByInterval(this._update, 150, this), t.on("move", this._limitedUpdate, this)), this._reset(), this._update()
},
addTo: function(t) {
return t.addLayer(this), this
},
onRemove: function(t) {
this._container.parentNode.removeChild(this._container), t.off({
viewreset: this._reset,
moveend: this._update
}, this), this._animated && t.off({
zoomanim: this._animateZoom,
zoomend: this._endZoomAnim
}, this), this.options.updateWhenIdle || t.off("move", this._limitedUpdate, this), this._container = null, this._map = null
},
bringToFront: function() {
var t = this._map._panes.tilePane;
return this._container && (t.appendChild(this._container), this._setAutoZIndex(t, Math.max)), this
},
bringToBack: function() {
var t = this._map._panes.tilePane;
return this._container && (t.insertBefore(this._container, t.firstChild), this._setAutoZIndex(t, Math.min)), this
},
getAttribution: function() {
return this.options.attribution
},
getContainer: function() {
return this._container
},
setOpacity: function(t) {
return this.options.opacity = t, this._map && this._updateOpacity(), this
},
setZIndex: function(t) {
return this.options.zIndex = t, this._updateZIndex(), this
},
setUrl: function(t, e) {
return this._url = t, e || this.redraw(), this
},
redraw: function() {
return this._map && (this._reset({
hard: !0
}), this._update()), this
},
_updateZIndex: function() {
this._container && this.options.zIndex !== i && (this._container.style.zIndex = this.options.zIndex)
},
_setAutoZIndex: function(t, e) {
var i, n, o, s = t.children,
a = -e(1 / 0, -1 / 0);
for (n = 0, o = s.length; o > n; n++) s[n] !== this._container && (i = parseInt(s[n].style.zIndex, 10), isNaN(i) || (a = e(a, i)));
this.options.zIndex = this._container.style.zIndex = (isFinite(a) ? a : 0) + e(1, -1)
},
_updateOpacity: function() {
var t, e = this._tiles;
if (o.Browser.ielt9)
for (t in e) o.DomUtil.setOpacity(e[t], this.options.opacity);
else o.DomUtil.setOpacity(this._container, this.options.opacity)
},
_initContainer: function() {
var t = this._map._panes.tilePane;
if (!this._container) {
if (this._container = o.DomUtil.create("div", "leaflet-layer"), this._updateZIndex(), this._animated) {
var e = "leaflet-tile-container";
this._bgBuffer = o.DomUtil.create("div", e, this._container), this._tileContainer = o.DomUtil.create("div", e, this._container)
} else this._tileContainer = this._container;
t.appendChild(this._container), this.options.opacity < 1 && this._updateOpacity()
}
},
_reset: function(t) {
for (var e in this._tiles) this.fire("tileunload", {
tile: this._tiles[e]
});
this._tiles = {}, this._tilesToLoad = 0, this.options.reuseTiles && (this._unusedTiles = []), this._tileContainer.innerHTML = "", this._animated && t && t.hard && this._clearBgBuffer(), this._initContainer()
},
_getTileSize: function() {
var t = this._map,
e = t.getZoom() + this.options.zoomOffset,
i = this.options.maxNativeZoom,
n = this.options.tileSize;
return i && e > i && (n = Math.round(t.getZoomScale(e) / t.getZoomScale(i) * n)), n
},
_update: function() {
if (this._map) {
var t = this._map,
e = t.getPixelBounds(),
i = t.getZoom(),
n = this._getTileSize();
if (!(i > this.options.maxZoom || i < this.options.minZoom)) {
var s = o.bounds(e.min.divideBy(n)._floor(), e.max.divideBy(n)._floor());
this._addTilesFromCenterOut(s), (this.options.unloadInvisibleTiles || this.options.reuseTiles) && this._removeOtherTiles(s)
}
}
},
_addTilesFromCenterOut: function(t) {
var i, n, s, a = [],
r = t.getCenter();
for (i = t.min.y; i <= t.max.y; i++)
for (n = t.min.x; n <= t.max.x; n++) s = new o.Point(n, i), this._tileShouldBeLoaded(s) && a.push(s);
var h = a.length;
if (0 !== h) {
a.sort(function(t, e) {
return t.distanceTo(r) - e.distanceTo(r)
});
var l = e.createDocumentFragment();
for (this._tilesToLoad || this.fire("loading"), this._tilesToLoad += h, n = 0; h > n; n++) this._addTile(a[n], l);
this._tileContainer.appendChild(l)
}
},
_tileShouldBeLoaded: function(t) {
if (t.x + ":" + t.y in this._tiles) return !1;
var e = this.options;
if (!e.continuousWorld) {
var i = this._getWrapTileNum();
if (e.noWrap && (t.x < 0 || t.x >= i.x) || t.y < 0 || t.y >= i.y) return !1
}
if (e.bounds) {
var n = e.tileSize,
o = t.multiplyBy(n),
s = o.add([n, n]),
a = this._map.unproject(o),
r = this._map.unproject(s);
if (e.continuousWorld || e.noWrap || (a = a.wrap(), r = r.wrap()), !e.bounds.intersects([a, r])) return !1
}
return !0
},
_removeOtherTiles: function(t) {
var e, i, n, o;
for (o in this._tiles) e = o.split(":"), i = parseInt(e[0], 10), n = parseInt(e[1], 10), (i < t.min.x || i > t.max.x || n < t.min.y || n > t.max.y) && this._removeTile(o)
},
_removeTile: function(t) {
var e = this._tiles[t];
this.fire("tileunload", {
tile: e,
url: e.src
}), this.options.reuseTiles ? (o.DomUtil.removeClass(e, "leaflet-tile-loaded"), this._unusedTiles.push(e)) : e.parentNode === this._tileContainer && this._tileContainer.removeChild(e), o.Browser.android || (e.onload = null, e.src = o.Util.emptyImageUrl), delete this._tiles[t]
},
_addTile: function(t, e) {
var i = this._getTilePos(t),
n = this._getTile();
o.DomUtil.setPosition(n, i, o.Browser.chrome), this._tiles[t.x + ":" + t.y] = n, this._loadTile(n, t), n.parentNode !== this._tileContainer && e.appendChild(n)
},
_getZoomForUrl: function() {
var t = this.options,
e = this._map.getZoom();
return t.zoomReverse && (e = t.maxZoom - e), e += t.zoomOffset, t.maxNativeZoom ? Math.min(e, t.maxNativeZoom) : e
},
_getTilePos: function(t) {
var e = this._map.getPixelOrigin(),
i = this._getTileSize();
return t.multiplyBy(i).subtract(e)
},
getTileUrl: function(t) {
return o.Util.template(this._url, o.extend({
s: this._getSubdomain(t),
z: t.z,
x: t.x,
y: t.y
}, this.options))
},
_getWrapTileNum: function() {
var t = this._map.options.crs,
e = t.getSize(this._map.getZoom());
return e.divideBy(this._getTileSize())._floor()
},
_adjustTilePoint: function(t) {
var e = this._getWrapTileNum();
this.options.continuousWorld || this.options.noWrap || (t.x = (t.x % e.x + e.x) % e.x), this.options.tms && (t.y = e.y - t.y - 1), t.z = this._getZoomForUrl()
},
_getSubdomain: function(t) {
var e = Math.abs(t.x + t.y) % this.options.subdomains.length;
return this.options.subdomains[e]
},
_getTile: function() {
if (this.options.reuseTiles && this._unusedTiles.length > 0) {
var t = this._unusedTiles.pop();
return this._resetTile(t), t
}
return this._createTile()
},
_resetTile: function() {},
_createTile: function() {
var t = o.DomUtil.create("img", "leaflet-tile");
return t.style.width = t.style.height = this._getTileSize() + "px", t.galleryimg = "no", t.onselectstart = t.onmousemove = o.Util.falseFn, o.Browser.ielt9 && this.options.opacity !== i && o.DomUtil.setOpacity(t, this.options.opacity), o.Browser.mobileWebkit3d && (t.style.WebkitBackfaceVisibility = "hidden"), t
},
_loadTile: function(t, e) {
t._layer = this, t.onload = this._tileOnLoad, t.onerror = this._tileOnError, this._adjustTilePoint(e), t.src = this.getTileUrl(e), this.fire("tileloadstart", {
tile: t,
url: t.src
})
},
_tileLoaded: function() {
this._tilesToLoad--, this._animated && o.DomUtil.addClass(this._tileContainer, "leaflet-zoom-animated"), this._tilesToLoad || (this.fire("load"), this._animated && (clearTimeout(this._clearBgBufferTimer), this._clearBgBufferTimer = setTimeout(o.bind(this._clearBgBuffer, this), 500)))
},
_tileOnLoad: function() {
var t = this._layer;
this.src !== o.Util.emptyImageUrl && (o.DomUtil.addClass(this, "leaflet-tile-loaded"), t.fire("tileload", {
tile: this,
url: this.src
})), t._tileLoaded()
},
_tileOnError: function() {
var t = this._layer;
t.fire("tileerror", {
tile: this,
url: this.src
});
var e = t.options.errorTileUrl;
e && (this.src = e), t._tileLoaded()
}
}), o.tileLayer = function(t, e) {
return new o.TileLayer(t, e)
}, o.TileLayer.WMS = o.TileLayer.extend({
defaultWmsParams: {
service: "WMS",
request: "GetMap",
version: "1.1.1",
layers: "",
styles: "",
format: "image/jpeg",
transparent: !1
},
initialize: function(t, e) {
this._url = t;
var i = o.extend({}, this.defaultWmsParams),
n = e.tileSize || this.options.tileSize;
i.width = i.height = e.detectRetina && o.Browser.retina ? 2 * n : n;
for (var s in e) this.options.hasOwnProperty(s) || "crs" === s || (i[s] = e[s]);
this.wmsParams = i, o.setOptions(this, e)
},
onAdd: function(t) {
this._crs = this.options.crs || t.options.crs, this._wmsVersion = parseFloat(this.wmsParams.version);
var e = this._wmsVersion >= 1.3 ? "crs" : "srs";
this.wmsParams[e] = this._crs.code, o.TileLayer.prototype.onAdd.call(this, t)
},
getTileUrl: function(t) {
var e = this._map,
i = this.options.tileSize,
n = t.multiplyBy(i),
s = n.add([i, i]),
a = this._crs.project(e.unproject(n, t.z)),
r = this._crs.project(e.unproject(s, t.z)),
h = this._wmsVersion >= 1.3 && this._crs === o.CRS.EPSG4326 ? [r.y, a.x, a.y, r.x].join(",") : [a.x, r.y, r.x, a.y].join(","),
l = o.Util.template(this._url, {
s: this._getSubdomain(t)
});
return l + o.Util.getParamString(this.wmsParams, l, !0) + "&BBOX=" + h
},
setParams: function(t, e) {
return o.extend(this.wmsParams, t), e || this.redraw(), this
}
}), o.tileLayer.wms = function(t, e) {
return new o.TileLayer.WMS(t, e)
}, o.TileLayer.Canvas = o.TileLayer.extend({
options: {
async: !1
},
initialize: function(t) {
o.setOptions(this, t)
},
redraw: function() {
this._map && (this._reset({
hard: !0
}), this._update());
for (var t in this._tiles) this._redrawTile(this._tiles[t]);
return this
},
_redrawTile: function(t) {
this.drawTile(t, t._tilePoint, this._map._zoom)
},
_createTile: function() {
var t = o.DomUtil.create("canvas", "leaflet-tile");
return t.width = t.height = this.options.tileSize, t.onselectstart = t.onmousemove = o.Util.falseFn, t
},
_loadTile: function(t, e) {
t._layer = this, t._tilePoint = e, this._redrawTile(t), this.options.async || this.tileDrawn(t)
},
drawTile: function() {},
tileDrawn: function(t) {
this._tileOnLoad.call(t)
}
}), o.tileLayer.canvas = function(t) {
return new o.TileLayer.Canvas(t)
}, o.ImageOverlay = o.Class.extend({
includes: o.Mixin.Events,
options: {
opacity: 1
},
initialize: function(t, e, i) {
this._url = t, this._bounds = o.latLngBounds(e), o.setOptions(this, i)
},
onAdd: function(t) {
this._map = t, this._image || this._initImage(), t._panes.overlayPane.appendChild(this._image), t.on("viewreset", this._reset, this), t.options.zoomAnimation && o.Browser.any3d && t.on("zoomanim", this._animateZoom, this), this._reset()
},
onRemove: function(t) {
t.getPanes().overlayPane.removeChild(this._image), t.off("viewreset", this._reset, this), t.options.zoomAnimation && t.off("zoomanim", this._animateZoom, this)
},
addTo: function(t) {
return t.addLayer(this), this
},
setOpacity: function(t) {
return this.options.opacity = t, this._updateOpacity(), this
},
bringToFront: function() {
return this._image && this._map._panes.overlayPane.appendChild(this._image), this
},
bringToBack: function() {
var t = this._map._panes.overlayPane;
return this._image && t.insertBefore(this._image, t.firstChild), this
},
setUrl: function(t) {
this._url = t, this._image.src = this._url
},
getAttribution: function() {
return this.options.attribution
},
_initImage: function() {
this._image = o.DomUtil.create("img", "leaflet-image-layer"), this._map.options.zoomAnimation && o.Browser.any3d ? o.DomUtil.addClass(this._image, "leaflet-zoom-animated") : o.DomUtil.addClass(this._image, "leaflet-zoom-hide"), this._updateOpacity(), o.extend(this._image, {
galleryimg: "no",
onselectstart: o.Util.falseFn,
onmousemove: o.Util.falseFn,
onload: o.bind(this._onImageLoad, this),
src: this._url
})
},
_animateZoom: function(t) {
var e = this._map,
i = this._image,
n = e.getZoomScale(t.zoom),
s = this._bounds.getNorthWest(),
a = this._bounds.getSouthEast(),
r = e._latLngToNewLayerPoint(s, t.zoom, t.center),
h = e._latLngToNewLayerPoint(a, t.zoom, t.center)._subtract(r),
l = r._add(h._multiplyBy(.5 * (1 - 1 / n)));
i.style[o.DomUtil.TRANSFORM] = o.DomUtil.getTranslateString(l) + " scale(" + n + ") "
},
_reset: function() {
var t = this._image,
e = this._map.latLngToLayerPoint(this._bounds.getNorthWest()),
i = this._map.latLngToLayerPoint(this._bounds.getSouthEast())._subtract(e);
o.DomUtil.setPosition(t, e), t.style.width = i.x + "px", t.style.height = i.y + "px"
},
_onImageLoad: function() {
this.fire("load")
},
_updateOpacity: function() {
o.DomUtil.setOpacity(this._image, this.options.opacity)
}
}), o.imageOverlay = function(t, e, i) {
return new o.ImageOverlay(t, e, i)
}, o.Icon = o.Class.extend({
options: {
className: ""
},
initialize: function(t) {
o.setOptions(this, t)
},
createIcon: function(t) {
return this._createIcon("icon", t)
},
createShadow: function(t) {
return this._createIcon("shadow", t)
},
_createIcon: function(t, e) {
var i = this._getIconUrl(t);
if (!i) {
if ("icon" === t) throw new Error("iconUrl not set in Icon options (see the docs).");
return null
}
var n;
return n = e && "IMG" === e.tagName ? this._createImg(i, e) : this._createImg(i), this._setIconStyles(n, t), n
},
_setIconStyles: function(t, e) {
var i, n = this.options,
s = o.point(n[e + "Size"]);
i = o.point("shadow" === e ? n.shadowAnchor || n.iconAnchor : n.iconAnchor), !i && s && (i = s.divideBy(2, !0)), t.className = "leaflet-marker-" + e + " " + n.className, i && (t.style.marginLeft = -i.x + "px", t.style.marginTop = -i.y + "px"), s && (t.style.width = s.x + "px", t.style.height = s.y + "px")
},
_createImg: function(t, i) {
return i = i || e.createElement("img"), i.src = t, i
},
_getIconUrl: function(t) {
return o.Browser.retina && this.options[t + "RetinaUrl"] ? this.options[t + "RetinaUrl"] : this.options[t + "Url"]
}
}), o.icon = function(t) {
return new o.Icon(t)
}, o.Icon.Default = o.Icon.extend({
options: {
iconSize: [25, 41],
iconAnchor: [12, 41],
popupAnchor: [1, -34],
shadowSize: [41, 41]
},
_getIconUrl: function(t) {
var e = t + "Url";
if (this.options[e]) return this.options[e];
o.Browser.retina && "icon" === t && (t += "-2x");
var i = o.Icon.Default.imagePath;
if (!i) throw new Error("Couldn't autodetect L.Icon.Default.imagePath, set it manually.");
return i + "/marker-" + t + ".png"
}
}), o.Icon.Default.imagePath = function() {
var t, i, n, o, s, a = e.getElementsByTagName("script"),
r = /[\/^]leaflet[\-\._]?([\w\-\._]*)\.js\??/;
for (t = 0, i = a.length; i > t; t++)
if (n = a[t].src, o = n.match(r)) return s = n.split(r)[0], (s ? s + "/" : "") + "images"
}(), o.Marker = o.Class.extend({
includes: o.Mixin.Events,
options: {
icon: new o.Icon.Default,
title: "",
alt: "",
clickable: !0,
draggable: !1,
keyboard: !0,
zIndexOffset: 0,
opacity: 1,
riseOnHover: !1,
riseOffset: 250
},
initialize: function(t, e) {
o.setOptions(this, e), this._latlng = o.latLng(t)
},
onAdd: function(t) {
this._map = t, t.on("viewreset", this.update, this), this._initIcon(), this.update(), this.fire("add"), t.options.zoomAnimation && t.options.markerZoomAnimation && t.on("zoomanim", this._animateZoom, this)
},
addTo: function(t) {
return t.addLayer(this), this
},
onRemove: function(t) {
this.dragging && this.dragging.disable(), this._removeIcon(), this._removeShadow(), this.fire("remove"), t.off({
viewreset: this.update,
zoomanim: this._animateZoom
}, this), this._map = null
},
getLatLng: function() {
return this._latlng
},
setLatLng: function(t) {
return this._latlng = o.latLng(t), this.update(), this.fire("move", {
latlng: this._latlng
})
},
setZIndexOffset: function(t) {
return this.options.zIndexOffset = t, this.update(), this
},
setIcon: function(t) {
return this.options.icon = t, this._map && (this._initIcon(), this.update()), this._popup && this.bindPopup(this._popup), this
},
update: function() {
if (this._icon) {
var t = this._map.latLngToLayerPoint(this._latlng).round();
this._setPos(t)
}
return this
},
_initIcon: function() {
var t = this.options,
e = this._map,
i = e.options.zoomAnimation && e.options.markerZoomAnimation,
n = i ? "leaflet-zoom-animated" : "leaflet-zoom-hide",
s = t.icon.createIcon(this._icon),
a = !1;
s !== this._icon && (this._icon && this._removeIcon(), a = !0, t.title && (s.title = t.title), t.alt && (s.alt = t.alt)), o.DomUtil.addClass(s, n), t.keyboard && (s.tabIndex = "0"), this._icon = s, this._initInteraction(), t.riseOnHover && o.DomEvent.on(s, "mouseover", this._bringToFront, this).on(s, "mouseout", this._resetZIndex, this);
var r = t.icon.createShadow(this._shadow),
h = !1;
r !== this._shadow && (this._removeShadow(), h = !0), r && o.DomUtil.addClass(r, n), this._shadow = r, t.opacity < 1 && this._updateOpacity();
var l = this._map._panes;
a && l.markerPane.appendChild(this._icon), r && h && l.shadowPane.appendChild(this._shadow)
},
_removeIcon: function() {
this.options.riseOnHover && o.DomEvent.off(this._icon, "mouseover", this._bringToFront).off(this._icon, "mouseout", this._resetZIndex), this._map._panes.markerPane.removeChild(this._icon), this._icon = null
},
_removeShadow: function() {
this._shadow && this._map._panes.shadowPane.removeChild(this._shadow), this._shadow = null
},
_setPos: function(t) {
o.DomUtil.setPosition(this._icon, t), this._shadow && o.DomUtil.setPosition(this._shadow, t), this._zIndex = t.y + this.options.zIndexOffset, this._resetZIndex()
},
_updateZIndex: function(t) {
this._icon.style.zIndex = this._zIndex + t
},
_animateZoom: function(t) {
var e = this._map._latLngToNewLayerPoint(this._latlng, t.zoom, t.center).round();
this._setPos(e)
},
_initInteraction: function() {
if (this.options.clickable) {
var t = this._icon,
e = ["dblclick", "mousedown", "mouseover", "mouseout", "contextmenu"];
o.DomUtil.addClass(t, "leaflet-clickable"), o.DomEvent.on(t, "click", this._onMouseClick, this), o.DomEvent.on(t, "keypress", this._onKeyPress, this);
for (var i = 0; i < e.length; i++) o.DomEvent.on(t, e[i], this._fireMouseEvent, this);
o.Handler.MarkerDrag && (this.dragging = new o.Handler.MarkerDrag(this), this.options.draggable && this.dragging.enable())
}
},
_onMouseClick: function(t) {
var e = this.dragging && this.dragging.moved();
(this.hasEventListeners(t.type) || e) && o.DomEvent.stopPropagation(t), e || (this.dragging && this.dragging._enabled || !this._map.dragging || !this._map.dragging.moved()) && this.fire(t.type, {
originalEvent: t,
latlng: this._latlng
})
},
_onKeyPress: function(t) {
13 === t.keyCode && this.fire("click", {
originalEvent: t,
latlng: this._latlng
})
},
_fireMouseEvent: function(t) {
this.fire(t.type, {
originalEvent: t,
latlng: this._latlng
}), "contextmenu" === t.type && this.hasEventListeners(t.type) && o.DomEvent.preventDefault(t), "mousedown" !== t.type ? o.DomEvent.stopPropagation(t) : o.DomEvent.preventDefault(t)
},
setOpacity: function(t) {
return this.options.opacity = t, this._map && this._updateOpacity(), this
},
_updateOpacity: function() {
o.DomUtil.setOpacity(this._icon, this.options.opacity), this._shadow && o.DomUtil.setOpacity(this._shadow, this.options.opacity)
},
_bringToFront: function() {
this._updateZIndex(this.options.riseOffset)
},
_resetZIndex: function() {
this._updateZIndex(0)
}
}), o.marker = function(t, e) {
return new o.Marker(t, e)
}, o.DivIcon = o.Icon.extend({
options: {
iconSize: [12, 12],
className: "leaflet-div-icon",
html: !1
},
createIcon: function(t) {
var i = t && "DIV" === t.tagName ? t : e.createElement("div"),
n = this.options;
return i.innerHTML = n.html !== !1 ? n.html : "", n.bgPos && (i.style.backgroundPosition = -n.bgPos.x + "px " + -n.bgPos.y + "px"), this._setIconStyles(i, "icon"), i
},
createShadow: function() {
return null
}
}), o.divIcon = function(t) {
return new o.DivIcon(t)
}, o.Map.mergeOptions({
closePopupOnClick: !0
}), o.Popup = o.Class.extend({
includes: o.Mixin.Events,
options: {
minWidth: 50,
maxWidth: 300,
autoPan: !0,
closeButton: !0,
offset: [0, 7],
autoPanPadding: [5, 5],
keepInView: !1,
className: "",
zoomAnimation: !0
},
initialize: function(t, e) {
o.setOptions(this, t), this._source = e, this._animated = o.Browser.any3d && this.options.zoomAnimation, this._isOpen = !1
},
onAdd: function(t) {
this._map = t, this._container || this._initLayout();
var e = t.options.fadeAnimation;
e && o.DomUtil.setOpacity(this._container, 0), t._panes.popupPane.appendChild(this._container), t.on(this._getEvents(), this), this.update(), e && o.DomUtil.setOpacity(this._container, 1), this.fire("open"), t.fire("popupopen", {
popup: this
}), this._source && this._source.fire("popupopen", {
popup: this
})
},
addTo: function(t) {
return t.addLayer(this), this
},
openOn: function(t) {
return t.openPopup(this), this
},
onRemove: function(t) {
t._panes.popupPane.removeChild(this._container), o.Util.falseFn(this._container.offsetWidth), t.off(this._getEvents(), this), t.options.fadeAnimation && o.DomUtil.setOpacity(this._container, 0), this._map = null, this.fire("close"), t.fire("popupclose", {
popup: this
}), this._source && this._source.fire("popupclose", {
popup: this
})
},
getLatLng: function() {
return this._latlng
},
setLatLng: function(t) {
return this._latlng = o.latLng(t), this._map && (this._updatePosition(), this._adjustPan()), this
},
getContent: function() {
return this._content
},
setContent: function(t) {
return this._content = t, this.update(), this
},
update: function() {
this._map && (this._container.style.visibility = "hidden", this._updateContent(), this._updateLayout(), this._updatePosition(), this._container.style.visibility = "", this._adjustPan())
},
_getEvents: function() {
var t = {
viewreset: this._updatePosition
};
return this._animated && (t.zoomanim = this._zoomAnimation), ("closeOnClick" in this.options ? this.options.closeOnClick : this._map.options.closePopupOnClick) && (t.preclick = this._close), this.options.keepInView && (t.moveend = this._adjustPan), t
},
_close: function() {
this._map && this._map.closePopup(this)
},
_initLayout: function() {
var t, e = "leaflet-popup",
i = e + " " + this.options.className + " leaflet-zoom-" + (this._animated ? "animated" : "hide"),
n = this._container = o.DomUtil.create("div", i);
this.options.closeButton && (t = this._closeButton = o.DomUtil.create("a", e + "-close-button", n), t.href = "#close", t.innerHTML = "×", o.DomEvent.disableClickPropagation(t), o.DomEvent.on(t, "click", this._onCloseButtonClick, this));
var s = this._wrapper = o.DomUtil.create("div", e + "-content-wrapper", n);
o.DomEvent.disableClickPropagation(s), this._contentNode = o.DomUtil.create("div", e + "-content", s), o.DomEvent.disableScrollPropagation(this._contentNode), o.DomEvent.on(s, "contextmenu", o.DomEvent.stopPropagation), this._tipContainer = o.DomUtil.create("div", e + "-tip-container", n), this._tip = o.DomUtil.create("div", e + "-tip", this._tipContainer)
},
_updateContent: function() {
if (this._content) {
if ("string" == typeof this._content) this._contentNode.innerHTML = this._content;
else {
for (; this._contentNode.hasChildNodes();) this._contentNode.removeChild(this._contentNode.firstChild);
this._contentNode.appendChild(this._content)
}
this.fire("contentupdate")
}
},
_updateLayout: function() {
var t = this._contentNode,
e = t.style;
e.width = "", e.whiteSpace = "nowrap";
var i = t.offsetWidth;
i = Math.min(i, this.options.maxWidth), i = Math.max(i, this.options.minWidth), e.width = i + 1 + "px", e.whiteSpace = "", e.height = "";
var n = t.offsetHeight,
s = this.options.maxHeight,
a = "leaflet-popup-scrolled";
s && n > s ? (e.height = s + "px", o.DomUtil.addClass(t, a)) : o.DomUtil.removeClass(t, a), this._containerWidth = this._container.offsetWidth
},
_updatePosition: function() {
if (this._map) {
var t = this._map.latLngToLayerPoint(this._latlng),
e = this._animated,
i = o.point(this.options.offset);
e && o.DomUtil.setPosition(this._container, t), this._containerBottom = -i.y - (e ? 0 : t.y), this._containerLeft = -Math.round(this._containerWidth / 2) + i.x + (e ? 0 : t.x), this._container.style.bottom = this._containerBottom + "px", this._container.style.left = this._containerLeft + "px"
}
},
_zoomAnimation: function(t) {
var e = this._map._latLngToNewLayerPoint(this._latlng, t.zoom, t.center);
o.DomUtil.setPosition(this._container, e)
},
_adjustPan: function() {
if (this.options.autoPan) {
var t = this._map,
e = this._container.offsetHeight,
i = this._containerWidth,
n = new o.Point(this._containerLeft, -e - this._containerBottom);
this._animated && n._add(o.DomUtil.getPosition(this._container));
var s = t.layerPointToContainerPoint(n),
a = o.point(this.options.autoPanPadding),
r = o.point(this.options.autoPanPaddingTopLeft || a),
h = o.point(this.options.autoPanPaddingBottomRight || a),
l = t.getSize(),
u = 0,
c = 0;
s.x + i + h.x > l.x && (u = s.x + i - l.x + h.x), s.x - u - r.x < 0 && (u = s.x - r.x), s.y + e + h.y > l.y && (c = s.y + e - l.y + h.y), s.y - c - r.y < 0 && (c = s.y - r.y), (u || c) && t.fire("autopanstart").panBy([u, c])
}
},
_onCloseButtonClick: function(t) {
this._close(), o.DomEvent.stop(t)
}
}), o.popup = function(t, e) {
return new o.Popup(t, e)
}, o.Map.include({
openPopup: function(t, e, i) {
if (this.closePopup(), !(t instanceof o.Popup)) {
var n = t;
t = new o.Popup(i).setLatLng(e).setContent(n)
}
return t._isOpen = !0, this._popup = t, this.addLayer(t)
},
closePopup: function(t) {
return t && t !== this._popup || (t = this._popup, this._popup = null), t && (this.removeLayer(t), t._isOpen = !1), this
}
}), o.Marker.include({
openPopup: function() {
return this._popup && this._map && !this._map.hasLayer(this._popup) && (this._popup.setLatLng(this._latlng), this._map.openPopup(this._popup)), this
},
closePopup: function() {
return this._popup && this._popup._close(), this
},
togglePopup: function() {
return this._popup && (this._popup._isOpen ? this.closePopup() : this.openPopup()), this
},
bindPopup: function(t, e) {
var i = o.point(this.options.icon.options.popupAnchor || [0, 0]);
return i = i.add(o.Popup.prototype.options.offset), e && e.offset && (i = i.add(e.offset)), e = o.extend({
offset: i
}, e), this._popupHandlersAdded || (this.on("click", this.togglePopup, this).on("remove", this.closePopup, this).on("move", this._movePopup, this), this._popupHandlersAdded = !0), t instanceof o.Popup ? (o.setOptions(t, e), this._popup = t) : this._popup = new o.Popup(e, this).setContent(t), this
},
setPopupContent: function(t) {
return this._popup && this._popup.setContent(t), this
},
unbindPopup: function() {
return this._popup && (this._popup = null, this.off("click", this.togglePopup, this).off("remove", this.closePopup, this).off("move", this._movePopup, this), this._popupHandlersAdded = !1), this
},
getPopup: function() {
return this._popup
},
_movePopup: function(t) {
this._popup.setLatLng(t.latlng)
}
}), o.LayerGroup = o.Class.extend({
initialize: function(t) {
this._layers = {};
var e, i;
if (t)
for (e = 0, i = t.length; i > e; e++) this.addLayer(t[e])
},
addLayer: function(t) {
var e = this.getLayerId(t);
return this._layers[e] = t, this._map && this._map.addLayer(t), this
},
removeLayer: function(t) {
var e = t in this._layers ? t : this.getLayerId(t);
return this._map && this._layers[e] && this._map.removeLayer(this._layers[e]), delete this._layers[e], this
},
hasLayer: function(t) {
return t ? t in this._layers || this.getLayerId(t) in this._layers : !1
},
clearLayers: function() {
return this.eachLayer(this.removeLayer, this), this
},
invoke: function(t) {
var e, i, n = Array.prototype.slice.call(arguments, 1);
for (e in this._layers) i = this._layers[e], i[t] && i[t].apply(i, n);
return this
},
onAdd: function(t) {
this._map = t, this.eachLayer(t.addLayer, t)
},
onRemove: function(t) {
this.eachLayer(t.removeLayer, t), this._map = null
},
addTo: function(t) {
return t.addLayer(this), this
},
eachLayer: function(t, e) {
for (var i in this._layers) t.call(e, this._layers[i]);
return this
},
getLayer: function(t) {
return this._layers[t]
},
getLayers: function() {
var t = [];
for (var e in this._layers) t.push(this._layers[e]);
return t
},
setZIndex: function(t) {
return this.invoke("setZIndex", t)
},
getLayerId: function(t) {
return o.stamp(t)
}
}), o.layerGroup = function(t) {
return new o.LayerGroup(t)
}, o.FeatureGroup = o.LayerGroup.extend({
includes: o.Mixin.Events,
statics: {
EVENTS: "click dblclick mouseover mouseout mousemove contextmenu popupopen popupclose"
},
addLayer: function(t) {
return this.hasLayer(t) ? this : ("on" in t && t.on(o.FeatureGroup.EVENTS, this._propagateEvent, this), o.LayerGroup.prototype.addLayer.call(this, t), this._popupContent && t.bindPopup && t.bindPopup(this._popupContent, this._popupOptions), this.fire("layeradd", {
layer: t
}))
},
removeLayer: function(t) {
return this.hasLayer(t) ? (t in this._layers && (t = this._layers[t]), t.off(o.FeatureGroup.EVENTS, this._propagateEvent, this), o.LayerGroup.prototype.removeLayer.call(this, t), this._popupContent && this.invoke("unbindPopup"), this.fire("layerremove", {
layer: t
})) : this
},
bindPopup: function(t, e) {
return this._popupContent = t, this._popupOptions = e, this.invoke("bindPopup", t, e)
},
openPopup: function(t) {
for (var e in this._layers) {
this._layers[e].openPopup(t);
break
}
return this
},
setStyle: function(t) {
return this.invoke("setStyle", t)
},
bringToFront: function() {
return this.invoke("bringToFront")
},
bringToBack: function() {
return this.invoke("bringToBack")
},
getBounds: function() {
var t = new o.LatLngBounds;
return this.eachLayer(function(e) {
t.extend(e instanceof o.Marker ? e.getLatLng() : e.getBounds())
}), t
},
_propagateEvent: function(t) {
t = o.extend({
layer: t.target,
target: this
}, t), this.fire(t.type, t)
}
}), o.featureGroup = function(t) {
return new o.FeatureGroup(t)
}, o.Path = o.Class.extend({
includes: [o.Mixin.Events],
statics: {
CLIP_PADDING: function() {
var e = o.Browser.mobile ? 1280 : 2e3,
i = (e / Math.max(t.outerWidth, t.outerHeight) - 1) / 2;
return Math.max(0, Math.min(.5, i))
}()
},
options: {
stroke: !0,
color: "#0033ff",
dashArray: null,
lineCap: null,
lineJoin: null,
weight: 5,
opacity: .5,
fill: !1,
fillColor: null,
fillOpacity: .2,
clickable: !0
},
initialize: function(t) {
o.setOptions(this, t)
},
onAdd: function(t) {
this._map = t, this._container || (this._initElements(), this._initEvents()), this.projectLatlngs(), this._updatePath(), this._container && this._map._pathRoot.appendChild(this._container), this.fire("add"), t.on({
viewreset: this.projectLatlngs,
moveend: this._updatePath
}, this)
},
addTo: function(t) {
return t.addLayer(this), this
},
onRemove: function(t) {
t._pathRoot.removeChild(this._container), this.fire("remove"), this._map = null, o.Browser.vml && (this._container = null, this._stroke = null, this._fill = null), t.off({
viewreset: this.projectLatlngs,
moveend: this._updatePath
}, this)
},
projectLatlngs: function() {},
setStyle: function(t) {
return o.setOptions(this, t), this._container && this._updateStyle(), this
},
redraw: function() {
return this._map && (this.projectLatlngs(), this._updatePath()), this
}
}), o.Map.include({
_updatePathViewport: function() {
var t = o.Path.CLIP_PADDING,
e = this.getSize(),
i = o.DomUtil.getPosition(this._mapPane),
n = i.multiplyBy(-1)._subtract(e.multiplyBy(t)._round()),
s = n.add(e.multiplyBy(1 + 2 * t)._round());
this._pathViewport = new o.Bounds(n, s)
}
}), o.Path.SVG_NS = "http://www.w3.org/2000/svg", o.Browser.svg = !(!e.createElementNS || !e.createElementNS(o.Path.SVG_NS, "svg").createSVGRect), o.Path = o.Path.extend({
statics: {
SVG: o.Browser.svg
},
bringToFront: function() {
var t = this._map._pathRoot,
e = this._container;
return e && t.lastChild !== e && t.appendChild(e), this
},
bringToBack: function() {
var t = this._map._pathRoot,
e = this._container,
i = t.firstChild;
return e && i !== e && t.insertBefore(e, i), this
},
getPathString: function() {},
_createElement: function(t) {
return e.createElementNS(o.Path.SVG_NS, t)
},
_initElements: function() {
this._map._initPathRoot(), this._initPath(), this._initStyle()
},
_initPath: function() {
this._container = this._createElement("g"), this._path = this._createElement("path"), this.options.className && o.DomUtil.addClass(this._path, this.options.className), this._container.appendChild(this._path)
},
_initStyle: function() {
this.options.stroke && (this._path.setAttribute("stroke-linejoin", "round"), this._path.setAttribute("stroke-linecap", "round")), this.options.fill && this._path.setAttribute("fill-rule", "evenodd"), this.options.pointerEvents && this._path.setAttribute("pointer-events", this.options.pointerEvents), this.options.clickable || this.options.pointerEvents || this._path.setAttribute("pointer-events", "none"), this._updateStyle()
},
_updateStyle: function() {
this.options.stroke ? (this._path.setAttribute("stroke", this.options.color), this._path.setAttribute("stroke-opacity", this.options.opacity), this._path.setAttribute("stroke-width", this.options.weight), this.options.dashArray ? this._path.setAttribute("stroke-dasharray", this.options.dashArray) : this._path.removeAttribute("stroke-dasharray"), this.options.lineCap && this._path.setAttribute("stroke-linecap", this.options.lineCap), this.options.lineJoin && this._path.setAttribute("stroke-linejoin", this.options.lineJoin)) : this._path.setAttribute("stroke", "none"), this.options.fill ? (this._path.setAttribute("fill", this.options.fillColor || this.options.color), this._path.setAttribute("fill-opacity", this.options.fillOpacity)) : this._path.setAttribute("fill", "none")
},
_updatePath: function() {
var t = this.getPathString();
t || (t = "M0 0"), this._path.setAttribute("d", t)
},
_initEvents: function() {
if (this.options.clickable) {
(o.Browser.svg || !o.Browser.vml) && o.DomUtil.addClass(this._path, "leaflet-clickable"), o.DomEvent.on(this._container, "click", this._onMouseClick, this);
for (var t = ["dblclick", "mousedown", "mouseover", "mouseout", "mousemove", "contextmenu"], e = 0; e < t.length; e++) o.DomEvent.on(this._container, t[e], this._fireMouseEvent, this)
}
},
_onMouseClick: function(t) {
this._map.dragging && this._map.dragging.moved() || this._fireMouseEvent(t)
},
_fireMouseEvent: function(t) {
if (this.hasEventListeners(t.type)) {
var e = this._map,
i = e.mouseEventToContainerPoint(t),
n = e.containerPointToLayerPoint(i),
s = e.layerPointToLatLng(n);
this.fire(t.type, {
latlng: s,
layerPoint: n,
containerPoint: i,
originalEvent: t
}), "contextmenu" === t.type && o.DomEvent.preventDefault(t), "mousemove" !== t.type && o.DomEvent.stopPropagation(t)
}
}
}), o.Map.include({
_initPathRoot: function() {
this._pathRoot || (this._pathRoot = o.Path.prototype._createElement("svg"), this._panes.overlayPane.appendChild(this._pathRoot), this.options.zoomAnimation && o.Browser.any3d ? (o.DomUtil.addClass(this._pathRoot, "leaflet-zoom-animated"), this.on({
zoomanim: this._animatePathZoom,
zoomend: this._endPathZoom
})) : o.DomUtil.addClass(this._pathRoot, "leaflet-zoom-hide"), this.on("moveend", this._updateSvgViewport), this._updateSvgViewport())
},
_animatePathZoom: function(t) {
var e = this.getZoomScale(t.zoom),
i = this._getCenterOffset(t.center)._multiplyBy(-e)._add(this._pathViewport.min);
this._pathRoot.style[o.DomUtil.TRANSFORM] = o.DomUtil.getTranslateString(i) + " scale(" + e + ") ", this._pathZooming = !0
},
_endPathZoom: function() {
this._pathZooming = !1
},
_updateSvgViewport: function() {
if (!this._pathZooming) {
this._updatePathViewport();
var t = this._pathViewport,
e = t.min,
i = t.max,
n = i.x - e.x,
s = i.y - e.y,
a = this._pathRoot,
r = this._panes.overlayPane;
o.Browser.mobileWebkit && r.removeChild(a), o.DomUtil.setPosition(a, e), a.setAttribute("width", n), a.setAttribute("height", s), a.setAttribute("viewBox", [e.x, e.y, n, s].join(" ")), o.Browser.mobileWebkit && r.appendChild(a)
}
}
}), o.Path.include({
bindPopup: function(t, e) {
return t instanceof o.Popup ? this._popup = t : ((!this._popup || e) && (this._popup = new o.Popup(e, this)), this._popup.setContent(t)), this._popupHandlersAdded || (this.on("click", this._openPopup, this).on("remove", this.closePopup, this), this._popupHandlersAdded = !0), this
},
unbindPopup: function() {
return this._popup && (this._popup = null, this.off("click", this._openPopup).off("remove", this.closePopup), this._popupHandlersAdded = !1), this
},
openPopup: function(t) {
return this._popup && (t = t || this._latlng || this._latlngs[Math.floor(this._latlngs.length / 2)], this._openPopup({
latlng: t
})), this
},
closePopup: function() {
return this._popup && this._popup._close(), this
},
_openPopup: function(t) {
this._popup.setLatLng(t.latlng), this._map.openPopup(this._popup)
}
}), o.Browser.vml = !o.Browser.svg && function() {
try {
var t = e.createElement("div");
t.innerHTML = '<v:shape adj="1"/>';
var i = t.firstChild;
return i.style.behavior = "url(#default#VML)", i && "object" == typeof i.adj
} catch (n) {
return !1
}
}(), o.Path = o.Browser.svg || !o.Browser.vml ? o.Path : o.Path.extend({
statics: {
VML: !0,
CLIP_PADDING: .02
},
_createElement: function() {
try {
return e.namespaces.add("lvml", "urn:schemas-microsoft-com:vml"),
function(t) {
return e.createElement("<lvml:" + t + ' class="lvml">')
}
} catch (t) {
return function(t) {
return e.createElement("<" + t + ' xmlns="urn:schemas-microsoft.com:vml" class="lvml">')
}
}
}(),
_initPath: function() {
var t = this._container = this._createElement("shape");
o.DomUtil.addClass(t, "leaflet-vml-shape" + (this.options.className ? " " + this.options.className : "")), this.options.clickable && o.DomUtil.addClass(t, "leaflet-clickable"), t.coordsize = "1 1", this._path = this._createElement("path"), t.appendChild(this._path), this._map._pathRoot.appendChild(t)
},
_initStyle: function() {
this._updateStyle()
},
_updateStyle: function() {
var t = this._stroke,
e = this._fill,
i = this.options,
n = this._container;
n.stroked = i.stroke, n.filled = i.fill, i.stroke ? (t || (t = this._stroke = this._createElement("stroke"), t.endcap = "round", n.appendChild(t)), t.weight = i.weight + "px", t.color = i.color, t.opacity = i.opacity, t.dashStyle = i.dashArray ? o.Util.isArray(i.dashArray) ? i.dashArray.join(" ") : i.dashArray.replace(/( *, *)/g, " ") : "", i.lineCap && (t.endcap = i.lineCap.replace("butt", "flat")), i.lineJoin && (t.joinstyle = i.lineJoin)) : t && (n.removeChild(t), this._stroke = null), i.fill ? (e || (e = this._fill = this._createElement("fill"), n.appendChild(e)), e.color = i.fillColor || i.color, e.opacity = i.fillOpacity) : e && (n.removeChild(e), this._fill = null)
},
_updatePath: function() {
var t = this._container.style;
t.display = "none", this._path.v = this.getPathString() + " ", t.display = ""
}
}), o.Map.include(o.Browser.svg || !o.Browser.vml ? {} : {
_initPathRoot: function() {
if (!this._pathRoot) {
var t = this._pathRoot = e.createElement("div");
t.className = "leaflet-vml-container", this._panes.overlayPane.appendChild(t), this.on("moveend", this._updatePathViewport), this._updatePathViewport()
}
}
}), o.Browser.canvas = function() {
return !!e.createElement("canvas").getContext
}(), o.Path = o.Path.SVG && !t.L_PREFER_CANVAS || !o.Browser.canvas ? o.Path : o.Path.extend({
statics: {
CANVAS: !0,
SVG: !1
},
redraw: function() {
return this._map && (this.projectLatlngs(), this._requestUpdate()), this
},
setStyle: function(t) {
return o.setOptions(this, t), this._map && (this._updateStyle(), this._requestUpdate()), this
},
onRemove: function(t) {
t.off("viewreset", this.projectLatlngs, this).off("moveend", this._updatePath, this), this.options.clickable && (this._map.off("click", this._onClick, this), this._map.off("mousemove", this._onMouseMove, this)), this._requestUpdate(), this.fire("remove"), this._map = null
},
_requestUpdate: function() {
this._map && !o.Path._updateRequest && (o.Path._updateRequest = o.Util.requestAnimFrame(this._fireMapMoveEnd, this._map))
},
_fireMapMoveEnd: function() {
o.Path._updateRequest = null, this.fire("moveend")
},
_initElements: function() {
this._map._initPathRoot(), this._ctx = this._map._canvasCtx
},
_updateStyle: function() {
var t = this.options;
t.stroke && (this._ctx.lineWidth = t.weight, this._ctx.strokeStyle = t.color), t.fill && (this._ctx.fillStyle = t.fillColor || t.color)
},
_drawPath: function() {
var t, e, i, n, s, a;
for (this._ctx.beginPath(), t = 0, i = this._parts.length; i > t; t++) {
for (e = 0, n = this._parts[t].length; n > e; e++) s = this._parts[t][e], a = (0 === e ? "move" : "line") + "To", this._ctx[a](s.x, s.y);
this instanceof o.Polygon && this._ctx.closePath()
}
},
_checkIfEmpty: function() {
return !this._parts.length
},
_updatePath: function() {
if (!this._checkIfEmpty()) {
var t = this._ctx,
e = this.options;
this._drawPath(), t.save(), this._updateStyle(), e.fill && (t.globalAlpha = e.fillOpacity, t.fill()), e.stroke && (t.globalAlpha = e.opacity, t.stroke()), t.restore()
}
},
_initEvents: function() {
this.options.clickable && (this._map.on("mousemove", this._onMouseMove, this), this._map.on("click", this._onClick, this))
},
_onClick: function(t) {
this._containsPoint(t.layerPoint) && this.fire("click", t)
},
_onMouseMove: function(t) {
this._map && !this._map._animatingZoom && (this._containsPoint(t.layerPoint) ? (this._ctx.canvas.style.cursor = "pointer", this._mouseInside = !0, this.fire("mouseover", t)) : this._mouseInside && (this._ctx.canvas.style.cursor = "", this._mouseInside = !1, this.fire("mouseout", t)))
}
}), o.Map.include(o.Path.SVG && !t.L_PREFER_CANVAS || !o.Browser.canvas ? {} : {
_initPathRoot: function() {
var t, i = this._pathRoot;
i || (i = this._pathRoot = e.createElement("canvas"), i.style.position = "absolute", t = this._canvasCtx = i.getContext("2d"), t.lineCap = "round", t.lineJoin = "round", this._panes.overlayPane.appendChild(i), this.options.zoomAnimation && (this._pathRoot.className = "leaflet-zoom-animated", this.on("zoomanim", this._animatePathZoom), this.on("zoomend", this._endPathZoom)), this.on("moveend", this._updateCanvasViewport), this._updateCanvasViewport())
},
_updateCanvasViewport: function() {
if (!this._pathZooming) {
this._updatePathViewport();
var t = this._pathViewport,
e = t.min,
i = t.max.subtract(e),
n = this._pathRoot;
o.DomUtil.setPosition(n, e), n.width = i.x, n.height = i.y, n.getContext("2d").translate(-e.x, -e.y)
}
}
}), o.LineUtil = {
simplify: function(t, e) {
if (!e || !t.length) return t.slice();
var i = e * e;
return t = this._reducePoints(t, i), t = this._simplifyDP(t, i)
},
pointToSegmentDistance: function(t, e, i) {
return Math.sqrt(this._sqClosestPointOnSegment(t, e, i, !0))
},
closestPointOnSegment: function(t, e, i) {
return this._sqClosestPointOnSegment(t, e, i)
},
_simplifyDP: function(t, e) {
var n = t.length,
o = typeof Uint8Array != i + "" ? Uint8Array : Array,
s = new o(n);
s[0] = s[n - 1] = 1, this._simplifyDPStep(t, s, e, 0, n - 1);
var a, r = [];
for (a = 0; n > a; a++) s[a] && r.push(t[a]);
return r
},
_simplifyDPStep: function(t, e, i, n, o) {
var s, a, r, h = 0;
for (a = n + 1; o - 1 >= a; a++) r = this._sqClosestPointOnSegment(t[a], t[n], t[o], !0), r > h && (s = a, h = r);
h > i && (e[s] = 1, this._simplifyDPStep(t, e, i, n, s), this._simplifyDPStep(t, e, i, s, o))
},
_reducePoints: function(t, e) {
for (var i = [t[0]], n = 1, o = 0, s = t.length; s > n; n++) this._sqDist(t[n], t[o]) > e && (i.push(t[n]), o = n);
return s - 1 > o && i.push(t[s - 1]), i
},
clipSegment: function(t, e, i, n) {
var o, s, a, r = n ? this._lastCode : this._getBitCode(t, i),
h = this._getBitCode(e, i);
for (this._lastCode = h;;) {
if (!(r | h)) return [t, e];
if (r & h) return !1;
o = r || h, s = this._getEdgeIntersection(t, e, o, i), a = this._getBitCode(s, i), o === r ? (t = s, r = a) : (e = s, h = a)
}
},
_getEdgeIntersection: function(t, e, i, n) {
var s = e.x - t.x,
a = e.y - t.y,
r = n.min,
h = n.max;
return 8 & i ? new o.Point(t.x + s * (h.y - t.y) / a, h.y) : 4 & i ? new o.Point(t.x + s * (r.y - t.y) / a, r.y) : 2 & i ? new o.Point(h.x, t.y + a * (h.x - t.x) / s) : 1 & i ? new o.Point(r.x, t.y + a * (r.x - t.x) / s) : void 0
},
_getBitCode: function(t, e) {
var i = 0;
return t.x < e.min.x ? i |= 1 : t.x > e.max.x && (i |= 2), t.y < e.min.y ? i |= 4 : t.y > e.max.y && (i |= 8), i
},
_sqDist: function(t, e) {
var i = e.x - t.x,
n = e.y - t.y;
return i * i + n * n
},
_sqClosestPointOnSegment: function(t, e, i, n) {
var s, a = e.x,
r = e.y,
h = i.x - a,
l = i.y - r,
u = h * h + l * l;
return u > 0 && (s = ((t.x - a) * h + (t.y - r) * l) / u, s > 1 ? (a = i.x, r = i.y) : s > 0 && (a += h * s, r += l * s)), h = t.x - a, l = t.y - r, n ? h * h + l * l : new o.Point(a, r)
}
}, o.Polyline = o.Path.extend({
initialize: function(t, e) {
o.Path.prototype.initialize.call(this, e), this._latlngs = this._convertLatLngs(t)
},
options: {
smoothFactor: 1,
noClip: !1
},
projectLatlngs: function() {
this._originalPoints = [];
for (var t = 0, e = this._latlngs.length; e > t; t++) this._originalPoints[t] = this._map.latLngToLayerPoint(this._latlngs[t])
},
getPathString: function() {
for (var t = 0, e = this._parts.length, i = ""; e > t; t++) i += this._getPathPartStr(this._parts[t]);
return i
},
getLatLngs: function() {
return this._latlngs
},
setLatLngs: function(t) {
return this._latlngs = this._convertLatLngs(t), this.redraw()
},
addLatLng: function(t) {
return this._latlngs.push(o.latLng(t)), this.redraw()
},
spliceLatLngs: function() {
var t = [].splice.apply(this._latlngs, arguments);
return this._convertLatLngs(this._latlngs, !0), this.redraw(), t
},
closestLayerPoint: function(t) {
for (var e, i, n = 1 / 0, s = this._parts, a = null, r = 0, h = s.length; h > r; r++)
for (var l = s[r], u = 1, c = l.length; c > u; u++) {
e = l[u - 1], i = l[u];
var d = o.LineUtil._sqClosestPointOnSegment(t, e, i, !0);
n > d && (n = d, a = o.LineUtil._sqClosestPointOnSegment(t, e, i))
}
return a && (a.distance = Math.sqrt(n)), a
},
getBounds: function() {
return new o.LatLngBounds(this.getLatLngs())
},
_convertLatLngs: function(t, e) {
var i, n, s = e ? t : [];
for (i = 0, n = t.length; n > i; i++) {
if (o.Util.isArray(t[i]) && "number" != typeof t[i][0]) return;
s[i] = o.latLng(t[i])
}
return s
},
_initEvents: function() {
o.Path.prototype._initEvents.call(this)
},
_getPathPartStr: function(t) {
for (var e, i = o.Path.VML, n = 0, s = t.length, a = ""; s > n; n++) e = t[n], i && e._round(), a += (n ? "L" : "M") + e.x + " " + e.y;
return a
},
_clipPoints: function() {
var t, e, i, n = this._originalPoints,
s = n.length;
if (this.options.noClip) return void(this._parts = [n]);
this._parts = [];
var a = this._parts,
r = this._map._pathViewport,
h = o.LineUtil;
for (t = 0, e = 0; s - 1 > t; t++) i = h.clipSegment(n[t], n[t + 1], r, t), i && (a[e] = a[e] || [], a[e].push(i[0]), (i[1] !== n[t + 1] || t === s - 2) && (a[e].push(i[1]), e++))
},
_simplifyPoints: function() {
for (var t = this._parts, e = o.LineUtil, i = 0, n = t.length; n > i; i++) t[i] = e.simplify(t[i], this.options.smoothFactor)
},
_updatePath: function() {
this._map && (this._clipPoints(), this._simplifyPoints(), o.Path.prototype._updatePath.call(this))
}
}), o.polyline = function(t, e) {
return new o.Polyline(t, e)
}, o.PolyUtil = {}, o.PolyUtil.clipPolygon = function(t, e) {
var i, n, s, a, r, h, l, u, c, d = [1, 4, 2, 8],
p = o.LineUtil;
for (n = 0, l = t.length; l > n; n++) t[n]._code = p._getBitCode(t[n], e);
for (a = 0; 4 > a; a++) {
for (u = d[a], i = [], n = 0, l = t.length, s = l - 1; l > n; s = n++) r = t[n], h = t[s], r._code & u ? h._code & u || (c = p._getEdgeIntersection(h, r, u, e), c._code = p._getBitCode(c, e), i.push(c)) : (h._code & u && (c = p._getEdgeIntersection(h, r, u, e), c._code = p._getBitCode(c, e), i.push(c)), i.push(r));
t = i
}
return t
}, o.Polygon = o.Polyline.extend({
options: {
fill: !0
},
initialize: function(t, e) {
o.Polyline.prototype.initialize.call(this, t, e), this._initWithHoles(t)
},
_initWithHoles: function(t) {
var e, i, n;
if (t && o.Util.isArray(t[0]) && "number" != typeof t[0][0])
for (this._latlngs = this._convertLatLngs(t[0]), this._holes = t.slice(1), e = 0, i = this._holes.length; i > e; e++) n = this._holes[e] = this._convertLatLngs(this._holes[e]), n[0].equals(n[n.length - 1]) && n.pop();
t = this._latlngs, t.length >= 2 && t[0].equals(t[t.length - 1]) && t.pop()
},
projectLatlngs: function() {
if (o.Polyline.prototype.projectLatlngs.call(this), this._holePoints = [], this._holes) {
var t, e, i, n;
for (t = 0, i = this._holes.length; i > t; t++)
for (this._holePoints[t] = [], e = 0, n = this._holes[t].length; n > e; e++) this._holePoints[t][e] = this._map.latLngToLayerPoint(this._holes[t][e])
}
},
setLatLngs: function(t) {
return t && o.Util.isArray(t[0]) && "number" != typeof t[0][0] ? (this._initWithHoles(t), this.redraw()) : o.Polyline.prototype.setLatLngs.call(this, t)
},
_clipPoints: function() {
var t = this._originalPoints,
e = [];
if (this._parts = [t].concat(this._holePoints), !this.options.noClip) {
for (var i = 0, n = this._parts.length; n > i; i++) {
var s = o.PolyUtil.clipPolygon(this._parts[i], this._map._pathViewport);
s.length && e.push(s)
}
this._parts = e
}
},
_getPathPartStr: function(t) {
var e = o.Polyline.prototype._getPathPartStr.call(this, t);
return e + (o.Browser.svg ? "z" : "x")
}
}), o.polygon = function(t, e) {
return new o.Polygon(t, e)
},
function() {
function t(t) {
return o.FeatureGroup.extend({
initialize: function(t, e) {
this._layers = {}, this._options = e, this.setLatLngs(t)
},
setLatLngs: function(e) {
var i = 0,
n = e.length;
for (this.eachLayer(function(t) {
n > i ? t.setLatLngs(e[i++]) : this.removeLayer(t)
}, this); n > i;) this.addLayer(new t(e[i++], this._options));
return this
},
getLatLngs: function() {
var t = [];
return this.eachLayer(function(e) {
t.push(e.getLatLngs())
}), t
}
})
}
o.MultiPolyline = t(o.Polyline), o.MultiPolygon = t(o.Polygon), o.multiPolyline = function(t, e) {
return new o.MultiPolyline(t, e)
}, o.multiPolygon = function(t, e) {
return new o.MultiPolygon(t, e)
}
}(), o.Rectangle = o.Polygon.extend({
initialize: function(t, e) {
o.Polygon.prototype.initialize.call(this, this._boundsToLatLngs(t), e)
},
setBounds: function(t) {
this.setLatLngs(this._boundsToLatLngs(t))
},
_boundsToLatLngs: function(t) {
return t = o.latLngBounds(t), [t.getSouthWest(), t.getNorthWest(), t.getNorthEast(), t.getSouthEast()]
}
}), o.rectangle = function(t, e) {
return new o.Rectangle(t, e)
}, o.Circle = o.Path.extend({
initialize: function(t, e, i) {
o.Path.prototype.initialize.call(this, i), this._latlng = o.latLng(t), this._mRadius = e
},
options: {
fill: !0
},
setLatLng: function(t) {
return this._latlng = o.latLng(t), this.redraw()
},
setRadius: function(t) {
return this._mRadius = t, this.redraw()
},
projectLatlngs: function() {
var t = this._getLngRadius(),
e = this._latlng,
i = this._map.latLngToLayerPoint([e.lat, e.lng - t]);
this._point = this._map.latLngToLayerPoint(e), this._radius = Math.max(this._point.x - i.x, 1)
},
getBounds: function() {
var t = this._getLngRadius(),
e = this._mRadius / 40075017 * 360,
i = this._latlng;
return new o.LatLngBounds([i.lat - e, i.lng - t], [i.lat + e, i.lng + t])
},
getLatLng: function() {
return this._latlng
},
getPathString: function() {
var t = this._point,
e = this._radius;
return this._checkIfEmpty() ? "" : o.Browser.svg ? "M" + t.x + "," + (t.y - e) + "A" + e + "," + e + ",0,1,1," + (t.x - .1) + "," + (t.y - e) + " z" : (t._round(), e = Math.round(e), "AL " + t.x + "," + t.y + " " + e + "," + e + " 0,23592600")
},
getRadius: function() {
return this._mRadius
},
_getLatRadius: function() {
return this._mRadius / 40075017 * 360
},
_getLngRadius: function() {
return this._getLatRadius() / Math.cos(o.LatLng.DEG_TO_RAD * this._latlng.lat)
},
_checkIfEmpty: function() {
if (!this._map) return !1;
var t = this._map._pathViewport,
e = this._radius,
i = this._point;
return i.x - e > t.max.x || i.y - e > t.max.y || i.x + e < t.min.x || i.y + e < t.min.y
}
}), o.circle = function(t, e, i) {
return new o.Circle(t, e, i)
}, o.CircleMarker = o.Circle.extend({
options: {
radius: 10,
weight: 2
},
initialize: function(t, e) {
o.Circle.prototype.initialize.call(this, t, null, e), this._radius = this.options.radius
},
projectLatlngs: function() {
this._point = this._map.latLngToLayerPoint(this._latlng)
},
_updateStyle: function() {
o.Circle.prototype._updateStyle.call(this), this.setRadius(this.options.radius)
},
setLatLng: function(t) {
return o.Circle.prototype.setLatLng.call(this, t), this._popup && this._popup._isOpen && this._popup.setLatLng(t), this
},
setRadius: function(t) {
return this.options.radius = this._radius = t, this.redraw()
},
getRadius: function() {
return this._radius
}
}), o.circleMarker = function(t, e) {
return new o.CircleMarker(t, e)
}, o.Polyline.include(o.Path.CANVAS ? {
_containsPoint: function(t, e) {
var i, n, s, a, r, h, l, u = this.options.weight / 2;
for (o.Browser.touch && (u += 10), i = 0, a = this._parts.length; a > i; i++)
for (l = this._parts[i], n = 0, r = l.length, s = r - 1; r > n; s = n++)
if ((e || 0 !== n) && (h = o.LineUtil.pointToSegmentDistance(t, l[s], l[n]), u >= h)) return !0;
return !1
}
} : {}), o.Polygon.include(o.Path.CANVAS ? {
_containsPoint: function(t) {
var e, i, n, s, a, r, h, l, u = !1;
if (o.Polyline.prototype._containsPoint.call(this, t, !0)) return !0;
for (s = 0, h = this._parts.length; h > s; s++)
for (e = this._parts[s], a = 0, l = e.length, r = l - 1; l > a; r = a++) i = e[a], n = e[r], i.y > t.y != n.y > t.y && t.x < (n.x - i.x) * (t.y - i.y) / (n.y - i.y) + i.x && (u = !u);
return u
}
} : {}), o.Circle.include(o.Path.CANVAS ? {
_drawPath: function() {
var t = this._point;
this._ctx.beginPath(), this._ctx.arc(t.x, t.y, this._radius, 0, 2 * Math.PI, !1)
},
_containsPoint: function(t) {
var e = this._point,
i = this.options.stroke ? this.options.weight / 2 : 0;
return t.distanceTo(e) <= this._radius + i
}
} : {}), o.CircleMarker.include(o.Path.CANVAS ? {
_updateStyle: function() {
o.Path.prototype._updateStyle.call(this)
}
} : {}), o.GeoJSON = o.FeatureGroup.extend({
initialize: function(t, e) {
o.setOptions(this, e), this._layers = {}, t && this.addData(t)
},
addData: function(t) {
var e, i, n, s = o.Util.isArray(t) ? t : t.features;
if (s) {
for (e = 0, i = s.length; i > e; e++) n = s[e], (n.geometries || n.geometry || n.features || n.coordinates) && this.addData(s[e]);
return this
}
var a = this.options;
if (!a.filter || a.filter(t)) {
var r = o.GeoJSON.geometryToLayer(t, a.pointToLayer, a.coordsToLatLng, a);
return r.feature = o.GeoJSON.asFeature(t), r.defaultOptions = r.options, this.resetStyle(r), a.onEachFeature && a.onEachFeature(t, r), this.addLayer(r)
}
},
resetStyle: function(t) {
var e = this.options.style;
e && (o.Util.extend(t.options, t.defaultOptions), this._setLayerStyle(t, e))
},
setStyle: function(t) {
this.eachLayer(function(e) {
this._setLayerStyle(e, t)
}, this)
},
_setLayerStyle: function(t, e) {
"function" == typeof e && (e = e(t.feature)), t.setStyle && t.setStyle(e)
}
}), o.extend(o.GeoJSON, {
geometryToLayer: function(t, e, i, n) {
var s, a, r, h, l = "Feature" === t.type ? t.geometry : t,
u = l.coordinates,
c = [];
switch (i = i || this.coordsToLatLng, l.type) {
case "Point":
return s = i(u), e ? e(t, s) : new o.Marker(s);
case "MultiPoint":
for (r = 0, h = u.length; h > r; r++) s = i(u[r]), c.push(e ? e(t, s) : new o.Marker(s));
return new o.FeatureGroup(c);
case "LineString":
return a = this.coordsToLatLngs(u, 0, i), new o.Polyline(a, n);
case "Polygon":
if (2 === u.length && !u[1].length) throw new Error("Invalid GeoJSON object.");
return a = this.coordsToLatLngs(u, 1, i), new o.Polygon(a, n);
case "MultiLineString":
return a = this.coordsToLatLngs(u, 1, i), new o.MultiPolyline(a, n);
case "MultiPolygon":
return a = this.coordsToLatLngs(u, 2, i), new o.MultiPolygon(a, n);
case "GeometryCollection":
for (r = 0, h = l.geometries.length; h > r; r++) c.push(this.geometryToLayer({
geometry: l.geometries[r],
type: "Feature",
properties: t.properties
}, e, i, n));
return new o.FeatureGroup(c);
default:
throw new Error("Invalid GeoJSON object.")
}
},
coordsToLatLng: function(t) {
return new o.LatLng(t[1], t[0], t[2])
},
coordsToLatLngs: function(t, e, i) {
var n, o, s, a = [];
for (o = 0, s = t.length; s > o; o++) n = e ? this.coordsToLatLngs(t[o], e - 1, i) : (i || this.coordsToLatLng)(t[o]), a.push(n);
return a
},
latLngToCoords: function(t) {
var e = [t.lng, t.lat];
return t.alt !== i && e.push(t.alt), e
},
latLngsToCoords: function(t) {
for (var e = [], i = 0, n = t.length; n > i; i++) e.push(o.GeoJSON.latLngToCoords(t[i]));
return e
},
getFeature: function(t, e) {
return t.feature ? o.extend({}, t.feature, {
geometry: e
}) : o.GeoJSON.asFeature(e)
},
asFeature: function(t) {
return "Feature" === t.type ? t : {
type: "Feature",
properties: {},
geometry: t
}
}
});
var a = {
toGeoJSON: function() {
return o.GeoJSON.getFeature(this, {
type: "Point",
coordinates: o.GeoJSON.latLngToCoords(this.getLatLng())
})
}
};
o.Marker.include(a), o.Circle.include(a), o.CircleMarker.include(a), o.Polyline.include({
toGeoJSON: function() {
return o.GeoJSON.getFeature(this, {
type: "LineString",
coordinates: o.GeoJSON.latLngsToCoords(this.getLatLngs())
})
}
}), o.Polygon.include({
toGeoJSON: function() {
var t, e, i, n = [o.GeoJSON.latLngsToCoords(this.getLatLngs())];
if (n[0].push(n[0][0]), this._holes)
for (t = 0, e = this._holes.length; e > t; t++) i = o.GeoJSON.latLngsToCoords(this._holes[t]), i.push(i[0]), n.push(i);
return o.GeoJSON.getFeature(this, {
type: "Polygon",
coordinates: n
})
}
}),
function() {
function t(t) {
return function() {
var e = [];
return this.eachLayer(function(t) {
e.push(t.toGeoJSON().geometry.coordinates)
}), o.GeoJSON.getFeature(this, {
type: t,
coordinates: e
})
}
}
o.MultiPolyline.include({
toGeoJSON: t("MultiLineString")
}), o.MultiPolygon.include({
toGeoJSON: t("MultiPolygon")
}), o.LayerGroup.include({
toGeoJSON: function() {
var e, i = this.feature && this.feature.geometry,
n = [];
if (i && "MultiPoint" === i.type) return t("MultiPoint").call(this);
var s = i && "GeometryCollection" === i.type;
return this.eachLayer(function(t) {
t.toGeoJSON && (e = t.toGeoJSON(), n.push(s ? e.geometry : o.GeoJSON.asFeature(e)))
}), s ? o.GeoJSON.getFeature(this, {
geometries: n,
type: "GeometryCollection"
}) : {
type: "FeatureCollection",
features: n
}
}
})
}(), o.geoJson = function(t, e) {
return new o.GeoJSON(t, e)
}, o.DomEvent = {
addListener: function(t, e, i, n) {
var s, a, r, h = o.stamp(i),
l = "_leaflet_" + e + h;
return t[l] ? this : (s = function(e) {
return i.call(n || t, e || o.DomEvent._getEvent())
}, o.Browser.pointer && 0 === e.indexOf("touch") ? this.addPointerListener(t, e, s, h) : (o.Browser.touch && "dblclick" === e && this.addDoubleTapListener && this.addDoubleTapListener(t, s, h), "addEventListener" in t ? "mousewheel" === e ? (t.addEventListener("DOMMouseScroll", s, !1), t.addEventListener(e, s, !1)) : "mouseenter" === e || "mouseleave" === e ? (a = s, r = "mouseenter" === e ? "mouseover" : "mouseout", s = function(e) {
return o.DomEvent._checkMouse(t, e) ? a(e) : void 0
}, t.addEventListener(r, s, !1)) : "click" === e && o.Browser.android ? (a = s, s = function(t) {
return o.DomEvent._filterClick(t, a)
}, t.addEventListener(e, s, !1)) : t.addEventListener(e, s, !1) : "attachEvent" in t && t.attachEvent("on" + e, s), t[l] = s, this))
},
removeListener: function(t, e, i) {
var n = o.stamp(i),
s = "_leaflet_" + e + n,
a = t[s];
return a ? (o.Browser.pointer && 0 === e.indexOf("touch") ? this.removePointerListener(t, e, n) : o.Browser.touch && "dblclick" === e && this.removeDoubleTapListener ? this.removeDoubleTapListener(t, n) : "removeEventListener" in t ? "mousewheel" === e ? (t.removeEventListener("DOMMouseScroll", a, !1), t.removeEventListener(e, a, !1)) : "mouseenter" === e || "mouseleave" === e ? t.removeEventListener("mouseenter" === e ? "mouseover" : "mouseout", a, !1) : t.removeEventListener(e, a, !1) : "detachEvent" in t && t.detachEvent("on" + e, a), t[s] = null, this) : this
},
stopPropagation: function(t) {
return t.stopPropagation ? t.stopPropagation() : t.cancelBubble = !0, o.DomEvent._skipped(t), this
},
disableScrollPropagation: function(t) {
var e = o.DomEvent.stopPropagation;
return o.DomEvent.on(t, "mousewheel", e).on(t, "MozMousePixelScroll", e)
},
disableClickPropagation: function(t) {
for (var e = o.DomEvent.stopPropagation, i = o.Draggable.START.length - 1; i >= 0; i--) o.DomEvent.on(t, o.Draggable.START[i], e);
return o.DomEvent.on(t, "click", o.DomEvent._fakeStop).on(t, "dblclick", e)
},
preventDefault: function(t) {
return t.preventDefault ? t.preventDefault() : t.returnValue = !1, this
},
stop: function(t) {
return o.DomEvent.preventDefault(t).stopPropagation(t)
},
getMousePosition: function(t, e) {
if (!e) return new o.Point(t.clientX, t.clientY);
var i = e.getBoundingClientRect();
return new o.Point(t.clientX - i.left - e.clientLeft, t.clientY - i.top - e.clientTop)
},
getWheelDelta: function(t) {
var e = 0;
return t.wheelDelta && (e = t.wheelDelta / 120), t.detail && (e = -t.detail / 3), e
},
_skipEvents: {},
_fakeStop: function(t) {
o.DomEvent._skipEvents[t.type] = !0
},
_skipped: function(t) {
var e = this._skipEvents[t.type];
return this._skipEvents[t.type] = !1, e
},
_checkMouse: function(t, e) {
var i = e.relatedTarget;
if (!i) return !0;
try {
for (; i && i !== t;) i = i.parentNode
} catch (n) {
return !1
}
return i !== t
},
_getEvent: function() {
var e = t.event;
if (!e)
for (var i = arguments.callee.caller; i && (e = i.arguments[0], !e || t.Event !== e.constructor);) i = i.caller;
return e
},
_filterClick: function(t, e) {
var i = t.timeStamp || t.originalEvent.timeStamp,
n = o.DomEvent._lastClick && i - o.DomEvent._lastClick;
return n && n > 100 && 500 > n || t.target._simulatedClick && !t._simulated ? void o.DomEvent.stop(t) : (o.DomEvent._lastClick = i, e(t))
}
}, o.DomEvent.on = o.DomEvent.addListener, o.DomEvent.off = o.DomEvent.removeListener, o.Draggable = o.Class.extend({
includes: o.Mixin.Events,
statics: {
START: o.Browser.touch ? ["touchstart", "mousedown"] : ["mousedown"],
END: {
mousedown: "mouseup",
touchstart: "touchend",
pointerdown: "touchend",
MSPointerDown: "touchend"
},
MOVE: {
mousedown: "mousemove",
touchstart: "touchmove",
pointerdown: "touchmove",
MSPointerDown: "touchmove"
}
},
initialize: function(t, e) {
this._element = t, this._dragStartTarget = e || t
},
enable: function() {
if (!this._enabled) {
for (var t = o.Draggable.START.length - 1; t >= 0; t--) o.DomEvent.on(this._dragStartTarget, o.Draggable.START[t], this._onDown, this);
this._enabled = !0
}
},
disable: function() {
if (this._enabled) {
for (var t = o.Draggable.START.length - 1; t >= 0; t--) o.DomEvent.off(this._dragStartTarget, o.Draggable.START[t], this._onDown, this);
this._enabled = !1, this._moved = !1
}
},
_onDown: function(t) {
if (this._moved = !1, !(t.shiftKey || 1 !== t.which && 1 !== t.button && !t.touches || (o.DomEvent.stopPropagation(t), o.Draggable._disabled || (o.DomUtil.disableImageDrag(), o.DomUtil.disableTextSelection(), this._moving)))) {
var i = t.touches ? t.touches[0] : t;
this._startPoint = new o.Point(i.clientX, i.clientY), this._startPos = this._newPos = o.DomUtil.getPosition(this._element), o.DomEvent.on(e, o.Draggable.MOVE[t.type], this._onMove, this).on(e, o.Draggable.END[t.type], this._onUp, this)
}
},
_onMove: function(t) {
if (t.touches && t.touches.length > 1) return void(this._moved = !0);
var i = t.touches && 1 === t.touches.length ? t.touches[0] : t,
n = new o.Point(i.clientX, i.clientY),
s = n.subtract(this._startPoint);
(s.x || s.y) && (o.Browser.touch && Math.abs(s.x) + Math.abs(s.y) < 3 || (o.DomEvent.preventDefault(t), this._moved || (this.fire("dragstart"), this._moved = !0, this._startPos = o.DomUtil.getPosition(this._element).subtract(s), o.DomUtil.addClass(e.body, "leaflet-dragging"), this._lastTarget = t.target || t.srcElement, o.DomUtil.addClass(this._lastTarget, "leaflet-drag-target")), this._newPos = this._startPos.add(s), this._moving = !0, o.Util.cancelAnimFrame(this._animRequest), this._animRequest = o.Util.requestAnimFrame(this._updatePosition, this, !0, this._dragStartTarget)))
},
_updatePosition: function() {
this.fire("predrag"), o.DomUtil.setPosition(this._element, this._newPos), this.fire("drag")
},
_onUp: function() {
o.DomUtil.removeClass(e.body, "leaflet-dragging"), this._lastTarget && (o.DomUtil.removeClass(this._lastTarget, "leaflet-drag-target"), this._lastTarget = null);
for (var t in o.Draggable.MOVE) o.DomEvent.off(e, o.Draggable.MOVE[t], this._onMove).off(e, o.Draggable.END[t], this._onUp);
o.DomUtil.enableImageDrag(), o.DomUtil.enableTextSelection(), this._moved && this._moving && (o.Util.cancelAnimFrame(this._animRequest), this.fire("dragend", {
distance: this._newPos.distanceTo(this._startPos)
})), this._moving = !1
}
}), o.Handler = o.Class.extend({
initialize: function(t) {
this._map = t
},
enable: function() {
this._enabled || (this._enabled = !0, this.addHooks())
},
disable: function() {
this._enabled && (this._enabled = !1, this.removeHooks())
},
enabled: function() {
return !!this._enabled
}
}), o.Map.mergeOptions({
dragging: !0,
inertia: !o.Browser.android23,
inertiaDeceleration: 3400,
inertiaMaxSpeed: 1 / 0,
inertiaThreshold: o.Browser.touch ? 32 : 18,
easeLinearity: .25,
worldCopyJump: !1
}), o.Map.Drag = o.Handler.extend({
addHooks: function() {
if (!this._draggable) {
var t = this._map;
this._draggable = new o.Draggable(t._mapPane, t._container), this._draggable.on({
dragstart: this._onDragStart,
drag: this._onDrag,
dragend: this._onDragEnd
}, this), t.options.worldCopyJump && (this._draggable.on("predrag", this._onPreDrag, this), t.on("viewreset", this._onViewReset, this), t.whenReady(this._onViewReset, this))
}
this._draggable.enable()
},
removeHooks: function() {
this._draggable.disable()
},
moved: function() {
return this._draggable && this._draggable._moved
},
_onDragStart: function() {
var t = this._map;
t._panAnim && t._panAnim.stop(), t.fire("movestart").fire("dragstart"), t.options.inertia && (this._positions = [], this._times = [])
},
_onDrag: function() {
if (this._map.options.inertia) {
var t = this._lastTime = +new Date,
e = this._lastPos = this._draggable._newPos;
this._positions.push(e), this._times.push(t), t - this._times[0] > 200 && (this._positions.shift(), this._times.shift())
}
this._map.fire("move").fire("drag")
},
_onViewReset: function() {
var t = this._map.getSize()._divideBy(2),
e = this._map.latLngToLayerPoint([0, 0]);
this._initialWorldOffset = e.subtract(t).x, this._worldWidth = this._map.project([0, 180]).x
},
_onPreDrag: function() {
var t = this._worldWidth,
e = Math.round(t / 2),
i = this._initialWorldOffset,
n = this._draggable._newPos.x,
o = (n - e + i) % t + e - i,
s = (n + e + i) % t - e - i,
a = Math.abs(o + i) < Math.abs(s + i) ? o : s;
this._draggable._newPos.x = a
},
_onDragEnd: function(t) {
var e = this._map,
i = e.options,
n = +new Date - this._lastTime,
s = !i.inertia || n > i.inertiaThreshold || !this._positions[0];
if (e.fire("dragend", t), s) e.fire("moveend");
else {
var a = this._lastPos.subtract(this._positions[0]),
r = (this._lastTime + n - this._times[0]) / 1e3,
h = i.easeLinearity,
l = a.multiplyBy(h / r),
u = l.distanceTo([0, 0]),
c = Math.min(i.inertiaMaxSpeed, u),
d = l.multiplyBy(c / u),
p = c / (i.inertiaDeceleration * h),
_ = d.multiplyBy(-p / 2).round();
_.x && _.y ? (_ = e._limitOffset(_, e.options.maxBounds), o.Util.requestAnimFrame(function() {
e.panBy(_, {
duration: p,
easeLinearity: h,
noMoveStart: !0
})
})) : e.fire("moveend")
}
}
}), o.Map.addInitHook("addHandler", "dragging", o.Map.Drag), o.Map.mergeOptions({
doubleClickZoom: !0
}), o.Map.DoubleClickZoom = o.Handler.extend({
addHooks: function() {
this._map.on("dblclick", this._onDoubleClick, this)
},
removeHooks: function() {
this._map.off("dblclick", this._onDoubleClick, this)
},
_onDoubleClick: function(t) {
var e = this._map,
i = e.getZoom() + (t.originalEvent.shiftKey ? -1 : 1);
"center" === e.options.doubleClickZoom ? e.setZoom(i) : e.setZoomAround(t.containerPoint, i)
}
}), o.Map.addInitHook("addHandler", "doubleClickZoom", o.Map.DoubleClickZoom), o.Map.mergeOptions({
scrollWheelZoom: !0
}), o.Map.ScrollWheelZoom = o.Handler.extend({
addHooks: function() {
o.DomEvent.on(this._map._container, "mousewheel", this._onWheelScroll, this), o.DomEvent.on(this._map._container, "MozMousePixelScroll", o.DomEvent.preventDefault), this._delta = 0
},
removeHooks: function() {
o.DomEvent.off(this._map._container, "mousewheel", this._onWheelScroll), o.DomEvent.off(this._map._container, "MozMousePixelScroll", o.DomEvent.preventDefault)
},
_onWheelScroll: function(t) {
var e = o.DomEvent.getWheelDelta(t);
this._delta += e, this._lastMousePos = this._map.mouseEventToContainerPoint(t), this._startTime || (this._startTime = +new Date);
var i = Math.max(40 - (+new Date - this._startTime), 0);
clearTimeout(this._timer), this._timer = setTimeout(o.bind(this._performZoom, this), i), o.DomEvent.preventDefault(t), o.DomEvent.stopPropagation(t)
},
_performZoom: function() {
var t = this._map,
e = this._delta,
i = t.getZoom();
e = e > 0 ? Math.ceil(e) : Math.floor(e), e = Math.max(Math.min(e, 4), -4), e = t._limitZoom(i + e) - i, this._delta = 0, this._startTime = null, e && ("center" === t.options.scrollWheelZoom ? t.setZoom(i + e) : t.setZoomAround(this._lastMousePos, i + e))
}
}), o.Map.addInitHook("addHandler", "scrollWheelZoom", o.Map.ScrollWheelZoom), o.extend(o.DomEvent, {
_touchstart: o.Browser.msPointer ? "MSPointerDown" : o.Browser.pointer ? "pointerdown" : "touchstart",
_touchend: o.Browser.msPointer ? "MSPointerUp" : o.Browser.pointer ? "pointerup" : "touchend",
addDoubleTapListener: function(t, i, n) {
function s(t) {
var e;
if (o.Browser.pointer ? (_.push(t.pointerId), e = _.length) : e = t.touches.length, !(e > 1)) {
var i = Date.now(),
n = i - (r || i);
h = t.touches ? t.touches[0] : t, l = n > 0 && u >= n, r = i
}
}
function a(t) {
if (o.Browser.pointer) {
var e = _.indexOf(t.pointerId);
if (-1 === e) return;
_.splice(e, 1)
}
if (l) {
if (o.Browser.pointer) {
var n, s = {};
for (var a in h) n = h[a], s[a] = "function" == typeof n ? n.bind(h) : n;
h = s
}
h.type = "dblclick", i(h), r = null
}
}
var r, h, l = !1,
u = 250,
c = "_leaflet_",
d = this._touchstart,
p = this._touchend,
_ = [];
t[c + d + n] = s, t[c + p + n] = a;
var m = o.Browser.pointer ? e.documentElement : t;
return t.addEventListener(d, s, !1), m.addEventListener(p, a, !1), o.Browser.pointer && m.addEventListener(o.DomEvent.POINTER_CANCEL, a, !1), this
},
removeDoubleTapListener: function(t, i) {
var n = "_leaflet_";
return t.removeEventListener(this._touchstart, t[n + this._touchstart + i], !1), (o.Browser.pointer ? e.documentElement : t).removeEventListener(this._touchend, t[n + this._touchend + i], !1), o.Browser.pointer && e.documentElement.removeEventListener(o.DomEvent.POINTER_CANCEL, t[n + this._touchend + i], !1), this
}
}), o.extend(o.DomEvent, {
POINTER_DOWN: o.Browser.msPointer ? "MSPointerDown" : "pointerdown",
POINTER_MOVE: o.Browser.msPointer ? "MSPointerMove" : "pointermove",
POINTER_UP: o.Browser.msPointer ? "MSPointerUp" : "pointerup",
POINTER_CANCEL: o.Browser.msPointer ? "MSPointerCancel" : "pointercancel",
_pointers: [],
_pointerDocumentListener: !1,
addPointerListener: function(t, e, i, n) {
switch (e) {
case "touchstart":
return this.addPointerListenerStart(t, e, i, n);
case "touchend":
return this.addPointerListenerEnd(t, e, i, n);
case "touchmove":
return this.addPointerListenerMove(t, e, i, n);
default:
throw "Unknown touch event type"
}
},
addPointerListenerStart: function(t, i, n, s) {
var a = "_leaflet_",
r = this._pointers,
h = function(t) {
o.DomEvent.preventDefault(t);
for (var e = !1, i = 0; i < r.length; i++)
if (r[i].pointerId === t.pointerId) {
e = !0;
break
}
e || r.push(t), t.touches = r.slice(), t.changedTouches = [t], n(t)
};
if (t[a + "touchstart" + s] = h, t.addEventListener(this.POINTER_DOWN, h, !1), !this._pointerDocumentListener) {
var l = function(t) {
for (var e = 0; e < r.length; e++)
if (r[e].pointerId === t.pointerId) {
r.splice(e, 1);
break
}
};
e.documentElement.addEventListener(this.POINTER_UP, l, !1), e.documentElement.addEventListener(this.POINTER_CANCEL, l, !1), this._pointerDocumentListener = !0
}
return this
},
addPointerListenerMove: function(t, e, i, n) {
function o(t) {
if (t.pointerType !== t.MSPOINTER_TYPE_MOUSE && "mouse" !== t.pointerType || 0 !== t.buttons) {
for (var e = 0; e < a.length; e++)
if (a[e].pointerId === t.pointerId) {
a[e] = t;
break
}
t.touches = a.slice(), t.changedTouches = [t], i(t)
}
}
var s = "_leaflet_",
a = this._pointers;
return t[s + "touchmove" + n] = o, t.addEventListener(this.POINTER_MOVE, o, !1), this
},
addPointerListenerEnd: function(t, e, i, n) {
var o = "_leaflet_",
s = this._pointers,
a = function(t) {
for (var e = 0; e < s.length; e++)
if (s[e].pointerId === t.pointerId) {
s.splice(e, 1);
break
}
t.touches = s.slice(), t.changedTouches = [t], i(t)
};
return t[o + "touchend" + n] = a, t.addEventListener(this.POINTER_UP, a, !1), t.addEventListener(this.POINTER_CANCEL, a, !1), this
},
removePointerListener: function(t, e, i) {
var n = "_leaflet_",
o = t[n + e + i];
switch (e) {
case "touchstart":
t.removeEventListener(this.POINTER_DOWN, o, !1);
break;
case "touchmove":
t.removeEventListener(this.POINTER_MOVE, o, !1);
break;
case "touchend":
t.removeEventListener(this.POINTER_UP, o, !1), t.removeEventListener(this.POINTER_CANCEL, o, !1)
}
return this
}
}), o.Map.mergeOptions({
touchZoom: o.Browser.touch && !o.Browser.android23,
bounceAtZoomLimits: !0
}), o.Map.TouchZoom = o.Handler.extend({
addHooks: function() {
o.DomEvent.on(this._map._container, "touchstart", this._onTouchStart, this)
},
removeHooks: function() {
o.DomEvent.off(this._map._container, "touchstart", this._onTouchStart, this)
},
_onTouchStart: function(t) {
var i = this._map;
if (t.touches && 2 === t.touches.length && !i._animatingZoom && !this._zooming) {
var n = i.mouseEventToLayerPoint(t.touches[0]),
s = i.mouseEventToLayerPoint(t.touches[1]),
a = i._getCenterLayerPoint();
this._startCenter = n.add(s)._divideBy(2), this._startDist = n.distanceTo(s), this._moved = !1, this._zooming = !0, this._centerOffset = a.subtract(this._startCenter), i._panAnim && i._panAnim.stop(), o.DomEvent.on(e, "touchmove", this._onTouchMove, this).on(e, "touchend", this._onTouchEnd, this), o.DomEvent.preventDefault(t)
}
},
_onTouchMove: function(t) {
var e = this._map;
if (t.touches && 2 === t.touches.length && this._zooming) {
var i = e.mouseEventToLayerPoint(t.touches[0]),
n = e.mouseEventToLayerPoint(t.touches[1]);
this._scale = i.distanceTo(n) / this._startDist, this._delta = i._add(n)._divideBy(2)._subtract(this._startCenter), 1 !== this._scale && (e.options.bounceAtZoomLimits || !(e.getZoom() === e.getMinZoom() && this._scale < 1 || e.getZoom() === e.getMaxZoom() && this._scale > 1)) && (this._moved || (o.DomUtil.addClass(e._mapPane, "leaflet-touching"), e.fire("movestart").fire("zoomstart"), this._moved = !0), o.Util.cancelAnimFrame(this._animRequest), this._animRequest = o.Util.requestAnimFrame(this._updateOnMove, this, !0, this._map._container), o.DomEvent.preventDefault(t))
}
},
_updateOnMove: function() {
var t = this._map,
e = this._getScaleOrigin(),
i = t.layerPointToLatLng(e),
n = t.getScaleZoom(this._scale);
t._animateZoom(i, n, this._startCenter, this._scale, this._delta, !1, !0)
},
_onTouchEnd: function() {
if (!this._moved || !this._zooming) return void(this._zooming = !1);
var t = this._map;
this._zooming = !1, o.DomUtil.removeClass(t._mapPane, "leaflet-touching"), o.Util.cancelAnimFrame(this._animRequest), o.DomEvent.off(e, "touchmove", this._onTouchMove).off(e, "touchend", this._onTouchEnd);
var i = this._getScaleOrigin(),
n = t.layerPointToLatLng(i),
s = t.getZoom(),
a = t.getScaleZoom(this._scale) - s,
r = a > 0 ? Math.ceil(a) : Math.floor(a),
h = t._limitZoom(s + r),
l = t.getZoomScale(h) / this._scale;
t._animateZoom(n, h, i, l)
},
_getScaleOrigin: function() {
var t = this._centerOffset.subtract(this._delta).divideBy(this._scale);
return this._startCenter.add(t)
}
}), o.Map.addInitHook("addHandler", "touchZoom", o.Map.TouchZoom), o.Map.mergeOptions({
tap: !0,
tapTolerance: 15
}), o.Map.Tap = o.Handler.extend({
addHooks: function() {
o.DomEvent.on(this._map._container, "touchstart", this._onDown, this)
},
removeHooks: function() {
o.DomEvent.off(this._map._container, "touchstart", this._onDown, this)
},
_onDown: function(t) {
if (t.touches) {
if (o.DomEvent.preventDefault(t), this._fireClick = !0, t.touches.length > 1) return this._fireClick = !1, void clearTimeout(this._holdTimeout);
var i = t.touches[0],
n = i.target;
this._startPos = this._newPos = new o.Point(i.clientX, i.clientY), n.tagName && "a" === n.tagName.toLowerCase() && o.DomUtil.addClass(n, "leaflet-active"), this._holdTimeout = setTimeout(o.bind(function() {
this._isTapValid() && (this._fireClick = !1, this._onUp(), this._simulateEvent("contextmenu", i))
}, this), 1e3), o.DomEvent.on(e, "touchmove", this._onMove, this).on(e, "touchend", this._onUp, this)
}
},
_onUp: function(t) {
if (clearTimeout(this._holdTimeout), o.DomEvent.off(e, "touchmove", this._onMove, this).off(e, "touchend", this._onUp, this), this._fireClick && t && t.changedTouches) {
var i = t.changedTouches[0],
n = i.target;
n && n.tagName && "a" === n.tagName.toLowerCase() && o.DomUtil.removeClass(n, "leaflet-active"), this._isTapValid() && this._simulateEvent("click", i)
}
},
_isTapValid: function() {
return this._newPos.distanceTo(this._startPos) <= this._map.options.tapTolerance
},
_onMove: function(t) {
var e = t.touches[0];
this._newPos = new o.Point(e.clientX, e.clientY)
},
_simulateEvent: function(i, n) {
var o = e.createEvent("MouseEvents");
o._simulated = !0, n.target._simulatedClick = !0, o.initMouseEvent(i, !0, !0, t, 1, n.screenX, n.screenY, n.clientX, n.clientY, !1, !1, !1, !1, 0, null), n.target.dispatchEvent(o)
}
}), o.Browser.touch && !o.Browser.pointer && o.Map.addInitHook("addHandler", "tap", o.Map.Tap), o.Map.mergeOptions({
boxZoom: !0
}), o.Map.BoxZoom = o.Handler.extend({
initialize: function(t) {
this._map = t, this._container = t._container, this._pane = t._panes.overlayPane, this._moved = !1
},
addHooks: function() {
o.DomEvent.on(this._container, "mousedown", this._onMouseDown, this)
},
removeHooks: function() {
o.DomEvent.off(this._container, "mousedown", this._onMouseDown), this._moved = !1
},
moved: function() {
return this._moved
},
_onMouseDown: function(t) {
return this._moved = !1, !t.shiftKey || 1 !== t.which && 1 !== t.button ? !1 : (o.DomUtil.disableTextSelection(), o.DomUtil.disableImageDrag(), this._startLayerPoint = this._map.mouseEventToLayerPoint(t), void o.DomEvent.on(e, "mousemove", this._onMouseMove, this).on(e, "mouseup", this._onMouseUp, this).on(e, "keydown", this._onKeyDown, this))
},
_onMouseMove: function(t) {
this._moved || (this._box = o.DomUtil.create("div", "leaflet-zoom-box", this._pane), o.DomUtil.setPosition(this._box, this._startLayerPoint), this._container.style.cursor = "crosshair", this._map.fire("boxzoomstart"));
var e = this._startLayerPoint,
i = this._box,
n = this._map.mouseEventToLayerPoint(t),
s = n.subtract(e),
a = new o.Point(Math.min(n.x, e.x), Math.min(n.y, e.y));
o.DomUtil.setPosition(i, a), this._moved = !0, i.style.width = Math.max(0, Math.abs(s.x) - 4) + "px", i.style.height = Math.max(0, Math.abs(s.y) - 4) + "px"
},
_finish: function() {
this._moved && (this._pane.removeChild(this._box), this._container.style.cursor = ""), o.DomUtil.enableTextSelection(), o.DomUtil.enableImageDrag(), o.DomEvent.off(e, "mousemove", this._onMouseMove).off(e, "mouseup", this._onMouseUp).off(e, "keydown", this._onKeyDown)
},
_onMouseUp: function(t) {
this._finish();
var e = this._map,
i = e.mouseEventToLayerPoint(t);
if (!this._startLayerPoint.equals(i)) {
var n = new o.LatLngBounds(e.layerPointToLatLng(this._startLayerPoint), e.layerPointToLatLng(i));
e.fitBounds(n), e.fire("boxzoomend", {
boxZoomBounds: n
})
}
},
_onKeyDown: function(t) {
27 === t.keyCode && this._finish()
}
}), o.Map.addInitHook("addHandler", "boxZoom", o.Map.BoxZoom), o.Map.mergeOptions({
keyboard: !0,
keyboardPanOffset: 80,
keyboardZoomOffset: 1
}), o.Map.Keyboard = o.Handler.extend({
keyCodes: {
left: [37],
right: [39],
down: [40],
up: [38],
zoomIn: [187, 107, 61, 171],
zoomOut: [189, 109, 173]
},
initialize: function(t) {
this._map = t, this._setPanOffset(t.options.keyboardPanOffset), this._setZoomOffset(t.options.keyboardZoomOffset)
},
addHooks: function() {
var t = this._map._container; - 1 === t.tabIndex && (t.tabIndex = "0"), o.DomEvent.on(t, "focus", this._onFocus, this).on(t, "blur", this._onBlur, this).on(t, "mousedown", this._onMouseDown, this), this._map.on("focus", this._addHooks, this).on("blur", this._removeHooks, this)
},
removeHooks: function() {
this._removeHooks();
var t = this._map._container;
o.DomEvent.off(t, "focus", this._onFocus, this).off(t, "blur", this._onBlur, this).off(t, "mousedown", this._onMouseDown, this), this._map.off("focus", this._addHooks, this).off("blur", this._removeHooks, this)
},
_onMouseDown: function() {
if (!this._focused) {
var i = e.body,
n = e.documentElement,
o = i.scrollTop || n.scrollTop,
s = i.scrollLeft || n.scrollLeft;
this._map._container.focus(), t.scrollTo(s, o)
}
},
_onFocus: function() {
this._focused = !0, this._map.fire("focus")
},
_onBlur: function() {
this._focused = !1, this._map.fire("blur")
},
_setPanOffset: function(t) {
var e, i, n = this._panKeys = {}, o = this.keyCodes;
for (e = 0, i = o.left.length; i > e; e++) n[o.left[e]] = [-1 * t, 0];
for (e = 0, i = o.right.length; i > e; e++) n[o.right[e]] = [t, 0];
for (e = 0, i = o.down.length; i > e; e++) n[o.down[e]] = [0, t];
for (e = 0, i = o.up.length; i > e; e++) n[o.up[e]] = [0, -1 * t]
},
_setZoomOffset: function(t) {
var e, i, n = this._zoomKeys = {}, o = this.keyCodes;
for (e = 0, i = o.zoomIn.length; i > e; e++) n[o.zoomIn[e]] = t;
for (e = 0, i = o.zoomOut.length; i > e; e++) n[o.zoomOut[e]] = -t
},
_addHooks: function() {
o.DomEvent.on(e, "keydown", this._onKeyDown, this)
},
_removeHooks: function() {
o.DomEvent.off(e, "keydown", this._onKeyDown, this)
},
_onKeyDown: function(t) {
var e = t.keyCode,
i = this._map;
if (e in this._panKeys) {
if (i._panAnim && i._panAnim._inProgress) return;
i.panBy(this._panKeys[e]), i.options.maxBounds && i.panInsideBounds(i.options.maxBounds)
} else {
if (!(e in this._zoomKeys)) return;
i.setZoom(i.getZoom() + this._zoomKeys[e])
}
o.DomEvent.stop(t)
}
}), o.Map.addInitHook("addHandler", "keyboard", o.Map.Keyboard), o.Handler.MarkerDrag = o.Handler.extend({
initialize: function(t) {
this._marker = t
},
addHooks: function() {
var t = this._marker._icon;
this._draggable || (this._draggable = new o.Draggable(t, t)), this._draggable.on("dragstart", this._onDragStart, this).on("drag", this._onDrag, this).on("dragend", this._onDragEnd, this), this._draggable.enable(), o.DomUtil.addClass(this._marker._icon, "leaflet-marker-draggable")
},
removeHooks: function() {
this._draggable.off("dragstart", this._onDragStart, this).off("drag", this._onDrag, this).off("dragend", this._onDragEnd, this), this._draggable.disable(), o.DomUtil.removeClass(this._marker._icon, "leaflet-marker-draggable")
},
moved: function() {
return this._draggable && this._draggable._moved
},
_onDragStart: function() {
this._marker.closePopup().fire("movestart").fire("dragstart")
},
_onDrag: function() {
var t = this._marker,
e = t._shadow,
i = o.DomUtil.getPosition(t._icon),
n = t._map.layerPointToLatLng(i);
e && o.DomUtil.setPosition(e, i), t._latlng = n, t.fire("move", {
latlng: n
}).fire("drag")
},
_onDragEnd: function(t) {
this._marker.fire("moveend").fire("dragend", t)
}
}), o.Control = o.Class.extend({
options: {
position: "topright"
},
initialize: function(t) {
o.setOptions(this, t)
},
getPosition: function() {
return this.options.position
},
setPosition: function(t) {
var e = this._map;
return e && e.removeControl(this), this.options.position = t, e && e.addControl(this), this
},
getContainer: function() {
return this._container
},
addTo: function(t) {
this._map = t;
var e = this._container = this.onAdd(t),
i = this.getPosition(),
n = t._controlCorners[i];
return o.DomUtil.addClass(e, "leaflet-control"), -1 !== i.indexOf("bottom") ? n.insertBefore(e, n.firstChild) : n.appendChild(e), this
},
removeFrom: function(t) {
var e = this.getPosition(),
i = t._controlCorners[e];
return i.removeChild(this._container), this._map = null, this.onRemove && this.onRemove(t), this
},
_refocusOnMap: function() {
this._map && this._map.getContainer().focus()
}
}), o.control = function(t) {
return new o.Control(t)
}, o.Map.include({
addControl: function(t) {
return t.addTo(this), this
},
removeControl: function(t) {
return t.removeFrom(this), this
},
_initControlPos: function() {
function t(t, s) {
var a = i + t + " " + i + s;
e[t + s] = o.DomUtil.create("div", a, n)
}
var e = this._controlCorners = {}, i = "leaflet-",
n = this._controlContainer = o.DomUtil.create("div", i + "control-container", this._container);
t("top", "left"), t("top", "right"), t("bottom", "left"), t("bottom", "right")
},
_clearControlPos: function() {
this._container.removeChild(this._controlContainer)
}
}), o.Control.Zoom = o.Control.extend({
options: {
position: "topleft",
zoomInText: "+",
zoomInTitle: "Zoom in",
zoomOutText: "-",
zoomOutTitle: "Zoom out"
},
onAdd: function(t) {
var e = "leaflet-control-zoom",
i = o.DomUtil.create("div", e + " leaflet-bar");
return this._map = t, this._zoomInButton = this._createButton(this.options.zoomInText, this.options.zoomInTitle, e + "-in", i, this._zoomIn, this), this._zoomOutButton = this._createButton(this.options.zoomOutText, this.options.zoomOutTitle, e + "-out", i, this._zoomOut, this), this._updateDisabled(), t.on("zoomend zoomlevelschange", this._updateDisabled, this), i
},
onRemove: function(t) {
t.off("zoomend zoomlevelschange", this._updateDisabled, this)
},
_zoomIn: function(t) {
this._map.zoomIn(t.shiftKey ? 3 : 1)
},
_zoomOut: function(t) {
this._map.zoomOut(t.shiftKey ? 3 : 1)
},
_createButton: function(t, e, i, n, s, a) {
var r = o.DomUtil.create("a", i, n);
r.innerHTML = t, r.href = "#", r.title = e;
var h = o.DomEvent.stopPropagation;
return o.DomEvent.on(r, "click", h).on(r, "mousedown", h).on(r, "dblclick", h).on(r, "click", o.DomEvent.preventDefault).on(r, "click", s, a).on(r, "click", this._refocusOnMap, a), r
},
_updateDisabled: function() {
var t = this._map,
e = "leaflet-disabled";
o.DomUtil.removeClass(this._zoomInButton, e), o.DomUtil.removeClass(this._zoomOutButton, e), t._zoom === t.getMinZoom() && o.DomUtil.addClass(this._zoomOutButton, e), t._zoom === t.getMaxZoom() && o.DomUtil.addClass(this._zoomInButton, e)
}
}), o.Map.mergeOptions({
zoomControl: !0
}), o.Map.addInitHook(function() {
this.options.zoomControl && (this.zoomControl = new o.Control.Zoom, this.addControl(this.zoomControl))
}), o.control.zoom = function(t) {
return new o.Control.Zoom(t)
}, o.Control.Attribution = o.Control.extend({
options: {
position: "bottomright",
prefix: '<a href="http://leafletjs.com" title="A JS library for interactive maps">Leaflet</a>'
},
initialize: function(t) {
o.setOptions(this, t), this._attributions = {}
},
onAdd: function(t) {
this._container = o.DomUtil.create("div", "leaflet-control-attribution"), o.DomEvent.disableClickPropagation(this._container);
for (var e in t._layers) t._layers[e].getAttribution && this.addAttribution(t._layers[e].getAttribution());
return t.on("layeradd", this._onLayerAdd, this).on("layerremove", this._onLayerRemove, this), this._update(), this._container
},
onRemove: function(t) {
t.off("layeradd", this._onLayerAdd).off("layerremove", this._onLayerRemove)
},
setPrefix: function(t) {
return this.options.prefix = t, this._update(), this
},
addAttribution: function(t) {
return t ? (this._attributions[t] || (this._attributions[t] = 0), this._attributions[t]++, this._update(), this) : void 0
},
removeAttribution: function(t) {
return t ? (this._attributions[t] && (this._attributions[t]--, this._update()), this) : void 0
},
_update: function() {
if (this._map) {
var t = [];
for (var e in this._attributions) this._attributions[e] && t.push(e);
var i = [];
this.options.prefix && i.push(this.options.prefix), t.length && i.push(t.join(", ")), this._container.innerHTML = i.join(" | ")
}
},
_onLayerAdd: function(t) {
t.layer.getAttribution && this.addAttribution(t.layer.getAttribution())
},
_onLayerRemove: function(t) {
t.layer.getAttribution && this.removeAttribution(t.layer.getAttribution())
}
}), o.Map.mergeOptions({
attributionControl: !0
}), o.Map.addInitHook(function() {
this.options.attributionControl && (this.attributionControl = (new o.Control.Attribution).addTo(this))
}), o.control.attribution = function(t) {
return new o.Control.Attribution(t)
}, o.Control.Scale = o.Control.extend({
options: {
position: "bottomleft",
maxWidth: 100,
metric: !0,
imperial: !0,
updateWhenIdle: !1
},
onAdd: function(t) {
this._map = t;
var e = "leaflet-control-scale",
i = o.DomUtil.create("div", e),
n = this.options;
return this._addScales(n, e, i), t.on(n.updateWhenIdle ? "moveend" : "move", this._update, this), t.whenReady(this._update, this), i
},
onRemove: function(t) {
t.off(this.options.updateWhenIdle ? "moveend" : "move", this._update, this)
},
_addScales: function(t, e, i) {
t.metric && (this._mScale = o.DomUtil.create("div", e + "-line", i)), t.imperial && (this._iScale = o.DomUtil.create("div", e + "-line", i))
},
_update: function() {
var t = this._map.getBounds(),
e = t.getCenter().lat,
i = 6378137 * Math.PI * Math.cos(e * Math.PI / 180),
n = i * (t.getNorthEast().lng - t.getSouthWest().lng) / 180,
o = this._map.getSize(),
s = this.options,
a = 0;
o.x > 0 && (a = n * (s.maxWidth / o.x)), this._updateScales(s, a)
},
_updateScales: function(t, e) {
t.metric && e && this._updateMetric(e), t.imperial && e && this._updateImperial(e)
},
_updateMetric: function(t) {
var e = this._getRoundNum(t);
this._mScale.style.width = this._getScaleWidth(e / t) + "px", this._mScale.innerHTML = 1e3 > e ? e + " m" : e / 1e3 + " km"
},
_updateImperial: function(t) {
var e, i, n, o = 3.2808399 * t,
s = this._iScale;
o > 5280 ? (e = o / 5280, i = this._getRoundNum(e), s.style.width = this._getScaleWidth(i / e) + "px", s.innerHTML = i + " mi") : (n = this._getRoundNum(o), s.style.width = this._getScaleWidth(n / o) + "px", s.innerHTML = n + " ft")
},
_getScaleWidth: function(t) {
return Math.round(this.options.maxWidth * t) - 10
},
_getRoundNum: function(t) {
var e = Math.pow(10, (Math.floor(t) + "").length - 1),
i = t / e;
return i = i >= 10 ? 10 : i >= 5 ? 5 : i >= 3 ? 3 : i >= 2 ? 2 : 1, e * i
}
}), o.control.scale = function(t) {
return new o.Control.Scale(t)
}, o.Control.Layers = o.Control.extend({
options: {
collapsed: !0,
position: "topright",
autoZIndex: !0
},
initialize: function(t, e, i) {
o.setOptions(this, i), this._layers = {}, this._lastZIndex = 0, this._handlingClick = !1;
for (var n in t) this._addLayer(t[n], n);
for (n in e) this._addLayer(e[n], n, !0)
},
onAdd: function(t) {
return this._initLayout(), this._update(), t.on("layeradd", this._onLayerChange, this).on("layerremove", this._onLayerChange, this), this._container
},
onRemove: function(t) {
t.off("layeradd", this._onLayerChange, this).off("layerremove", this._onLayerChange, this)
},
addBaseLayer: function(t, e) {
return this._addLayer(t, e), this._update(), this
},
addOverlay: function(t, e) {
return this._addLayer(t, e, !0), this._update(), this
},
removeLayer: function(t) {
var e = o.stamp(t);
return delete this._layers[e], this._update(), this
},
_initLayout: function() {
var t = "leaflet-control-layers",
e = this._container = o.DomUtil.create("div", t);
e.setAttribute("aria-haspopup", !0), o.Browser.touch ? o.DomEvent.on(e, "click", o.DomEvent.stopPropagation) : o.DomEvent.disableClickPropagation(e).disableScrollPropagation(e);
var i = this._form = o.DomUtil.create("form", t + "-list");
if (this.options.collapsed) {
o.Browser.android || o.DomEvent.on(e, "mouseover", this._expand, this).on(e, "mouseout", this._collapse, this);
var n = this._layersLink = o.DomUtil.create("a", t + "-toggle", e);
n.href = "#", n.title = "Layers", o.Browser.touch ? o.DomEvent.on(n, "click", o.DomEvent.stop).on(n, "click", this._expand, this) : o.DomEvent.on(n, "focus", this._expand, this), o.DomEvent.on(i, "click", function() {
setTimeout(o.bind(this._onInputClick, this), 0)
}, this), this._map.on("click", this._collapse, this)
} else this._expand();
this._baseLayersList = o.DomUtil.create("div", t + "-base", i), this._separator = o.DomUtil.create("div", t + "-separator", i), this._overlaysList = o.DomUtil.create("div", t + "-overlays", i), e.appendChild(i)
},
_addLayer: function(t, e, i) {
var n = o.stamp(t);
this._layers[n] = {
layer: t,
name: e,
overlay: i
}, this.options.autoZIndex && t.setZIndex && (this._lastZIndex++, t.setZIndex(this._lastZIndex))
},
_update: function() {
if (this._container) {
this._baseLayersList.innerHTML = "", this._overlaysList.innerHTML = "";
var t, e, i = !1,
n = !1;
for (t in this._layers) e = this._layers[t], this._addItem(e), n = n || e.overlay, i = i || !e.overlay;
this._separator.style.display = n && i ? "" : "none"
}
},
_onLayerChange: function(t) {
var e = this._layers[o.stamp(t.layer)];
if (e) {
this._handlingClick || this._update();
var i = e.overlay ? "layeradd" === t.type ? "overlayadd" : "overlayremove" : "layeradd" === t.type ? "baselayerchange" : null;
i && this._map.fire(i, e)
}
},
_createRadioElement: function(t, i) {
var n = '<input type="radio" class="leaflet-control-layers-selector" name="' + t + '"';
i && (n += ' checked="checked"'), n += "/>";
var o = e.createElement("div");
return o.innerHTML = n, o.firstChild
},
_addItem: function(t) {
var i, n = e.createElement("label"),
s = this._map.hasLayer(t.layer);
t.overlay ? (i = e.createElement("input"), i.type = "checkbox", i.className = "leaflet-control-layers-selector", i.defaultChecked = s) : i = this._createRadioElement("leaflet-base-layers", s), i.layerId = o.stamp(t.layer), o.DomEvent.on(i, "click", this._onInputClick, this);
var a = e.createElement("span");
a.innerHTML = " " + t.name, n.appendChild(i), n.appendChild(a);
var r = t.overlay ? this._overlaysList : this._baseLayersList;
return r.appendChild(n), n
},
_onInputClick: function() {
var t, e, i, n = this._form.getElementsByTagName("input"),
o = n.length;
for (this._handlingClick = !0, t = 0; o > t; t++) e = n[t], i = this._layers[e.layerId], e.checked && !this._map.hasLayer(i.layer) ? this._map.addLayer(i.layer) : !e.checked && this._map.hasLayer(i.layer) && this._map.removeLayer(i.layer);
this._handlingClick = !1, this._refocusOnMap()
},
_expand: function() {
o.DomUtil.addClass(this._container, "leaflet-control-layers-expanded")
},
_collapse: function() {
this._container.className = this._container.className.replace(" leaflet-control-layers-expanded", "")
}
}), o.control.layers = function(t, e, i) {
return new o.Control.Layers(t, e, i)
}, o.PosAnimation = o.Class.extend({
includes: o.Mixin.Events,
run: function(t, e, i, n) {
this.stop(), this._el = t, this._inProgress = !0, this._newPos = e, this.fire("start"), t.style[o.DomUtil.TRANSITION] = "all " + (i || .25) + "s cubic-bezier(0,0," + (n || .5) + ",1)", o.DomEvent.on(t, o.DomUtil.TRANSITION_END, this._onTransitionEnd, this), o.DomUtil.setPosition(t, e), o.Util.falseFn(t.offsetWidth), this._stepTimer = setInterval(o.bind(this._onStep, this), 50)
},
stop: function() {
this._inProgress && (o.DomUtil.setPosition(this._el, this._getPos()), this._onTransitionEnd(), o.Util.falseFn(this._el.offsetWidth))
},
_onStep: function() {
var t = this._getPos();
return t ? (this._el._leaflet_pos = t, void this.fire("step")) : void this._onTransitionEnd()
},
_transformRe: /([-+]?(?:\d*\.)?\d+)\D*, ([-+]?(?:\d*\.)?\d+)\D*\)/,
_getPos: function() {
var e, i, n, s = this._el,
a = t.getComputedStyle(s);
if (o.Browser.any3d) {
if (n = a[o.DomUtil.TRANSFORM].match(this._transformRe), !n) return;
e = parseFloat(n[1]), i = parseFloat(n[2])
} else e = parseFloat(a.left), i = parseFloat(a.top);
return new o.Point(e, i, !0)
},
_onTransitionEnd: function() {
o.DomEvent.off(this._el, o.DomUtil.TRANSITION_END, this._onTransitionEnd, this), this._inProgress && (this._inProgress = !1, this._el.style[o.DomUtil.TRANSITION] = "", this._el._leaflet_pos = this._newPos, clearInterval(this._stepTimer), this.fire("step").fire("end"))
}
}), o.Map.include({
setView: function(t, e, n) {
if (e = e === i ? this._zoom : this._limitZoom(e), t = this._limitCenter(o.latLng(t), e, this.options.maxBounds), n = n || {}, this._panAnim && this._panAnim.stop(), this._loaded && !n.reset && n !== !0) {
n.animate !== i && (n.zoom = o.extend({
animate: n.animate
}, n.zoom), n.pan = o.extend({
animate: n.animate
}, n.pan));
var s = this._zoom !== e ? this._tryAnimatedZoom && this._tryAnimatedZoom(t, e, n.zoom) : this._tryAnimatedPan(t, n.pan);
if (s) return clearTimeout(this._sizeTimer), this
}
return this._resetView(t, e), this
},
panBy: function(t, e) {
if (t = o.point(t).round(), e = e || {}, !t.x && !t.y) return this;
if (this._panAnim || (this._panAnim = new o.PosAnimation, this._panAnim.on({
step: this._onPanTransitionStep,
end: this._onPanTransitionEnd
}, this)), e.noMoveStart || this.fire("movestart"), e.animate !== !1) {
o.DomUtil.addClass(this._mapPane, "leaflet-pan-anim");
var i = this._getMapPanePos().subtract(t);
this._panAnim.run(this._mapPane, i, e.duration || .25, e.easeLinearity)
} else this._rawPanBy(t), this.fire("move").fire("moveend");
return this
},
_onPanTransitionStep: function() {
this.fire("move")
},
_onPanTransitionEnd: function() {
o.DomUtil.removeClass(this._mapPane, "leaflet-pan-anim"), this.fire("moveend")
},
_tryAnimatedPan: function(t, e) {
var i = this._getCenterOffset(t)._floor();
return (e && e.animate) === !0 || this.getSize().contains(i) ? (this.panBy(i, e), !0) : !1
}
}), o.PosAnimation = o.DomUtil.TRANSITION ? o.PosAnimation : o.PosAnimation.extend({
run: function(t, e, i, n) {
this.stop(), this._el = t, this._inProgress = !0, this._duration = i || .25, this._easeOutPower = 1 / Math.max(n || .5, .2), this._startPos = o.DomUtil.getPosition(t), this._offset = e.subtract(this._startPos), this._startTime = +new Date, this.fire("start"), this._animate()
},
stop: function() {
this._inProgress && (this._step(), this._complete())
},
_animate: function() {
this._animId = o.Util.requestAnimFrame(this._animate, this), this._step()
},
_step: function() {
var t = +new Date - this._startTime,
e = 1e3 * this._duration;
e > t ? this._runFrame(this._easeOut(t / e)) : (this._runFrame(1), this._complete())
},
_runFrame: function(t) {
var e = this._startPos.add(this._offset.multiplyBy(t));
o.DomUtil.setPosition(this._el, e), this.fire("step")
},
_complete: function() {
o.Util.cancelAnimFrame(this._animId), this._inProgress = !1, this.fire("end")
},
_easeOut: function(t) {
return 1 - Math.pow(1 - t, this._easeOutPower)
}
}), o.Map.mergeOptions({
zoomAnimation: !0,
zoomAnimationThreshold: 4
}), o.DomUtil.TRANSITION && o.Map.addInitHook(function() {
this._zoomAnimated = this.options.zoomAnimation && o.DomUtil.TRANSITION && o.Browser.any3d && !o.Browser.android23 && !o.Browser.mobileOpera, this._zoomAnimated && o.DomEvent.on(this._mapPane, o.DomUtil.TRANSITION_END, this._catchTransitionEnd, this)
}), o.Map.include(o.DomUtil.TRANSITION ? {
_catchTransitionEnd: function(t) {
this._animatingZoom && t.propertyName.indexOf("transform") >= 0 && this._onZoomTransitionEnd()
},
_nothingToAnimate: function() {
return !this._container.getElementsByClassName("leaflet-zoom-animated").length
},
_tryAnimatedZoom: function(t, e, i) {
if (this._animatingZoom) return !0;
if (i = i || {}, !this._zoomAnimated || i.animate === !1 || this._nothingToAnimate() || Math.abs(e - this._zoom) > this.options.zoomAnimationThreshold) return !1;
var n = this.getZoomScale(e),
o = this._getCenterOffset(t)._divideBy(1 - 1 / n),
s = this._getCenterLayerPoint()._add(o);
return i.animate === !0 || this.getSize().contains(o) ? (this.fire("movestart").fire("zoomstart"), this._animateZoom(t, e, s, n, null, !0), !0) : !1
},
_animateZoom: function(t, e, i, n, s, a, r) {
r || (this._animatingZoom = !0), o.DomUtil.addClass(this._mapPane, "leaflet-zoom-anim"), this._animateToCenter = t, this._animateToZoom = e, o.Draggable && (o.Draggable._disabled = !0), o.Util.requestAnimFrame(function() {
this.fire("zoomanim", {
center: t,
zoom: e,
origin: i,
scale: n,
delta: s,
backwards: a
})
}, this)
},
_onZoomTransitionEnd: function() {
this._animatingZoom = !1, o.DomUtil.removeClass(this._mapPane, "leaflet-zoom-anim"), this._resetView(this._animateToCenter, this._animateToZoom, !0, !0), o.Draggable && (o.Draggable._disabled = !1)
}
} : {}), o.TileLayer.include({
_animateZoom: function(t) {
this._animating || (this._animating = !0, this._prepareBgBuffer());
var e = this._bgBuffer,
i = o.DomUtil.TRANSFORM,
n = t.delta ? o.DomUtil.getTranslateString(t.delta) : e.style[i],
s = o.DomUtil.getScaleString(t.scale, t.origin);
e.style[i] = t.backwards ? s + " " + n : n + " " + s
},
_endZoomAnim: function() {
var t = this._tileContainer,
e = this._bgBuffer;
t.style.visibility = "", t.parentNode.appendChild(t), o.Util.falseFn(e.offsetWidth), this._animating = !1
},
_clearBgBuffer: function() {
var t = this._map;
!t || t._animatingZoom || t.touchZoom._zooming || (this._bgBuffer.innerHTML = "", this._bgBuffer.style[o.DomUtil.TRANSFORM] = "")
},
_prepareBgBuffer: function() {
var t = this._tileContainer,
e = this._bgBuffer,
i = this._getLoadedTilesPercentage(e),
n = this._getLoadedTilesPercentage(t);
return e && i > .5 && .5 > n ? (t.style.visibility = "hidden", void this._stopLoadingImages(t)) : (e.style.visibility = "hidden", e.style[o.DomUtil.TRANSFORM] = "", this._tileContainer = e, e = this._bgBuffer = t, this._stopLoadingImages(e), void clearTimeout(this._clearBgBufferTimer))
},
_getLoadedTilesPercentage: function(t) {
var e, i, n = t.getElementsByTagName("img"),
o = 0;
for (e = 0, i = n.length; i > e; e++) n[e].complete && o++;
return o / i
},
_stopLoadingImages: function(t) {
var e, i, n, s = Array.prototype.slice.call(t.getElementsByTagName("img"));
for (e = 0, i = s.length; i > e; e++) n = s[e], n.complete || (n.onload = o.Util.falseFn, n.onerror = o.Util.falseFn, n.src = o.Util.emptyImageUrl, n.parentNode.removeChild(n))
}
}), o.Map.include({
_defaultLocateOptions: {
watch: !1,
setView: !1,
maxZoom: 1 / 0,
timeout: 1e4,
maximumAge: 0,
enableHighAccuracy: !1
},
locate: function(t) {
if (t = this._locateOptions = o.extend(this._defaultLocateOptions, t), !navigator.geolocation) return this._handleGeolocationError({
code: 0,
message: "Geolocation not supported."
}), this;
var e = o.bind(this._handleGeolocationResponse, this),
i = o.bind(this._handleGeolocationError, this);
return t.watch ? this._locationWatchId = navigator.geolocation.watchPosition(e, i, t) : navigator.geolocation.getCurrentPosition(e, i, t), this
},
stopLocate: function() {
return navigator.geolocation && navigator.geolocation.clearWatch(this._locationWatchId), this._locateOptions && (this._locateOptions.setView = !1), this
},
_handleGeolocationError: function(t) {
var e = t.code,
i = t.message || (1 === e ? "permission denied" : 2 === e ? "position unavailable" : "timeout");
this._locateOptions.setView && !this._loaded && this.fitWorld(), this.fire("locationerror", {
code: e,
message: "Geolocation error: " + i + "."
})
},
_handleGeolocationResponse: function(t) {
var e = t.coords.latitude,
i = t.coords.longitude,
n = new o.LatLng(e, i),
s = 180 * t.coords.accuracy / 40075017,
a = s / Math.cos(o.LatLng.DEG_TO_RAD * e),
r = o.latLngBounds([e - s, i - a], [e + s, i + a]),
h = this._locateOptions;
if (h.setView) {
var l = Math.min(this.getBoundsZoom(r), h.maxZoom);
this.setView(n, l)
}
var u = {
latlng: n,
bounds: r,
timestamp: t.timestamp
};
for (var c in t.coords) "number" == typeof t.coords[c] && (u[c] = t.coords[c]);
this.fire("locationfound", u)
}
})
}(window, document);
|
//Single vector tile, received from GeoMixer server
// dataProvider: has single method "load": function(x, y, z, v, s, d, callback), which calls "callback" with the following parameters:
// - {Object[]} data - information about vector objects in tile
// - {Number[4]} [bbox] - optional bbox of objects in tile
// options:
// x, y, z, v, s, d: GeoMixer vector tile point
// dateZero: zero Date for temporal layers
// isGeneralized: flag for generalized tile
var VectorTile = function(dataProvider, options) {
this.dataProvider = dataProvider;
this.loadDef = new L.gmx.Deferred();
this.data = null;
this.dataOptions = null;
this.x = options.x;
this.y = options.y;
this.z = options.z;
this.v = options.v;
this.s = options.s || -1;
this.d = options.d || -1;
// this._itemsArr = options._itemsArr;
this.attributes = options.attributes;
this.isGeneralized = options.isGeneralized;
this.isFlatten = options.isFlatten;
this.bounds = gmxAPIutils.getTileBounds(this.x, this.y, this.z);
this.gmxTilePoint = {x: this.x, y: this.y, z: this.z, s: this.s, d: this.d};
this.vectorTileKey = VectorTile.makeTileKey(this.x, this.y, this.z, this.v, this.s, this.d);
if (this.s >= 0 && options.dateZero) {
this.beginDate = new Date(options.dateZero.valueOf() + this.s * this.d * gmxAPIutils.oneDay * 1000);
this.endDate = new Date(options.dateZero.valueOf() + (this.s + 1) * this.d * gmxAPIutils.oneDay * 1000);
}
this.state = 'notLoaded'; //notLoaded, loading, loaded
};
VectorTile.prototype = {
addData: function(data, keys) {
if (keys) {
this.removeData(keys, true);
}
var len = data.length,
dataOptions = new Array(len),
dataBounds = gmxAPIutils.bounds();
for (var i = 0; i < len; i++) {
var dataOption = this._parseItem(data[i]);
dataOptions[i] = dataOption;
dataBounds.extendBounds(dataOption.bounds);
}
if (!this.data) {
this.data = data;
this.dataOptions = dataOptions;
} else {
this.data = this.data.concat(data);
this.dataOptions = this.dataOptions.concat(dataOptions);
}
this.state = 'loaded';
this.loadDef.resolve(this.data);
return dataBounds;
},
removeData: function(keys) {
for (var arr = this.data || [], i = arr.length - 1; i >= 0; i--) {
if (keys[arr[i][0]]) {
arr.splice(i, 1);
if (this.dataOptions) { this.dataOptions.splice(i, 1); }
}
}
},
load: function() {
if (this.state === 'notLoaded') {
this.state = 'loading';
var _this = this;
this.dataProvider.load(_this.x, _this.y, _this.z, _this.v, _this.s, _this.d, function(data, bbox, srs, isGeneralized) {
_this.bbox = bbox;
_this.srs = srs;
if (isGeneralized) { _this.isGeneralized = isGeneralized; }
_this.addData(data);
});
}
return this.loadDef;
},
clear: function() {
this.state = 'notLoaded';
this.data = null;
this.dataOptions = null;
this.loadDef = new L.gmx.Deferred();
},
// TODO: Для упаковки атрибутов
// _getLinkProp: function(nm, val) {
// var attr = this.attributes,
// name = attr[nm - 1],
// arr = this._itemsArr[name],
// len = arr.length,
// i = 0;
// for (; i < len; i++) {
// if (val === arr[i]) { return i; }
// }
// arr[i] = val;
// return i;
// },
_parseItem: function(it) {
var len = it.length - 1,
// props = new Uint32Array(len),
i;
// props[0] = it[0];
// TODO: old properties null = ''
for (i = 1; i < len; i++) {
if (it[i] === null) { it[i] = ''; }
// props[i] = this._getLinkProp(i, it[i]);
}
var geo = it[len],
needFlatten = this.isFlatten,
type = geo.type,
isLikePolygon = type.indexOf('POLYGON') !== -1 || type.indexOf('Polygon') !== -1,
isPolygon = type === 'POLYGON' || type === 'Polygon',
coords = geo.coordinates,
hiddenLines = [],
bounds = null,
boundsArr = [];
if (isLikePolygon) {
if (isPolygon) { coords = [coords]; }
bounds = gmxAPIutils.bounds();
var edgeBounds = gmxAPIutils.bounds().extendBounds(this.bounds).addBuffer(-0.05),
hiddenFlag = false;
for (i = 0, len = coords.length; i < len; i++) {
var arr = [],
hiddenLines1 = [];
for (var j = 0, len1 = coords[i].length; j < len1; j++) {
if (needFlatten && typeof coords[i][j][0] !== 'number') {
coords[i][j] = gmxAPIutils.flattenRing(coords[i][j]);
}
var b = gmxAPIutils.bounds(coords[i][j]);
arr.push(b);
if (j === 0) { bounds.extendBounds(b); }
// EdgeLines calc
var edgeArr = gmxAPIutils.getHidden(coords[i][j], edgeBounds);
hiddenLines1.push(edgeArr);
if (edgeArr.length) {
hiddenFlag = true;
}
}
boundsArr.push(arr);
hiddenLines.push(hiddenLines1);
}
if (!hiddenFlag) { hiddenLines = null; }
if (isPolygon) { boundsArr = boundsArr[0]; }
} else if (type === 'POINT' || type === 'Point') {
bounds = gmxAPIutils.bounds([coords]);
} else if (type === 'MULTIPOINT' || type === 'MultiPoint') {
bounds = gmxAPIutils.bounds();
for (i = 0, len = coords.length; i < len; i++) {
bounds.extendBounds(gmxAPIutils.bounds([coords[i]]));
}
} else if (type === 'LINESTRING' || type === 'LineString') {
bounds = gmxAPIutils.bounds(coords);
} else if (type === 'MULTILINESTRING' || type === 'MultiLineString') {
bounds = gmxAPIutils.bounds();
for (i = 0, len = coords.length; i < len; i++) {
bounds.extendBounds(gmxAPIutils.bounds(coords[i]));
}
}
var dataOption = {
// props: props,
bounds: bounds,
boundsArr: boundsArr
};
if (hiddenLines) {
dataOption.hiddenLines = hiddenLines;
}
return dataOption;
}
};
//class methods
VectorTile.makeTileKey = function(x, y, z, v, s, d) {
return z + '_' + x + '_' + y + '_' + v + '_' + s + '_' + d;
};
VectorTile.createTileKey = function(opt) {
return [opt.z, opt.x, opt.y, opt.v, opt.s, opt.d].join('_');
};
VectorTile.parseTileKey = function(gmxTileKey) {
var p = gmxTileKey.split('_').map(function(it) { return Number(it); });
return {z: p[0], x: p[1], y: p[2], v: p[3], s: p[4], d: p[5]};
};
VectorTile.boundsFromTileKey = function(gmxTileKey) {
var p = VectorTile.parseTileKey(gmxTileKey);
return gmxAPIutils.getTileBounds(p.x, p.y, p.z);
};
|
"use strict";
const OPCUAClient = require("..").OPCUAClient;
const ClientSecureChannelLayer = require("..").ClientSecureChannelLayer;
// eslint-disable-next-line import/order
const describe = require("node-opcua-leak-detector").describeWithLeakDetector;
describe("OPCUA Client", function () {
it("it should create a client", function () {
const client = OPCUAClient.create({});
});
it("should create a ClientSecureChannelLayer", function () {
const channel = new ClientSecureChannelLayer({});
channel.dispose();
});
});
|
(function (gulp, gulpLoadPlugins, pkg) {
'use strict';
//|**
//|
//| Gulpfile
//|
//| This file is the streaming build system
//|
//| .-------------------------------------------------------------------.
//| | NAMING CONVENTIONS: |
//| |-------------------------------------------------------------------|
//| | Singleton-literals and prototype objects | PascalCase |
//| |-------------------------------------------------------------------|
//| | Functions and public variables | camelCase |
//| |-------------------------------------------------------------------|
//| | Global variables and constants | UPPERCASE |
//| |-------------------------------------------------------------------|
//| | Private variables | _underscorePrefix |
//| '-------------------------------------------------------------------'
//|
//| Comment syntax for the entire project follows JSDoc:
//| - http://code.google.com/p/jsdoc-toolkit/wiki/TagReference
//|
//| For performance reasons we're only matching one level down:
//| - 'test/spec/{,*/}*.js'
//|
//| Use this if you want to recursively match all subfolders:
//| - 'test/spec/**/*.js'
//|
//'*/
var $ = gulpLoadPlugins({ pattern: '*', lazy: false }),
_ = { dist: './dist', test: './test' },
source = require('./.amrc').source,
module = 'sprite',
inline = '// <%= pkg.name %>@v<%= pkg.version %>, <%= pkg.license[0].type %> licensed. <%= pkg.homepage %>\n',
extended = [
'/**',
' * <%= pkg.title %>',
' * @description <%= pkg.description %>',
' * @version v<%= pkg.version %>',
' * @author <%= pkg.author.name %>',
' * @link <%= pkg.homepage %>',
' * @license <%= pkg.license[0].type %>',
' */\n'
].join('\n');
//|**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//| ✓ validate
//'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
gulp.task('jsonlint', function() {
var stream = gulp.src([
'package.json',
'bower.json',
'.bowerrc',
'.jshintrc',
'.jscs.json'
])
.pipe($.plumber())
.pipe($.jsonlint())
.pipe($.jsonlint.reporter())
.pipe($.notify({
message: '<%= options.date %> ✓ jsonlint: <%= file.relative %>',
templateOptions: {
date: new Date()
}
}));
return stream;
});
gulp.task('jshint', function () {
var stream = gulp.src(wrap(source[module].files, source[module].name))
.pipe($.plumber())
.pipe($.notify({
message: '<%= options.date %> ✓ jshint: <%= file.relative %>',
templateOptions: {
date: new Date()
}
}))
.pipe($.concat(source[module].name + '.js'))
.pipe($.removeUseStrict())
.pipe($.jshint('.jshintrc'))
.pipe($.jshint.reporter('default'))
.pipe($.jscs());
return stream;
});
gulp.task('mocha', function () {
var stream = gulp.src(_.test + '/**/*.js')
.pipe($.plumber())
.pipe($.mocha({ reporter: 'list' }));
return stream;
});
//|**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//| ✓ compress
//'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
gulp.task('src', ['validate'], function () {
var stream = gulp.src(wrap(source[module].files, source[module].name))
.pipe($.plumber())
.pipe($.notify({
message: '<%= options.date %> ✓ src: <%= file.relative %>',
templateOptions: {
date: new Date()
}
}))
.pipe($.concat(source[module].name + '.js'))
.pipe($.removeUseStrict())
.pipe($.header(extended, { pkg: pkg }))
.pipe($.size())
.pipe(gulp.dest(_.dist));
return stream;
});
gulp.task('min', ['src'], function () {
var min = gulp.src(_.dist + '/' + source[module].name + '.js')
.pipe($.plumber())
.pipe($.notify({
message: '<%= options.date %> ✓ min: <%= file.relative %>',
templateOptions: {
date: new Date()
}
}))
.pipe($.rename(source[module].name + '.min.js'))
.pipe($.uglify())
.pipe($.header(inline, { pkg: pkg }))
.pipe($.size())
.pipe(gulp.dest(_.dist));
return min;
});
//|**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//| ✓ versioning
//'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
gulp.task('bump', function () {
var bumpType = process.env.BUMP || 'patch';
var stream = gulp.src(['package.json', 'bower.json'])
.pipe($.bump({ type: bumpType }))
.pipe(gulp.dest('./'));
return stream;
});
gulp.task('tag', ['bump', 'min'], function () {
var version = 'v' + pkg.version;
var message = 'Release ' + version;
var stream = gulp.src('./')
.pipe($.git.commit(message))
.pipe($.git.tag(version, message))
.pipe($.git.push('origin', 'master', '--tags'))
.pipe($.gulp.dest('./'));
return stream;
});
gulp.task('npm', ['tag'], function (done) {
var process = require('child_process')
.spawn('npm', ['publish'], { stdio: 'inherit' })
.on('close', done);
});
//|**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//| ✓ default
//'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
gulp.task('clean', function () {
var stream = gulp.src(_.dist, { read: false })
.pipe($.plumber())
.pipe($.clean());
return stream;
});
gulp.task('default', function() {
gulp.start('min');
});
//|**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//| ✓ shortcuts
//'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
gulp.task('validate', ['jsonlint', 'jshint']);
gulp.task('release', ['npm']);
gulp.task('test', ['mocha']);
gulp.task('ci', ['min']);
//|**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//| ✓ utils
//'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
function wrap(src) {
src.unshift('source/AM.prefix');
src.push('source/AM.suffix');
return src;
}
}(require('gulp'), require('gulp-load-plugins'), require('./package.json')));
|
/**
* @author: Hasin Hayder [hasin_at_leevio_dot_com | http://hasin.me]
* @license: MIT
*/
var currentTab=0, oldTab=1, tabRemoved=false;
chrome.tabs.onActivated.addListener(function(activeInfo) {
if(!tabRemoved){
//plain switch
if(oldTab!=activeInfo.tabId){
oldTab = currentTab;
currentTab = activeInfo.tabId;
}
}else{
//this tab got focus because previous tab was closed. So just update the currentTab
currentTab = activeInfo.tabId;
tabRemoved=false;
}
});
//listen for the Alt + Z keypress event
chrome.commands.onCommand.addListener(function (command) {
//alert(command);
if (command == "switch") {
chrome.tabs.update(oldTab,{selected:true});
}
});
//listen when a tab is closed
chrome.tabs.onRemoved.addListener(function(){
tabRemoved=true;
})
|
var MongoClient = require('mongodb').MongoClient;
var Code = require('code');
var Lab = require('lab');
var lab = exports.lab = Lab.script();
var Hapi = require('hapi');
var Joi = require('joi');
var async = require('async');
var describe = lab.describe;
var it = lab.it;
var before = lab.before;
var after = lab.after;
var expect = Code.expect;
var mongoUrl = 'mongodb://localhost:27017/hapi-job-queue-test';
var server;
var server2;
var plugin;
var plugin2;
var output = null;
var counter = 0;
before(function(done) {
server = new Hapi.Server();
server.connection({port: 3000});
server2 = new Hapi.Server();
server2.connection({port: 3001});
output = null;
single = false;
counter = 0;
server.register(require('hapi-auth-bearer-token'), function (err) {
server.auth.strategy('simple', 'bearer-access-token', {
allowQueryToken: true,
accessTokenName: 'token',
validateFunc: function( token, callback ) {
if(token === "1234"){
callback(null, true, { token: token });
} else {
callback(null, false, { token: token });
}
}
});
});
server2.register(require('hapi-auth-bearer-token'), function (err) {
server2.auth.strategy('simple', 'bearer-access-token', {
allowQueryToken: true,
accessTokenName: 'token',
validateFunc: function( token, callback ) {
if(token === "1234"){
callback(null, true, { token: token });
} else {
callback(null, false, { token: token });
}
}
});
});
MongoClient.connect(mongoUrl, function(err, db) {
if (err) {
return next(err);
}
db.dropDatabase(function(err) {
server.register([
{ register: require('../'), options: {
connectionUrl: mongoUrl,
endpoint: '/jobs',
auth: 'simple',
jobs: [
{
name: 'test-job',
enabled: true,
schedule: 'every 1 seconds',
method: function(data, cb) {
output = data.time;
counter++;
setTimeout(cb, 100);
},
tasks: [
{
time: 1
},
{
time: 2
}
]
}
]
} }
], function() {
server.method('testMethod', function(data, cb) {
output = 'methodized';
setTimeout(cb, 50);
});
server.method('deep.testMethod', function(data, cb) {
output = 'methodized';
setTimeout(cb, 50);
});
plugin = server.plugins.jobs;
//second test server
server2.register([
{ register: require('../'), options: {
connectionUrl: mongoUrl,
endpoint: '/jobs',
auth: 'simple',
jobs: [
{
name: 'test-job',
enabled: true,
schedule: 'every 1 seconds',
method: function(data, cb) {
output = data.time;
counter++;
setTimeout(cb, 100);
},
tasks: [
{
time: 1
},
{
time: 2
}
]
}
]
} }
], function() {
server2.method('testMethod', function(data, cb) {
output = 'methodized';
setTimeout(cb, 50);
});
plugin2 = server2.plugins.jobs;
done();
});
});
});
});
});
describe('job queue', { timeout: 5000 }, function() {
describe('setup', function() {
it('should expose db connection', function(done) {
expect(plugin.db).to.exist();
done();
});
it('should expose database collection', function(done) {
expect(plugin.collection).to.exist();
done();
});
it('should expose settings object', function(done) {
expect(plugin.settings).to.exist();
done();
});
it('should initialize jobs', function(done) {
plugin.collection.find({name: 'test-job'}).toArray(function(err, jobs) {
expect(err).to.not.exist();
expect(jobs.length).to.equal(1);
var job = jobs[0];
expect(job.name).to.equal('test-job');
expect(job.locked).to.equal(false);
expect(job.lastRun).to.equal(undefined);
expect(job.timeToRun).to.equal(undefined);
expect(job.group).to.deep.equal(['test-job']);
expect(job.tasks).to.deep.equal([{time: 1}, {time: 2}]);
expect(job.enabled).to.equal(true);
expect(job.nextRun).to.exist();
done();
});
});
});
describe('methods', function() {
it('should add a job', function(done) {
plugin.add({
name: 'test-job2',
enabled: true,
group: 'group1',
cron: '* 15 10 ? * *',
cronSeconds: true,
method: function(cb) {
output = 2;
cb();
}
}, function(err) {
expect(err).to.not.exist();
plugin.collection.find({name: 'test-job2'}).toArray(function(err, jobs) {
expect(jobs.length).to.equal(1);
var job = jobs[0];
expect(job.name).to.equal('test-job2');
expect(job.locked).to.equal(false);
expect(job.lastRun).to.equal(undefined);
expect(job.timeToRun).to.equal(undefined);
expect(job.group).to.deep.equal(['group1']);
expect(job.tasks).to.equal(null);
expect(job.enabled).to.equal(true);
expect(job.nextRun).to.exist();
done();
});
});
});
it('should add a job only once', function(done) {
plugin.add({
name: 'test-job2',
enabled: true,
group: 'group1',
cron: '* 15 10 ? * *',
cronSeconds: true,
method: function(cb) {
output = 2;
cb();
}
}, function(err) {
expect(err.toString()).to.equal('Error: Job already loaded');
done();
});
});
it('should only add a job once', function(done) {
plugin.add({
name: 'test-job',
enabled: false,
method: function(cb) {
output = 'ran';
cb();
}
}, function(err) {
expect(err).to.not.be.null();
plugin.collection.find({name: 'test-job'}).toArray(function(err, jobs) {
expect(jobs.length).to.equal(1);
done();
});
});
});
it('should add job to job object', function(done) {
expect(plugin.jobs['test-job']).to.exist();
expect(typeof plugin.jobs['test-job'].method).to.equal('function');
done();
});
it('should check if a job is valid before disabling', function(done) {
plugin.disable('fake-job', function(err) {
expect(err).to.not.be.null();
done();
});
});
it('should disable a job', function(done) {
plugin.disable('test-job', function(err) {
expect(err).to.not.exist();
plugin.collection.find({name: 'test-job'}).toArray(function(err, jobs) {
expect(err).to.not.exist();
expect(jobs.length).to.equal(1);
expect(jobs[0].enabled).to.equal(false);
done();
});
});
});
it('should check if a job is valid before enabling', function(done) {
plugin.enable('fake-job', function(err) {
expect(err).to.not.be.null();
done();
});
});
it('should enable a job', function(done) {
plugin.enable('test-job', function(err) {
expect(err).to.not.exist();
plugin.collection.find({name: 'test-job'}).toArray(function(err, jobs) {
expect(err).to.not.exist();
expect(jobs.length).to.equal(1);
expect(jobs[0].enabled).to.equal(true);
done();
});
});
});
it('should enable a group', function(done) {
plugin.enableGroup('test-job', function(err) {
expect(err).to.not.exist();
plugin.collection.find({group: 'test-job'}).toArray(function(err, jobs) {
expect(err).to.not.exist();
expect(jobs.length).to.equal(1);
expect(jobs[0].enabled).to.equal(true);
done();
});
});
});
it('should disable a group', function(done) {
plugin.disableGroup('test-job', function(err) {
expect(err).to.not.exist();
plugin.collection.find({group: 'test-job'}).toArray(function(err, jobs) {
expect(err).to.not.exist();
expect(jobs.length).to.equal(1);
expect(jobs[0].enabled).to.equal(false);
done();
});
});
});
it('should re-schedule a job', function(done) {
plugin.reschedule('test-job', { schedule: 'every 30 seconds' }, function(err) {
expect(err).to.not.exist();
expect(plugin.jobs['test-job'].schedule).to.equal('every 30 seconds');
done();
});
});
});
describe('runner', function() {
it('should run a job at the specified time', function(done) {
output = null;
counter = 0;
// tests multi server setups.
async.parallel([
function(next) {
plugin.enable('test-job', function(err) {
plugin.reschedule('test-job', { schedule: 'every 1 seconds' }, function(err) {
expect(err).to.not.exist();
next();
});
});
},
function(next) {
plugin2.enable('test-job', function(err) {
plugin2.reschedule('test-job', { schedule: 'every 1 seconds' }, function(err) {
expect(err).to.not.exist();
next();
});
});
}
], function() {
setTimeout(function() {
expect(output).to.equal(2);
expect(counter).to.equal(2);
done();
}, 1400);
});
});
it('should lock a running job', function(done) {
output = null;
plugin.reschedule('test-job', { schedule: 'every 1 seconds' }, function(err) {
expect(err).to.not.exist();
setTimeout(function() {
plugin.collection.find({group: 'test-job'}).toArray(function(err, jobs) {
expect(err).to.not.exist();
expect(jobs[0].locked).to.equal(true);
done();
});
}, 1050);
});
});
it('should unlock a job when it finishes', function(done) {
output = null;
plugin.reschedule('test-job', { schedule: 'every 1 seconds' }, function(err) {
expect(err).to.not.exist();
setTimeout(function() {
plugin.collection.find({group: 'test-job'}).toArray(function(err, jobs) {
expect(err).to.not.exist();
expect(jobs[0].locked).to.equal(false);
done();
});
}, 1400);
});
});
it('should time how long a job takes to process', function(done) {
plugin.collection.find({group: 'test-job'}).toArray(function(err, jobs) {
expect(err).to.not.exist();
expect(jobs[0].timeToRun).to.be.above(0);
done();
});
});
it('should run a job right away', function(done) {
single = false;
plugin.add({
name: 'test-single',
enabled: true,
single: true,
method: function(data, cb) {
single = data;
cb();
}
}, function(err) {
expect(err).to.not.exist();
expect(single).to.equal(false);
plugin.runSingle('test-single', [true], function(err, jobError) {
expect(err).to.not.exist();
expect(jobError).to.not.exist();
expect(single).to.equal(true);
done();
});
});
});
it('should run a scheduled job right away', function(done) {
single = false;
plugin.add({
name: 'test-single3',
enabled: true,
schedule: 'at 6:00 am',
method: function(data, cb) {
single = data;
cb();
}
}, function(err) {
expect(err).to.not.exist();
expect(single).to.equal(false);
plugin.runSingle('test-single3', [true], function(err, jobError) {
expect(err).to.not.exist();
expect(jobError).to.not.exist();
expect(single).to.equal(true);
done();
});
});
});
it('should handle a failed job', function(done) {
plugin.add({
name: 'test-fail',
enabled: true,
single: true,
method: function(data, cb) {
cb(new Error('Test error'));
}
}, function(err) {
expect(err).to.not.exist();
plugin.runSingle('test-fail', [true], function(err, jobError) {
expect(err).to.not.exist();
expect(jobError.toString()).to.equal('Error: Test error');
done();
});
});
});
it('should run a job right away without data', function(done) {
var single = false;
plugin.add({
name: 'test-single2',
enabled: true,
single: true,
method: function(data, cb) {
single = true;
cb();
}
}, function(err) {
expect(err).to.not.exist();
expect(single).to.equal(false);
plugin.runSingle('test-single2', function(err, jobError) {
expect(err).to.not.exist();
expect(jobError).to.not.exist();
expect(single).to.equal(true);
done();
});
});
});
it('should run a job with empty data', function(done) {
var single = false;
plugin.add({
name: 'test-single4',
enabled: true,
single: true,
method: function(data, cb) {
single = true;
cb();
}
}, function(err) {
expect(err).to.not.exist();
expect(single).to.equal(false);
plugin.runSingle('test-single4', {}, function(err, jobError) {
expect(err).to.not.exist();
expect(jobError).to.not.exist();
expect(single).to.equal(true);
done();
});
});
});
it('should run a job method by name', function(done) {
output = null;
plugin.add({
name: 'test-method',
enabled: true,
single: true,
method: 'testMethod'
}, function(err) {
expect(err).to.not.exist();
expect(output).to.equal(null);
plugin.runSingle('test-method', function(err, jobError) {
expect(err).to.not.exist();
expect(jobError).to.not.exist();
expect(output).to.equal('methodized');
done();
});
});
});
it('should run a job method by name when nested', function(done) {
output = null;
plugin.add({
name: 'deep-test-method',
enabled: true,
single: true,
method: 'deep.testMethod'
}, function(err) {
expect(err).to.not.exist();
expect(output).to.equal(null);
plugin.runSingle('deep-test-method', function(err, jobError) {
expect(err).to.not.exist();
expect(jobError).to.not.exist();
expect(output).to.equal('methodized');
done();
});
});
});
//TODO: Still thinking about groups - Not sure if they're needed
it.skip('should run a group of jobs right away', function(done) {
done();
});
});
describe('api', function() {
it('should return all jobs', function(done) {
server.inject({
method: 'get',
url: '/jobs/?token=1234'
}, function(response) {
Joi.validate(response, {
raw: Joi.any(),
headers: Joi.any(),
rawPayload: Joi.any(),
payload: Joi.any(),
request: Joi.any(),
statusCode: Joi.allow(200),
result: Joi.array().items(
Joi.object().keys({
_id: Joi.any(),
name: Joi.string(),
tasks: Joi.array().allow(null),
group: Joi.array(),
locked: Joi.boolean(),
enabled: Joi.boolean(),
nextRun: Joi.date().allow(null),
lastRun: Joi.date(),
single: Joi.boolean(),
timeToRun: Joi.number()
})
)
}, function(err, res) {
if (err) {
console.log(err);
}
expect(err).to.not.exist();
done();
});
});
});
it('should enable a job', function(done) {
plugin.disable('test-job', function(err) {
expect(err).to.not.exist();
server.inject({
method: 'get',
url: '/jobs/enable/test-job?token=1234'
}, function(response) {
expect(response.statusCode).to.equal(200);
expect(response.result).to.deep.equal({ success: true});
plugin.collection.find({name: 'test-job'}).toArray(function(err, jobs) {
expect(err).to.not.exist();
expect(jobs.length).to.equal(1);
expect(jobs[0].enabled).to.equal(true);
done();
});
});
});
});
it('should disable a job', function(done) {
plugin.enable('test-job', function(err) {
expect(err).to.not.exist();
server.inject({
method: 'get',
url: '/jobs/disable/test-job?token=1234'
}, function(response) {
expect(response.statusCode).to.equal(200);
expect(response.result).to.deep.equal({ success: true});
plugin.collection.find({group: 'test-job'}).toArray(function(err, jobs) {
expect(err).to.not.exist();
expect(jobs.length).to.equal(1);
expect(jobs[0].enabled).to.equal(false);
done();
});
});
});
});
it('should run a job', function(done) {
single = false;
server.inject({
method: 'post',
url: '/jobs/run/test-single?token=1234',
payload: [true]
}, function(response) {
expect(response.statusCode).to.equal(200);
expect(response.result).to.deep.equal({ success: true});
expect(single).to.equal(true);
done();
});
});
it('should use auth setting', function(done) {
server.inject({
method: 'get',
url: '/jobs/'
}, function(response) {
expect(response.statusCode).to.equal(401);
done();
});
});
});
});
|
// Regular expression that matches all symbols in the Halfwidth and Fullwidth Forms block as per Unicode v3.2.0:
/[\uFF00-\uFFEF]/; |
RocketChat.models.Users.roleBaseQuery = function(userId) {
return { _id: userId };
};
RocketChat.models.Users.findUsersInRoles = function(roles, scope, options) {
roles = [].concat(roles);
const query = {
roles: { $in: roles },
};
return this.find(query, options);
};
|
/*
---
name: Core
description: The heart of MooTools.
license: MIT-style license.
copyright: Copyright (c) 2006-2010 [Valerio Proietti](http://mad4milk.net/).
authors: The MooTools production team (http://mootools.net/developers/)
inspiration:
- Class implementation inspired by [Base.js](http://dean.edwards.name/weblog/2006/03/base/) Copyright (c) 2006 Dean Edwards, [GNU Lesser General Public License](http://opensource.org/licenses/lgpl-license.php)
- Some functionality inspired by [Prototype.js](http://prototypejs.org) Copyright (c) 2005-2007 Sam Stephenson, [MIT License](http://opensource.org/licenses/mit-license.php)
provides: [Core, MooTools, Type, typeOf, instanceOf, Native]
...
*/
(function(){
this.MooTools = {
version: '1.3.3dev',
build: 'a1bec0f00e10a8cd4b457a4108c061c0c83b63e2'
};
// typeOf, instanceOf
var typeOf = this.typeOf = function(item){
if (item == null) return 'null';
if (item.$family) return item.$family();
if (item.nodeName){
if (item.nodeType == 1) return 'element';
if (item.nodeType == 3) return (/\S/).test(item.nodeValue) ? 'textnode' : 'whitespace';
} else if (typeof item.length == 'number'){
if (item.callee) return 'arguments';
if ('item' in item) return 'collection';
}
return typeof item;
};
var instanceOf = this.instanceOf = function(item, object){
if (item == null) return false;
var constructor = item.$constructor || item.constructor;
while (constructor){
if (constructor === object) return true;
constructor = constructor.parent;
}
return item instanceof object;
};
// Function overloading
var Function = this.Function;
var enumerables = true;
for (var i in {toString: 1}) enumerables = null;
if (enumerables) enumerables = ['hasOwnProperty', 'valueOf', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'constructor'];
Function.prototype.overloadSetter = function(usePlural){
var self = this;
return function(a, b){
if (a == null) return this;
if (usePlural || typeof a != 'string'){
for (var k in a) self.call(this, k, a[k]);
if (enumerables) for (var i = enumerables.length; i--;){
k = enumerables[i];
if (a.hasOwnProperty(k)) self.call(this, k, a[k]);
}
} else {
self.call(this, a, b);
}
return this;
};
};
Function.prototype.overloadGetter = function(usePlural){
var self = this;
return function(a){
var args, result;
if (usePlural || typeof a != 'string') args = a;
else if (arguments.length > 1) args = arguments;
if (args){
result = {};
for (var i = 0; i < args.length; i++) result[args[i]] = self.call(this, args[i]);
} else {
result = self.call(this, a);
}
return result;
};
};
Function.prototype.extend = function(key, value){
this[key] = value;
}.overloadSetter();
Function.prototype.implement = function(key, value){
this.prototype[key] = value;
}.overloadSetter();
// From
var slice = Array.prototype.slice;
Function.from = function(item){
return (typeOf(item) == 'function') ? item : function(){
return item;
};
};
Array.from = function(item){
if (item == null) return [];
return (Type.isEnumerable(item) && typeof item != 'string') ? (typeOf(item) == 'array') ? item : slice.call(item) : [item];
};
Number.from = function(item){
var number = parseFloat(item);
return isFinite(number) ? number : null;
};
String.from = function(item){
return item + '';
};
// hide, protect
Function.implement({
hide: function(){
this.$hidden = true;
return this;
},
protect: function(){
this.$protected = true;
return this;
}
});
// Type
var Type = this.Type = function(name, object){
if (name){
var lower = name.toLowerCase();
var typeCheck = function(item){
return (typeOf(item) == lower);
};
Type['is' + name] = typeCheck;
if (object != null){
object.prototype.$family = (function(){
return lower;
}).hide();
}
}
if (object == null) return null;
object.extend(this);
object.$constructor = Type;
object.prototype.$constructor = object;
return object;
};
var toString = Object.prototype.toString;
Type.isEnumerable = function(item){
return (item != null && typeof item.length == 'number' && toString.call(item) != '[object Function]' );
};
var hooks = {};
var hooksOf = function(object){
var type = typeOf(object.prototype);
return hooks[type] || (hooks[type] = []);
};
var implement = function(name, method){
if (method && method.$hidden) return;
var hooks = hooksOf(this);
for (var i = 0; i < hooks.length; i++){
var hook = hooks[i];
if (typeOf(hook) == 'type') implement.call(hook, name, method);
else hook.call(this, name, method);
}
var previous = this.prototype[name];
if (previous == null || !previous.$protected) this.prototype[name] = method;
if (this[name] == null && typeOf(method) == 'function') extend.call(this, name, function(item){
return method.apply(item, slice.call(arguments, 1));
});
};
var extend = function(name, method){
if (method && method.$hidden) return;
var previous = this[name];
if (previous == null || !previous.$protected) this[name] = method;
};
Type.implement({
implement: implement.overloadSetter(),
extend: extend.overloadSetter(),
alias: function(name, existing){
implement.call(this, name, this.prototype[existing]);
}.overloadSetter(),
mirror: function(hook){
hooksOf(this).push(hook);
return this;
}
});
new Type('Type', Type);
// Default Types
var force = function(name, object, methods){
var isType = (object != Object),
prototype = object.prototype;
if (isType) object = new Type(name, object);
for (var i = 0, l = methods.length; i < l; i++){
var key = methods[i],
generic = object[key],
proto = prototype[key];
if (generic) generic.protect();
if (isType && proto){
delete prototype[key];
prototype[key] = proto.protect();
}
}
if (isType) object.implement(prototype);
return force;
};
force('String', String, [
'charAt', 'charCodeAt', 'concat', 'indexOf', 'lastIndexOf', 'match', 'quote', 'replace', 'search',
'slice', 'split', 'substr', 'substring', 'toLowerCase', 'toUpperCase'
])('Array', Array, [
'pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift', 'concat', 'join', 'slice',
'indexOf', 'lastIndexOf', 'filter', 'forEach', 'every', 'map', 'some', 'reduce', 'reduceRight'
])('Number', Number, [
'toExponential', 'toFixed', 'toLocaleString', 'toPrecision'
])('Function', Function, [
'apply', 'call', 'bind'
])('RegExp', RegExp, [
'exec', 'test'
])('Object', Object, [
'create', 'defineProperty', 'defineProperties', 'keys',
'getPrototypeOf', 'getOwnPropertyDescriptor', 'getOwnPropertyNames',
'preventExtensions', 'isExtensible', 'seal', 'isSealed', 'freeze', 'isFrozen'
])('Date', Date, ['now']);
Object.extend = extend.overloadSetter();
Date.extend('now', function(){
return +(new Date);
});
new Type('Boolean', Boolean);
// fixes NaN returning as Number
Number.prototype.$family = function(){
return isFinite(this) ? 'number' : 'null';
}.hide();
// Number.random
Number.extend('random', function(min, max){
return Math.floor(Math.random() * (max - min + 1) + min);
});
// forEach, each
var hasOwnProperty = Object.prototype.hasOwnProperty;
Object.extend('forEach', function(object, fn, bind){
for (var key in object){
if (hasOwnProperty.call(object, key)) fn.call(bind, object[key], key, object);
}
});
Object.each = Object.forEach;
Array.implement({
forEach: function(fn, bind){
for (var i = 0, l = this.length; i < l; i++){
if (i in this) fn.call(bind, this[i], i, this);
}
},
each: function(fn, bind){
Array.forEach(this, fn, bind);
return this;
}
});
// Array & Object cloning, Object merging and appending
var cloneOf = function(item){
switch (typeOf(item)){
case 'array': return item.clone();
case 'object': return Object.clone(item);
default: return item;
}
};
Array.implement('clone', function(){
var i = this.length, clone = new Array(i);
while (i--) clone[i] = cloneOf(this[i]);
return clone;
});
var mergeOne = function(source, key, current){
switch (typeOf(current)){
case 'object':
if (typeOf(source[key]) == 'object') Object.merge(source[key], current);
else source[key] = Object.clone(current);
break;
case 'array': source[key] = current.clone(); break;
default: source[key] = current;
}
return source;
};
Object.extend({
merge: function(source, k, v){
if (typeOf(k) == 'string') return mergeOne(source, k, v);
for (var i = 1, l = arguments.length; i < l; i++){
var object = arguments[i];
for (var key in object) mergeOne(source, key, object[key]);
}
return source;
},
clone: function(object){
var clone = {};
for (var key in object) clone[key] = cloneOf(object[key]);
return clone;
},
append: function(original){
for (var i = 1, l = arguments.length; i < l; i++){
var extended = arguments[i] || {};
for (var key in extended) original[key] = extended[key];
}
return original;
}
});
// Object-less types
['Object', 'WhiteSpace', 'TextNode', 'Collection', 'Arguments'].each(function(name){
new Type(name);
});
// Unique ID
var UID = Date.now();
String.extend('uniqueID', function(){
return (UID++).toString(36);
});
})();
/*
---
name: Array
description: Contains Array Prototypes like each, contains, and erase.
license: MIT-style license.
requires: Type
provides: Array
...
*/
Array.implement({
/*<!ES5>*/
every: function(fn, bind){
for (var i = 0, l = this.length; i < l; i++){
if ((i in this) && !fn.call(bind, this[i], i, this)) return false;
}
return true;
},
filter: function(fn, bind){
var results = [];
for (var i = 0, l = this.length; i < l; i++){
if ((i in this) && fn.call(bind, this[i], i, this)) results.push(this[i]);
}
return results;
},
indexOf: function(item, from){
var len = this.length;
for (var i = (from < 0) ? Math.max(0, len + from) : from || 0; i < len; i++){
if (this[i] === item) return i;
}
return -1;
},
map: function(fn, bind){
var results = [];
for (var i = 0, l = this.length; i < l; i++){
if (i in this) results[i] = fn.call(bind, this[i], i, this);
}
return results;
},
some: function(fn, bind){
for (var i = 0, l = this.length; i < l; i++){
if ((i in this) && fn.call(bind, this[i], i, this)) return true;
}
return false;
},
/*</!ES5>*/
clean: function(){
return this.filter(function(item){
return item != null;
});
},
invoke: function(methodName){
var args = Array.slice(arguments, 1);
return this.map(function(item){
return item[methodName].apply(item, args);
});
},
associate: function(keys){
var obj = {}, length = Math.min(this.length, keys.length);
for (var i = 0; i < length; i++) obj[keys[i]] = this[i];
return obj;
},
link: function(object){
var result = {};
for (var i = 0, l = this.length; i < l; i++){
for (var key in object){
if (object[key](this[i])){
result[key] = this[i];
delete object[key];
break;
}
}
}
return result;
},
contains: function(item, from){
return this.indexOf(item, from) != -1;
},
append: function(array){
this.push.apply(this, array);
return this;
},
getLast: function(){
return (this.length) ? this[this.length - 1] : null;
},
getRandom: function(){
return (this.length) ? this[Number.random(0, this.length - 1)] : null;
},
include: function(item){
if (!this.contains(item)) this.push(item);
return this;
},
combine: function(array){
for (var i = 0, l = array.length; i < l; i++) this.include(array[i]);
return this;
},
erase: function(item){
for (var i = this.length; i--;){
if (this[i] === item) this.splice(i, 1);
}
return this;
},
empty: function(){
this.length = 0;
return this;
},
flatten: function(){
var array = [];
for (var i = 0, l = this.length; i < l; i++){
var type = typeOf(this[i]);
if (type == 'null') continue;
array = array.concat((type == 'array' || type == 'collection' || type == 'arguments' || instanceOf(this[i], Array)) ? Array.flatten(this[i]) : this[i]);
}
return array;
},
pick: function(){
for (var i = 0, l = this.length; i < l; i++){
if (this[i] != null) return this[i];
}
return null;
},
hexToRgb: function(array){
if (this.length != 3) return null;
var rgb = this.map(function(value){
if (value.length == 1) value += value;
return value.toInt(16);
});
return (array) ? rgb : 'rgb(' + rgb + ')';
},
rgbToHex: function(array){
if (this.length < 3) return null;
if (this.length == 4 && this[3] == 0 && !array) return 'transparent';
var hex = [];
for (var i = 0; i < 3; i++){
var bit = (this[i] - 0).toString(16);
hex.push((bit.length == 1) ? '0' + bit : bit);
}
return (array) ? hex : '#' + hex.join('');
}
});
/*
---
name: String
description: Contains String Prototypes like camelCase, capitalize, test, and toInt.
license: MIT-style license.
requires: Type
provides: String
...
*/
String.implement({
test: function(regex, params){
return ((typeOf(regex) == 'regexp') ? regex : new RegExp('' + regex, params)).test(this);
},
contains: function(string, separator){
return (separator) ? (separator + this + separator).indexOf(separator + string + separator) > -1 : this.indexOf(string) > -1;
},
trim: function(){
return this.replace(/^\s+|\s+$/g, '');
},
clean: function(){
return this.replace(/\s+/g, ' ').trim();
},
camelCase: function(){
return this.replace(/-\D/g, function(match){
return match.charAt(1).toUpperCase();
});
},
hyphenate: function(){
return this.replace(/[A-Z]/g, function(match){
return ('-' + match.charAt(0).toLowerCase());
});
},
capitalize: function(){
return this.replace(/\b[a-z]/g, function(match){
return match.toUpperCase();
});
},
escapeRegExp: function(){
return this.replace(/([-.*+?^${}()|[\]\/\\])/g, '\\$1');
},
toInt: function(base){
return parseInt(this, base || 10);
},
toFloat: function(){
return parseFloat(this);
},
hexToRgb: function(array){
var hex = this.match(/^#?(\w{1,2})(\w{1,2})(\w{1,2})$/);
return (hex) ? hex.slice(1).hexToRgb(array) : null;
},
rgbToHex: function(array){
var rgb = this.match(/\d{1,3}/g);
return (rgb) ? rgb.rgbToHex(array) : null;
},
substitute: function(object, regexp){
return this.replace(regexp || (/\\?\{([^{}]+)\}/g), function(match, name){
if (match.charAt(0) == '\\') return match.slice(1);
return (object[name] != null) ? object[name] : '';
});
}
});
/*
---
name: Function
description: Contains Function Prototypes like create, bind, pass, and delay.
license: MIT-style license.
requires: Type
provides: Function
...
*/
Function.extend({
attempt: function(){
for (var i = 0, l = arguments.length; i < l; i++){
try {
return arguments[i]();
} catch (e){}
}
return null;
}
});
Function.implement({
attempt: function(args, bind){
try {
return this.apply(bind, Array.from(args));
} catch (e){}
return null;
},
/*<!ES5>*/
bind: function(bind){
var self = this,
args = (arguments.length > 1) ? Array.slice(arguments, 1) : null;
return function(){
if (!args && !arguments.length) return self.call(bind);
if (args && arguments.length) return self.apply(bind, args.concat(Array.from(arguments)));
return self.apply(bind, args || arguments);
};
},
/*</!ES5>*/
pass: function(args, bind){
var self = this;
if (args != null) args = Array.from(args);
return function(){
return self.apply(bind, args || arguments);
};
},
delay: function(delay, bind, args){
return setTimeout(this.pass((args == null ? [] : args), bind), delay);
},
periodical: function(periodical, bind, args){
return setInterval(this.pass((args == null ? [] : args), bind), periodical);
}
});
/*
---
name: Number
description: Contains Number Prototypes like limit, round, times, and ceil.
license: MIT-style license.
requires: Type
provides: Number
...
*/
Number.implement({
limit: function(min, max){
return Math.min(max, Math.max(min, this));
},
round: function(precision){
precision = Math.pow(10, precision || 0).toFixed(precision < 0 ? -precision : 0);
return Math.round(this * precision) / precision;
},
times: function(fn, bind){
for (var i = 0; i < this; i++) fn.call(bind, i, this);
},
toFloat: function(){
return parseFloat(this);
},
toInt: function(base){
return parseInt(this, base || 10);
}
});
Number.alias('each', 'times');
(function(math){
var methods = {};
math.each(function(name){
if (!Number[name]) methods[name] = function(){
return Math[name].apply(null, [this].concat(Array.from(arguments)));
};
});
Number.implement(methods);
})(['abs', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'exp', 'floor', 'log', 'max', 'min', 'pow', 'sin', 'sqrt', 'tan']);
/*
---
name: Class
description: Contains the Class Function for easily creating, extending, and implementing reusable Classes.
license: MIT-style license.
requires: [Array, String, Function, Number]
provides: Class
...
*/
(function(){
var Class = this.Class = new Type('Class', function(params){
if (instanceOf(params, Function)) params = {initialize: params};
var newClass = function(){
reset(this);
if (newClass.$prototyping) return this;
this.$caller = null;
var value = (this.initialize) ? this.initialize.apply(this, arguments) : this;
this.$caller = this.caller = null;
return value;
}.extend(this).implement(params);
newClass.$constructor = Class;
newClass.prototype.$constructor = newClass;
newClass.prototype.parent = parent;
return newClass;
});
var parent = function(){
if (!this.$caller) throw new Error('The method "parent" cannot be called.');
var name = this.$caller.$name,
parent = this.$caller.$owner.parent,
previous = (parent) ? parent.prototype[name] : null;
if (!previous) throw new Error('The method "' + name + '" has no parent.');
return previous.apply(this, arguments);
};
var reset = function(object){
for (var key in object){
var value = object[key];
switch (typeOf(value)){
case 'object':
var F = function(){};
F.prototype = value;
object[key] = reset(new F);
break;
case 'array': object[key] = value.clone(); break;
}
}
return object;
};
var wrap = function(self, key, method){
if (method.$origin) method = method.$origin;
var wrapper = function(){
if (method.$protected && this.$caller == null) throw new Error('The method "' + key + '" cannot be called.');
var caller = this.caller, current = this.$caller;
this.caller = current; this.$caller = wrapper;
var result = method.apply(this, arguments);
this.$caller = current; this.caller = caller;
return result;
}.extend({$owner: self, $origin: method, $name: key});
return wrapper;
};
var implement = function(key, value, retain){
if (Class.Mutators.hasOwnProperty(key)){
value = Class.Mutators[key].call(this, value);
if (value == null) return this;
}
if (typeOf(value) == 'function'){
if (value.$hidden) return this;
this.prototype[key] = (retain) ? value : wrap(this, key, value);
} else {
Object.merge(this.prototype, key, value);
}
return this;
};
var getInstance = function(klass){
klass.$prototyping = true;
var proto = new klass;
delete klass.$prototyping;
return proto;
};
Class.implement('implement', implement.overloadSetter());
Class.Mutators = {
Extends: function(parent){
this.parent = parent;
this.prototype = getInstance(parent);
},
Implements: function(items){
Array.from(items).each(function(item){
var instance = new item;
for (var key in instance) implement.call(this, key, instance[key], true);
}, this);
}
};
})();
/*
---
name: Browser
description: The Browser Object. Contains Browser initialization, Window and Document, and the Browser Hash.
license: MIT-style license.
requires: [Array, Function, Number, String]
provides: [Browser, Window, Document]
...
*/
(function(){
var document = this.document;
var window = document.window = this;
var UID = 1;
this.$uid = (window.ActiveXObject) ? function(item){
return (item.uid || (item.uid = [UID++]))[0];
} : function(item){
return item.uid || (item.uid = UID++);
};
$uid(window);
$uid(document);
var ua = navigator.userAgent.toLowerCase(),
platform = navigator.platform.toLowerCase(),
UA = ua.match(/(opera|ie|firefox|chrome|version)[\s\/:]([\w\d\.]+)?.*?(safari|version[\s\/:]([\w\d\.]+)|$)/) || [null, 'unknown', 0],
mode = UA[1] == 'ie' && document.documentMode;
var Browser = this.Browser = {
extend: Function.prototype.extend,
name: (UA[1] == 'version') ? UA[3] : UA[1],
version: mode || parseFloat((UA[1] == 'opera' && UA[4]) ? UA[4] : UA[2]),
Platform: {
name: ua.match(/ip(?:ad|od|hone)/) ? 'ios' : (ua.match(/(?:webos|android)/) || platform.match(/mac|win|linux/) || ['other'])[0]
},
Features: {
xpath: !!(document.evaluate),
air: !!(window.runtime),
query: !!(document.querySelector),
json: !!(window.JSON)
},
Plugins: {}
};
Browser[Browser.name] = true;
Browser[Browser.name + parseInt(Browser.version, 10)] = true;
Browser.Platform[Browser.Platform.name] = true;
// Request
Browser.Request = (function(){
var XMLHTTP = function(){
return new XMLHttpRequest();
};
var MSXML2 = function(){
return new ActiveXObject('MSXML2.XMLHTTP');
};
var MSXML = function(){
return new ActiveXObject('Microsoft.XMLHTTP');
};
return Function.attempt(function(){
XMLHTTP();
return XMLHTTP;
}, function(){
MSXML2();
return MSXML2;
}, function(){
MSXML();
return MSXML;
});
})();
Browser.Features.xhr = !!(Browser.Request);
// Flash detection
var version = (Function.attempt(function(){
return navigator.plugins['Shockwave Flash'].description;
}, function(){
return new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version');
}) || '0 r0').match(/\d+/g);
Browser.Plugins.Flash = {
version: Number(version[0] || '0.' + version[1]) || 0,
build: Number(version[2]) || 0
};
// String scripts
Browser.exec = function(text){
if (!text) return text;
if (window.execScript){
window.execScript(text);
} else {
var script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.text = text;
document.head.appendChild(script);
document.head.removeChild(script);
}
return text;
};
String.implement('stripScripts', function(exec){
var scripts = '';
var text = this.replace(/<script[^>]*>([\s\S]*?)<\/script>/gi, function(all, code){
scripts += code + '\n';
return '';
});
if (exec === true) Browser.exec(scripts);
else if (typeOf(exec) == 'function') exec(scripts, text);
return text;
});
// Window, Document
Browser.extend({
Document: this.Document,
Window: this.Window,
Element: this.Element,
Event: this.Event
});
this.Window = this.$constructor = new Type('Window', function(){});
this.$family = Function.from('window').hide();
Window.mirror(function(name, method){
window[name] = method;
});
this.Document = document.$constructor = new Type('Document', function(){});
document.$family = Function.from('document').hide();
Document.mirror(function(name, method){
document[name] = method;
});
document.html = document.documentElement;
if (!document.head) document.head = document.getElementsByTagName('head')[0];
if (document.execCommand) try {
document.execCommand("BackgroundImageCache", false, true);
} catch (e){}
/*<ltIE9>*/
if (this.attachEvent && !this.addEventListener){
var unloadEvent = function(){
this.detachEvent('onunload', unloadEvent);
document.head = document.html = document.window = null;
};
this.attachEvent('onunload', unloadEvent);
}
// IE fails on collections and <select>.options (refers to <select>)
var arrayFrom = Array.from;
try {
arrayFrom(document.html.childNodes);
} catch(e){
Array.from = function(item){
if (typeof item != 'string' && Type.isEnumerable(item) && typeOf(item) != 'array'){
var i = item.length, array = new Array(i);
while (i--) array[i] = item[i];
return array;
}
return arrayFrom(item);
};
var prototype = Array.prototype,
slice = prototype.slice;
['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift', 'concat', 'join', 'slice'].each(function(name){
var method = prototype[name];
Array[name] = function(item){
return method.apply(Array.from(item), slice.call(arguments, 1));
};
});
}
/*</ltIE9>*/
})();
/*
---
name: Slick.Parser
description: Standalone CSS3 Selector parser
provides: Slick.Parser
...
*/
;(function(){
var parsed,
separatorIndex,
combinatorIndex,
reversed,
cache = {},
reverseCache = {},
reUnescape = /\\/g;
var parse = function(expression, isReversed){
if (expression == null) return null;
if (expression.Slick === true) return expression;
expression = ('' + expression).replace(/^\s+|\s+$/g, '');
reversed = !!isReversed;
var currentCache = (reversed) ? reverseCache : cache;
if (currentCache[expression]) return currentCache[expression];
parsed = {
Slick: true,
expressions: [],
raw: expression,
reverse: function(){
return parse(this.raw, true);
}
};
separatorIndex = -1;
while (expression != (expression = expression.replace(regexp, parser)));
parsed.length = parsed.expressions.length;
return currentCache[parsed.raw] = (reversed) ? reverse(parsed) : parsed;
};
var reverseCombinator = function(combinator){
if (combinator === '!') return ' ';
else if (combinator === ' ') return '!';
else if ((/^!/).test(combinator)) return combinator.replace(/^!/, '');
else return '!' + combinator;
};
var reverse = function(expression){
var expressions = expression.expressions;
for (var i = 0; i < expressions.length; i++){
var exp = expressions[i];
var last = {parts: [], tag: '*', combinator: reverseCombinator(exp[0].combinator)};
for (var j = 0; j < exp.length; j++){
var cexp = exp[j];
if (!cexp.reverseCombinator) cexp.reverseCombinator = ' ';
cexp.combinator = cexp.reverseCombinator;
delete cexp.reverseCombinator;
}
exp.reverse().push(last);
}
return expression;
};
var escapeRegExp = function(string){// Credit: XRegExp 0.6.1 (c) 2007-2008 Steven Levithan <http://stevenlevithan.com/regex/xregexp/> MIT License
return string.replace(/[-[\]{}()*+?.\\^$|,#\s]/g, function(match){
return '\\' + match;
});
};
var regexp = new RegExp(
/*
#!/usr/bin/env ruby
puts "\t\t" + DATA.read.gsub(/\(\?x\)|\s+#.*$|\s+|\\$|\\n/,'')
__END__
"(?x)^(?:\
\\s* ( , ) \\s* # Separator \n\
| \\s* ( <combinator>+ ) \\s* # Combinator \n\
| ( \\s+ ) # CombinatorChildren \n\
| ( <unicode>+ | \\* ) # Tag \n\
| \\# ( <unicode>+ ) # ID \n\
| \\. ( <unicode>+ ) # ClassName \n\
| # Attribute \n\
\\[ \
\\s* (<unicode1>+) (?: \
\\s* ([*^$!~|]?=) (?: \
\\s* (?:\
([\"']?)(.*?)\\9 \
)\
) \
)? \\s* \
\\](?!\\]) \n\
| :+ ( <unicode>+ )(?:\
\\( (?:\
(?:([\"'])([^\\12]*)\\12)|((?:\\([^)]+\\)|[^()]*)+)\
) \\)\
)?\
)"
*/
"^(?:\\s*(,)\\s*|\\s*(<combinator>+)\\s*|(\\s+)|(<unicode>+|\\*)|\\#(<unicode>+)|\\.(<unicode>+)|\\[\\s*(<unicode1>+)(?:\\s*([*^$!~|]?=)(?:\\s*(?:([\"']?)(.*?)\\9)))?\\s*\\](?!\\])|(:+)(<unicode>+)(?:\\((?:(?:([\"'])([^\\13]*)\\13)|((?:\\([^)]+\\)|[^()]*)+))\\))?)"
.replace(/<combinator>/, '[' + escapeRegExp(">+~`!@$%^&={}\\;</") + ']')
.replace(/<unicode>/g, '(?:[\\w\\u00a1-\\uFFFF-]|\\\\[^\\s0-9a-f])')
.replace(/<unicode1>/g, '(?:[:\\w\\u00a1-\\uFFFF-]|\\\\[^\\s0-9a-f])')
);
function parser(
rawMatch,
separator,
combinator,
combinatorChildren,
tagName,
id,
className,
attributeKey,
attributeOperator,
attributeQuote,
attributeValue,
pseudoMarker,
pseudoClass,
pseudoQuote,
pseudoClassQuotedValue,
pseudoClassValue
){
if (separator || separatorIndex === -1){
parsed.expressions[++separatorIndex] = [];
combinatorIndex = -1;
if (separator) return '';
}
if (combinator || combinatorChildren || combinatorIndex === -1){
combinator = combinator || ' ';
var currentSeparator = parsed.expressions[separatorIndex];
if (reversed && currentSeparator[combinatorIndex])
currentSeparator[combinatorIndex].reverseCombinator = reverseCombinator(combinator);
currentSeparator[++combinatorIndex] = {combinator: combinator, tag: '*'};
}
var currentParsed = parsed.expressions[separatorIndex][combinatorIndex];
if (tagName){
currentParsed.tag = tagName.replace(reUnescape, '');
} else if (id){
currentParsed.id = id.replace(reUnescape, '');
} else if (className){
className = className.replace(reUnescape, '');
if (!currentParsed.classList) currentParsed.classList = [];
if (!currentParsed.classes) currentParsed.classes = [];
currentParsed.classList.push(className);
currentParsed.classes.push({
value: className,
regexp: new RegExp('(^|\\s)' + escapeRegExp(className) + '(\\s|$)')
});
} else if (pseudoClass){
pseudoClassValue = pseudoClassValue || pseudoClassQuotedValue;
pseudoClassValue = pseudoClassValue ? pseudoClassValue.replace(reUnescape, '') : null;
if (!currentParsed.pseudos) currentParsed.pseudos = [];
currentParsed.pseudos.push({
key: pseudoClass.replace(reUnescape, ''),
value: pseudoClassValue,
type: pseudoMarker.length == 1 ? 'class' : 'element'
});
} else if (attributeKey){
attributeKey = attributeKey.replace(reUnescape, '');
attributeValue = (attributeValue || '').replace(reUnescape, '');
var test, regexp;
switch (attributeOperator){
case '^=' : regexp = new RegExp( '^'+ escapeRegExp(attributeValue) ); break;
case '$=' : regexp = new RegExp( escapeRegExp(attributeValue) +'$' ); break;
case '~=' : regexp = new RegExp( '(^|\\s)'+ escapeRegExp(attributeValue) +'(\\s|$)' ); break;
case '|=' : regexp = new RegExp( '^'+ escapeRegExp(attributeValue) +'(-|$)' ); break;
case '=' : test = function(value){
return attributeValue == value;
}; break;
case '*=' : test = function(value){
return value && value.indexOf(attributeValue) > -1;
}; break;
case '!=' : test = function(value){
return attributeValue != value;
}; break;
default : test = function(value){
return !!value;
};
}
if (attributeValue == '' && (/^[*$^]=$/).test(attributeOperator)) test = function(){
return false;
};
if (!test) test = function(value){
return value && regexp.test(value);
};
if (!currentParsed.attributes) currentParsed.attributes = [];
currentParsed.attributes.push({
key: attributeKey,
operator: attributeOperator,
value: attributeValue,
test: test
});
}
return '';
};
// Slick NS
var Slick = (this.Slick || {});
Slick.parse = function(expression){
return parse(expression);
};
Slick.escapeRegExp = escapeRegExp;
if (!this.Slick) this.Slick = Slick;
}).apply(/*<CommonJS>*/(typeof exports != 'undefined') ? exports : /*</CommonJS>*/this);
/*
---
name: Slick.Finder
description: The new, superfast css selector engine.
provides: Slick.Finder
requires: Slick.Parser
...
*/
;(function(){
var local = {},
featuresCache = {},
toString = Object.prototype.toString;
// Feature / Bug detection
local.isNativeCode = function(fn){
return (/\{\s*\[native code\]\s*\}/).test('' + fn);
};
local.isXML = function(document){
return (!!document.xmlVersion) || (!!document.xml) || (toString.call(document) == '[object XMLDocument]') ||
(document.nodeType == 9 && document.documentElement.nodeName != 'HTML');
};
local.setDocument = function(document){
// convert elements / window arguments to document. if document cannot be extrapolated, the function returns.
var nodeType = document.nodeType;
if (nodeType == 9); // document
else if (nodeType) document = document.ownerDocument; // node
else if (document.navigator) document = document.document; // window
else return;
// check if it's the old document
if (this.document === document) return;
this.document = document;
// check if we have done feature detection on this document before
var root = document.documentElement,
rootUid = this.getUIDXML(root),
features = featuresCache[rootUid],
feature;
if (features){
for (feature in features){
this[feature] = features[feature];
}
return;
}
features = featuresCache[rootUid] = {};
features.root = root;
features.isXMLDocument = this.isXML(document);
features.brokenStarGEBTN
= features.starSelectsClosedQSA
= features.idGetsName
= features.brokenMixedCaseQSA
= features.brokenGEBCN
= features.brokenCheckedQSA
= features.brokenEmptyAttributeQSA
= features.isHTMLDocument
= features.nativeMatchesSelector
= false;
var starSelectsClosed, starSelectsComments,
brokenSecondClassNameGEBCN, cachedGetElementsByClassName,
brokenFormAttributeGetter;
var selected, id = 'slick_uniqueid';
var testNode = document.createElement('div');
var testRoot = document.body || document.getElementsByTagName('body')[0] || root;
testRoot.appendChild(testNode);
// on non-HTML documents innerHTML and getElementsById doesnt work properly
try {
testNode.innerHTML = '<a id="'+id+'"></a>';
features.isHTMLDocument = !!document.getElementById(id);
} catch(e){};
if (features.isHTMLDocument){
testNode.style.display = 'none';
// IE returns comment nodes for getElementsByTagName('*') for some documents
testNode.appendChild(document.createComment(''));
starSelectsComments = (testNode.getElementsByTagName('*').length > 1);
// IE returns closed nodes (EG:"</foo>") for getElementsByTagName('*') for some documents
try {
testNode.innerHTML = 'foo</foo>';
selected = testNode.getElementsByTagName('*');
starSelectsClosed = (selected && !!selected.length && selected[0].nodeName.charAt(0) == '/');
} catch(e){};
features.brokenStarGEBTN = starSelectsComments || starSelectsClosed;
// IE returns elements with the name instead of just id for getElementsById for some documents
try {
testNode.innerHTML = '<a name="'+ id +'"></a><b id="'+ id +'"></b>';
features.idGetsName = document.getElementById(id) === testNode.firstChild;
} catch(e){};
if (testNode.getElementsByClassName){
// Safari 3.2 getElementsByClassName caches results
try {
testNode.innerHTML = '<a class="f"></a><a class="b"></a>';
testNode.getElementsByClassName('b').length;
testNode.firstChild.className = 'b';
cachedGetElementsByClassName = (testNode.getElementsByClassName('b').length != 2);
} catch(e){};
// Opera 9.6 getElementsByClassName doesnt detects the class if its not the first one
try {
testNode.innerHTML = '<a class="a"></a><a class="f b a"></a>';
brokenSecondClassNameGEBCN = (testNode.getElementsByClassName('a').length != 2);
} catch(e){};
features.brokenGEBCN = cachedGetElementsByClassName || brokenSecondClassNameGEBCN;
}
if (testNode.querySelectorAll){
// IE 8 returns closed nodes (EG:"</foo>") for querySelectorAll('*') for some documents
try {
testNode.innerHTML = 'foo</foo>';
selected = testNode.querySelectorAll('*');
features.starSelectsClosedQSA = (selected && !!selected.length && selected[0].nodeName.charAt(0) == '/');
} catch(e){};
// Safari 3.2 querySelectorAll doesnt work with mixedcase on quirksmode
try {
testNode.innerHTML = '<a class="MiX"></a>';
features.brokenMixedCaseQSA = !testNode.querySelectorAll('.MiX').length;
} catch(e){};
// Webkit and Opera dont return selected options on querySelectorAll
try {
testNode.innerHTML = '<select><option selected="selected">a</option></select>';
features.brokenCheckedQSA = (testNode.querySelectorAll(':checked').length == 0);
} catch(e){};
// IE returns incorrect results for attr[*^$]="" selectors on querySelectorAll
try {
testNode.innerHTML = '<a class=""></a>';
features.brokenEmptyAttributeQSA = (testNode.querySelectorAll('[class*=""]').length != 0);
} catch(e){};
}
// IE6-7, if a form has an input of id x, form.getAttribute(x) returns a reference to the input
try {
testNode.innerHTML = '<form action="s"><input id="action"/></form>';
brokenFormAttributeGetter = (testNode.firstChild.getAttribute('action') != 's');
} catch(e){};
// native matchesSelector function
features.nativeMatchesSelector = root.matchesSelector || /*root.msMatchesSelector ||*/ root.mozMatchesSelector || root.webkitMatchesSelector;
if (features.nativeMatchesSelector) try {
// if matchesSelector trows errors on incorrect sintaxes we can use it
features.nativeMatchesSelector.call(root, ':slick');
features.nativeMatchesSelector = null;
} catch(e){};
}
try {
root.slick_expando = 1;
delete root.slick_expando;
features.getUID = this.getUIDHTML;
} catch(e) {
features.getUID = this.getUIDXML;
}
testRoot.removeChild(testNode);
testNode = selected = testRoot = null;
// getAttribute
features.getAttribute = (features.isHTMLDocument && brokenFormAttributeGetter) ? function(node, name){
var method = this.attributeGetters[name];
if (method) return method.call(node);
var attributeNode = node.getAttributeNode(name);
return (attributeNode) ? attributeNode.nodeValue : null;
} : function(node, name){
var method = this.attributeGetters[name];
return (method) ? method.call(node) : node.getAttribute(name);
};
// hasAttribute
features.hasAttribute = (root && this.isNativeCode(root.hasAttribute)) ? function(node, attribute) {
return node.hasAttribute(attribute);
} : function(node, attribute) {
node = node.getAttributeNode(attribute);
return !!(node && (node.specified || node.nodeValue));
};
// contains
// FIXME: Add specs: local.contains should be different for xml and html documents?
features.contains = (root && this.isNativeCode(root.contains)) ? function(context, node){
return context.contains(node);
} : (root && root.compareDocumentPosition) ? function(context, node){
return context === node || !!(context.compareDocumentPosition(node) & 16);
} : function(context, node){
if (node) do {
if (node === context) return true;
} while ((node = node.parentNode));
return false;
};
// document order sorting
// credits to Sizzle (http://sizzlejs.com/)
features.documentSorter = (root.compareDocumentPosition) ? function(a, b){
if (!a.compareDocumentPosition || !b.compareDocumentPosition) return 0;
return a.compareDocumentPosition(b) & 4 ? -1 : a === b ? 0 : 1;
} : ('sourceIndex' in root) ? function(a, b){
if (!a.sourceIndex || !b.sourceIndex) return 0;
return a.sourceIndex - b.sourceIndex;
} : (document.createRange) ? function(a, b){
if (!a.ownerDocument || !b.ownerDocument) return 0;
var aRange = a.ownerDocument.createRange(), bRange = b.ownerDocument.createRange();
aRange.setStart(a, 0);
aRange.setEnd(a, 0);
bRange.setStart(b, 0);
bRange.setEnd(b, 0);
return aRange.compareBoundaryPoints(Range.START_TO_END, bRange);
} : null ;
root = null;
for (feature in features){
this[feature] = features[feature];
}
};
// Main Method
var reSimpleSelector = /^([#.]?)((?:[\w-]+|\*))$/,
reEmptyAttribute = /\[.+[*$^]=(?:""|'')?\]/,
qsaFailExpCache = {};
local.search = function(context, expression, append, first){
var found = this.found = (first) ? null : (append || []);
if (!context) return found;
else if (context.navigator) context = context.document; // Convert the node from a window to a document
else if (!context.nodeType) return found;
// setup
var parsed, i,
uniques = this.uniques = {},
hasOthers = !!(append && append.length),
contextIsDocument = (context.nodeType == 9);
if (this.document !== (contextIsDocument ? context : context.ownerDocument)) this.setDocument(context);
// avoid duplicating items already in the append array
if (hasOthers) for (i = found.length; i--;) uniques[this.getUID(found[i])] = true;
// expression checks
if (typeof expression == 'string'){ // expression is a string
/*<simple-selectors-override>*/
var simpleSelector = expression.match(reSimpleSelector);
simpleSelectors: if (simpleSelector) {
var symbol = simpleSelector[1],
name = simpleSelector[2],
node, nodes;
if (!symbol){
if (name == '*' && this.brokenStarGEBTN) break simpleSelectors;
nodes = context.getElementsByTagName(name);
if (first) return nodes[0] || null;
for (i = 0; node = nodes[i++];){
if (!(hasOthers && uniques[this.getUID(node)])) found.push(node);
}
} else if (symbol == '#'){
if (!this.isHTMLDocument || !contextIsDocument) break simpleSelectors;
node = context.getElementById(name);
if (!node) return found;
if (this.idGetsName && node.getAttributeNode('id').nodeValue != name) break simpleSelectors;
if (first) return node || null;
if (!(hasOthers && uniques[this.getUID(node)])) found.push(node);
} else if (symbol == '.'){
if (!this.isHTMLDocument || ((!context.getElementsByClassName || this.brokenGEBCN) && context.querySelectorAll)) break simpleSelectors;
if (context.getElementsByClassName && !this.brokenGEBCN){
nodes = context.getElementsByClassName(name);
if (first) return nodes[0] || null;
for (i = 0; node = nodes[i++];){
if (!(hasOthers && uniques[this.getUID(node)])) found.push(node);
}
} else {
var matchClass = new RegExp('(^|\\s)'+ Slick.escapeRegExp(name) +'(\\s|$)');
nodes = context.getElementsByTagName('*');
for (i = 0; node = nodes[i++];){
className = node.className;
if (!(className && matchClass.test(className))) continue;
if (first) return node;
if (!(hasOthers && uniques[this.getUID(node)])) found.push(node);
}
}
}
if (hasOthers) this.sort(found);
return (first) ? null : found;
}
/*</simple-selectors-override>*/
/*<query-selector-override>*/
querySelector: if (context.querySelectorAll) {
if (!this.isHTMLDocument
|| qsaFailExpCache[expression]
//TODO: only skip when expression is actually mixed case
|| this.brokenMixedCaseQSA
|| (this.brokenCheckedQSA && expression.indexOf(':checked') > -1)
|| (this.brokenEmptyAttributeQSA && reEmptyAttribute.test(expression))
|| (!contextIsDocument //Abort when !contextIsDocument and...
// there are multiple expressions in the selector
// since we currently only fix non-document rooted QSA for single expression selectors
&& expression.indexOf(',') > -1
)
|| Slick.disableQSA
) break querySelector;
var _expression = expression, _context = context;
if (!contextIsDocument){
// non-document rooted QSA
// credits to Andrew Dupont
var currentId = _context.getAttribute('id'), slickid = 'slickid__';
_context.setAttribute('id', slickid);
_expression = '#' + slickid + ' ' + _expression;
context = _context.parentNode;
}
try {
if (first) return context.querySelector(_expression) || null;
else nodes = context.querySelectorAll(_expression);
} catch(e) {
qsaFailExpCache[expression] = 1;
break querySelector;
} finally {
if (!contextIsDocument){
if (currentId) _context.setAttribute('id', currentId);
else _context.removeAttribute('id');
context = _context;
}
}
if (this.starSelectsClosedQSA) for (i = 0; node = nodes[i++];){
if (node.nodeName > '@' && !(hasOthers && uniques[this.getUID(node)])) found.push(node);
} else for (i = 0; node = nodes[i++];){
if (!(hasOthers && uniques[this.getUID(node)])) found.push(node);
}
if (hasOthers) this.sort(found);
return found;
}
/*</query-selector-override>*/
parsed = this.Slick.parse(expression);
if (!parsed.length) return found;
} else if (expression == null){ // there is no expression
return found;
} else if (expression.Slick){ // expression is a parsed Slick object
parsed = expression;
} else if (this.contains(context.documentElement || context, expression)){ // expression is a node
(found) ? found.push(expression) : found = expression;
return found;
} else { // other junk
return found;
}
/*<pseudo-selectors>*//*<nth-pseudo-selectors>*/
// cache elements for the nth selectors
this.posNTH = {};
this.posNTHLast = {};
this.posNTHType = {};
this.posNTHTypeLast = {};
/*</nth-pseudo-selectors>*//*</pseudo-selectors>*/
// if append is null and there is only a single selector with one expression use pushArray, else use pushUID
this.push = (!hasOthers && (first || (parsed.length == 1 && parsed.expressions[0].length == 1))) ? this.pushArray : this.pushUID;
if (found == null) found = [];
// default engine
var j, m, n;
var combinator, tag, id, classList, classes, attributes, pseudos;
var currentItems, currentExpression, currentBit, lastBit, expressions = parsed.expressions;
search: for (i = 0; (currentExpression = expressions[i]); i++) for (j = 0; (currentBit = currentExpression[j]); j++){
combinator = 'combinator:' + currentBit.combinator;
if (!this[combinator]) continue search;
tag = (this.isXMLDocument) ? currentBit.tag : currentBit.tag.toUpperCase();
id = currentBit.id;
classList = currentBit.classList;
classes = currentBit.classes;
attributes = currentBit.attributes;
pseudos = currentBit.pseudos;
lastBit = (j === (currentExpression.length - 1));
this.bitUniques = {};
if (lastBit){
this.uniques = uniques;
this.found = found;
} else {
this.uniques = {};
this.found = [];
}
if (j === 0){
this[combinator](context, tag, id, classes, attributes, pseudos, classList);
if (first && lastBit && found.length) break search;
} else {
if (first && lastBit) for (m = 0, n = currentItems.length; m < n; m++){
this[combinator](currentItems[m], tag, id, classes, attributes, pseudos, classList);
if (found.length) break search;
} else for (m = 0, n = currentItems.length; m < n; m++) this[combinator](currentItems[m], tag, id, classes, attributes, pseudos, classList);
}
currentItems = this.found;
}
// should sort if there are nodes in append and if you pass multiple expressions.
if (hasOthers || (parsed.expressions.length > 1)) this.sort(found);
return (first) ? (found[0] || null) : found;
};
// Utils
local.uidx = 1;
local.uidk = 'slick-uniqueid';
local.getUIDXML = function(node){
var uid = node.getAttribute(this.uidk);
if (!uid){
uid = this.uidx++;
node.setAttribute(this.uidk, uid);
}
return uid;
};
local.getUIDHTML = function(node){
return node.uniqueNumber || (node.uniqueNumber = this.uidx++);
};
// sort based on the setDocument documentSorter method.
local.sort = function(results){
if (!this.documentSorter) return results;
results.sort(this.documentSorter);
return results;
};
/*<pseudo-selectors>*//*<nth-pseudo-selectors>*/
local.cacheNTH = {};
local.matchNTH = /^([+-]?\d*)?([a-z]+)?([+-]\d+)?$/;
local.parseNTHArgument = function(argument){
var parsed = argument.match(this.matchNTH);
if (!parsed) return false;
var special = parsed[2] || false;
var a = parsed[1] || 1;
if (a == '-') a = -1;
var b = +parsed[3] || 0;
parsed =
(special == 'n') ? {a: a, b: b} :
(special == 'odd') ? {a: 2, b: 1} :
(special == 'even') ? {a: 2, b: 0} : {a: 0, b: a};
return (this.cacheNTH[argument] = parsed);
};
local.createNTHPseudo = function(child, sibling, positions, ofType){
return function(node, argument){
var uid = this.getUID(node);
if (!this[positions][uid]){
var parent = node.parentNode;
if (!parent) return false;
var el = parent[child], count = 1;
if (ofType){
var nodeName = node.nodeName;
do {
if (el.nodeName != nodeName) continue;
this[positions][this.getUID(el)] = count++;
} while ((el = el[sibling]));
} else {
do {
if (el.nodeType != 1) continue;
this[positions][this.getUID(el)] = count++;
} while ((el = el[sibling]));
}
}
argument = argument || 'n';
var parsed = this.cacheNTH[argument] || this.parseNTHArgument(argument);
if (!parsed) return false;
var a = parsed.a, b = parsed.b, pos = this[positions][uid];
if (a == 0) return b == pos;
if (a > 0){
if (pos < b) return false;
} else {
if (b < pos) return false;
}
return ((pos - b) % a) == 0;
};
};
/*</nth-pseudo-selectors>*//*</pseudo-selectors>*/
local.pushArray = function(node, tag, id, classes, attributes, pseudos){
if (this.matchSelector(node, tag, id, classes, attributes, pseudos)) this.found.push(node);
};
local.pushUID = function(node, tag, id, classes, attributes, pseudos){
var uid = this.getUID(node);
if (!this.uniques[uid] && this.matchSelector(node, tag, id, classes, attributes, pseudos)){
this.uniques[uid] = true;
this.found.push(node);
}
};
local.matchNode = function(node, selector){
if (this.isHTMLDocument && this.nativeMatchesSelector){
try {
return this.nativeMatchesSelector.call(node, selector.replace(/\[([^=]+)=\s*([^'"\]]+?)\s*\]/g, '[$1="$2"]'));
} catch(matchError) {}
}
var parsed = this.Slick.parse(selector);
if (!parsed) return true;
// simple (single) selectors
var expressions = parsed.expressions, reversedExpressions, simpleExpCounter = 0, i;
for (i = 0; (currentExpression = expressions[i]); i++){
if (currentExpression.length == 1){
var exp = currentExpression[0];
if (this.matchSelector(node, (this.isXMLDocument) ? exp.tag : exp.tag.toUpperCase(), exp.id, exp.classes, exp.attributes, exp.pseudos)) return true;
simpleExpCounter++;
}
}
if (simpleExpCounter == parsed.length) return false;
var nodes = this.search(this.document, parsed), item;
for (i = 0; item = nodes[i++];){
if (item === node) return true;
}
return false;
};
local.matchPseudo = function(node, name, argument){
var pseudoName = 'pseudo:' + name;
if (this[pseudoName]) return this[pseudoName](node, argument);
var attribute = this.getAttribute(node, name);
return (argument) ? argument == attribute : !!attribute;
};
local.matchSelector = function(node, tag, id, classes, attributes, pseudos){
if (tag){
var nodeName = (this.isXMLDocument) ? node.nodeName : node.nodeName.toUpperCase();
if (tag == '*'){
if (nodeName < '@') return false; // Fix for comment nodes and closed nodes
} else {
if (nodeName != tag) return false;
}
}
if (id && node.getAttribute('id') != id) return false;
var i, part, cls;
if (classes) for (i = classes.length; i--;){
cls = node.getAttribute('class') || node.className;
if (!(cls && classes[i].regexp.test(cls))) return false;
}
if (attributes) for (i = attributes.length; i--;){
part = attributes[i];
if (part.operator ? !part.test(this.getAttribute(node, part.key)) : !this.hasAttribute(node, part.key)) return false;
}
if (pseudos) for (i = pseudos.length; i--;){
part = pseudos[i];
if (!this.matchPseudo(node, part.key, part.value)) return false;
}
return true;
};
var combinators = {
' ': function(node, tag, id, classes, attributes, pseudos, classList){ // all child nodes, any level
var i, item, children;
if (this.isHTMLDocument){
getById: if (id){
item = this.document.getElementById(id);
if ((!item && node.all) || (this.idGetsName && item && item.getAttributeNode('id').nodeValue != id)){
// all[id] returns all the elements with that name or id inside node
// if theres just one it will return the element, else it will be a collection
children = node.all[id];
if (!children) return;
if (!children[0]) children = [children];
for (i = 0; item = children[i++];){
var idNode = item.getAttributeNode('id');
if (idNode && idNode.nodeValue == id){
this.push(item, tag, null, classes, attributes, pseudos);
break;
}
}
return;
}
if (!item){
// if the context is in the dom we return, else we will try GEBTN, breaking the getById label
if (this.contains(this.root, node)) return;
else break getById;
} else if (this.document !== node && !this.contains(node, item)) return;
this.push(item, tag, null, classes, attributes, pseudos);
return;
}
getByClass: if (classes && node.getElementsByClassName && !this.brokenGEBCN){
children = node.getElementsByClassName(classList.join(' '));
if (!(children && children.length)) break getByClass;
for (i = 0; item = children[i++];) this.push(item, tag, id, null, attributes, pseudos);
return;
}
}
getByTag: {
children = node.getElementsByTagName(tag);
if (!(children && children.length)) break getByTag;
if (!this.brokenStarGEBTN) tag = null;
for (i = 0; item = children[i++];) this.push(item, tag, id, classes, attributes, pseudos);
}
},
'>': function(node, tag, id, classes, attributes, pseudos){ // direct children
if ((node = node.firstChild)) do {
if (node.nodeType == 1) this.push(node, tag, id, classes, attributes, pseudos);
} while ((node = node.nextSibling));
},
'+': function(node, tag, id, classes, attributes, pseudos){ // next sibling
while ((node = node.nextSibling)) if (node.nodeType == 1){
this.push(node, tag, id, classes, attributes, pseudos);
break;
}
},
'^': function(node, tag, id, classes, attributes, pseudos){ // first child
node = node.firstChild;
if (node){
if (node.nodeType == 1) this.push(node, tag, id, classes, attributes, pseudos);
else this['combinator:+'](node, tag, id, classes, attributes, pseudos);
}
},
'~': function(node, tag, id, classes, attributes, pseudos){ // next siblings
while ((node = node.nextSibling)){
if (node.nodeType != 1) continue;
var uid = this.getUID(node);
if (this.bitUniques[uid]) break;
this.bitUniques[uid] = true;
this.push(node, tag, id, classes, attributes, pseudos);
}
},
'++': function(node, tag, id, classes, attributes, pseudos){ // next sibling and previous sibling
this['combinator:+'](node, tag, id, classes, attributes, pseudos);
this['combinator:!+'](node, tag, id, classes, attributes, pseudos);
},
'~~': function(node, tag, id, classes, attributes, pseudos){ // next siblings and previous siblings
this['combinator:~'](node, tag, id, classes, attributes, pseudos);
this['combinator:!~'](node, tag, id, classes, attributes, pseudos);
},
'!': function(node, tag, id, classes, attributes, pseudos){ // all parent nodes up to document
while ((node = node.parentNode)) if (node !== this.document) this.push(node, tag, id, classes, attributes, pseudos);
},
'!>': function(node, tag, id, classes, attributes, pseudos){ // direct parent (one level)
node = node.parentNode;
if (node !== this.document) this.push(node, tag, id, classes, attributes, pseudos);
},
'!+': function(node, tag, id, classes, attributes, pseudos){ // previous sibling
while ((node = node.previousSibling)) if (node.nodeType == 1){
this.push(node, tag, id, classes, attributes, pseudos);
break;
}
},
'!^': function(node, tag, id, classes, attributes, pseudos){ // last child
node = node.lastChild;
if (node){
if (node.nodeType == 1) this.push(node, tag, id, classes, attributes, pseudos);
else this['combinator:!+'](node, tag, id, classes, attributes, pseudos);
}
},
'!~': function(node, tag, id, classes, attributes, pseudos){ // previous siblings
while ((node = node.previousSibling)){
if (node.nodeType != 1) continue;
var uid = this.getUID(node);
if (this.bitUniques[uid]) break;
this.bitUniques[uid] = true;
this.push(node, tag, id, classes, attributes, pseudos);
}
}
};
for (var c in combinators) local['combinator:' + c] = combinators[c];
var pseudos = {
/*<pseudo-selectors>*/
'empty': function(node){
var child = node.firstChild;
return !(child && child.nodeType == 1) && !(node.innerText || node.textContent || '').length;
},
'not': function(node, expression){
return !this.matchNode(node, expression);
},
'contains': function(node, text){
return (node.innerText || node.textContent || '').indexOf(text) > -1;
},
'first-child': function(node){
while ((node = node.previousSibling)) if (node.nodeType == 1) return false;
return true;
},
'last-child': function(node){
while ((node = node.nextSibling)) if (node.nodeType == 1) return false;
return true;
},
'only-child': function(node){
var prev = node;
while ((prev = prev.previousSibling)) if (prev.nodeType == 1) return false;
var next = node;
while ((next = next.nextSibling)) if (next.nodeType == 1) return false;
return true;
},
/*<nth-pseudo-selectors>*/
'nth-child': local.createNTHPseudo('firstChild', 'nextSibling', 'posNTH'),
'nth-last-child': local.createNTHPseudo('lastChild', 'previousSibling', 'posNTHLast'),
'nth-of-type': local.createNTHPseudo('firstChild', 'nextSibling', 'posNTHType', true),
'nth-last-of-type': local.createNTHPseudo('lastChild', 'previousSibling', 'posNTHTypeLast', true),
'index': function(node, index){
return this['pseudo:nth-child'](node, '' + index + 1);
},
'even': function(node){
return this['pseudo:nth-child'](node, '2n');
},
'odd': function(node){
return this['pseudo:nth-child'](node, '2n+1');
},
/*</nth-pseudo-selectors>*/
/*<of-type-pseudo-selectors>*/
'first-of-type': function(node){
var nodeName = node.nodeName;
while ((node = node.previousSibling)) if (node.nodeName == nodeName) return false;
return true;
},
'last-of-type': function(node){
var nodeName = node.nodeName;
while ((node = node.nextSibling)) if (node.nodeName == nodeName) return false;
return true;
},
'only-of-type': function(node){
var prev = node, nodeName = node.nodeName;
while ((prev = prev.previousSibling)) if (prev.nodeName == nodeName) return false;
var next = node;
while ((next = next.nextSibling)) if (next.nodeName == nodeName) return false;
return true;
},
/*</of-type-pseudo-selectors>*/
// custom pseudos
'enabled': function(node){
return !node.disabled;
},
'disabled': function(node){
return node.disabled;
},
'checked': function(node){
return node.checked || node.selected;
},
'focus': function(node){
return this.isHTMLDocument && this.document.activeElement === node && (node.href || node.type || this.hasAttribute(node, 'tabindex'));
},
'root': function(node){
return (node === this.root);
},
'selected': function(node){
return node.selected;
}
/*</pseudo-selectors>*/
};
for (var p in pseudos) local['pseudo:' + p] = pseudos[p];
// attributes methods
local.attributeGetters = {
'class': function(){
return this.getAttribute('class') || this.className;
},
'for': function(){
return ('htmlFor' in this) ? this.htmlFor : this.getAttribute('for');
},
'href': function(){
return ('href' in this) ? this.getAttribute('href', 2) : this.getAttribute('href');
},
'style': function(){
return (this.style) ? this.style.cssText : this.getAttribute('style');
},
'tabindex': function(){
var attributeNode = this.getAttributeNode('tabindex');
return (attributeNode && attributeNode.specified) ? attributeNode.nodeValue : null;
},
'type': function(){
return this.getAttribute('type');
}
};
// Slick
var Slick = local.Slick = (this.Slick || {});
Slick.version = '1.1.5';
// Slick finder
Slick.search = function(context, expression, append){
return local.search(context, expression, append);
};
Slick.find = function(context, expression){
return local.search(context, expression, null, true);
};
// Slick containment checker
Slick.contains = function(container, node){
local.setDocument(container);
return local.contains(container, node);
};
// Slick attribute getter
Slick.getAttribute = function(node, name){
return local.getAttribute(node, name);
};
// Slick matcher
Slick.match = function(node, selector){
if (!(node && selector)) return false;
if (!selector || selector === node) return true;
local.setDocument(node);
return local.matchNode(node, selector);
};
// Slick attribute accessor
Slick.defineAttributeGetter = function(name, fn){
local.attributeGetters[name] = fn;
return this;
};
Slick.lookupAttributeGetter = function(name){
return local.attributeGetters[name];
};
// Slick pseudo accessor
Slick.definePseudo = function(name, fn){
local['pseudo:' + name] = function(node, argument){
return fn.call(node, argument);
};
return this;
};
Slick.lookupPseudo = function(name){
var pseudo = local['pseudo:' + name];
if (pseudo) return function(argument){
return pseudo.call(this, argument);
};
return null;
};
// Slick overrides accessor
Slick.override = function(regexp, fn){
local.override(regexp, fn);
return this;
};
Slick.isXML = local.isXML;
Slick.uidOf = function(node){
return local.getUIDHTML(node);
};
if (!this.Slick) this.Slick = Slick;
}).apply(/*<CommonJS>*/(typeof exports != 'undefined') ? exports : /*</CommonJS>*/this);
/*
---
name: Element
description: One of the most important items in MooTools. Contains the dollar function, the dollars function, and an handful of cross-browser, time-saver methods to let you easily work with HTML Elements.
license: MIT-style license.
requires: [Window, Document, Array, String, Function, Number, Slick.Parser, Slick.Finder]
provides: [Element, Elements, $, $$, Iframe, Selectors]
...
*/
var Element = function(tag, props){
var konstructor = Element.Constructors[tag];
if (konstructor) return konstructor(props);
if (typeof tag != 'string') return document.id(tag).set(props);
if (!props) props = {};
if (!(/^[\w-]+$/).test(tag)){
var parsed = Slick.parse(tag).expressions[0][0];
tag = (parsed.tag == '*') ? 'div' : parsed.tag;
if (parsed.id && props.id == null) props.id = parsed.id;
var attributes = parsed.attributes;
if (attributes) for (var attr, i = 0, l = attributes.length; i < l; i++){
attr = attributes[i];
if (props[attr.key] != null) continue;
if (attr.value != null && attr.operator == '=') props[attr.key] = attr.value;
else if (!attr.value && !attr.operator) props[attr.key] = true;
}
if (parsed.classList && props['class'] == null) props['class'] = parsed.classList.join(' ');
}
return document.newElement(tag, props);
};
if (Browser.Element) Element.prototype = Browser.Element.prototype;
new Type('Element', Element).mirror(function(name){
if (Array.prototype[name]) return;
var obj = {};
obj[name] = function(){
var results = [], args = arguments, elements = true;
for (var i = 0, l = this.length; i < l; i++){
var element = this[i], result = results[i] = element[name].apply(element, args);
elements = (elements && typeOf(result) == 'element');
}
return (elements) ? new Elements(results) : results;
};
Elements.implement(obj);
});
if (!Browser.Element){
Element.parent = Object;
Element.Prototype = {'$family': Function.from('element').hide()};
Element.mirror(function(name, method){
Element.Prototype[name] = method;
});
}
Element.Constructors = {};
var IFrame = new Type('IFrame', function(){
var params = Array.link(arguments, {
properties: Type.isObject,
iframe: function(obj){
return (obj != null);
}
});
var props = params.properties || {}, iframe;
if (params.iframe) iframe = document.id(params.iframe);
var onload = props.onload || function(){};
delete props.onload;
props.id = props.name = [props.id, props.name, iframe ? (iframe.id || iframe.name) : 'IFrame_' + String.uniqueID()].pick();
iframe = new Element(iframe || 'iframe', props);
var onLoad = function(){
onload.call(iframe.contentWindow);
};
if (window.frames[props.id]) onLoad();
else iframe.addListener('load', onLoad);
return iframe;
});
var Elements = this.Elements = function(nodes){
if (nodes && nodes.length){
var uniques = {}, node;
for (var i = 0; node = nodes[i++];){
var uid = Slick.uidOf(node);
if (!uniques[uid]){
uniques[uid] = true;
this.push(node);
}
}
}
};
Elements.prototype = {length: 0};
Elements.parent = Array;
new Type('Elements', Elements).implement({
filter: function(filter, bind){
if (!filter) return this;
return new Elements(Array.filter(this, (typeOf(filter) == 'string') ? function(item){
return item.match(filter);
} : filter, bind));
}.protect(),
push: function(){
var length = this.length;
for (var i = 0, l = arguments.length; i < l; i++){
var item = document.id(arguments[i]);
if (item) this[length++] = item;
}
return (this.length = length);
}.protect(),
unshift: function(){
var items = [];
for (var i = 0, l = arguments.length; i < l; i++){
var item = document.id(arguments[i]);
if (item) items.push(item);
}
return Array.prototype.unshift.apply(this, items);
}.protect(),
concat: function(){
var newElements = new Elements(this);
for (var i = 0, l = arguments.length; i < l; i++){
var item = arguments[i];
if (Type.isEnumerable(item)) newElements.append(item);
else newElements.push(item);
}
return newElements;
}.protect(),
append: function(collection){
for (var i = 0, l = collection.length; i < l; i++) this.push(collection[i]);
return this;
}.protect(),
empty: function(){
while (this.length) delete this[--this.length];
return this;
}.protect()
});
(function(){
// FF, IE
var splice = Array.prototype.splice, object = {'0': 0, '1': 1, length: 2};
splice.call(object, 1, 1);
if (object[1] == 1) Elements.implement('splice', function(){
var length = this.length;
splice.apply(this, arguments);
while (length >= this.length) delete this[length--];
return this;
}.protect());
Elements.implement(Array.prototype);
Array.mirror(Elements);
/*<ltIE8>*/
var createElementAcceptsHTML;
try {
var x = document.createElement('<input name=x>');
createElementAcceptsHTML = (x.name == 'x');
} catch(e){}
var escapeQuotes = function(html){
return ('' + html).replace(/&/g, '&').replace(/"/g, '"');
};
/*</ltIE8>*/
Document.implement({
newElement: function(tag, props){
if (props && props.checked != null) props.defaultChecked = props.checked;
/*<ltIE8>*/// Fix for readonly name and type properties in IE < 8
if (createElementAcceptsHTML && props){
tag = '<' + tag;
if (props.name) tag += ' name="' + escapeQuotes(props.name) + '"';
if (props.type) tag += ' type="' + escapeQuotes(props.type) + '"';
tag += '>';
delete props.name;
delete props.type;
}
/*</ltIE8>*/
return this.id(this.createElement(tag)).set(props);
}
});
})();
Document.implement({
newTextNode: function(text){
return this.createTextNode(text);
},
getDocument: function(){
return this;
},
getWindow: function(){
return this.window;
},
id: (function(){
var types = {
string: function(id, nocash, doc){
id = Slick.find(doc, '#' + id.replace(/(\W)/g, '\\$1'));
return (id) ? types.element(id, nocash) : null;
},
element: function(el, nocash){
$uid(el);
if (!nocash && !el.$family && !(/^(?:object|embed)$/i).test(el.tagName)){
Object.append(el, Element.Prototype);
}
return el;
},
object: function(obj, nocash, doc){
if (obj.toElement) return types.element(obj.toElement(doc), nocash);
return null;
}
};
types.textnode = types.whitespace = types.window = types.document = function(zero){
return zero;
};
return function(el, nocash, doc){
if (el && el.$family && el.uid) return el;
var type = typeOf(el);
return (types[type]) ? types[type](el, nocash, doc || document) : null;
};
})()
});
if (window.$ == null) Window.implement('$', function(el, nc){
return document.id(el, nc, this.document);
});
Window.implement({
getDocument: function(){
return this.document;
},
getWindow: function(){
return this;
}
});
[Document, Element].invoke('implement', {
getElements: function(expression){
return Slick.search(this, expression, new Elements);
},
getElement: function(expression){
return document.id(Slick.find(this, expression));
}
});
if (window.$$ == null) Window.implement('$$', function(selector){
if (arguments.length == 1){
if (typeof selector == 'string') return Slick.search(this.document, selector, new Elements);
else if (Type.isEnumerable(selector)) return new Elements(selector);
}
return new Elements(arguments);
});
(function(){
var collected = {}, storage = {};
var formProps = {input: 'checked', option: 'selected', textarea: 'value'};
var get = function(uid){
return (storage[uid] || (storage[uid] = {}));
};
var clean = function(item){
var uid = item.uid;
if (item.removeEvents) item.removeEvents();
if (item.clearAttributes) item.clearAttributes();
if (uid != null){
delete collected[uid];
delete storage[uid];
}
return item;
};
var camels = ['defaultValue', 'accessKey', 'cellPadding', 'cellSpacing', 'colSpan', 'frameBorder', 'maxLength', 'readOnly',
'rowSpan', 'tabIndex', 'useMap'
];
var bools = ['compact', 'nowrap', 'ismap', 'declare', 'noshade', 'checked', 'disabled', 'readOnly', 'multiple', 'selected',
'noresize', 'defer', 'defaultChecked'
];
var attributes = {
'html': 'innerHTML',
'class': 'className',
'for': 'htmlFor',
'text': (function(){
var temp = document.createElement('div');
return (temp.textContent == null) ? 'innerText' : 'textContent';
})()
};
var readOnly = ['type'];
var expandos = ['value', 'defaultValue'];
var uriAttrs = /^(?:href|src|usemap)$/i;
bools = bools.associate(bools);
camels = camels.associate(camels.map(String.toLowerCase));
readOnly = readOnly.associate(readOnly);
Object.append(attributes, expandos.associate(expandos));
var inserters = {
before: function(context, element){
var parent = element.parentNode;
if (parent) parent.insertBefore(context, element);
},
after: function(context, element){
var parent = element.parentNode;
if (parent) parent.insertBefore(context, element.nextSibling);
},
bottom: function(context, element){
element.appendChild(context);
},
top: function(context, element){
element.insertBefore(context, element.firstChild);
}
};
inserters.inside = inserters.bottom;
var injectCombinator = function(expression, combinator){
if (!expression) return combinator;
expression = Object.clone(Slick.parse(expression));
var expressions = expression.expressions;
for (var i = expressions.length; i--;)
expressions[i][0].combinator = combinator;
return expression;
};
Element.implement({
set: function(prop, value){
var property = Element.Properties[prop];
(property && property.set) ? property.set.call(this, value) : this.setProperty(prop, value);
}.overloadSetter(),
get: function(prop){
var property = Element.Properties[prop];
return (property && property.get) ? property.get.apply(this) : this.getProperty(prop);
}.overloadGetter(),
erase: function(prop){
var property = Element.Properties[prop];
(property && property.erase) ? property.erase.apply(this) : this.removeProperty(prop);
return this;
},
setProperty: function(attribute, value){
attribute = camels[attribute] || attribute;
if (value == null) return this.removeProperty(attribute);
var key = attributes[attribute];
(key) ? this[key] = value :
(bools[attribute]) ? this[attribute] = !!value : this.setAttribute(attribute, '' + value);
return this;
},
setProperties: function(attributes){
for (var attribute in attributes) this.setProperty(attribute, attributes[attribute]);
return this;
},
getProperty: function(attribute){
attribute = camels[attribute] || attribute;
var key = attributes[attribute] || readOnly[attribute];
return (key) ? this[key] :
(bools[attribute]) ? !!this[attribute] :
(uriAttrs.test(attribute) ? this.getAttribute(attribute, 2) :
(key = this.getAttributeNode(attribute)) ? key.nodeValue : null) || null;
},
getProperties: function(){
var args = Array.from(arguments);
return args.map(this.getProperty, this).associate(args);
},
removeProperty: function(attribute){
attribute = camels[attribute] || attribute;
var key = attributes[attribute];
(key) ? this[key] = '' :
(bools[attribute]) ? this[attribute] = false : this.removeAttribute(attribute);
return this;
},
removeProperties: function(){
Array.each(arguments, this.removeProperty, this);
return this;
},
hasClass: function(className){
return this.className.clean().contains(className, ' ');
},
addClass: function(className){
if (!this.hasClass(className)) this.className = (this.className + ' ' + className).clean();
return this;
},
removeClass: function(className){
this.className = this.className.replace(new RegExp('(^|\\s)' + className + '(?:\\s|$)'), '$1');
return this;
},
toggleClass: function(className, force){
if (force == null) force = !this.hasClass(className);
return (force) ? this.addClass(className) : this.removeClass(className);
},
adopt: function(){
var parent = this, fragment, elements = Array.flatten(arguments), length = elements.length;
if (length > 1) parent = fragment = document.createDocumentFragment();
for (var i = 0; i < length; i++){
var element = document.id(elements[i], true);
if (element) parent.appendChild(element);
}
if (fragment) this.appendChild(fragment);
return this;
},
appendText: function(text, where){
return this.grab(this.getDocument().newTextNode(text), where);
},
grab: function(el, where){
inserters[where || 'bottom'](document.id(el, true), this);
return this;
},
inject: function(el, where){
inserters[where || 'bottom'](this, document.id(el, true));
return this;
},
replaces: function(el){
el = document.id(el, true);
el.parentNode.replaceChild(this, el);
return this;
},
wraps: function(el, where){
el = document.id(el, true);
return this.replaces(el).grab(el, where);
},
getPrevious: function(expression){
return document.id(Slick.find(this, injectCombinator(expression, '!~')));
},
getAllPrevious: function(expression){
return Slick.search(this, injectCombinator(expression, '!~'), new Elements);
},
getNext: function(expression){
return document.id(Slick.find(this, injectCombinator(expression, '~')));
},
getAllNext: function(expression){
return Slick.search(this, injectCombinator(expression, '~'), new Elements);
},
getFirst: function(expression){
return document.id(Slick.search(this, injectCombinator(expression, '>'))[0]);
},
getLast: function(expression){
return document.id(Slick.search(this, injectCombinator(expression, '>')).getLast());
},
getParent: function(expression){
return document.id(Slick.find(this, injectCombinator(expression, '!')));
},
getParents: function(expression){
return Slick.search(this, injectCombinator(expression, '!'), new Elements);
},
getSiblings: function(expression){
return Slick.search(this, injectCombinator(expression, '~~'), new Elements);
},
getChildren: function(expression){
return Slick.search(this, injectCombinator(expression, '>'), new Elements);
},
getWindow: function(){
return this.ownerDocument.window;
},
getDocument: function(){
return this.ownerDocument;
},
getElementById: function(id){
return document.id(Slick.find(this, '#' + ('' + id).replace(/(\W)/g, '\\$1')));
},
getSelected: function(){
this.selectedIndex; // Safari 3.2.1
return new Elements(Array.from(this.options).filter(function(option){
return option.selected;
}));
},
toQueryString: function(){
var queryString = [];
this.getElements('input, select, textarea').each(function(el){
var type = el.type;
if (!el.name || el.disabled || type == 'submit' || type == 'reset' || type == 'file' || type == 'image') return;
var value = (el.get('tag') == 'select') ? el.getSelected().map(function(opt){
// IE
return document.id(opt).get('value');
}) : ((type == 'radio' || type == 'checkbox') && !el.checked) ? null : el.get('value');
Array.from(value).each(function(val){
if (typeof val != 'undefined') queryString.push(encodeURIComponent(el.name) + '=' + encodeURIComponent(val));
});
});
return queryString.join('&');
},
destroy: function(){
var children = clean(this).getElementsByTagName('*');
Array.each(children, clean);
Element.dispose(this);
return null;
},
empty: function(){
Array.from(this.childNodes).each(Element.dispose);
return this;
},
dispose: function(){
return (this.parentNode) ? this.parentNode.removeChild(this) : this;
},
match: function(expression){
return !expression || Slick.match(this, expression);
}
});
var cleanClone = function(node, element, keepid){
if (!keepid) node.setAttributeNode(document.createAttribute('id'));
if (node.clearAttributes){
node.clearAttributes();
node.mergeAttributes(element);
node.removeAttribute('uid');
if (node.options){
var no = node.options, eo = element.options;
for (var i = no.length; i--;) no[i].selected = eo[i].selected;
}
}
var prop = formProps[element.tagName.toLowerCase()];
if (prop && element[prop]) node[prop] = element[prop];
};
Element.implement('clone', function(contents, keepid){
contents = contents !== false;
var clone = this.cloneNode(contents), i;
if (contents){
var ce = clone.getElementsByTagName('*'), te = this.getElementsByTagName('*');
for (i = ce.length; i--;) cleanClone(ce[i], te[i], keepid);
}
cleanClone(clone, this, keepid);
if (Browser.ie){
var co = clone.getElementsByTagName('object'), to = this.getElementsByTagName('object');
for (i = co.length; i--;) co[i].outerHTML = to[i].outerHTML;
}
return document.id(clone);
});
var contains = {contains: function(element){
return Slick.contains(this, element);
}};
if (!document.contains) Document.implement(contains);
if (!document.createElement('div').contains) Element.implement(contains);
[Element, Window, Document].invoke('implement', {
addListener: function(type, fn){
if (type == 'unload'){
var old = fn, self = this;
fn = function(){
self.removeListener('unload', fn);
old();
};
} else {
collected[$uid(this)] = this;
}
if (this.addEventListener) this.addEventListener(type, fn, !!arguments[2]);
else this.attachEvent('on' + type, fn);
return this;
},
removeListener: function(type, fn){
if (this.removeEventListener) this.removeEventListener(type, fn, !!arguments[2]);
else this.detachEvent('on' + type, fn);
return this;
},
retrieve: function(property, dflt){
var storage = get($uid(this)), prop = storage[property];
if (dflt != null && prop == null) prop = storage[property] = dflt;
return prop != null ? prop : null;
},
store: function(property, value){
var storage = get($uid(this));
storage[property] = value;
return this;
},
eliminate: function(property){
var storage = get($uid(this));
delete storage[property];
return this;
}
});
/*<ltIE9>*/
if (window.attachEvent && !window.addEventListener) window.addListener('unload', function(){
Object.each(collected, clean);
if (window.CollectGarbage) CollectGarbage();
});
/*</ltIE9>*/
})();
Element.Properties = {};
Element.Properties.style = {
set: function(style){
this.style.cssText = style;
},
get: function(){
return this.style.cssText;
},
erase: function(){
this.style.cssText = '';
}
};
Element.Properties.tag = {
get: function(){
return this.tagName.toLowerCase();
}
};
/*<ltIE9>*/
(function(maxLength){
if (maxLength != null) Element.Properties.maxlength = Element.Properties.maxLength = {
get: function(){
var maxlength = this.getAttribute('maxLength');
return maxlength == maxLength ? null : maxlength;
}
};
})(document.createElement('input').getAttribute('maxLength'));
/*</ltIE9>*/
/*<!webkit>*/
Element.Properties.html = (function(){
var tableTest = Function.attempt(function(){
var table = document.createElement('table');
table.innerHTML = '<tr><td></td></tr>';
});
var wrapper = document.createElement('div');
var translations = {
table: [1, '<table>', '</table>'],
select: [1, '<select>', '</select>'],
tbody: [2, '<table><tbody>', '</tbody></table>'],
tr: [3, '<table><tbody><tr>', '</tr></tbody></table>']
};
translations.thead = translations.tfoot = translations.tbody;
var html = {
set: function(){
var html = Array.flatten(arguments).join('');
var wrap = (!tableTest && translations[this.get('tag')]);
if (wrap){
var first = wrapper;
first.innerHTML = wrap[1] + html + wrap[2];
for (var i = wrap[0]; i--;) first = first.firstChild;
this.empty().adopt(first.childNodes);
} else {
this.innerHTML = html;
}
}
};
html.erase = html.set;
return html;
})();
/*</!webkit>*/
|
import gulp from 'gulp';
import runSequence from 'run-sequence';
gulp.task('dev', ['clean'], function(cb) {
global.isProd = false;
runSequence(['styles', 'images', 'fonts', 'views','json','externalScripts'], 'browserify', 'watch', cb);
});
|
'use strict';
// Declare app level module which depends on views, and components
var appModule = angular.module('myApp', ['ui.router','myApp.homepage']);
appModule.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/homepage');
});
|
const express = require('express')
const session = require('express-session')
const MongoStore = require('connect-mongo')(session)
const mainRouter = express.Router()
const passport = require('../utils/passport')
const mongoose = require('../db/index')
const userController = require('../controllers/userController')
const { logger } = require('../utils')
mainRouter.use(session({
secret: process.env.SESSION_SECRET,
store: new MongoStore({ mongooseConnection: mongoose.connection }),
resave: false,
saveUninitialized: false
}))
mainRouter.use(passport.initialize())
mainRouter.use(passport.session())
const authMiddleware = (req, res, next) => {
if (!req.isAuthenticated()) return res.status(401).send()
else next()
}
// user
const userRouter = express.Router()
userRouter.get('/oauth', passport.authenticate('github'))
userRouter.get('/oauth/callback', passport.authenticate('github'), userController.oauthCallback)
userRouter.get('/logout', authMiddleware, userController.logout)
userRouter.get('/checkAuth', userController.checkAuth)
userRouter.get('/details', authMiddleware, userController.getUserDetails)
mainRouter.use('/user', userRouter)
module.exports = mainRouter
|
var gulp = require( 'gulp' );
var rename = require( 'gulp-rename' );
var browserify = require( 'browserify' );
var browserifyInc = require( 'browserify-incremental' );
var reactify = require( 'reactify' );
var xtend = require( 'xtend' );
var source = require( 'vinyl-source-stream' );
var server = require( 'gulp-express' );
gulp.task( 'browserify', function () {
var bundler = browserify( xtend( browserifyInc.args, {
entries: [ './src/client/index.jsx' ],
extensions: [ '.jsx' ],
transform: [ reactify ],
debug: true
} ) );
browserifyInc( bundler, { cacheFile: './browserify-cache.json' } );
return bundler.bundle()
.pipe( source( 'main.js' ) )
.pipe( gulp.dest( 'public/js' ) );
} );
gulp.task( 'server', function () {
server.run( {
file: './app.js'
} );
} );
gulp.task( 'watch', function () {
gulp.watch( './src/client/**/*', [ 'browserify' ] );
gulp.watch( './src/server/**/*', [ server.notify ] );
} );
gulp.task( 'default', [ 'browserify', 'server', 'watch' ] );
|
/**
* Gulp Task to generate CSS from SCSS
* Dependencies:
* - browser-sync
* - gulp-sass
* - gulp-sourcemaps
* - gulp-autoprefixer
*/
var gulp = require('gulp');
var browsersync = require('browser-sync').get('Dev Server');
var sass = require('gulp-sass');
var autoprefixer = require('gulp-autoprefixer');
var sourcemaps = require('gulp-sourcemaps');
var handleErrors = require('../../util/handleErrors');
var config = require('../../config');
gulp.task('sass', function() {
var sassConfig = config.sass;
sassConfig.onError = browsersync.notify;
browsersync.notify('Compiling Sass');
return gulp.src(sassConfig.src)
.pipe(sourcemaps.init())
.pipe(sass(sassConfig.options).on('error', handleErrors))
.pipe(autoprefixer(config.autoprefixer))
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest(sassConfig.dest));
}); |
import PropTypes from 'prop-types';
import React from 'react';
import Input from 'mcs-lite-ui/lib/Input';
import Button from 'mcs-lite-ui/lib/Button';
import MobileFixedFooter from 'mcs-lite-ui/lib/MobileFixedFooter';
import MobileHeader from 'mcs-lite-ui/lib/MobileHeader';
import validators from 'mcs-lite-ui/lib/utils/validators';
import IconMenu from 'mcs-lite-icon/lib/IconMenu';
import Helmet from 'react-helmet';
import { Link } from 'react-router';
import { updatePathname } from 'mcs-lite-ui/lib/utils/routerHelper';
import StyledLink from '../../components/StyledLink';
import { Container, Label, ButtonWrapper, StyledP } from './styled-components';
class Password extends React.Component {
static propTypes = {
// Redux Action
changePassword: PropTypes.func.isRequired,
// React-intl I18n
getMessages: PropTypes.func.isRequired,
};
state = { new1: '', new2: '' };
onChange = e => this.setState({ [e.target.name]: e.target.value });
onSubmit = e => {
this.props.changePassword({
password: this.state.new2,
message: this.props.getMessages('success'),
});
e.preventDefault();
};
render() {
const { new1, new2 } = this.state;
const { onChange, onSubmit } = this;
const { getMessages: t } = this.props;
const isNew1Error = validators.isLt8(new1);
const isNew2Error = validators.isNotEqual(new1, new2);
return (
<div>
<Helmet>
<title>{t('changePassword')}</title>
</Helmet>
<MobileHeader.MobileHeader
title={t('changePassword')}
leftChildren={
<MobileHeader.MobileHeaderIcon
component={Link}
to={updatePathname('/account')}
>
<IconMenu />
</MobileHeader.MobileHeaderIcon>
}
/>
<form onSubmit={onSubmit}>
<main>
<Container>
<div>
<Label htmlFor="new1">{t('newPassword.label')}</Label>
<Input
name="new1"
value={new1}
onChange={onChange}
placeholder={t('newPassword.placeholder')}
type="password"
required
kind={isNew1Error ? 'error' : 'primary'}
/>
{isNew1Error && (
<StyledP color="error">{t('lengthError')}</StyledP>
)}
</div>
<div>
<Label htmlFor="new2">{t('newPasswordAgain.label')}</Label>
<Input
name="new2"
value={new2}
onChange={onChange}
placeholder={t('newPasswordAgain.placeholder')}
type="password"
required
kind={isNew2Error ? 'error' : 'primary'}
/>
{isNew2Error && (
<StyledP color="error">{t('newPasswordAgain.error')}</StyledP>
)}
</div>
</Container>
</main>
<MobileFixedFooter>
<ButtonWrapper>
<StyledLink to={updatePathname('/account')}>
<Button kind="default" block>
{t('cancel')}
</Button>
</StyledLink>
<Button component="input" type="submit" value={t('save')} block />
</ButtonWrapper>
</MobileFixedFooter>
</form>
</div>
);
}
}
export default Password;
|
/*!
* Angular Material Design
* https://github.com/angular/material
* @license MIT
* v1.1.0-rc.5-master-3a0f323
*/
(function( window, angular, undefined ){
"use strict";
/**
* @ngdoc module
* @name material.components.navBar
*/
angular.module('material.components.navBar', ['material.core'])
.controller('MdNavBarController', MdNavBarController)
.directive('mdNavBar', MdNavBar)
.controller('MdNavItemController', MdNavItemController)
.directive('mdNavItem', MdNavItem);
/*****************************************************************************
* PUBLIC DOCUMENTATION *
*****************************************************************************/
/**
* @ngdoc directive
* @name mdNavBar
* @module material.components.navBar
*
* @restrict E
*
* @description
* The `<md-nav-bar>` directive renders a list of material tabs that can be used
* for top-level page navigation. Unlike `<md-tabs>`, it has no concept of a tab
* body and no bar pagination.
*
* Because it deals with page navigation, certain routing concepts are built-in.
* Route changes via via ng-href, ui-sref, or ng-click events are supported.
* Alternatively, the user could simply watch currentNavItem for changes.
*
* Accessibility functionality is implemented as a site navigator with a
* listbox, according to
* https://www.w3.org/TR/wai-aria-practices/#Site_Navigator_Tabbed_Style
*
* @param {string=} mdSelectedNavItem The name of the current tab; this must
* match the name attribute of `<md-nav-item>`
* @param {string=} navBarAriaLabel An aria-label for the nav-bar
*
* @usage
* <hljs lang="html">
* <md-nav-bar md-selected-nav-item="currentNavItem">
* <md-nav-item md-nav-click="goto('page1')" name="page1">Page One</md-nav-item>
* <md-nav-item md-nav-sref="app.page2" name="page2">Page Two</md-nav-item>
* <md-nav-item md-nav-href="#page3" name="page3">Page Three</md-nav-item>
* </md-nav-bar>
*</hljs>
* <hljs lang="js">
* (function() {
* ‘use strict’;
*
* $rootScope.$on('$routeChangeSuccess', function(event, current) {
* $scope.currentLink = getCurrentLinkFromRoute(current);
* });
* });
* </hljs>
*/
/*****************************************************************************
* mdNavItem
*****************************************************************************/
/**
* @ngdoc directive
* @name mdNavItem
* @module material.components.navBar
*
* @restrict E
*
* @description
* `<md-nav-item>` describes a page navigation link within the `<md-nav-bar>`
* component. It renders an md-button as the actual link.
*
* Exactly one of the mdNavClick, mdNavHref, mdNavSref attributes are required to be
* specified.
*
* @param {Function=} mdNavClick Function which will be called when the
* link is clicked to change the page. Renders as an `ng-click`.
* @param {string=} mdNavHref url to transition to when this link is clicked.
* Renders as an `ng-href`.
* @param {string=} mdNavSref Ui-router state to transition to when this link is
* clicked. Renders as a `ui-sref`.
* @param {string=} name The name of this link. Used by the nav bar to know
* which link is currently selected.
*
* @usage
* See `<md-nav-bar>` for usage.
*/
/*****************************************************************************
* IMPLEMENTATION *
*****************************************************************************/
function MdNavBar($mdAria) {
return {
restrict: 'E',
transclude: true,
controller: MdNavBarController,
controllerAs: 'ctrl',
bindToController: true,
scope: {
'mdSelectedNavItem': '=?',
'navBarAriaLabel': '@?',
},
template:
'<div class="md-nav-bar">' +
'<nav role="navigation">' +
'<ul class="_md-nav-bar-list" ng-transclude role="listbox"' +
'tabindex="0"' +
'ng-focus="ctrl.onFocus()"' +
'ng-blur="ctrl.onBlur()"' +
'ng-keydown="ctrl.onKeydown($event)"' +
'aria-label="{{ctrl.navBarAriaLabel}}">' +
'</ul>' +
'</nav>' +
'<md-nav-ink-bar></md-nav-ink-bar>' +
'</div>',
link: function(scope, element, attrs, ctrl) {
if (!ctrl.navBarAriaLabel) {
$mdAria.expectAsync(element, 'aria-label', angular.noop);
}
},
};
}
MdNavBar.$inject = ["$mdAria"];
/**
* Controller for the nav-bar component.
*
* Accessibility functionality is implemented as a site navigator with a
* listbox, according to
* https://www.w3.org/TR/wai-aria-practices/#Site_Navigator_Tabbed_Style
* @param {!angular.JQLite} $element
* @param {!angular.Scope} $scope
* @param {!angular.Timeout} $timeout
* @param {!Object} $mdConstant
* @constructor
* @final
* ngInject
*/
function MdNavBarController($element, $scope, $timeout, $mdConstant) {
// Injected variables
/** @private @const {!angular.Timeout} */
this._$timeout = $timeout;
/** @private @const {!angular.Scope} */
this._$scope = $scope;
/** @private @const {!Object} */
this._$mdConstant = $mdConstant;
// Data-bound variables.
/** @type {string} */
this.mdSelectedNavItem;
/** @type {string} */
this.navBarAriaLabel;
// State variables.
/** @type {?angular.JQLite} */
this._navBarEl = $element[0];
/** @type {?angular.JQLite} */
this._inkbar;
var self = this;
// need to wait for transcluded content to be available
var deregisterTabWatch = this._$scope.$watch(function() {
return self._navBarEl.querySelectorAll('._md-nav-button').length;
},
function(newLength) {
if (newLength > 0) {
self._initTabs();
deregisterTabWatch();
}
});
}
MdNavBarController.$inject = ["$element", "$scope", "$timeout", "$mdConstant"];
/**
* Initializes the tab components once they exist.
* @private
*/
MdNavBarController.prototype._initTabs = function() {
this._inkbar = angular.element(this._navBarEl.getElementsByTagName('md-nav-ink-bar')[0]);
var self = this;
this._$timeout(function() {
self._updateTabs(self.mdSelectedNavItem, undefined);
});
this._$scope.$watch('ctrl.mdSelectedNavItem', function(newValue, oldValue) {
// Wait a digest before update tabs for products doing
// anything dynamic in the template.
self._$timeout(function() {
self._updateTabs(newValue, oldValue);
});
});
};
/**
* Set the current tab to be selected.
* @param {string|undefined} newValue New current tab name.
* @param {string|undefined} oldValue Previous tab name.
* @private
*/
MdNavBarController.prototype._updateTabs = function(newValue, oldValue) {
var self = this;
var tabs = this._getTabs();
var oldIndex = -1;
var newIndex = -1;
var newTab = this._getTabByName(newValue);
var oldTab = this._getTabByName(oldValue);
if (oldTab) {
oldTab.setSelected(false);
oldIndex = tabs.indexOf(oldTab);
}
if (newTab) {
newTab.setSelected(true);
newIndex = tabs.indexOf(newTab);
}
this._$timeout(function() {
self._updateInkBarStyles(newTab, newIndex, oldIndex);
});
};
/**
* Repositions the ink bar to the selected tab.
* @private
*/
MdNavBarController.prototype._updateInkBarStyles = function(tab, newIndex, oldIndex) {
this._inkbar.toggleClass('_md-left', newIndex < oldIndex)
.toggleClass('_md-right', newIndex > oldIndex);
this._inkbar.css({display: newIndex < 0 ? 'none' : ''});
if(tab){
var tabEl = tab.getButtonEl();
var left = tabEl.offsetLeft;
this._inkbar.css({left: left + 'px', width: tabEl.offsetWidth + 'px'});
}
};
/**
* Returns an array of the current tabs.
* @return {!Array<!NavItemController>}
* @private
*/
MdNavBarController.prototype._getTabs = function() {
var linkArray = Array.prototype.slice.call(
this._navBarEl.querySelectorAll('.md-nav-item'));
return linkArray.map(function(el) {
return angular.element(el).controller('mdNavItem')
});
};
/**
* Returns the tab with the specified name.
* @param {string} name The name of the tab, found in its name attribute.
* @return {!NavItemController|undefined}
* @private
*/
MdNavBarController.prototype._getTabByName = function(name) {
return this._findTab(function(tab) {
return tab.getName() == name;
});
};
/**
* Returns the selected tab.
* @return {!NavItemController|undefined}
* @private
*/
MdNavBarController.prototype._getSelectedTab = function() {
return this._findTab(function(tab) {
return tab.isSelected()
});
};
/**
* Returns the focused tab.
* @return {!NavItemController|undefined}
*/
MdNavBarController.prototype.getFocusedTab = function() {
return this._findTab(function(tab) {
return tab.hasFocus()
});
};
/**
* Find a tab that matches the specified function.
* @private
*/
MdNavBarController.prototype._findTab = function(fn) {
var tabs = this._getTabs();
for (var i = 0; i < tabs.length; i++) {
if (fn(tabs[i])) {
return tabs[i];
}
}
return null;
};
/**
* Direct focus to the selected tab when focus enters the nav bar.
*/
MdNavBarController.prototype.onFocus = function() {
var tab = this._getSelectedTab();
if (tab) {
tab.setFocused(true);
}
};
/**
* Clear tab focus when focus leaves the nav bar.
*/
MdNavBarController.prototype.onBlur = function() {
var tab = this.getFocusedTab();
if (tab) {
tab.setFocused(false);
}
};
/**
* Move focus from oldTab to newTab.
* @param {!NavItemController} oldTab
* @param {!NavItemController} newTab
* @private
*/
MdNavBarController.prototype._moveFocus = function(oldTab, newTab) {
oldTab.setFocused(false);
newTab.setFocused(true);
};
/**
* Responds to keypress events.
* @param {!Event} e
*/
MdNavBarController.prototype.onKeydown = function(e) {
var keyCodes = this._$mdConstant.KEY_CODE;
var tabs = this._getTabs();
var focusedTab = this.getFocusedTab();
if (!focusedTab) return;
var focusedTabIndex = tabs.indexOf(focusedTab);
// use arrow keys to navigate between tabs
switch (e.keyCode) {
case keyCodes.UP_ARROW:
case keyCodes.LEFT_ARROW:
if (focusedTabIndex > 0) {
this._moveFocus(focusedTab, tabs[focusedTabIndex - 1]);
}
break;
case keyCodes.DOWN_ARROW:
case keyCodes.RIGHT_ARROW:
if (focusedTabIndex < tabs.length - 1) {
this._moveFocus(focusedTab, tabs[focusedTabIndex + 1]);
}
break;
case keyCodes.SPACE:
case keyCodes.ENTER:
// timeout to avoid a "digest already in progress" console error
this._$timeout(function() {
focusedTab.getButtonEl().click();
});
break;
}
};
/**
* ngInject
*/
function MdNavItem($$rAF) {
return {
restrict: 'E',
require: ['mdNavItem', '^mdNavBar'],
controller: MdNavItemController,
bindToController: true,
controllerAs: 'ctrl',
replace: true,
transclude: true,
template:
'<li class="md-nav-item" role="option" aria-selected="{{ctrl.isSelected()}}">' +
'<md-button ng-if="ctrl.mdNavSref" class="_md-nav-button md-accent"' +
'ng-class="ctrl.getNgClassMap()"' +
'tabindex="-1"' +
'ui-sref="{{ctrl.mdNavSref}}">' +
'<span ng-transclude class="_md-nav-button-text"></span>' +
'</md-button>' +
'<md-button ng-if="ctrl.mdNavHref" class="_md-nav-button md-accent"' +
'ng-class="ctrl.getNgClassMap()"' +
'tabindex="-1"' +
'ng-href="{{ctrl.mdNavHref}}">' +
'<span ng-transclude class="_md-nav-button-text"></span>' +
'</md-button>' +
'<md-button ng-if="ctrl.mdNavClick" class="_md-nav-button md-accent"' +
'ng-class="ctrl.getNgClassMap()"' +
'tabindex="-1"' +
'ng-click="ctrl.mdNavClick()">' +
'<span ng-transclude class="_md-nav-button-text"></span>' +
'</md-button>' +
'</li>',
scope: {
'mdNavClick': '&?',
'mdNavHref': '@?',
'mdNavSref': '@?',
'name': '@',
},
link: function(scope, element, attrs, controllers) {
var mdNavItem = controllers[0];
var mdNavBar = controllers[1];
// When accessing the element's contents synchronously, they
// may not be defined yet because of transclusion. There is a higher chance
// that it will be accessible if we wait one frame.
$$rAF(function() {
if (!mdNavItem.name) {
mdNavItem.name = angular.element(element[0].querySelector('._md-nav-button-text'))
.text().trim();
}
var navButton = angular.element(element[0].querySelector('._md-nav-button'));
navButton.on('click', function() {
mdNavBar.mdSelectedNavItem = mdNavItem.name;
scope.$apply();
});
});
}
};
}
MdNavItem.$inject = ["$$rAF"];
/**
* Controller for the nav-item component.
* @param {!angular.JQLite} $element
* @constructor
* @final
* ngInject
*/
function MdNavItemController($element) {
/** @private @const {!angular.JQLite} */
this._$element = $element;
// Data-bound variables
/** @const {?Function} */
this.mdNavClick;
/** @const {?string} */
this.mdNavHref;
/** @const {?string} */
this.name;
// State variables
/** @private {boolean} */
this._selected = false;
/** @private {boolean} */
this._focused = false;
var hasNavClick = !!($element.attr('md-nav-click'));
var hasNavHref = !!($element.attr('md-nav-href'));
var hasNavSref = !!($element.attr('md-nav-sref'));
// Cannot specify more than one nav attribute
if ((hasNavClick ? 1:0) + (hasNavHref ? 1:0) + (hasNavSref ? 1:0) > 1) {
throw Error(
'Must specify exactly one of md-nav-click, md-nav-href, ' +
'md-nav-sref for nav-item directive');
}
}
MdNavItemController.$inject = ["$element"];
/**
* Returns a map of class names and values for use by ng-class.
* @return {!Object<string,boolean>}
*/
MdNavItemController.prototype.getNgClassMap = function() {
return {
'md-active': this._selected,
'md-primary': this._selected,
'md-unselected': !this._selected,
'md-focused': this._focused,
};
};
/**
* Get the name attribute of the tab.
* @return {string}
*/
MdNavItemController.prototype.getName = function() {
return this.name;
};
/**
* Get the button element associated with the tab.
* @return {!Element}
*/
MdNavItemController.prototype.getButtonEl = function() {
return this._$element[0].querySelector('._md-nav-button');
};
/**
* Set the selected state of the tab.
* @param {boolean} isSelected
*/
MdNavItemController.prototype.setSelected = function(isSelected) {
this._selected = isSelected;
};
/**
* @return {boolean}
*/
MdNavItemController.prototype.isSelected = function() {
return this._selected;
};
/**
* Set the focused state of the tab.
* @param {boolean} isFocused
*/
MdNavItemController.prototype.setFocused = function(isFocused) {
this._focused = isFocused;
};
/**
* @return {boolean}
*/
MdNavItemController.prototype.hasFocus = function() {
return this._focused;
};
})(window, window.angular); |
jQuery.noConflict();
jQuery(document).ready(function(){
//search box of header
jQuery('#keyword').bind('focusin focusout', function(e){
var t = jQuery(this);
if(e.type == 'focusin' && t.val() == 'Search here') {
t.val('');
} else if(e.type == 'focusout' && t.val() == '') {
t.val('Search here');
}
});
//userinfo
jQuery('.userinfo').click(function(){
if(!jQuery(this).hasClass('userinfodrop')) {
var t = jQuery(this);
jQuery('.userdrop').width(t.width() + 30); //make this width the same with the user info wrapper
jQuery('.userdrop').slideDown('fast');
t.addClass('userinfodrop'); //add class to change color and background
} else {
jQuery(this).removeClass('userinfodrop');
jQuery('.userdrop').hide();
}
//remove notification box if visible
jQuery('.notialert').removeClass('notiactive');
jQuery('.notibox').hide();
return false;
});
//notification onclick
jQuery('.notialert').click(function(){
var t = jQuery(this);
var url = t.attr('href');
if(!t.hasClass('notiactive')) {
jQuery('.notibox').slideDown('fast'); //show notification box
jQuery('.noticontent').empty(); //clear data
jQuery('.notibox .tabmenu li').each(function(){
jQuery(this).removeClass('current'); //reset active tab menu
});
//make first li as default active menu
jQuery('.notibox .tabmenu li:first-child').addClass('current');
t.addClass('notiactive');
jQuery('.notibox .loader').show(); //show loading image while waiting a response from server
jQuery.post(url,function(data){
jQuery('.notibox .loader').hide(); //hide loader after response
jQuery('.noticontent').append(data); //append data from server to .noticontent box
});
} else {
t.removeClass('notiactive');
jQuery('.notibox').hide();
}
//this will hide user info drop down when visible
jQuery('.userinfo').removeClass('userinfodrop');
jQuery('.userdrop').hide();
return false;
});
jQuery(document).click(function(event) {
var ud = jQuery('.userdrop');
var nb = jQuery('.notibox');
//hide user drop menu when clicked outside of this element
if(!jQuery(event.target).is('.userdrop') && ud.is(':visible')) {
ud.hide();
jQuery('.userinfo').removeClass('userinfodrop');
}
//hide notification box when clicked outside of this element
if(!jQuery(event.target).is('.notibox') && nb.is(':visible')) {
nb.hide();
jQuery('.notialert').removeClass('notiactive');
}
});
//notification box tab menu
jQuery('.tabmenu a').click(function(){
var url = jQuery(this).attr('href');
//reset active menu
jQuery('.tabmenu li').each(function(){
jQuery(this).removeClass('current');
});
jQuery('.noticontent').empty(); //empty content first to display new data
jQuery('.notibox .loader').show();
jQuery(this).parent().addClass('current'); //add current class to menu
jQuery.post(url,function(data){
jQuery('.notibox .loader').hide();
jQuery('.noticontent').append(data); //inject new data from server
});
return false;
});
// Widget Box Title on Hover event
// show arrow image in the right side of the title upon hover
jQuery('.widgetbox .title').hover(function(){
if(!jQuery(this).parent().hasClass('uncollapsible'))
jQuery(this).addClass('titlehover');
}, function(){
jQuery(this).removeClass('titlehover');
});
//show/hide widget content when widget title is clicked
jQuery('.widgetbox .title').click(function(){
if(!jQuery(this).parent().hasClass('uncollapsible')) {
if(jQuery(this).next().is(':visible')) {
jQuery(this).next().slideUp('fast');
jQuery(this).addClass('widgettoggle');
} else {
jQuery(this).next().slideDown('fast');
jQuery(this).removeClass('widgettoggle');
}
}
});
//wrap menu to em when click will return to true
//this code is required in order the code (next below this code) to work.
jQuery('.leftmenu a span').each(function(){
jQuery(this).wrapInner('<em />');
});
jQuery('.leftmenu a').click(function(e) {
var t = jQuery(this);
var p = t.parent();
var ul = p.find('ul');
var li = jQuery(this).parents('.lefticon');
//check if menu have sub menu
if(jQuery(this).hasClass('menudrop')) {
//check if menu is collapsed
if(!li.length > 0) {
//check if sub menu is available
if(ul.length > 0) {
//check if menu is visible
if(ul.is(':visible')) {
ul.slideUp('fast');
p.next().css({borderTop: '0'});
t.removeClass('active');
} else {
ul.slideDown('fast');
p.next().css({borderTop: '1px solid #ddd'});
t.addClass('active');
}
}
if(jQuery(e.target).is('em'))
return true;
else
return false;
} else {
return true;
}
//redirect to assigned link when menu does not have a sub menu
} else {
return true;
}
});
//show tooltip menu when left menu is collapsed
jQuery('.leftmenu > ul > li').hover(function(){
if(jQuery(this).parents('.lefticon').length > 0) {
jQuery(this).find('.menutip').stop(true,true).fadeIn();
}
},function(){
if(jQuery(this).parents('.lefticon').length > 0) {
jQuery(this).find('.menutip').stop(true,true).fadeOut();
}
});
//show/hide left menu to switch into full/icon only menu
jQuery('#togglemenuleft a').click(function(){
if(jQuery('.mainwrapper').hasClass('lefticon')) {
jQuery('.mainwrapper').removeClass('lefticon');
jQuery(this).removeClass('toggle');
//remove all tooltip element upon switching to full menu view
jQuery('.leftmenu > ul > li').each(function(){
jQuery(this).find('.subtitle').remove();
if(jQuery(this).hasClass('current'))
jQuery(this).find('ul').show().unwrap();
else
jQuery(this).find('ul').hide().unwrap();
});
} else {
jQuery('.mainwrapper').addClass('lefticon');
jQuery(this).addClass('toggle');
showTooltipLeftMenu();
}
});
function showTooltipLeftMenu() {
//create tooltip menu upon switching to icon only menu view
jQuery('.leftmenu > ul > li > a').each(function(){
var text = jQuery(this).text(); //get the text
jQuery(this).removeClass('active'); //reset active in switching icon view
jQuery(this).parent().attr('style',''); //clear style attribute to this menu
jQuery(this).parent().find('ul').show(); //hide sub menu when there are showed sub menu
jQuery(this).after('<div class="menutip"><span class="subtitle">'+text+'</span></div>'); //append menu tooltip
jQuery(this).parent()
.find('.menutip')
.append(jQuery(this)
.parent()
.find('ul'));
});
}
/** FLOAT LEFT SIDEBAR **/
jQuery(document).scroll(function(){
var pos = jQuery(document).scrollTop();
if(pos > 50) {
jQuery('.floatleft').css({position: 'fixed', top: '10px', right: '10px'});
} else {
jQuery('.floatleft').css({position: 'absolute', top: 0, right: 0});
}
});
/** FLOAT RIGHT SIDEBAR **/
jQuery(document).scroll(function(){
if(jQuery(this).width() > 580) {
var pos = jQuery(document).scrollTop();
if(pos > 50) {
jQuery('.floatright').css({position: 'fixed', top: '10px', right: '10px'});
} else {
jQuery('.floatright').css({position: 'absolute', top: 0, right: 0});
}
}
});
//NOTIFICATION CLOSE BUTTON
jQuery('.notification .close').click(function(){
jQuery(this).parent().fadeOut();
});
//button hover
jQuery('.btn').hover(function(){
jQuery(this).stop().animate({backgroundColor: '#eee'});
},function(){
jQuery(this).stop().animate({backgroundColor: '#f7f7f7'});
});
//standard button hover
jQuery('.stdbtn').hover(function(){
jQuery(this).stop().animate({opacity: 0.75});
},function(){
jQuery(this).stop().animate({opacity: 1});
});
//buttons in error page
jQuery('.errorWrapper a').hover(function(){
jQuery(this).switchClass('default','hover');
},function(){
jQuery(this).switchClass('hover', 'default');
});
//screen resize
var TO = false;
jQuery(window).resize(function(){
if(jQuery(this).width() < 1024) {
jQuery('.mainwrapper').addClass('lefticon');
jQuery('#togglemenuleft').hide();
jQuery('.mainright').insertBefore('.footer');
if(jQuery('.menutip').length == 0)
showTooltipLeftMenu();
if(jQuery(this).width() <= 580) {
jQuery('.stdtable').wrap('<div class="tablewrapper"></div>');
if(jQuery('.headerinner2').length == 0)
insertHeaderInner2();
} else {
removeHeaderInner2();
}
} else {
toggleLeftMenu();
removeHeaderInner2();
}
});
if(jQuery(window).width() < 1024) {
jQuery('.mainwrapper').addClass('lefticon');
jQuery('#togglemenuleft').hide();
jQuery('.mainright').insertBefore('.footer');
if(jQuery('.menutip').length == 0)
showTooltipLeftMenu();
if(jQuery(window).width() <= 580) {
jQuery('table').wrap('<div class="tablewrapper"></div>');
insertHeaderInner2();
}
} else {
toggleLeftMenu();
}
function toggleLeftMenu() {
if(!jQuery('.mainwrapper').hasClass('lefticon')) {
jQuery('.mainwrapper').removeClass('lefticon');
jQuery('#togglemenuleft').show();
} else {
jQuery('#togglemenuleft').show();
jQuery('#togglemenuleft a').addClass('toggle');
}
}
function insertHeaderInner2() {
jQuery('.headerinner').after('<div class="headerinner2"></div>');
jQuery('#searchPanel').appendTo('.headerinner2');
jQuery('#userPanel').appendTo('.headerinner2');
jQuery('#userPanel').addClass('userinfomenu');
}
function removeHeaderInner2() {
jQuery('#searchPanel').insertBefore('#notiPanel');
jQuery('#userPanel').insertAfter('#notiPanel');
jQuery('#userPanel').removeClass('userinfomenu');
jQuery('.headerinner2').remove();
}
//autocomplete
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
];
jQuery( "#keyword" ).autocomplete({
source: availableTags
});
// jQuery('body').append('<div class="theme"><h4>Theme Color</h4><div><a href="darkblue/dashboard.html" class="darkblue"></a><a href="gray/dashboard.html" class="gray"></a></div></div>');
}); |
define(function () {
function RangeValidator(fieldName) {
this.validate = function (value) {
var valid = $.isNumeric(value.min) &&
$.isNumeric(value.max) &&
value.min <= value.max;
if (!valid) {
return fieldName +
" needs have valid numbers for min and max, and min must be less than or equal to max.";
} else {
return null;
}
};
this.rulesAsString = function () {
return "min > max";
};
}
return RangeValidator;
}); |
//Copyright ©2013-2014 Memba® Sarl. All rights reserved.
/*jslint browser:true*/
/*jshint browser:true*/
; (function ($, undefined) {
"use strict";
var fn = Function,
global = fn('return this')(),
kendo = global.kendo,
api = global.api = global.api || {},
MODULE = 'api.js: ',
DEBUG = false;
api.endPoints = {
root: 'http://phonegap-owin.azurewebsites.net',
externalLogins: '/api/Account/ExternalLogins',
token: '/Token',
register: '/api/Account/Register',
registerExternal: '/api/Account/RegisterExternal',
logOut: '/api/Account/Logout',
userInfo: '/api/Account/UserInfo',
values: '/api/values'
};
if (DEBUG) {
api.endPoints.root = 'http://localhost:64260';
}
api._util = {
getSecurityHeaders : function () {
var accessToken = sessionStorage["accessToken"] || localStorage["accessToken"];
if (accessToken) {
return { "Authorization": "Bearer " + accessToken };
}
return {};
},
clearAccessToken : function () {
localStorage.removeItem("accessToken");
sessionStorage.removeItem("accessToken");
},
setAccessToken : function (accessToken, persistent) {
if (persistent) {
localStorage["accessToken"] = accessToken;
} else {
sessionStorage["accessToken"] = accessToken;
}
},
archiveSessionStorageToLocalStorage : function () {
var backup = {};
for (var i = 0; i < sessionStorage.length; i++) {
backup[sessionStorage.key(i)] = sessionStorage[sessionStorage.key(i)];
}
localStorage["sessionStorageBackup"] = JSON.stringify(backup);
sessionStorage.clear();
},
restoreSessionStorageFromLocalStorage : function () {
var backupText = localStorage["sessionStorageBackup"],
backup;
if (backupText) {
backup = JSON.parse(backupText);
for (var key in backup) {
sessionStorage[key] = backup[key];
}
localStorage.removeItem("sessionStorageBackup");
}
}
};
//Use $.deferred as in http://jsfiddle.net/L96cD/
//See http://jqfundamentals.com/chapter/ajax-deferreds
//Se also http://joseoncode.com/2011/09/26/a-walkthrough-jquery-deferred-and-promise/
api.getExternalLogins = function (returnUrl, generateState) {
try {
return $.ajax({
url: api.endPoints.root + api.endPoints.externalLogins,
type: 'GET',
cache: false, //Adds a parameter _ with a timestamp to the query string
data: {
returnUrl: returnUrl, //encodeURIComponent(returnUrl),
generateState: generateState ? 'true' : 'false'
}
});
} catch (err) {
var dfd = new $.Deferred();
dfd.reject(err);
return dfd.promise();
}
};
api.register = function (userName, password) {
try {
return $.ajax({
url: api.endPoints.root + api.endPoints.register,
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify({
UserName: userName,
Password: password,
ConfirmPassword: password
}),
type: 'POST'
});
} catch (err) {
var dfd = new $.Deferred();
dfd.reject(err);
return dfd.promise();
}
};
api.registerExternal = function (userName) {
try {
return $.ajax({
url: api.endPoints.root + api.endPoints.registerExternal,
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify({
UserName: userName
}),
type: 'POST',
xhrFields: { withCredentials: true },
headers: api._util.getSecurityHeaders()
});
} catch (err) {
var dfd = new $.Deferred();
dfd.reject(err);
return dfd.promise();
}
};
api.openSession = function (userName, password, rememberMe) {
//debugger;
//following instructions at http://www.asp.net/web-api/overview/security/individual-accounts-in-web-api
//and http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api
try {
return $.ajax({
url: api.endPoints.root + api.endPoints.token,
contentType: 'application/x-www-form-urlencoded',
data: {
grant_type: 'password',
username: userName,
password: password
},
type: 'POST'
}).then(function (data) {
api._util.setAccessToken(data.access_token, rememberMe);
return data;
});
} catch (err) {
var dfd = new $.Deferred();
dfd.reject(err);
return dfd.promise();
}
};
api.parseExternalToken = function (hash) {
//#access_token=-QikJ_IFEkQ54bamU0HsYdlx6Nrn8itee83yPtXZNapdik6dm4fZCVrKcwdLT5f4QCUPNVaCvPrK90bs-sC22yQIoBEkjYciFplQc1kYjxFWlg1oQFtDqnUmso8xIpNAaRnO7MAdO2AKV3PoBL-E8B51yxGNAGDJAX0oScE0OzU8dIcELbgf1bsCPomLch5WwY_92Z1s5v3Iybdyh7WxIkYdylU5lyVptfF3r86aH5edphrrLyTOyWyxNtmSkkwwfCQX3Enx6uQbi5siiabOGf7NfsHiGAWqR8prUcxot9YMnGjJnAZFBvwLhb-qjAhGuruOmIiB4zRiJ9j4qwH9KMWXikoQ7DL8FAuxUecQ2Jna5FsDeS6WaNTqPhEKnv0mgk-MzIr7rGubENuwRakkijaw1Lk8n7p4hQwXdqEzXjA&token_type=bearer&expires_in=1209600&state=MCHBpm1G-Et-rwB9appTxjrQ8oaIttV3kYUUmEyrr401
var keyValues = hash.substr(1).split('&'),
data = {};
$.each(keyValues, function (index, keyValue) {
var pos = keyValue.indexOf('=');
if (pos > 0 && pos < keyValue.length - 1) {
data[keyValue.substr(0, pos)] = keyValue.substr(pos + 1);
}
});
//TODO: check state
api._util.setAccessToken(data.access_token, true);
return data;
};
/**
* Api's that require being logged in (security headers)
*/
api.getUserInfo = function () {
try {
return $.ajax({
url: api.endPoints.root + api.endPoints.userInfo,
type: 'GET',
cache: false,
xhrFields: { withCredentials: true },
headers: api._util.getSecurityHeaders()
/*
beforeSend: function (xhr, settings) {
xhr.withCredentials = true;
xhr.setRequestHeader('Authorization', 'Bearer ' + session.access_token);
}
*/
});
} catch (err) {
var dfd = new $.Deferred();
dfd.reject(err);
return dfd.promise();
}
};
api.getValues = function () {
try {
return $.ajax({
url: api.endPoints.root + api.endPoints.values,
type: 'GET',
xhrFields: { withCredentials: true },
headers: api._util.getSecurityHeaders()
/*
beforeSend: function (xhr, settings) {
xhr.withCredentials = true;
xhr.setRequestHeader('Authorization', 'Bearer ' + session.access_token);
}
*/
});
} catch (err) {
var dfd = new $.Deferred();
dfd.reject(err);
return dfd.promise();
}
};
api.logOut = function () {
try {
return $.ajax({
url: api.endPoints.root + api.endPoints.logOut,
contentType: 'application/x-www-form-urlencoded',
type: 'POST',
xhrFields: { withCredentials: true },
headers: api._util.getSecurityHeaders()
/*
beforeSend: function (xhr, settings) {
xhr.withCredentials = true;
xhr.setRequestHeader('Authorization', 'Bearer ' + session.access_token);
}
*/
}).then(function (data) {
api._util.clearAccessToken();
return data;
});
} catch (err) {
var dfd = new $.Deferred();
dfd.reject(err);
return dfd.promise();
}
};
}(jQuery));
/*
function AppDataModel() {
var self = this,
// Routes
addExternalLoginUrl = "/api/Account/AddExternalLogin",
changePasswordUrl = "/api/Account/changePassword",
loginUrl = "/Token",
logoutUrl = "/api/Account/Logout",
registerUrl = "/api/Account/Register",
registerExternalUrl = "/api/Account/RegisterExternal",
removeLoginUrl = "/api/Account/RemoveLogin",
setPasswordUrl = "/api/Account/setPassword",
siteUrl = "/",
userInfoUrl = "/api/Account/UserInfo";
// Route operations
function externalLoginsUrl(returnUrl, generateState) {
return "/api/Account/ExternalLogins?returnUrl=" + (encodeURIComponent(returnUrl)) +
"&generateState=" + (generateState ? "true" : "false");
}
function manageInfoUrl(returnUrl, generateState) {
return "/api/Account/ManageInfo?returnUrl=" + (encodeURIComponent(returnUrl)) +
"&generateState=" + (generateState ? "true" : "false");
}
// Other private operations
function getSecurityHeaders() {
var accessToken = sessionStorage["accessToken"] || localStorage["accessToken"];
if (accessToken) {
return { "Authorization": "Bearer " + accessToken };
}
return {};
}
// Operations
self.clearAccessToken = function () {
localStorage.removeItem("accessToken");
sessionStorage.removeItem("accessToken");
};
self.setAccessToken = function (accessToken, persistent) {
if (persistent) {
localStorage["accessToken"] = accessToken;
} else {
sessionStorage["accessToken"] = accessToken;
}
};
self.toErrorsArray = function (data) {
var errors = new Array(),
items;
if (!data || !data.message) {
return null;
}
if (data.modelState) {
for (var key in data.modelState) {
items = data.modelState[key];
if (items.length) {
for (var i = 0; i < items.length; i++) {
errors.push(items[i]);
}
}
}
}
if (errors.length === 0) {
errors.push(data.message);
}
return errors;
};
// Data
self.returnUrl = siteUrl;
// Data access operations
self.addExternalLogin = function (data) {
return $.ajax(addExternalLoginUrl, {
type: "POST",
data: data,
headers: getSecurityHeaders()
});
};
self.changePassword = function (data) {
return $.ajax(changePasswordUrl, {
type: "POST",
data: data,
headers: getSecurityHeaders()
});
};
self.getExternalLogins = function (returnUrl, generateState) {
return $.ajax(externalLoginsUrl(returnUrl, generateState), {
cache: false,
headers: getSecurityHeaders()
});
};
self.getManageInfo = function (returnUrl, generateState) {
return $.ajax(manageInfoUrl(returnUrl, generateState), {
cache: false,
headers: getSecurityHeaders()
});
};
self.getUserInfo = function (accessToken) {
var headers;
if (typeof (accessToken) !== "undefined") {
headers = {
"Authorization": "Bearer " + accessToken
};
} else {
headers = getSecurityHeaders();
}
return $.ajax(userInfoUrl, {
cache: false,
headers: headers
});
};
self.login = function (data) {
return $.ajax(loginUrl, {
type: "POST",
data: data
});
};
self.logout = function () {
return $.ajax(logoutUrl, {
type: "POST",
headers: getSecurityHeaders()
});
};
self.register = function (data) {
return $.ajax(registerUrl, {
type: "POST",
data: data
});
};
self.registerExternal = function (accessToken, data) {
return $.ajax(registerExternalUrl, {
type: "POST",
data: data,
headers: {
"Authorization": "Bearer " + accessToken
}
});
};
self.removeLogin = function (data) {
return $.ajax(removeLoginUrl, {
type: "POST",
data: data,
headers: getSecurityHeaders()
});
};
self.setPassword = function (data) {
return $.ajax(setPasswordUrl, {
type: "POST",
data: data,
headers: getSecurityHeaders()
});
};
}
*/ |
import React from 'react'
class ConnectionSelector extends React.Component {
constructor(props) {
super(props)
this.state = {
room: this.props.room || 'smoky', // @todo un-hardcode
username: ''
}
this.onJoinClicked = this.onJoinClicked.bind(this)
this.setUsername = this.setUsername.bind(this)
}
onJoinClicked() {
this.props.onJoinClicked(this.state)
}
setUsername(e) {
if (e.keyCode === 13) {
return this.onJoinClicked()
}
return this.setState({ username: e.target.value })
}
render() {
return (
<div className="connection-selector">
<input
className="username"
required
autoFocus
placeholder="Enter a username"
onKeyUp={this.setUsername}
/>
{ this.state.username && (
<button
className="go"
onClick={this.onJoinClicked}
>
Go! / ⏎
</button>
) }
</div>
)
}
}
ConnectionSelector.propTypes = {
room: React.PropTypes.string,
onJoinClicked: React.PropTypes.func
}
export default ConnectionSelector
|
const Foo = a;
export { Foo as Bar };
|
import _BidStatus from "./BidStatus"
import PropTypes from "prop-types"
import block from "bem-cn-lite"
import classNames from "classnames"
import titleAndYear from "desktop/apps/auction/utils/titleAndYear"
import { connect } from "react-redux"
import { get } from "lodash"
// FIXME: Rewire
let BidStatus = _BidStatus
function ListArtwork(props) {
const {
saleArtwork,
artistDisplay,
date,
image,
isAuction,
isClosed,
isMobile,
lotLabel,
sale_message,
title,
} = props
const b = block("auction-page-ListArtwork")
const auctionArtworkClasses = classNames(String(b()), {
"auction-open": isClosed,
})
return isMobile ? (
<a
className={auctionArtworkClasses}
key={saleArtwork._id}
href={`/artwork/${saleArtwork.id}`}
>
<div className={b("image")}>
<img src={image} alt={title} />
</div>
<div className={b("metadata")}>
{isAuction ? (
<div className={b("lot-number")}>Lot {lotLabel}</div>
) : (
<div>{sale_message}</div>
)}
<div className={b("artists")}>{artistDisplay}</div>
<div
className={b("title")}
dangerouslySetInnerHTML={{
__html: titleAndYear(title, date),
}}
/>
{isAuction && !isClosed && (
<div className={b("bid-status")}>
<BidStatus artworkItem={saleArtwork} />
</div>
)}
</div>
</a>
) : (
// Desktop
<a
className={auctionArtworkClasses}
key={saleArtwork._id}
href={`/artwork/${saleArtwork.id}`}
>
<div className={b("image-container")}>
<div className={b("image")}>
<img src={image} alt={saleArtwork.title} />
</div>
</div>
<div className={b("metadata")}>
<div className={b("artists")}>{artistDisplay}</div>
<div
className={b("title")}
dangerouslySetInnerHTML={{
__html: titleAndYear(title, date),
}}
/>
</div>
{isAuction ? (
<div className={b("lot-number")}>Lot {saleArtwork.lot_label}</div>
) : (
<div>{sale_message}</div>
)}
{isAuction && !props.isClosed && (
<div className={b("bid-status")}>
<BidStatus artworkItem={saleArtwork} />
</div>
)}
</a>
)
}
ListArtwork.propTypes = {
saleArtwork: PropTypes.object.isRequired,
date: PropTypes.string.isRequired,
image: PropTypes.string.isRequired,
isAuction: PropTypes.bool.isRequired,
isClosed: PropTypes.bool.isRequired,
isMobile: PropTypes.bool.isRequired,
lotLabel: PropTypes.string.isRequired,
artistDisplay: PropTypes.string.isRequired,
sale_message: PropTypes.string,
title: PropTypes.string.isRequired,
}
const mapStateToProps = (state, props) => {
const { saleArtwork } = props
const image = get(
saleArtwork,
"artwork.images.0.image_medium",
"/images/missing_image.png"
)
const { artists } = saleArtwork
const artistDisplay =
artists && artists.length > 0 ? artists.map(aa => aa.name).join(", ") : ""
return {
date: saleArtwork.date,
image,
isAuction: state.app.auction.get("is_auction"),
isClosed: state.artworkBrowser.isClosed || state.app.auction.isClosed(),
isMobile: state.app.isMobile,
lotLabel: saleArtwork.lot_label,
artistDisplay,
sale_message: saleArtwork.sale_message,
title: saleArtwork.title,
}
}
export default connect(mapStateToProps)(ListArtwork)
export const test = { ListArtwork }
|
function solve(params) {
var nk = params[0].split(' ').map(Number),
s = params[1].split(' ').map(Number),
p = [],
answer,
result;
Array.prototype.copy = function () {
var copiedArray = [];
for(var i = 0; i < this.length; i++) {
copiedArray.push(this[i]);
}
return copiedArray;
};
for(var j = 0; j < nk[1]; j++) {
for(var i = 0, len = nk[0]; i < len; i++) {
var currentNumber = s[i],
previousNumber = s[i - 1],
nextNumber = s[i + 1];
if(i === 0) {
previousNumber = s[len - 1];
} else if(i === len - 1) {
nextNumber = s[0];
}
if(currentNumber === 0) {
result = Math.abs(previousNumber - nextNumber);
} else if(currentNumber !== 0 && currentNumber % 2 === 0) {
result = Math.max(previousNumber, nextNumber);
} else if(currentNumber === 1) {
result = previousNumber + nextNumber;
} else if(currentNumber !== 1 && currentNumber % 2 === 1) {
result = Math.min(previousNumber, nextNumber);
}
p.push(result);
}
s = p.copy();
p = [];
}
answer = s.reduce(function (s, item) {
return s + item;
}, 0);
return answer;
}
console.log(solve(
["5 1", "9 0 2 4 1"]
));
console.log('----------------------------');
console.log(solve(
["10 3", "1 9 1 9 1 9 1 9 1 9"]
));
console.log('----------------------------');
console.log(solve(
["10 10", "0 1 2 3 4 5 6 7 8 9"]
));
|
// 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, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, 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.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require foundation
//= require turbolinks
//= require_tree .
//= require select2
semaphore = false;
wait_ajax_complete = 2000; // To avoid conflict with checkComputerStatus and Resque workers.
var ready = function() {
$(document).foundation();
$('#select-classroom').select2();
$('#select-classroom').on("change", function(e){
window.location.pathname = '/classrooms/'+e.val;
});
$('.ajax-computer').change(function(e){
semaphore = true;
computer_id = $(this).data('pc-id');
status = verifyStatus($(this).children('.onoffswitch-checkbox'));
if(validateDateTimePicker(this, status)) {
$.ajax({
url: '/computers/' + computer_id + '/change_status',
type: 'PUT',
data: {
status: status,
datetime: $('#date-time-' + computer_id).val()
},
complete: function() {
setTimeout(function() { semaphore = false; }, wait_ajax_complete);
}
});
}
});
$('#onoffswitch-class').change(function(e){
semaphore = true;
class_id = $(this).data('class-id');
status = verifyStatus($(this).children('.onoffswitch-checkbox'));
if(validateDateTimePicker(this, status)) {
changeAllComputers(status);
$.ajax({
url: '/computers/' + class_id + '/change_all_statuses',
type: 'PUT',
data: {
status: status,
datetime: $('#date-time-all').val()
},
complete: function() {
setTimeout(function() { semaphore = false; }, wait_ajax_complete);
}
});
}
});
$("input[id^='date-time-']").each(function() {
$(this).datetimepicker({
format: 'd/m/Y H:i',
minDate: 0,
minTime: 0,
mask: true,
lang: 'pt'
});
});
};
function validateDateTimePicker(element, status) {
datetime = $(element).parent().find('.date-time');
if(status === 'off'){
if(verifyDate(element)) {
datetime.css('border', '1px solid #cccccc');
datetime.fadeOut('slow');
} else {
$(element).children('.onoffswitch-checkbox').prop('checked', true);
datetime.css('border', '1px solid red');
alert('Você precisa agendar antes de desligar o computador');
return false;
}
} else {
datetime.fadeIn('slow');
}
return true;
}
function verifyDate(element) {
return $(element).parent().find('.date-time').val() !== '__/__/____ __:__';
}
function changeAllComputers(status){
$('[id^="switch-pc-"]').each(function(){
if(status === 'on'){
$(this).prop('checked', true);
$('.date-time').fadeIn('slow');
} else {
$(this).prop('checked', false);
$('.date-time').fadeOut('slow');
}
});
};
function verifyStatus(element){
if($(element).is(':checked')) return 'on';
else return 'off';
};
function checkComputerStatus() {
if(semaphore) return;
$.ajax({
url: '/computers/get_computers_status',
data: {
classroom: $('#select-classroom').val()
},
success: function(data) {
var count = 0;
$(data).each(function(index) {
checkbox = $('#switch-pc-' + data[index].id);
if(checkbox.is(':checked') && !data[index].online) {
checkbox.parent().parent().find('.date-time').fadeOut('slow');
checkbox.prop('checked', false);
}
if(!checkbox.is(':checked') && data[index].online) {
checkbox.parent().parent().find('.date-time').fadeIn('slow');
checkbox.prop('checked', true);
}
if(data[index].online) count++;
});
if(count == 0) {
$('#date-time-all').fadeOut('slow');
$('[id^=switch-sala]').prop('checked', false);
} else {
$('#date-time-all').fadeIn('slow');
$('[id^=switch-sala]').prop('checked', true);
}
},
error: function(data) {}
});
}
$(document).ready(ready);
$(document).on('page:load', ready);
setInterval(checkComputerStatus, 3000);
|
import React, { Component } from 'react';
import AppHeader from '../../components/AppHeader';
import Sidebar from '../../components/Sidebar';
import ApplicationsList from '../../components/ApplicationsList';
import './styles.css';
class Home extends Component {
render() {
return (
<div className="home">
<AppHeader />
<div className="body">
<Sidebar />
<ApplicationsList />
</div>
</div>
);
}
};
export default Home;
|
import React, { Component } from 'react';
import TodoItem from './TodoItem'
export default class TodoList extends Component {
constructor(props){
super(props)
}
render() {
var handler=this.props.changeHandler;
var todoItems = this.props.data.map(function(item) {
return (
<div>
<TodoItem text={item.text} isComplete={item.isComplete} id={item.id} changeHandler={handler}/>
</div>
)
});
return (
<div>
<h2>todos</h2>
{todoItems}
</div>
);
}
}
|
var app = app || {};
app.FoodDetailsView = Backbone.View.extend({// show food details, such as calories and food type, allow user to select how many servings they've had
el: "#food-details",
tagName: "div",
detailedTemplate: template("detailed-template"), // grab detailed item view template
initialize: function(options){
this.bus = options.bus;
this.bus.on("showDetailsOnFood", this.onShowDetailsOnFood, this);
},
events: {
"keypress #quantity" : "addToSelectedFoods"
},
/*
* @desc Function that sets how many number of servings the user has
* @param event object - takes the event object that's passed on keypress and if there is a value
* @return Backbone Model - returns an updated backbone Model to the Firebase Collection
*/
addToSelectedFoods : function(e){
this.$quantity = $("#quantity");
if (e.which === ENTER_KEY && this.$quantity.val().trim()){ // need to fix on click..because this if statement prevents adding selected foods
var numberOfServings = parseInt(this.$quantity.val(), 10);
this.model.set({ num_servings: numberOfServings });
app.selectedFoods.add(this.model.toJSON());
}
},
onShowDetailsOnFood: function(food){ // triggered by bus event to render the food details
this.model = food;
this.render();
},
render: function(){ // hides detail placeholder and renders food details
if (app.selectedFoods.length) {
$("#detail-placeholder").hide();
}
if (this.model){ // initially there is no model, the model is passed when the event is triggered
this.$el.html(this.detailedTemplate(this.model.toJSON())); // renders the details of a food selected, and refreshes the view on new food selected
}
return this;
}
}); |
datab = [{},{"SOP Class Name":{"colspan":"1","rowspan":"1","text":"Modality Worklist Information Model - FIND"},"SOP Class UID":{"colspan":"1","rowspan":"1","text":"1.2.840.10008.5.1.4.31"}}]; |
/**
* Location is a Backbone model representing a place in the world
*
*/
define([
'underscore',
'backbone'
], function (_, Backbone) {
var CodeDefinition = Backbone.Model.extend({
});
return CodeDefinition;
});
|
"use strict";
// elephant-harness
// Node.js - Electron - NW.js controller for PHP scripts
// elephant-harness is licensed under the terms of the MIT license.
// Copyright (c) 2016 - 2018 Dimitar D. Mitov
// 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.
// Set all interpreter arguments:
// interpreter switches, script and script arguments:
module.exports.setArguments = function (settings) {
let interpreterArguments = [];
// Interpreter switches, if any, go before the script:
if (Array.isArray(settings.interpreterSwitches)) {
interpreterArguments = settings.interpreterSwitches;
}
// The full path of the script is the minimal interpreter argument:
interpreterArguments.push(settings.script);
// Script arguments, if any, go after the script full path:
if (Array.isArray(settings.scriptArguments)) {
Array.prototype.push.apply(interpreterArguments, settings.scriptArguments);
}
return interpreterArguments;
};
|
var SECRETHASH = "" // Generate using gen.html
var API_KEY = "" // Get by registering with parse
var JAVASCRIPT_KEY = "" // Get by registering with parse |
/**
* Created with WebStorm.
* Date: 2/3/2014
* Time: 12:24 PM
* @author Adam C. Nowak
* @description
*/
/*jslint browser: true */
/*jslint devel: true */
/*jslint nomen: true */
/*global $, jQuery, _, ko, Mustache */
/*global ldrly, ui */
"use strict";
ldrly.integration.rest.leaderboard = {};
ldrly.integration.rest.leaderboard.assign = {};
ldrly.integration.rest.leaderboard.unassign = {};
ldrly.integration.rest.leaderboard.create = function (data, callback) {
var self = this,
endpoints = ldrly.config.getEndPoints(),
url_base = endpoints.ldrly.url,
url_resource = '/profile/user/',
url = url_base + url_resource;
// username = data.username,
// password = data.password;
// function basicAuth(xhr) {
// var auth = 'Basic ' + window.btoa(username + ":" + password);
// xhr.setRequestHeader('Authorization', auth);
// }
var request = $.ajax(
{
url : url,
type : 'POST',
// beforeSend: basicAuth,
data : JSON.stringify(data),
contentType : 'application/json; charset=utf-8',
dataType : 'json',
headers : {
'Accept' : 'application/json'
}
}
);
request.done(function (result) {
callback(undefined, result);
});
request.always(function (result) {
});
request.fail(function (XHR, textStatus, errorThrown) {
console.log("Error! " + textStatus + ':' + errorThrown);
//Create an Error Object
var error = { responseText : XHR.responseText, status : XHR.leaderboardus, statusText : XHR.leaderboardusText };
//Pass back the Error
callback(error);
});
};
ldrly.integration.rest.leaderboard.retrieve = function (id, callback) {
var self = this,
endpoints = ldrly.config.getEndPoints(),
url_base = endpoints.ldrly.url,
url_resource = '/profile/user/' + id,
url = url_base + url_resource;
// username = data.username,
// password = data.password;
// function basicAuth(xhr) {
// var auth = 'Basic ' + window.btoa(username + ":" + password);
// xhr.setRequestHeader('Authorization', auth);
// }
var request = $.ajax(
{
url : url,
type : 'GET',
// beforeSend: basicAuth,
// data : JSON.stringify(data),
contentType : 'application/json; charset=utf-8',
dataType : 'json',
headers : {
'Accept' : 'application/json'
}
}
);
request.done(function (result) {
callback(undefined, result);
});
request.always(function (result) {
});
request.fail(function (XHR, textStatus, errorThrown) {
console.log("Error! " + textStatus + ':' + errorThrown);
//Create an Error Object
var error = { responseText : XHR.responseText, status : XHR.leaderboardus, statusText : XHR.leaderboardusText };
//Pass back the Error
callback(error);
});
};
ldrly.integration.rest.leaderboard.list = function (callback) {
var self = this,
endpoints = ldrly.config.getEndPoints(),
url_base = endpoints.ldrly.url,
url_resource = '/profile/user/',
url = url_base + url_resource;
// username = data.username,
// password = data.password;
// function basicAuth(xhr) {
// var auth = 'Basic ' + window.btoa(username + ":" + password);
// xhr.setRequestHeader('Authorization', auth);
// }
var request = $.ajax(
{
url : url,
type : 'GET',
// beforeSend: basicAuth,
// data : JSON.stringify(data),
contentType : 'application/json; charset=utf-8',
dataType : 'json',
headers : {
'Accept' : 'application/json'
}
}
);
request.done(function (result) {
callback(undefined, result);
});
request.always(function (result) {
});
request.fail(function (XHR, textStatus, errorThrown) {
console.log("Error! " + textStatus + ':' + errorThrown);
//Create an Error Object
var error = { responseText : XHR.responseText, status : XHR.leaderboardus, statusText : XHR.leaderboardusText };
//Pass back the Error
callback(error);
});
};
ldrly.integration.rest.leaderboard.update = function (id, data, callback) {
var self = this,
endpoints = ldrly.config.getEndPoints(),
url_base = endpoints.ldrly.url,
url_resource = '/profile/user/' + id,
url = url_base + url_resource;
// username = data.username,
// password = data.password;
// function basicAuth(xhr) {
// var auth = 'Basic ' + window.btoa(username + ":" + password);
// xhr.setRequestHeader('Authorization', auth);
// }
var request = $.ajax(
{
url : url,
type : 'PUT',
// beforeSend: basicAuth,
data : JSON.stringify(data),
contentType : 'application/json; charset=utf-8',
dataType : 'json',
headers : {
'Accept' : 'application/json'
}
}
);
request.done(function (result) {
callback(undefined, result);
});
request.always(function (result) {
});
request.fail(function (XHR, textStatus, errorThrown) {
console.log("Error! " + textStatus + ':' + errorThrown);
//Create an Error Object
var error = { responseText : XHR.responseText, status : XHR.leaderboardus, statusText : XHR.leaderboardusText };
//Pass back the Error
callback(error);
});
};
ldrly.integration.rest.leaderboard.password = function (id, data, callback) {
var self = this,
endpoints = ldrly.config.getEndPoints(),
url_base = endpoints.ldrly.url,
url_resource = '/profile/user/' + id + '/password/',
url = url_base + url_resource;
// username = data.username,
// password = data.password;
// function basicAuth(xhr) {
// var auth = 'Basic ' + window.btoa(username + ":" + password);
// xhr.setRequestHeader('Authorization', auth);
// }
var request = $.ajax(
{
url : url,
type : 'PUT',
// beforeSend: basicAuth,
data : JSON.stringify(data),
contentType : 'application/json; charset=utf-8',
dataType : 'json',
headers : {
'Accept' : 'application/json'
}
}
);
request.done(function (result) {
callback(undefined, result);
});
request.always(function (result) {
});
request.fail(function (XHR, textStatus, errorThrown) {
console.log("Error! " + textStatus + ':' + errorThrown);
//Create an Error Object
var error = { responseText : XHR.responseText, status : XHR.leaderboardus, statusText : XHR.leaderboardusText };
//Pass back the Error
callback(error);
});
};
ldrly.integration.rest.leaderboard.destroy = function (id, callback) {
var self = this,
endpoints = ldrly.config.getEndPoints(),
url_base = endpoints.ldrly.url,
url_resource = '/profile/user/' + id,
url = url_base + url_resource;
// username = data.username,
// password = data.password;
// function basicAuth(xhr) {
// var auth = 'Basic ' + window.btoa(username + ":" + password);
// xhr.setRequestHeader('Authorization', auth);
// }
var request = $.ajax(
{
url : url,
type : 'DELETE',
// beforeSend: basicAuth,
// data : JSON.stringify(data),
contentType : 'application/json; charset=utf-8',
dataType : 'json',
headers : {
'Accept' : 'application/json'
}
}
);
request.done(function (result) {
callback(undefined, result);
});
request.always(function (result) {
});
request.fail(function (XHR, textStatus, errorThrown) {
console.log("Error! " + textStatus + ':' + errorThrown);
//Create an Error Object
var error = { responseText : XHR.responseText, status : XHR.leaderboardus, statusText : XHR.leaderboardusText };
//Pass back the Error
callback(error);
});
};
ldrly.integration.rest.leaderboard.assign.position = function (id, ppid, callback) {
var self = this,
endpoints = ldrly.config.getEndPoints(),
url_base = endpoints.ldrly.url,
url_resource = '/profile/user/' + id + '/assign/profile/position/' + ppid,
url = url_base + url_resource;
// username = data.username,
// password = data.password;
// function basicAuth(xhr) {
// var auth = 'Basic ' + window.btoa(username + ":" + password);
// xhr.setRequestHeader('Authorization', auth);
// }
var request = $.ajax(
{
url : url,
type : 'POST',
// beforeSend: basicAuth,
// data : JSON.stringify(data),
contentType : 'application/json; charset=utf-8',
dataType : 'json',
headers : {
'Accept' : 'application/json'
}
}
);
request.done(function (result) {
callback(undefined, result);
});
request.always(function (result) {
});
request.fail(function (XHR, textStatus, errorThrown) {
console.log("Error! " + textStatus + ':' + errorThrown);
//Create an Error Object
var error = { responseText : XHR.responseText, status : XHR.leaderboardus, statusText : XHR.leaderboardusText };
//Pass back the Error
callback(error);
});
};
ldrly.integration.rest.leaderboard.unassign.position = function (id, ppid, callback) {
var self = this,
endpoints = ldrly.config.getEndPoints(),
url_base = endpoints.ldrly.url,
url_resource = '/profile/user/' + id + '/assign/profile/position/' + ppid,
url = url_base + url_resource;
// username = data.username,
// password = data.password;
// function basicAuth(xhr) {
// var auth = 'Basic ' + window.btoa(username + ":" + password);
// xhr.setRequestHeader('Authorization', auth);
// }
var request = $.ajax(
{
url : url,
type : 'DELETE',
// beforeSend: basicAuth,
// data : JSON.stringify(data),
contentType : 'application/json; charset=utf-8',
dataType : 'json',
headers : {
'Accept' : 'application/json'
}
}
);
request.done(function (result) {
callback(undefined, result);
});
request.always(function (result) {
});
request.fail(function (XHR, textStatus, errorThrown) {
console.log("Error! " + textStatus + ':' + errorThrown);
//Create an Error Object
var error = { responseText : XHR.responseText, status : XHR.leaderboardus, statusText : XHR.leaderboardusText };
//Pass back the Error
callback(error);
});
}; |
var striptags = require('striptags'),
mongoosastic = require('mongoosastic'),
mongoose = require('mongoose'),
Schema = mongoose.Schema,
_ = require('lodash'),
UserModel = require('../user/model'),
TagModel = require('../tag/model');
var BookmarkSchema = new Schema({
name: {
type: String,
required: true
},
url: {
type: String,
required: true,
unique: true
},
content: {
type: String,
// required: true,
es_indexed: true
},
tagString: String,
tags: [
{
type: Schema.Types.ObjectId,
ref: 'Tag'
}
]
});
BookmarkSchema.methods = {
setTags: function(str) {
var instance = this;
var tagArray = str.split(", ");
_(tagArray).forEach(function(tag) {
TagModel.create({name: tag}, function(err, newTag) {
if (err) {
next(err);
} else {
instance.tags.push(newTag);
}
});
});
}
validateName: function(next) {
if (this.name) {
next();
} else {
this.name = this.url;
next();
}
},
getContent: function(req, res, body) {
var instance = this;
instance.setContent(body);
instance.save(function(err, saved) {
if (err) {
next(err);
} else {
instance.on('es-indexed', function(err, response) {
if (err) {
next(err);
}
});
UserModel.findById(req.payload._id)
.exec(function(err, user) {
if (err) {
next(err);
} else {
user.bookmarks.push(saved);
user.save(function(err, user) {
if (err) {
next (err);
} else {
res.json(saved);
}
});
}
});
}
});
},
setContent: function(body) {
this.content = striptags(body).replace(/\s+/g, ' ');
}
};
BookmarkSchema.pre('validate', function(next) {
this.validateName(next);
});
BookmarkSchema.plugin(mongoosastic);
module.exports = mongoose.model('Bookmark', BookmarkSchema); |
/*
Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang( 'basicstyles', 'lt', {
bold: 'Pusjuodis',
italic: 'Kursyvas',
strike: 'Perbrauktas',
subscript: 'Apatinis indeksas',
superscript: 'Viršutinis indeksas',
underline: 'Pabrauktas'
} );
|
(function (){
'use strict';
angular.module('eliteApp').directive('markdown', [markdown]);
function markdown(Showdown) {
var converter = new showdown.Converter();
var directive = {
link: link,
restrict: 'A'
};
return directive;
function link(scope, element, attrs){
attrs.$observe('markdown', function (value) {
var markup = converter.makeHtml(value);
element.html(markup);
});
};
}
})(); |
foo(5, 6) > 7 |
(function () {
'use strict';
angular
.module('sample-with-tests', ['ngRoute'])
.config(['$routeProvider', '$locationProvider',
function ($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
controller: 'SampleController',
templateUrl: 'views/content.html'
})
.otherwise({
redirectTo: '/'
});
$locationProvider.html5Mode(true);
}
]);
})();
|
var gulp = require('gulp'),
browserSync = require('browser-sync'),
config = require('../config'),
chalk = require('chalk'),
PushBullet = require('pushbullet');
var connection = {};
/**
* Run the build task and start a server with BrowserSync
*/
gulp.task('browsersync', function() {
// Serve files and connect browsers
browserSync(null, {
server: {
baseDir: config.destPath
},
logConnections: false,
debugInfo: false,
open: true
}, function (err, data) {
if (err !== null) {
console.log(
chalk.red('✘ Setting up a local server failed... Please try again. Aborting.\n') +
chalk.red(err)
);
process.exit(0);
}
// Store started state globally
connection.external = data.options.external;
connection.port = data.options.port;
config.server.lrStarted = true;
if(config.pushbullet.enabled){
var pusher = new PushBullet('rBXwIUuQRJkcgOZ1OkWgPAqBKTWMFEHu');
for(var i=0; i<config.pushbullet.user.length; i++){
pusher.link(config.pushbullet.user[i].email, 'Web Starter Kit', connection.external+':'+connection.port, function(error, response) {
if(err){
console.log(chalk.red('✘ Error pushing to devices! '+ err));
}
else{
console.log(chalk.green('Successful pushing to '+response.receiver_email_normalized+'!'));
}
});
}
}
else{
console.log(chalk.green('Pushbullet disabled!'));
}
});
});
|
/* 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: Kyle Scholz http://kylescholz.com/
* Copyright: 2006-2007
*/
/**
* SnowflakeLayout
*
* @author Kyle Scholz
*
* @version 0.3.3
*
* @param {DOMElement} container
*/
var SnowflakeLayout = function( container, useVectorGraphics ) {
this.container = container;
this.containerLeft=0; this.containerTop=0;
this.containerWidth=0; this.containerHeight=0;
this.svg = useVectorGraphics && document.implementation.hasFeature("org.w3c.dom.svg", '1.1') ? true : false;
// Render model with SVG if it's supported.
if ( this.svg ) {
this.view = new SVGGraphView( container, 1 );
// Otherwise, use HTML.
} else {
this.view = new HTMLGraphView( container, 1 );
}
// Create the model that we'll use to represent the nodes and relationships
// in our graph.
this.model = new SnowflakeGraphModel( this.view );
this.model.start();
this.setSize();
// for queueing loaders
this.dataNodeQueue = new Array();
// the data graph defines the nodes and edges
this.dataGraph = new DataGraph();
this.dataGraph.subscribe( this );
// if this is IE, turn on caching of javascript-loaded images explicitly
if ( document.all ) {
document.createStyleSheet().addRule('html',
'filter:expression(document.execCommand("BackgroundImageCache", false, true))' );
}
// attach an onresize event
var resizeEvent = new EventHandler( this, this.setSize );
if (window.addEventListener) {
window.addEventListener("resize",resizeEvent,false);
} else {
window.attachEvent("onresize",resizeEvent);
}
// attach an onmousemove event
if (window.Event) { document.captureEvents(Event.MOUSEMOVE); }
var mouseMoveEvent = new EventHandler( this, this.handleMouseMoveEvent );
if (document.addEventListener) {
document.addEventListener("mousemove",mouseMoveEvent,false);
} else {
document.attachEvent("onmousemove",mouseMoveEvent);
}
// attach an onmouseup event
var mouseUpEvent = new EventHandler( this, this.handleMouseUpEvent );
if (document.addEventListener) {
document.addEventListener("mouseup",mouseUpEvent,false);
} else {
document.attachEvent("onmouseup",mouseUpEvent);
}
this.config = new this.defaultConfig( this );
}
/*
* Respond to a resize event in the browser.
*/
SnowflakeLayout.prototype.setSize = function() {
if ( this.container.tagName == "BODY" ) {
// Get the size of our window.
if (document.all) {
this.containerWidth = document.body.offsetWidth - 5;
this.containerHeight = document.documentElement.offsetHeight - 5;
} else {
this.containerWidth = window.innerWidth - 5;
this.containerHeight = window.innerHeight - 5;
}
this.containerLeft = 0;
this.containerTop = 0;
} else {
this.containerWidth = this.container.offsetWidth;
this.containerHeight = this.container.offsetHeight;
this.containerLeft = this.container.offsetLeft;
this.containerTop = this.container.offsetTop;
}
this.view.setSize( this.containerLeft, this.containerTop,
this.containerWidth, this.containerHeight );
var rootNode = this.model.findRoot();
if ( rootNode ) { this.model.setNodePosition( rootNode, true ); }
}
/*
* A default mousemove handler. Moves the selected node and updates child
* positions according to geometric model.
*
* @param {Object} e
*/
SnowflakeLayout.prototype.handleMouseMoveEvent = function( e ) {
if ( this.model.selected && !this.model.nodes[this.model.selected].fixed ) {
// TODO: This is a very temporary fix. In Firefox 2, our EventHandler
// factory piles mouse events onto the arguments list.
e = arguments[arguments.length-1];
var mouseX = e.pageX ? e.pageX : e.clientX;
var mouseY = e.pageY ? e.pageY : e.clientY;
mouseX -= this.view.centerX;
mouseY -= this.view.centerY;
var node = this.model.nodes[this.model.selected];
if ( node.parent ) {
// set the node position
node.positionX=mouseX/this.view.skewX;
// TODO: fix skew
node.positionY=mouseY/this.view.skewY;
// determine new angle and radius
var dx = node.parent.positionX-node.positionX;
var dy = node.parent.positionY-node.positionY;
var d = Math.sqrt(dx*dx+dy*dy);
dx = dx/this.view.skewX;
dy = dy/this.view.skewY;
// TODO: fix skew
var t = Math.acos( dx/d ) * (180/Math.PI);
if ( node.positionY > node.parent.positionY ) {
t*=(-1);
}
t=90-t;
if ( (node.targetT - t) < -180) {
t-=360;
}
node.rootAngle=t;
node.positionR=d;
node.positionT=t;
node.updateChildren();
this.model.setNodePosition( node );
}
}
}
/*
* A default mouseup handler. Resets the selected node's position
* and clears the selection.
*/
SnowflakeLayout.prototype.handleMouseUpEvent = function() {
if ( this.model.selected ) {
var node = this.model.nodes[this.model.selected];
node.parent.updateChildren();
this.model.setNodePosition( node.parent );
this.model.selected = null;
}
}
/*
* A default mousedown handler. Sets the selected node.
*
* @param {Number} id
*/
SnowflakeLayout.prototype.handleMouseDownEvent = function( id ) {
this.model.selected = id;
}
/*
* Handle a new node.
*
* @param {DataGraphNode} dataNode
*/
SnowflakeLayout.prototype.newDataGraphNode = function( dataNode ) {
this.enqueueNode( dataNode );
}
SnowflakeLayout.prototype.newDataGraphEdge = function( nodeA, nodeB ) { }
/*
* Enqueue a node for modeling later.
*
* @param {DataGraphNode} dataNode
*/
SnowflakeLayout.prototype.enqueueNode = function( dataNode ) {
this.dataNodeQueue.push( dataNode );
}
/*
* Dequeue a node and create a particle representation in the model.
*
* @param {DataGraphNode} dataNode
*/
SnowflakeLayout.prototype.dequeueNode = function() {
var node = this.dataNodeQueue.shift();
if ( node ) {
this.addNode( node );
return true;
}
return false;
}
/*
* Called by timer to control dequeuing of nodes into addNode.
*/
SnowflakeLayout.prototype.update = function() {
this.dequeueNode();
}
/*
* Clear all nodes and edges connected to the root.
*/
SnowflakeLayout.prototype.clear = function( modelNode ) {
var rootNode = this.model.findRoot(modelNode);
if ( rootNode ) {
this.model.removeNode(rootNode);
this.model.updateQueue = [];
}
}
/*
* Recenter the graph on the specified node.
*/
SnowflakeLayout.prototype.recenter = function( modelNode ) {
var root = this.model.findRoot( modelNode );
modelNode.emancipate();
modelNode.targetX = 0;
modelNode.targetY = 0;
this.clear( root );
this.model.updateQueue.push(modelNode);
}
/*
* Create a default configuration object with a reference to our layout.
*
* @param {SnowflakeLayout} layout
*/
SnowflakeLayout.prototype.defaultConfig = function( layout ) {
// A default configuration class. This is used if a
// className was not indicated in your dataNode or if the
// indicated class was not found.
this._default={
model: function( dataNode ) {
return {
childRadius: 80,
fanAngle: dataNode.root ? 360: 120,
rootAngle: 0
};
},
view: function( dataNode, modelNode ) {
return layout.defaultNodeView( dataNode, modelNode );
}
}
}
/*
* Add a particle to the model and view.
*
* @param {DataGraphNode} node
*/
SnowflakeLayout.prototype.addNode = function( dataNode ) {
var modelNode = this.makeNodeModel(dataNode);
var domElement = this.makeNodeView( dataNode, modelNode );
var viewNode = this.view.addNode( modelNode, domElement );
dataNode.modelNode = modelNode;
dataNode.viewNode = viewNode;
return dataNode;
}
/* Build node views from configuration
*
* @param {DataGraphNode} dataNode
* @param {SnowflakeNode} modelNode
*/
SnowflakeLayout.prototype.makeNodeView = function( dataNode, modelNode ) {
var configNode = (dataNode.type in this.config) ? this.config[dataNode.type] : this.config['_default'];
return configNode.view( dataNode, modelNode );
}
/* Build model nodes from configuration
*
* @param {DataGraphNode} dataNode
*/
SnowflakeLayout.prototype.makeNodeModel = function( dataNode ) {
var configNode = (dataNode.type in this.config) ? this.config[dataNode.type] : this.config['_default'];
for( var attribute in configNode.model(dataNode) ) {
dataNode[attribute] = configNode.model(dataNode)[attribute];
}
var modelNode = this.model.addNode( dataNode.childRadius, dataNode.fanAngle, dataNode.rootAngle );
if ( dataNode.parent ) {
dataNode.parent.modelNode.addChild(modelNode);
modelNode.positionX = dataNode.parent.modelNode.positionX;
modelNode.positionY = dataNode.parent.modelNode.positionY;
var props = this.viewEdgeBuilder(dataNode.parent, dataNode);
this.view.addEdge(modelNode, dataNode.parent.modelNode, props);
return modelNode;
} else {
this.model.updateQueue.push( modelNode );
return modelNode;
}
}
/* Default node view builder
*
* @param {SnowflakeNode} modelNode
* @param {DataNode} dataNode
*/
SnowflakeLayout.prototype.defaultNodeView = function( dataNode, modelNode ) {
var nodeElement;
if ( this.svg ) {
nodeElement = document.createElementNS("http://www.w3.org/2000/svg", "circle");
nodeElement.setAttribute('stroke', '#444444');
nodeElement.setAttribute('stroke-width', '.25px');
nodeElement.setAttribute('fill', "#aaaaaa");
nodeElement.setAttribute('r', 6 + 'px');
nodeElement.onmousedown = new EventHandler( this, this.handleMouseDownEvent, modelNode.id )
} else {
nodeElement = document.createElement( 'div' );
nodeElement.style.position = "absolute";
nodeElement.style.width = "12px";
nodeElement.style.height = "12px";
nodeElement.style.backgroundImage = "url(http://kylescholz.com/cgi-bin/bubble.pl?title=&r=12&pt=8&b=444444&c=aaaaaa)";
nodeElement.innerHTML = '<img width="1" height="1">';
nodeElement.onmousedown = new EventHandler( this, this.handleMouseDownEvent, modelNode.id )
}
return nodeElement;
}
/* Default edge view builder
*
* @param {DataNode} dataNodeSrc
* @param {DataNode} dataNodeDest
*/
SnowflakeLayout.prototype.makeEdgeView = function( dataNodeSrc, dataNodeDest ) {
var props;
if ( this.svg ) {
props = {
'stroke': '#888888',
'stroke-width': '2px',
'stroke-dasharray': '2,4'
}
} else {
props = {
'pixelColor': '#888888',
'pixelWidth': '2px',
'pixelHeight': '2px',
'pixels': 5
}
}
return props;
}
SnowflakeLayout.prototype.viewEdgeBuilder = SnowflakeLayout.prototype.makeEdgeView; |
/* */
var _curry2 = require('./internal/_curry2');
var _dispatchable = require('./internal/_dispatchable');
var _xany = require('./internal/_xany');
module.exports = _curry2(_dispatchable('any', _xany, function any(fn, list) {
var idx = 0;
while (idx < list.length) {
if (fn(list[idx])) {
return true;
}
idx += 1;
}
return false;
}));
|
module.exports = function(config){
config.set({
basePath : '../',
files : [
'app/lib/angular/angular.js',
'http://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular.min.js',
'test/lib/angular/angular-mocks.js',
'app/js/*.js',
'test/unit/*.js'
],
exclude : [
'app/lib/angular/angular-loader.js',
'app/lib/angular/*.min.js',
'app/lib/angular/angular-scenario.js'
],
autoWatch : true,
frameworks: ['jasmine'],
browsers : ['Chrome'],
plugins : [
'karma-junit-reporter',
'karma-chrome-launcher',
'karma-firefox-launcher',
'karma-jasmine'
],
junitReporter : {
outputFile: 'test_out/unit.xml',
suite: 'unit'
}
})}
|
import React from 'react';
class Counter extends React.Component {
render() {
const {count, decrease, increase} = this.props;
return (
<div className="container">
<h2>This is counter</h2>
<p>Counter: <span className="count">{count}</span></p>
<button className="button-decrease" onClick={decrease}>-</button>
<button className="button-increase" onClick={increase}>+</button>
</div>
);
}
}
export default Counter;
|
'use strict';
var IoTServer = require("../iot");
var inquirer = require("inquirer");
var chalk = require('chalk');
inquirer.prompt([{
type: "input",
name: "iotBaseURL",
message: "Enter the URL to the IoT Server",
default: "http://iotserver:7101"
}], function(answers) {
var iot = new IoTServer(answers.iotBaseURL);
iot.setPrincipal('iot', 'welcome1');
var sharedSecret = "secret";
var device;
iot.createDevice(sharedSecret, "JS Gateway")
.then(function (gateway) {
device = gateway;
console.log(chalk.bold("Gateway created: ") + chalk.cyan(gateway.getID()));
return gateway.activate([iot.CAPABILITIES.direct_activation, iot.CAPABILITIES.indirect_activation]);
})
.then(function (gateway) {
var attributes = {
manufacturer: "My Dude",
endpointName: "Dude!",
description: "node description"
};
return gateway.indirectEnrollDevice(attributes);
})
.then(function (response) {
console.log(
chalk.bold("Indirect Device enrolled. ID:"),
chalk.cyan(response.body.endpointId));
// leaking endointId
return device.delete();
})
.then(function (gateway) {
console.log(chalk.bold("Gateway deleted."));
})
.catch(function (error) {
console.log(chalk.bold.red("*** Error ***"));
console.log(error.body || error);
console.trace();
if (device) device.delete();
});
});
|
var app = angular.module("styleguide.controllers", [
"main-controller",
"section-controller",
"stack-controller",
"detail-controller",
"add-controller",
"edit-controller"
]); |
'use strict';
/**
* Module dependencies
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
/**
* Student Schema
*/
var StudentSchema = new Schema({
created: {
type: Date,
default: Date.now
},
title: {
type: String,
default: '',
trim: true,
required: 'Title cannot be blank'
},
content: {
type: String,
default: '',
trim: true
},
user: {
type: Schema.ObjectId,
ref: 'User'
}
});
mongoose.model('Student', StudentSchema);
|
module.exports = {
'secret': 'Long, random string of characters',
'mongouri': 'mongodb://127.0.0.1:27017/UselessJS-tests',
'tokensExpiry': 1440 // in seconds
};
|
'use strict';
var gulp = require('gulp');
var argv = require('yargs').argv;
var rename = require('gulp-rename');
var replace = require('gulp-replace');
var camel = require('to-camel-case');
var _gulp;
var api = {
config: config,
task: task
};
var generators = [['list', '']];
var templatesPath = './';
var gulpTaskCreated = false;
function config (options) {
if (!options.templatesPath || !options.gulp) {
console.log('templatesPath or gulp parameters not set in config correctly.');
return;
}
_gulp = options.gulp;
templatesPath += options.templatesPath + '/';
}
function task (placeholder, destination) {
if (placeholder && destination) {
generators.push([placeholder, destination]);
if (!gulpTaskCreated) {
gulpTaskCreated = true;
// this function should run once because it iterates on the flags
// the 'dogen' task gets and runs the appropriate the generator
createDogenGulpTask();
}
}
}
function createDogenGulpTask () {
_gulp.task('dogen', function(){
var excludeKeys = '_$0';
var args = Object.keys(argv).filter(function (key) {
return excludeKeys.indexOf(key) === -1;
});
var placeholderKey = args[0];
var placeholderValue = argv[placeholderKey];
var path = argv.path;
if (argv.list) {
listGeneratorsToConsole();
return;
}
generators.forEach(function(task){
var placeholder = task[0];
var destination = task[1];
if (path !== undefined) {
destination += path + '/';
}
if (placeholderValue !== undefined && placeholderKey === placeholder) {
return creator(placeholder, placeholderValue, destination);
}
});
});
}
function creator (placeholder, placeholderValue, dest) {
var templatePlaceholder = '_' + placeholder + '_';
var reNormal = new RegExp('(' + templatePlaceholder + ')', 'gm');
var reCamelCase = new RegExp('(=' + placeholder + '=)', 'gm');
var placeholderValueCamelCase = camel(placeholderValue);
console.log('Creating', placeholder, ':', placeholderValue, 'in', dest);
return _gulp.src(templatesPath + templatePlaceholder + '/**/*')
.pipe(rename(function (path) {
if (path.basename.indexOf(templatePlaceholder) > -1){
path.basename = path.basename.replace(templatePlaceholder, placeholderValue);
}
}))
.pipe(replace(reNormal, placeholderValue))
.pipe(replace(reCamelCase, placeholderValueCamelCase))
.pipe(_gulp.dest(dest + placeholderValue));
}
function listGeneratorsToConsole () {
var list = generators.map(function(generator){
return '\t' + generator.join(': ');
});
list.shift();
console.log('\navailable dogen tasks:\n');
console.log(list.join('\n'), '\n');
}
module.exports = api;
|
// Based on https://github.com/mattdesl/glsl-fxaa
import fxaa from './modules/fxaa/fxaa.glsl.js';
export default /* glsl */`
precision highp float;
uniform sampler2D tMap;
uniform vec2 uResolution;
in vec2 v_rgbNW;
in vec2 v_rgbNE;
in vec2 v_rgbSW;
in vec2 v_rgbSE;
in vec2 v_rgbM;
in vec2 vUv;
out vec4 FragColor;
${fxaa}
void main() {
FragColor = fxaa(tMap, vUv * uResolution, uResolution, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);
}
`;
|
'use strict';
const addressParser = require('./utils').addressParser;
const addressFormatter = require('./utils').addressFormatter;
const format = require('string-format');
const escapeStringRegexp = require('escape-string-regexp');
function isValidPassthroughType(passthrough) {
return typeof passthrough === 'function' ||
typeof passthrough === 'string' ||
passthrough instanceof RegExp;
}
function shouldPassthrough(passthrough, toAddr) {
if (typeof passthrough === 'function') {
return passthrough(toAddr);
}
if (typeof passthrough === 'string') {
passthrough = new RegExp(escapeStringRegexp(passthrough));
}
return passthrough.test(toAddr);
}
function trap(options) {
options = options || {};
const subject = options.subject || '[DEBUG] - To: {0}, Subject: {1}';
const to = options.to || '';
const passthrough = options.passthrough || false;
return (mail, callback) => {
if (!mail || !mail.data) {
return callback();
}
const toAddrs = addressParser(mail.data.to || '').map(x => addressFormatter(x));
if (toAddrs.length === 0) {
return callback();
}
if (!to) {
return callback(new Error('options.to is missed.'));
}
if (passthrough) {
if (!isValidPassthroughType(passthrough)) {
return callback(new Error('options.passthrough can be only a string, regex or function.'));
}
if (toAddrs.length > 1) {
return callback(new Error('options.passthrough can be used with a single recipient only.'));
}
if (shouldPassthrough(passthrough, toAddrs.join())) {
return callback();
}
}
// TODO: intercept cc
// TODO: intercept bcc
mail.data.subject = format(subject, toAddrs.join(','), mail.data.subject);
mail.data.to = to;
callback();
};
}
module.exports = trap;
|
App.ApplicationController = Ember.Controller.extend({
currentUser: {},
isLoggedIn: false,
schools: [],
init: function() {
this._super();
// first check for the logged in user
var hasCurrrentUser = (Parse.User.current() != null);
this.set('isLoggedIn', hasCurrrentUser);
if(hasCurrrentUser) {
this.send('setCurrentUser', Parse.User.current());
}
// load the schools
this.send("getSchools");
},
actions: {
deactivateNavLinks: function() {
$("li[id$='-link']").removeClass("active");
},
setCurrentUser: function(user) {
if(user && user.attributes) {
// TODO: SET SCHOOL , call fetch
// var school = user.get("school") || {};
this.set('currentUser', App.User.create(user.attributes));
this.set('isLoggedIn', true);
// now set the user's events, snapshots
this.send('getCurrentUserEvents', user);
this.send('getCurrentUserSnaps', user);
}
},
navigateTo: function(route) {
this.transitionToRoute(route);
this.send('deactivateNavLinks');
$("#" + route + "-link").addClass("active");
},
logout: function() {
Parse.User.logOut();
window.location = "/";
},
// This function will retreive the events for the user
getCurrentUserEvents: function(user) {
var _self = this;
App.Event.find(undefined, user, function(results, error) {
if (!error) {
if(results && results.length > 0) {
_self.get('currentUser').set('events', results);
}
}
}
);
},
// This function will retreive the snapshots for the user
getCurrentUserSnaps: function(user) {
var _self = this;
App.Snapshot.find(undefined, user, function(results, error) {
if (!error) {
if(results && results.length > 0) {
_self.get('currentUser').set('snaps', results);
}
}
}
);
},
// retrieve all schools
getSchools: function() {
var _self = this;
App.School.find(undefined, function(results, error) {
if (!error) {
if(results && results.length > 0) {
_self.set('schools', results);
}
}
}
);
}
}
}); |
AtajoUiModule
.controller('$atajoUiHeaderBar', [
'$scope',
'$element',
'$attrs',
'$q',
'$atajoUiConfig',
'$atajoUiHistory',
function($scope, $element, $attrs, $q, $atajoUiConfig, $atajoUiHistory) {
var TITLE = 'title';
var BACK_TEXT = 'back-text';
var BACK_BUTTON = 'back-button';
var DEFAULT_TITLE = 'default-title';
var PREVIOUS_TITLE = 'previous-title';
var HIDE = 'hide';
var self = this;
var titleText = '';
var previousTitleText = '';
var titleLeft = 0;
var titleRight = 0;
var titleCss = '';
var isBackEnabled = false;
var isBackShown = true;
var isNavBackShown = true;
var isBackElementShown = false;
var titleTextWidth = 0;
self.beforeEnter = function(viewData) {
$scope.$broadcast('$atajoUiView.beforeEnter', viewData);
};
self.title = function(newTitleText) {
if (arguments.length && newTitleText !== titleText) {
getEle(TITLE).innerHTML = newTitleText;
titleText = newTitleText;
titleTextWidth = 0;
}
return titleText;
};
self.enableBack = function(shouldEnable, disableReset) {
// whether or not the back button show be visible, according
// to the navigation and history
if (arguments.length) {
isBackEnabled = shouldEnable;
if (!disableReset) self.updateBackButton();
}
return isBackEnabled;
};
self.showBack = function(shouldShow, disableReset) {
// different from enableBack() because this will always have the back
// visually hidden if false, even if the history says it should show
if (arguments.length) {
isBackShown = shouldShow;
if (!disableReset) self.updateBackButton();
}
return isBackShown;
};
self.showNavBack = function(shouldShow) {
// different from showBack() because this is for the entire nav bar's
// setting for all of it's child headers. For internal use.
isNavBackShown = shouldShow;
self.updateBackButton();
};
self.updateBackButton = function() {
var ele;
if ((isBackShown && isNavBackShown && isBackEnabled) !== isBackElementShown) {
isBackElementShown = isBackShown && isNavBackShown && isBackEnabled;
ele = getEle(BACK_BUTTON);
ele && ele.classList[ isBackElementShown ? 'remove' : 'add' ](HIDE);
}
if (isBackEnabled) {
ele = ele || getEle(BACK_BUTTON);
if (ele) {
if (self.backButtonIcon !== $atajoUiConfig.backButton.icon()) {
ele = getEle(BACK_BUTTON + ' .icon');
if (ele) {
self.backButtonIcon = $atajoUiConfig.backButton.icon();
ele.className = 'icon ' + self.backButtonIcon;
}
}
if (self.backButtonText !== $atajoUiConfig.backButton.text()) {
ele = getEle(BACK_BUTTON + ' .back-text');
if (ele) {
ele.textContent = self.backButtonText = $atajoUiConfig.backButton.text();
}
}
}
}
};
self.titleTextWidth = function() {
var element = getEle(TITLE);
if ( element ) {
// If the element has a nav-bar-title, use that instead
// to calculate the width of the title
var children = angular.element(element).children();
for ( var i = 0; i < children.length; i++ ) {
if ( angular.element(children[i]).hasClass('nav-bar-title') ) {
element = children[i];
break;
}
}
}
var bounds = atajoui.DomUtil.getTextBounds(element);
titleTextWidth = Math.min(bounds && bounds.width || 30);
return titleTextWidth;
};
self.titleWidth = function() {
var titleWidth = self.titleTextWidth();
var offsetWidth = getEle(TITLE).offsetWidth;
if (offsetWidth < titleWidth) {
titleWidth = offsetWidth + (titleLeft - titleRight - 5);
}
return titleWidth;
};
self.titleTextX = function() {
return ($element[0].offsetWidth / 2) - (self.titleWidth() / 2);
};
self.titleLeftRight = function() {
return titleLeft - titleRight;
};
self.backButtonTextLeft = function() {
var offsetLeft = 0;
var ele = getEle(BACK_TEXT);
while (ele) {
offsetLeft += ele.offsetLeft;
ele = ele.parentElement;
}
return offsetLeft;
};
self.resetBackButton = function(viewData) {
if ($atajoUiConfig.backButton.previousTitleText()) {
var previousTitleEle = getEle(PREVIOUS_TITLE);
if (previousTitleEle) {
previousTitleEle.classList.remove(HIDE);
var view = (viewData && $atajoUiHistory.getViewById(viewData.viewId));
var newPreviousTitleText = $atajoUiHistory.backTitle(view);
if (newPreviousTitleText !== previousTitleText) {
previousTitleText = previousTitleEle.innerHTML = newPreviousTitleText;
}
}
var defaultTitleEle = getEle(DEFAULT_TITLE);
if (defaultTitleEle) {
defaultTitleEle.classList.remove(HIDE);
}
}
};
self.align = function(textAlign) {
var titleEle = getEle(TITLE);
textAlign = textAlign || $attrs.alignTitle || $atajoUiConfig.navBar.alignTitle();
var widths = self.calcWidths(textAlign, false);
if (isBackShown && previousTitleText && $atajoUiConfig.backButton.previousTitleText()) {
var previousTitleWidths = self.calcWidths(textAlign, true);
var availableTitleWidth = $element[0].offsetWidth - previousTitleWidths.titleLeft - previousTitleWidths.titleRight;
if (self.titleTextWidth() <= availableTitleWidth) {
widths = previousTitleWidths;
}
}
return self.updatePositions(titleEle, widths.titleLeft, widths.titleRight, widths.buttonsLeft, widths.buttonsRight, widths.css, widths.showPrevTitle);
};
self.calcWidths = function(textAlign, isPreviousTitle) {
var titleEle = getEle(TITLE);
var backBtnEle = getEle(BACK_BUTTON);
var x, y, z, b, c, d, childSize, bounds;
var childNodes = $element[0].childNodes;
var buttonsLeft = 0;
var buttonsRight = 0;
var isCountRightOfTitle;
var updateTitleLeft = 0;
var updateTitleRight = 0;
var updateCss = '';
var backButtonWidth = 0;
// Compute how wide the left children are
// Skip all titles (there may still be two titles, one leaving the dom)
// Once we encounter a titleEle, realize we are now counting the right-buttons, not left
for (x = 0; x < childNodes.length; x++) {
c = childNodes[x];
childSize = 0;
if (c.nodeType == 1) {
// element node
if (c === titleEle) {
isCountRightOfTitle = true;
continue;
}
if (c.classList.contains(HIDE)) {
continue;
}
if (isBackShown && c === backBtnEle) {
for (y = 0; y < c.childNodes.length; y++) {
b = c.childNodes[y];
if (b.nodeType == 1) {
if (b.classList.contains(BACK_TEXT)) {
for (z = 0; z < b.children.length; z++) {
d = b.children[z];
if (isPreviousTitle) {
if (d.classList.contains(DEFAULT_TITLE)) continue;
backButtonWidth += d.offsetWidth;
} else {
if (d.classList.contains(PREVIOUS_TITLE)) continue;
backButtonWidth += d.offsetWidth;
}
}
} else {
backButtonWidth += b.offsetWidth;
}
} else if (b.nodeType == 3 && b.nodeValue.trim()) {
bounds = atajoui.DomUtil.getTextBounds(b);
backButtonWidth += bounds && bounds.width || 0;
}
}
childSize = backButtonWidth || c.offsetWidth;
} else {
// not the title, not the back button, not a hidden element
childSize = c.offsetWidth;
}
} else if (c.nodeType == 3 && c.nodeValue.trim()) {
// text node
bounds = atajoui.DomUtil.getTextBounds(c);
childSize = bounds && bounds.width || 0;
}
if (isCountRightOfTitle) {
buttonsRight += childSize;
} else {
buttonsLeft += childSize;
}
}
// Size and align the header titleEle based on the sizes of the left and
// right children, and the desired alignment mode
if (textAlign == 'left') {
updateCss = 'title-left';
if (buttonsLeft) {
updateTitleLeft = buttonsLeft + 15;
}
if (buttonsRight) {
updateTitleRight = buttonsRight + 15;
}
} else if (textAlign == 'right') {
updateCss = 'title-right';
if (buttonsLeft) {
updateTitleLeft = buttonsLeft + 15;
}
if (buttonsRight) {
updateTitleRight = buttonsRight + 15;
}
} else {
// center the default
var margin = Math.max(buttonsLeft, buttonsRight) + 10;
if (margin > 10) {
updateTitleLeft = updateTitleRight = margin;
}
}
return {
backButtonWidth: backButtonWidth,
buttonsLeft: buttonsLeft,
buttonsRight: buttonsRight,
titleLeft: updateTitleLeft,
titleRight: updateTitleRight,
showPrevTitle: isPreviousTitle,
css: updateCss
};
};
self.updatePositions = function(titleEle, updateTitleLeft, updateTitleRight, buttonsLeft, buttonsRight, updateCss, showPreviousTitle) {
var deferred = $q.defer();
// only make DOM updates when there are actual changes
if (titleEle) {
if (updateTitleLeft !== titleLeft) {
titleEle.style.left = updateTitleLeft ? updateTitleLeft + 'px' : '';
titleLeft = updateTitleLeft;
}
if (updateTitleRight !== titleRight) {
titleEle.style.right = updateTitleRight ? updateTitleRight + 'px' : '';
titleRight = updateTitleRight;
}
if (updateCss !== titleCss) {
updateCss && titleEle.classList.add(updateCss);
titleCss && titleEle.classList.remove(titleCss);
titleCss = updateCss;
}
}
if ($atajoUiConfig.backButton.previousTitleText()) {
var prevTitle = getEle(PREVIOUS_TITLE);
var defaultTitle = getEle(DEFAULT_TITLE);
prevTitle && prevTitle.classList[ showPreviousTitle ? 'remove' : 'add'](HIDE);
defaultTitle && defaultTitle.classList[ showPreviousTitle ? 'add' : 'remove'](HIDE);
}
atajoui.requestAnimationFrame(function() {
if (titleEle && titleEle.offsetWidth + 10 < titleEle.scrollWidth) {
var minRight = buttonsRight + 5;
var testRight = $element[0].offsetWidth - titleLeft - self.titleTextWidth() - 20;
updateTitleRight = testRight < minRight ? minRight : testRight;
if (updateTitleRight !== titleRight) {
titleEle.style.right = updateTitleRight + 'px';
titleRight = updateTitleRight;
}
}
deferred.resolve();
});
return deferred.promise;
};
self.setCss = function(elementClassname, css) {
atajoui.DomUtil.cachedStyles(getEle(elementClassname), css);
};
var eleCache = {};
function getEle(className) {
if (!eleCache[className]) {
eleCache[className] = $element[0].querySelector('.' + className);
}
return eleCache[className];
}
$scope.$on('$destroy', function() {
for (var n in eleCache) eleCache[n] = null;
});
}]);
|
version https://git-lfs.github.com/spec/v1
oid sha256:53b740ed042dc9e47986e61d1f960bd550aaf36b26a734665b86fa6d528124ba
size 2214
|
exports.seed = function(knex, Promise) {
// Deletes ALL existing entries
return knex('kudo').del()
.then(function () {
// Inserts seed entries
return knex('kudo').insert([
{
body: "Hey thanks for help on the ERD's",
to_user_id: 2,
from_user_id: 1,
votes: 5,
created_at: "Today",
from: "admin",
to: "devin-h"
},
{
body: "Hey thanks for help on the ERD's",
to_user_id: 2,
from_user_id: 3,
votes: 5,
created_at: "Today",
from: "jodan-f",
to: "devin-h"
},
{
body: "Hey thanks for help on the ERD'sn",
to_user_id: 3,
from_user_id: 2,
votes: 5,
created_at: "Today",
from: "devin-h",
to: "jordan-f"
}
]);
});
};
|
/* globals module, __dirname */
module.exports = {
context: __dirname + "/src",
entry: {
javascript: "./app.js",
},
output: {
filename: "app.js",
path: __dirname + "/dist",
publicPath: "http://localhost:9090/"
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loaders: ["react-hot", "babel-loader?stage=0"],
}
]
},
devServer: {
port: 9090
}
}
|
import {T} from './T'
import {filter} from './filter'
import {filter as filterRamda} from 'ramda'
const sampleObject = {
a: 1,
b: 2,
c: 3,
d: 4,
}
test('happy', () => {
const isEven = n => n % 2 === 0
expect(filter(isEven, [1, 2, 3, 4])).toEqual([2, 4])
expect(
filter(isEven, {
a: 1,
b: 2,
d: 3,
})
).toEqual({b: 2})
})
test('predicate when input is object', () => {
const obj = {
a: 1,
b: 2,
}
const predicate = (val, prop, inputObject) => {
expect(inputObject).toEqual(obj)
expect(typeof prop).toEqual('string')
return val < 2
}
expect(filter(predicate, obj)).toEqual({a: 1})
})
test('with object', () => {
const isEven = n => n % 2 === 0
const result = filter(isEven, sampleObject)
const expectedResult = {
b: 2,
d: 4,
}
expect(result).toEqual(expectedResult)
})
test('bad inputs difference between Ramda and Rambda', () => {
expect(() => filter(T, null)).toThrowWithMessage(
Error,
`Incorrect iterable input`
)
expect(() => filter(T)(undefined)).toThrowWithMessage(
Error,
`Incorrect iterable input`
)
expect(() => filterRamda(T, null)).toThrowWithMessage(
TypeError,
`Cannot read properties of null (reading 'filter')`
)
expect(() => filterRamda(T, undefined)).toThrowWithMessage(
TypeError,
`Cannot read properties of undefined (reading 'filter')`
)
})
|
restularIndex.controller('TableCtrl', function($scope, $filter, $compile, $interpolate){
$scope.interpolate = function(value) {
return $interpolate(value)($scope)
}
// route template
$scope.routes = singularRoutes
//resources
$scope.resource = "articles"
$scope.nestedResource = ""
// updates variables and template on resource or nestedResource update
$scope.$watchGroup(['resource', 'nestedResource'], function (newValues){
// newValues[0] == resource
// newValues[1] == nestedResource
// singular resource variables
downcaseNewValue = $filter('lowercase')(newValues[0])
upcaseNewValue = $filter('capitalize')(newValues[0])
$scope.singularDowncaseResource = $filter('transform')(downcaseNewValue, ['singularize'])
$scope.singularPropercaseResource = $filter('transform')(upcaseNewValue, ['singularize'])
$scope.pluralDowncaseResource = downcaseNewValue
if (newValues[1]) {
// show nested route templates IF nestedResource
$scope.routes = nestedRoutes
// nested resource variables
downcaseNestedResource = $filter('lowercase')(newValues[1])
$scope.singularDowncaseNestedResource = $filter('transform')(downcaseNestedResource, ['singularize'])
$scope.pluralDowncaseNestedResource = downcaseNestedResource
} else {
// show singularRoutes IF !nestedResource
$scope.routes = singularRoutes
}
});
}); |
export update from './update';
export changePassword from './changePassword';
export changeBankAccount from './changeBankAccount';
export sendConfirmationEmail from './sendConfirmationEmail';
export confirmEmail from './confirmEmail';
export attachInfo from './attachInfo'; |
'use strict';
// Author: ThemeREX.com
// forms-widgets.html scripts
//
(function($) {
$(document).ready(function() {
"use strict";
// Init Theme Core
Core.init();
// Init Demo JS
Demo.init();
// Time picker
$('.inline-tp').timepicker();
$('#timepicker1').timepicker({
beforeShow: function(input, inst) {
var newclass = 'allcp-form';
var themeClass = $(this).parents('.allcp-form').attr('class');
var smartpikr = inst.dpDiv.parent();
if (!smartpikr.hasClass(themeClass)) {
inst.dpDiv.wrap('<div class="' + themeClass + '"></div>');
}
}
});
$('#timepicker2').timepicker({
showOn: 'both',
buttonText: '<i class="imoon imoon-clock"></i>',
beforeShow: function(input, inst) {
var newclass = 'allcp-form';
var themeClass = $(this).parents('.allcp-form').attr('class');
var smartpikr = inst.dpDiv.parent();
if (!smartpikr.hasClass(themeClass)) {
inst.dpDiv.wrap('<div class="' + themeClass + '"></div>');
}
}
});
$('#timepicker3').timepicker({
showOn: 'both',
disabled: true,
buttonText: '<i class="imoon imoon-clock"></i>',
beforeShow: function(input, inst) {
var newclass = 'allcp-form';
var themeClass = $(this).parents('.allcp-form').attr('class');
var smartpikr = inst.dpDiv.parent();
if (!smartpikr.hasClass(themeClass)) {
inst.dpDiv.wrap('<div class="' + themeClass + '"></div>');
}
}
});
/* @date time picker
------------------------------------------------------------------ */
$('#datetimepicker1').datetimepicker({
prevText: '<i class="fa fa-chevron-left"></i>',
nextText: '<i class="fa fa-chevron-right"></i>',
beforeShow: function(input, inst) {
var newclass = 'allcp-form';
var themeClass = $(this).parents('.allcp-form').attr('class');
var smartpikr = inst.dpDiv.parent();
if (!smartpikr.hasClass(themeClass)) {
inst.dpDiv.wrap('<div class="' + themeClass + '"></div>');
}
}
});
$('#datetimepicker2').datetimepicker({
showOn: 'both',
buttonText: '<i class="fa fa-calendar-o"></i>',
prevText: '<i class="fa fa-chevron-left"></i>',
nextText: '<i class="fa fa-chevron-right"></i>',
beforeShow: function(input, inst) {
var newclass = 'allcp-form';
var themeClass = $(this).parents('.allcp-form').attr('class');
var smartpikr = inst.dpDiv.parent();
if (!smartpikr.hasClass(themeClass)) {
inst.dpDiv.wrap('<div class="' + themeClass + '"></div>');
}
}
});
$('#datetimepicker3').datetimepicker({
showOn: 'both',
buttonText: '<i class="fa fa-calendar-o"></i>',
disabled: true,
prevText: '<i class="fa fa-chevron-left"></i>',
nextText: '<i class="fa fa-chevron-right"></i>',
beforeShow: function(input, inst) {
var newclass = 'allcp-form';
var themeClass = $(this).parents('.allcp-form').attr('class');
var smartpikr = inst.dpDiv.parent();
if (!smartpikr.hasClass(themeClass)) {
inst.dpDiv.wrap('<div class="' + themeClass + '"></div>');
}
}
});
$('.inline-dtp').datetimepicker({
prevText: '<i class="fa fa-chevron-left"></i>',
nextText: '<i class="fa fa-chevron-right"></i>',
});
/* @date picker
------------------------------------------------------------------ */
$("#datepicker1").datepicker({
prevText: '<i class="fa fa-chevron-left"></i>',
nextText: '<i class="fa fa-chevron-right"></i>',
showButtonPanel: false,
beforeShow: function(input, inst) {
var newclass = 'allcp-form';
var themeClass = $(this).parents('.allcp-form').attr('class');
var smartpikr = inst.dpDiv.parent();
if (!smartpikr.hasClass(themeClass)) {
inst.dpDiv.wrap('<div class="' + themeClass + '"></div>');
}
}
});
$('#datepicker2').datepicker({
numberOfMonths: 3,
showOn: 'both',
buttonText: '<i class="fa fa-calendar-o"></i>',
prevText: '<i class="fa fa-chevron-left"></i>',
nextText: '<i class="fa fa-chevron-right"></i>',
beforeShow: function(input, inst) {
var newclass = 'allcp-form';
var themeClass = $(this).parents('.allcp-form').attr('class');
var smartpikr = inst.dpDiv.parent();
if (!smartpikr.hasClass(themeClass)) {
inst.dpDiv.wrap('<div class="' + themeClass + '"></div>');
}
}
});
$('#datepicker3').datepicker({
showOn: 'both',
disabled: true,
buttonText: '<i class="fa fa-calendar-o"></i>',
prevText: '<i class="fa fa-chevron-left"></i>',
nextText: '<i class="fa fa-chevron-right"></i>',
beforeShow: function(input, inst) {
var newclass = 'allcp-form';
var themeClass = $(this).parents('.allcp-form').attr('class');
var smartpikr = inst.dpDiv.parent();
if (!smartpikr.hasClass(themeClass)) {
inst.dpDiv.wrap('<div class="' + themeClass + '"></div>');
}
}
});
$('.inline-dp').datepicker({
numberOfMonths: 1,
prevText: '<i class="fa fa-chevron-left"></i>',
nextText: '<i class="fa fa-chevron-right"></i>',
showButtonPanel: false
});
/* @month picker
------------------------------------------------------------------ */
$("#monthpicker1").monthpicker({
changeYear: false,
stepYears: 1,
prevText: '<i class="fa fa-chevron-left"></i>',
nextText: '<i class="fa fa-chevron-right"></i>',
showButtonPanel: true,
beforeShow: function(input, inst) {
var newclass = 'allcp-form';
var themeClass = $(this).parents('.allcp-form').attr('class');
var smartpikr = inst.dpDiv.parent();
if (!smartpikr.hasClass(themeClass)) {
inst.dpDiv.wrap('<div class="' + themeClass + '"></div>');
}
}
});
$("#monthpicker2").monthpicker({
prevText: '<i class="fa fa-chevron-left"></i>',
nextText: '<i class="fa fa-chevron-right"></i>',
showOn: 'both',
buttonText: '<i class="fa fa-calendar-o"></i>',
showButtonPanel: true,
beforeShow: function(input, inst) {
var newclass = 'allcp-form';
var themeClass = $(this).parents('.allcp-form').attr('class');
var smartpikr = inst.dpDiv.parent();
if (!smartpikr.hasClass(themeClass)) {
inst.dpDiv.wrap('<div class="' + themeClass + '"></div>');
}
}
});
$("#monthpicker3").monthpicker({
changeYear: false,
stepYears: 1,
prevText: '<i class="fa fa-chevron-left"></i>',
nextText: '<i class="fa fa-chevron-right"></i>',
showOn: 'both',
buttonText: '<i class="fa fa-calendar-o"></i>',
showButtonPanel: true,
disabled: true,
});
$('.inline-mp').monthpicker({
prevText: '<i class="fa fa-chevron-left"></i>',
nextText: '<i class="fa fa-chevron-right"></i>',
showButtonPanel: false
});
/* @color picker
------------------------------------------------------------------ */
var cPicker1 = $("#colorpicker1"),
cPicker2 = $("#colorpicker2");
var cContainer1 = cPicker1.parents('.sfcolor').parent(),
cContainer2 = cPicker2.parents('.sfcolor').parent();
$(cContainer1).add(cContainer2).addClass('posr');
$("#colorpicker1").spectrum({
color: bgInfo,
appendTo: cContainer1,
containerClassName: 'sp-left'
});
$("#colorpicker2").spectrum({
color: bgPrimary,
appendTo: cContainer2,
containerClassName: 'sp-left',
showInput: true,
showPalette: true,
palette: [
[bgPrimary, bgSuccess, bgInfo],
[bgWarning, bgDanger, bgAlert],
[bgSystem, bgDark, bgBlack]
]
});
$("#colorpicker3").spectrum({
color: bgLightDr,
showInput: true
});
$(".inline-cp").spectrum({
color: bgInfo,
showInput: true,
showPalette: true,
chooseText: "Select Color",
flat: true,
palette: [
[bgPrimary, bgSuccess, bgInfo, bgWarning,
bgDanger, bgAlert, bgSystem, bgDark,
bgSystem, bgDark, bgBlack
]
]
});
$("#colorpicker1, #colorpicker2, #colorpicker3, .inline-cp").show();
/* @numeric stepper
------------------------------------------------------------------ */
$('#stepper1').stepper({
wheel_step: 0.1,
arrow_step: 0.2
});
$('#stepper2').stepper({
UI: false,
allowWheel: false
});
/* @ui slider
------------------------------------------------------------------ */
$("#slider1").slider({
range: "min",
min: 0,
max: 100,
value: 30,
slide: function(event, ui) {
$(".slider-countbox").val("$" + ui.value);
}
});
$("#slider2").slider({
range: true,
values: [27, 63]
});
$("#slider3").slider({
range: true,
values: [7, 53]
});
$("#slider4").slider({
range: true,
values: [57, 93]
});
$("#slider5").slider({
range: true,
values: [37, 63]
});
// Form Switcher
$('#form-switcher > button').on('click', function() {
var btnData = $(this).data('form-layout');
var btnActive = $('#form-elements-pane .allcp-form.active');
btnActive.removeClass('slideInUp').addClass('animated fadeOutRight animated-shorter');
btnActive.one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function() {
btnActive.removeClass('active fadeOutRight animated-shorter');
$('#' + btnData).addClass('active animated slideInUp animated-shorter')
});
});
// Cache DOM
var pageHeader = $('.content-header').find('b');
var allcpForm = $('.allcp-form');
var options = allcpForm.find('.option');
var switches = allcpForm.find('.switch');
var buttons = allcpForm.find('.button');
var Panel = allcpForm.find('.panel');
// Skin Switcher
$('#skin-switcher a').on('click', function() {
var btnData = $(this).data('form-skin');
$('#skin-switcher a').removeClass('item-active');
$(this).addClass('item-active')
allcpForm.each(function(i, e) {
var skins = 'theme-primary theme-info theme-success theme-warning theme-danger theme-alert theme-system theme-dark'
var panelSkins = 'panel-primary panel-info panel-success panel-warning panel-danger panel-alert panel-system panel-dark'
$(e).removeClass(skins).addClass('theme-' + btnData);
Panel.removeClass(panelSkins).addClass('panel-' + btnData);
pageHeader.removeClass().addClass('text-' + btnData);
});
$(options).each(function(i, e) {
if ($(e).hasClass('block')) {
$(e).removeClass().addClass('block mt15 option option-' + btnData);
} else {
$(e).removeClass().addClass('option option-' + btnData);
}
});
$('body').find('.ui-slider').each(function(i, e) {
$(e).addClass('slider-primary');
});
$(switches).each(function(i, ele) {
if ($(ele).hasClass('switch-round')) {
if ($(ele).hasClass('block')) {
$(ele).removeClass().addClass('block mt15 switch switch-round switch-' + btnData);
} else {
$(ele).removeClass().addClass('switch switch-round switch-' + btnData);
}
} else {
if ($(ele).hasClass('block')) {
$(ele).removeClass().addClass('block mt15 switch switch-' + btnData);
} else {
$(ele).removeClass().addClass('switch switch-' + btnData);
}
}
});
buttons.removeClass().addClass('button btn-' + btnData);
});
setTimeout(function() {
allcpForm.addClass('theme-primary');
Panel.addClass('panel-primary');
pageHeader.addClass('text-primary');
$(options).each(function(i, e) {
if ($(e).hasClass('block')) {
$(e).removeClass().addClass('block mt15 option option-primary');
} else {
$(e).removeClass().addClass('option option-primary');
}
});
$('body').find('.ui-slider').each(function(i, e) {
$(e).addClass('slider-primary');
});
$(switches).each(function(i, ele) {
if ($(ele).hasClass('switch-round')) {
if ($(ele).hasClass('block')) {
$(ele).removeClass().addClass('block mt15 switch switch-round switch-primary');
} else {
$(ele).removeClass().addClass('switch switch-round switch-primary');
}
} else {
if ($(ele).hasClass('block')) {
$(ele).removeClass().addClass('block mt15 switch switch-primary');
} else {
$(ele).removeClass().addClass('switch switch-primary');
}
}
});
buttons.removeClass().addClass('button btn-primary');
}, 800);
});
})(jQuery);
|
define([], function () {
return angular.module('test', ['ionic', 'starter.services.common', 'starter.resources']);
}); |
// ==UserScript==
// @name Duolingo Strength Overview
// @description Allows to overview strength of all skills and lessons of Duolingo in compact way.
// @namespace https://github.com/tstep
// @match *://www.duolingo.com/*
// @author Tatiana Stepanova
// @version 0.1
// ==/UserScript==
/*
Copyright (c) 2014 Tatiana Stepanova (https://github.com/tstep)
Licensed under the MIT License (MIT)
Full text of the license is available at https://raw.githubusercontent.com/tstep/DuoScripts/master/LICENSE
*/
function inject(f) {
var injectionInterval = window.setInterval(function() {
window.clearInterval(injectionInterval);
var script = document.createElement('script');
script.type = 'text/javascript';
script.setAttribute('name', 'strength_overview');
script.textContent = '(' + f.toString() + ')()';
document.body.appendChild(script);
}, 1000);
}
inject(main);
function main() {
console.log('Duolingo Strength Overview');
var user = duo.user;
var data = user.attributes.language_data[user.attributes.learning_language];
console.log(data.language_string + " strength: " + data.language_strength);
var skills = data.skills.models;
for (var i=0; i<skills.length; i++) {
var skill = skills[i];
console.log(skill.attributes.title + ': ' + skill.attributes.strength);
}
}
|
import React from 'react';
import KeyboardAwareScrollView from '@ui/KeyboardAwareScrollView';
import { Switch, Route, withRouter } from '@ui/NativeWebRouter';
import Header from '@ui/Header';
import BackgroundView from '@ui/BackgroundView';
import Progress from '@ui/Progress';
import ModalView from '@ui/ModalView';
import BillingAddress from './BillingAddress';
import PaymentMethod from './PaymentMethod';
import PaymentMethodConfirmation from './PaymentMethodConfirmation';
import Complete from './Complete';
function lastDirectory(pathname = '') {
const pathParts = pathname.split('/');
return pathParts.slice(pathParts.length - 1)[0];
}
const progressForLocation = ({ pathname }) => {
let step = 0;
const directory = lastDirectory(pathname);
if (directory === 'address') step = 1;
if (directory === 'method') step = 2;
if (directory === 'confirm' || directory === 'done') step = 3;
return step / 3; // 3 steps == start the user with progress
};
const Checkout = withRouter(({ match, location }) => (
<ModalView backTo="/give" onBackReplace>
<BackgroundView>
<Header titleText="Add Account" backButton />
<Progress progress={progressForLocation(location)} />
<KeyboardAwareScrollView>
<Switch>
<Route exact path={`${match.url}/address`} component={BillingAddress} />
<Route exact path={`${match.url}/method`} component={PaymentMethod} />
<Route exact path={`${match.url}/confirm`} component={PaymentMethodConfirmation} />
<Route exact path={`${match.url}/done`} component={Complete} />
</Switch>
</KeyboardAwareScrollView>
</BackgroundView>
</ModalView>
));
export default Checkout;
|
const CompositeXform = require('../../composite-xform');
const CfRuleExtXform = require('./cf-rule-ext-xform');
const ConditionalFormattingExtXform = require('./conditional-formatting-ext-xform');
class ConditionalFormattingsExtXform extends CompositeXform {
constructor() {
super();
this.map = {
'x14:conditionalFormatting': (this.cfXform = new ConditionalFormattingExtXform()),
};
}
get tag() {
return 'x14:conditionalFormattings';
}
hasContent(model) {
if (model.hasExtContent === undefined) {
model.hasExtContent = model.some(cf => cf.rules.some(CfRuleExtXform.isExt));
}
return model.hasExtContent;
}
prepare(model, options) {
model.forEach(cf => {
this.cfXform.prepare(cf, options);
});
}
render(xmlStream, model) {
if (this.hasContent(model)) {
xmlStream.openNode(this.tag);
model.forEach(cf => this.cfXform.render(xmlStream, cf));
xmlStream.closeNode();
}
}
createNewModel() {
return [];
}
onParserClose(name, parser) {
// model is array of conditional formatting objects
this.model.push(parser.model);
}
}
module.exports = ConditionalFormattingsExtXform;
|
'use strict';
var assert = require('assert');
var electronWatch = require('./');
it('should ', function () {
assert.strictEqual(electronWatch('unicorns'), 'unicorns & rainbows');
});
|
import React from 'react';
import Info from "./cv/info"
import WorkExperience from "./cv/workexperience"
import AwardsSkills from "./cv/awardskills"
import data from "../data/seed"
module.exports = React.createClass({
// RENDER
render: function() {
return (
<div className="cv">
<div className="box">
<h1>CURRICULUM VITAE</h1>
<Info />
<WorkExperience experiences={data.EXPERIENCES}/>
<AwardsSkills skills={data.SKILLS}/>
</div>
<br/>
</div>
);
}
}); |
version https://git-lfs.github.com/spec/v1
oid sha256:2e9db6469ceaf89fd8457e4a6393ee53e55a3201402d0af5f1f3f6aad56e699f
size 16491
|
'use strict';
const http = require('http');
const selenium = require('selenium-standalone');
const nodeStatic = require('node-static');
let grid, staticServer;
module.exports = {
startStaticServer,
stopStaticServer,
startSelenium,
stopSelenium
};
function startStaticServer() {
return new Promise((resolve, reject) => {
const file = new nodeStatic.Server('./test/site');
const server = http
.createServer((request, response) => {
request
.addListener('end', () => {
file.serve(request, response);
})
.resume();
})
.listen(8080, err => {
if (err) {
return reject(err);
}
console.log('Started static server on port ' + 8080);
staticServer = server;
resolve(server);
});
});
}
function startSelenium() {
return new Promise((resolve, reject) => {
selenium.start((err, sel) => {
if (err) {
return reject(err);
}
console.log('Started Selenium server');
grid = sel;
resolve(sel);
});
});
}
function stopSelenium() {
return new Promise((resolve, reject) => {
grid.on('exit', () => {
resolve(true);
});
grid.kill();
});
}
function stopStaticServer() {
return new Promise((resolve, reject) => {
staticServer.close(() => {
resolve(true);
});
});
}
|
/**
* Created by dx.yang on 15/4/23.
*/
angular.module('kai')
.service('ipHandlerService', [
function() {
var self = this;
//IP转成无符号数值
self.IP2Num = function(ip) {
ip = ip.split('.');
var num = ip[0] * 256 * 256 * 256 + ip[1] * 256 * 256 + ip[2] * 256 + ip[3] * 1;
num = num >>> 0;
return num;
};
//无符号转成IP地址
self.Num2IP = function(num) {
var tt = [];
tt[0] = (num >>> 24) >>> 0;
tt[1] = ((num << 8) >>> 24) >>> 0;
tt[2] = (num << 16) >>> 24;
tt[3] = (num << 24) >>> 24;
var str = tt[0] + '.' + tt[1] + '.' + tt[2] + '.' + tt[3];
return str;
};
// drop
self.calcNeeded = function(value){
var tmpvar = parseInt(value, 10);
if (isNaN(tmpvar) || tmpvar > 0xfffffffe || tmpvar < 1){
return '';
}
var expval = parseInt(Math.log(tmpvar) / Math.log(2)) + 1;
var maxaddrval = Math.pow(2, expval);
if (maxaddrval - tmpvar < 2){
expval+=1;
}
return 32 - expval;
};
self.getIpRange = function(ipNum, prefixLength) {
var ipnet = self.Num2IP(ipNum);
var ipnetArr = ipnet.split('.');
var sn = 0;
for (i = 1; i <= prefixLength; i++) {
sn = sn >>> 1;
sn = sn + 0x80000000;
}
var nm4 = sn & 0xFF;
var nm3 = (sn >> 8) & 0xFF;
var nm2 = (sn >> 16) & 0xFF;
var nm1 = (sn >> 24) & 0xFF;
var s1 = (ipnetArr[0] & 0xFF) & (nm1 & 0xFF);
var s2 = (ipnetArr[1] & 0xFF) & (nm2 & 0xFF);
var s3 = (ipnetArr[2] & 0xFF) & (nm3 & 0xFF);
var s4 = (ipnetArr[3] & 0xFF) & (nm4 & 0xFF);
var b1 = (ipnetArr[0] & 0xFF) | (~nm1 & 0xFF);
var b2 = (ipnetArr[1] & 0xFF) | (~nm2 & 0xFF);
var b3 = (ipnetArr[2] & 0xFF) | (~nm3 & 0xFF);
var b4 = (ipnetArr[3] & 0xFF) | (~nm4 & 0xFF);
var ipStart = [
s1,
s2,
s3,
s4 + 1
];
var ipEnd = [
b1,
b2,
b3,
b4 - 1
];
return {
start: ipStart.join('.'),
end: ipEnd.join('.')
};
};
}
]);
|
var onClearMarkdown = require('../markdown/js/properties/onClear').body;
var onClearProp = {
nameAttr: "onClear",
renderString: onClearMarkdown
};
module.exports = onClearProp;
|
if (process.env.NODE_ENV === 'test') {
module.exports = require('./jest.js')
} else {
module.exports = require('./storybook.js')
}
|
MagentoBlock = Class.create();
MagentoBlock.prototype = {
storageKeys: {
prefix: 'm2e_mb_'
},
// ---------------------------------------
initialize: function() {},
// ---------------------------------------
getHashedStorage: function(id)
{
var hashedStorageKey = this.storageKeys.prefix + md5(id).substr(0, 10);
var resultStorage = LocalStorageObj.get(hashedStorageKey);
if (resultStorage === null) {
return '';
}
return resultStorage;
},
setHashedStorage: function(id)
{
var hashedStorageKey = this.storageKeys.prefix + md5(id).substr(0, 10);
LocalStorageObj.set(hashedStorageKey, 1);
},
deleteHashedStorage: function(id)
{
var hashedStorageKey = this.storageKeys.prefix + md5(id).substr(0, 10);
LocalStorageObj.remove(hashedStorageKey);
LocalStorageObj.remove(id);
},
deleteAllHashedStorage: function()
{
LocalStorageObj.removeAllByPrefix(this.storageKeys.prefix);
},
// ---------------------------------------
show: function(blockClass,init)
{
blockClass = blockClass || '';
if (blockClass == '') {
return false;
}
$$('div.'+blockClass)[0].select('div.entry-edit-head div.entry-edit-head-right div.block_visibility_changer').each(function(o) {
o.remove();
});
$$('div.'+blockClass)[0].select('div.entry-edit-head div.entry-edit-head-right div.block_tips_changer').each(function(o) {
o.show();
});
var tempObj = $$('div.'+blockClass)[0].select('div.entry-edit-head div.entry-edit-head-left')[0];
tempObj.writeAttribute("onclick", "MagentoBlockObj.hide('"+blockClass+"','0');");
var tempHtml = $$('div.'+blockClass)[0].select('div.entry-edit-head div.entry-edit-head-right')[0].innerHTML;
var tempHtml2 = '<div class="block_visibility_changer collapseable" style="float: right; color: white; font-size: 11px; margin-left: 20px;">';
tempHtml2 += '<a href="javascript:void(0);" onclick="MagentoBlockObj.hide(\''+blockClass+'\',\'0\');" style="width: 20px; border: 0px;" class="open"> </a>';
tempHtml2 += '</div>';
$$('div.'+blockClass)[0].select('div.entry-edit-head div.entry-edit-head-right')[0].innerHTML = tempHtml2 + tempHtml;
this.deleteHashedStorage(blockClass);
if (init == '0') {
$$('div.'+blockClass+' div.fieldset')[0].show();
} else {
$$('div.'+blockClass+' div.fieldset')[0].show();
}
$$('div.'+blockClass+' div.entry-edit-head')[0].setStyle({marginBottom: '0px'});
$$('div.'+blockClass+' div.fieldset')[0].setStyle({marginBottom: '15px'});
return true;
},
hide: function(blockClass,init)
{
blockClass = blockClass || '';
if (blockClass == '') {
return false;
}
$$('div.'+blockClass)[0].select('div.entry-edit-head div.entry-edit-head-right div.block_visibility_changer').each(function(o) {
o.remove();
});
$$('div.'+blockClass)[0].select('div.entry-edit-head div.entry-edit-head-right div.block_tips_changer').each(function(o) {
o.hide();
});
var tempObj = $$('div.'+blockClass)[0].select('div.entry-edit-head div.entry-edit-head-left')[0];
tempObj.writeAttribute("onclick", "MagentoBlockObj.show('"+blockClass+"','0');");
var tempHtml = $$('div.'+blockClass)[0].select('div.entry-edit-head div.entry-edit-head-right')[0].innerHTML;
var tempHtml2 = '<div class="block_visibility_changer collapseable" style="float: right; color: white; font-size: 11px; margin-left: 20px;">';
tempHtml2 += '<a href="javascript:void(0);" onclick="MagentoBlockObj.show(\''+blockClass+'\',\'0\');" style="width: 20px; border: 0px;"> </a>';
tempHtml2 += '</div>';
$$('div.'+blockClass)[0].select('div.entry-edit-head div.entry-edit-head-right')[0].innerHTML = tempHtml2 + tempHtml;
this.setHashedStorage(blockClass);
if (init == '0') {
$$('div.'+blockClass+' div.fieldset')[0].hide();
} else {
$$('div.'+blockClass+' div.fieldset')[0].hide();
}
$$('div.'+blockClass+' div.entry-edit-head')[0].setStyle({marginBottom: '15px'});
$$('div.'+blockClass+' div.fieldset')[0].setStyle({marginBottom: '0px'});
return true;
},
// ---------------------------------------
observePrepareStart: function(blockObj)
{
var self = this;
var tempCollapseable = blockObj.readAttribute('collapseable');
if (typeof tempCollapseable == 'string' && tempCollapseable == 'no') {
return;
}
var tempId = blockObj.readAttribute('id');
if (typeof tempId != 'string') {
tempId = 'magento_block_md5_' + md5(blockObj.innerHTML.replace(/[^A-Za-z]/g,''));
blockObj.writeAttribute("id",tempId);
}
var blockClass = tempId + '_hide';
blockObj.addClassName(blockClass);
var tempObj = blockObj.select('div.entry-edit-head div.entry-edit-head-left')[0];
tempObj.setStyle({cursor: 'pointer'});
var isClosed = this.getHashedStorage(blockClass);
if (isClosed == '' || isClosed == '0') {
self.show(blockClass,'1');
} else {
self.hide(blockClass,'1');
}
}
// ---------------------------------------
}; |
/** @module reiter/flattenDeep */
import flattenDepth from "./flattenDepth.js";
/**
* Recursively flattens `iterable`.
*
* @since 0.0.1
* @generator
* @function flattenDeep
* @param {ForOfIterable} iterable The iterable.
* @yields {*} The next element when traversing a fully flattened `iterable`.
* @see [flatten]{@link module:reiter/flatten}
* @see [flattenDepth]{@link module:reiter/flattenDepth}
* @example
*
* reiter.flattenDeep([1, [2], [3, [[[4]]]], [5, 6]])
* // => 1, 2, 3, 4, 5, 6
*/
export default flattenDepth(Infinity);
|
'use strict';
var Singular = require('singular');
var core = require('./core.js');
var server = require('./server.js');
var router = require('./router.js');
var socketIo = require('./socket-io.js');
var awaits = require('./awaits.js');
var Error = require('./error.js');
var glob = require('glob');
var path = require('path');
var _ = require('underscore');
module.exports = HelicopterApp;
/**
* Helicopter application constructor.
*
* @param {object} config Configuration object.
* @extends Singular
*/
function HelicopterApp(config) {
Singular.call(this, config);
this.module(core);
this.module(server);
this.module(router);
this.module(socketIo);
this.module(awaits);
}
Object.setPrototypeOf(HelicopterApp.prototype, Singular.prototype);
/**
* Helicopter error constructor.
* @type {HelicopterError}
*/
HelicopterApp.Error = Error;
/**
* Create new sub class of Helicopter application.
*
* @param {string} name Constructor name.
* @param {object} proto Prototype object. If prototype has property
* `constructor` then it's prototype will be extended
* and returned.
* @return {HyphenApp} New HyphenApp extended constructor.
*/
HelicopterApp.extend = function (name, proto) {
if (arguments.length < 2) {
proto = name;
name = null;
}
var Super = this;
var ctor;
if (proto.hasOwnProperty('constructor')) {
ctor = proto.constructor;
} else {
ctor = function () {
Super.apply(this, arguments);
};
}
if (name) {
Object.defineProperty(ctor, 'name', {
value: name
});
}
Object.setPrototypeOf(ctor.prototype, this.prototype);
Object.getOwnPropertyNames(proto).forEach(function (name) {
if (['constructor', 'prototype'].indexOf(name) > -1) {
return;
}
ctor.prototype[name] = proto[name];
});
Object.getOwnPropertyNames(this).forEach((name) => {
if (['name', 'constructor', 'length', 'caller', 'arguments', 'prototype'].indexOf(name) > -1) {
return;
}
ctor[name] = this[name];
});
return ctor;
};
/**
* Initialize application.
*/
HelicopterApp.prototype.init = function () {
this.loadConfig();
};
/**
* Commands factory.
*
* @return {object} Return object with commands for cli application.
*/
HelicopterApp.prototype.commands = function () {
return {};
};
/**
* Get configuration with dir name. If dir name not specified then
* `config.dir + '/config'` will be used.
*
* @param {string} [dir] Configuration directory name.
* @return {object} Configuration object.
*/
HelicopterApp.prototype.getConfig = function (dir) {
dir = path.resolve(this.config.dir, dir || 'config');
var files = glob.sync('*.js', {cwd: dir});
return files.reduce(function (result, file) {
return _.extend(result, require(path.join(dir, file)));
}, {});
};
/**
* Load configuration from directory and append it to existed. This method
* loads environment configuration if `env` option is specified in config.
*
* @param {string?} [dir] Configuration directory.
*/
HelicopterApp.prototype.loadConfig = function (dir) {
dir = dir || 'config';
var env = this.config.env;
_.extend(this.config, this.getConfig(dir));
if (env) {
_.extend(this.config, this.getConfig(path.join(dir, env)));
}
};
/**
* Initialize and returns service by name.
*
* @param {string} name Service name.
* @return {object} Service instance.
*/
HelicopterApp.prototype.service = function (name) {
return this.get(name + 'Service');
};
|
import { setData } from '@progress/kendo-angular-intl';
setData({
name: "az-Latn",
identity: {
language: "az",
script: "Latn"
},
territory: "AZ",
numbers: {
symbols: {
decimal: ",",
group: ".",
list: ";",
percentSign: "%",
plusSign: "+",
minusSign: "-",
exponential: "E",
superscriptingExponent: "×",
perMille: "‰",
infinity: "∞",
nan: "NaN",
timeSeparator: ":"
},
decimal: {
patterns: [
"n"
],
groupSize: [
3
]
},
scientific: {
patterns: [
"nEn"
],
groupSize: []
},
percent: {
patterns: [
"n%"
],
groupSize: [
3
]
},
currency: {
patterns: [
"$ n"
],
groupSize: [
3
],
"unitPattern-count-one": "n $",
"unitPattern-count-other": "n $"
},
accounting: {
patterns: [
"$ n"
],
groupSize: [
3
]
},
currencies: {
ADP: {
displayName: "Andora Pesetası",
"displayName-count-one": "Andora pesetası",
"displayName-count-other": "Andora pesetası",
symbol: "ADP"
},
AED: {
displayName: "Birləşmiş Ərəb Əmirlikləri Dirhəmi",
"displayName-count-one": "BƏƏ dirhəmi",
"displayName-count-other": "BƏƏ dirhəmi",
symbol: "AED"
},
AFA: {
displayName: "Əfqanıstan Əfqanisi (1927–2002)",
"displayName-count-one": "Əfqanıstan əfqanisi (1927–2002)",
"displayName-count-other": "Əfqanıstan əfqanisi (1927–2002)",
symbol: "AFA"
},
AFN: {
displayName: "Əfqanıstan Əfqanisi",
"displayName-count-one": "Əfqanıstan əfqanisi",
"displayName-count-other": "Əfqanıstan əfqanisi",
symbol: "AFN"
},
ALK: {
displayName: "Albaniya Leki (1946–1965)",
"displayName-count-one": "Albaniya leki (1946–1965)",
"displayName-count-other": "Albaniya leki (1946–1965)"
},
ALL: {
displayName: "Albaniya Leki",
"displayName-count-one": "Albaniya leki",
"displayName-count-other": "Albaniya leki",
symbol: "ALL"
},
AMD: {
displayName: "Ermənistan Dramı",
"displayName-count-one": "Ermənistan dramı",
"displayName-count-other": "Ermənistan dramı",
symbol: "AMD"
},
ANG: {
displayName: "Niderland Antilyası Gilderi",
"displayName-count-one": "Niderland Antilyası gilderi",
"displayName-count-other": "Niderland Antilya gilderi",
symbol: "ANG"
},
AOA: {
displayName: "Anqola Kvanzası",
"displayName-count-one": "Anqola kvanzasi",
"displayName-count-other": "Anqola kvanzasi",
symbol: "AOA",
"symbol-alt-narrow": "Kz"
},
AOK: {
displayName: "Anqola Kvanzasi (1977–1990)",
"displayName-count-one": "Anqola kvanzasi (1977–1990)",
"displayName-count-other": "Anqola kvanzasi (1977–1990)",
symbol: "AOK"
},
AON: {
displayName: "Anqola Yeni Kvanzası (1990–2000)",
"displayName-count-one": "Anqola yeni kvanzası (1990–2000)",
"displayName-count-other": "Anqola yeni kvanzası (1990–2000)",
symbol: "AON"
},
AOR: {
displayName: "Anqola Kvanzası (1995–1999)",
"displayName-count-one": "Anqola kvanzası (1995–1999)",
"displayName-count-other": "Anqola kvanzası (1995–1999)",
symbol: "AOR"
},
ARA: {
displayName: "Argentina avstralı",
"displayName-count-one": "Argentina avstralı",
"displayName-count-other": "Argentina avstralı",
symbol: "ARA"
},
ARL: {
displayName: "ARL",
symbol: "ARL"
},
ARM: {
displayName: "ARM",
symbol: "ARM"
},
ARP: {
displayName: "Argentina pesosu (1983–1985)",
"displayName-count-one": "Argentina pesosu (1983–1985)",
"displayName-count-other": "Argentina pesosu (1983–1985)",
symbol: "ARP"
},
ARS: {
displayName: "Argentina Pesosu",
"displayName-count-one": "Argentina pesosu",
"displayName-count-other": "Argentina pesosu",
symbol: "ARS",
"symbol-alt-narrow": "$"
},
ATS: {
displayName: "Avstriya Şillinqi",
"displayName-count-one": "Avstriya şillinqi",
"displayName-count-other": "Avstriya şillinqi",
symbol: "ATS"
},
AUD: {
displayName: "Avstraliya Dolları",
"displayName-count-one": "Avstraliya dolları",
"displayName-count-other": "Avstraliya dolları",
symbol: "A$",
"symbol-alt-narrow": "$"
},
AWG: {
displayName: "Aruba Florini",
"displayName-count-one": "Aruba florini",
"displayName-count-other": "Aruba florini",
symbol: "AWG"
},
AZM: {
displayName: "Azərbaycan Manatı (1993–2006)",
"displayName-count-one": "Azərbaycan manatı (1993–2006)",
"displayName-count-other": "Azərbaycan manatı (1993–2006)",
symbol: "AZM"
},
AZN: {
displayName: "Azərbaycan Manatı",
"displayName-count-one": "Azərbaycan manatı",
"displayName-count-other": "Azərbaycan manatı",
symbol: "₼"
},
BAD: {
displayName: "Bosniya-Herseqovina Dinarı",
"displayName-count-one": "Bosniya-Herseqovina dinarı",
"displayName-count-other": "Bosniya-Herseqovina dinarı",
symbol: "BAD"
},
BAM: {
displayName: "Bosniya-Herseqovina Markası",
"displayName-count-one": "Bosniya-Herseqovina markası",
"displayName-count-other": "Bosniya-Herseqovina markası",
symbol: "BAM",
"symbol-alt-narrow": "KM"
},
BAN: {
displayName: "BAN",
symbol: "BAN"
},
BBD: {
displayName: "Barbados Dolları",
"displayName-count-one": "Barbados dolları",
"displayName-count-other": "Barbados dolları",
symbol: "BBD",
"symbol-alt-narrow": "$"
},
BDT: {
displayName: "Banqladeş Takası",
"displayName-count-one": "Banqladeş takası",
"displayName-count-other": "Banqladeş takası",
symbol: "BDT",
"symbol-alt-narrow": "৳"
},
BEC: {
displayName: "Belçika Frankı (deyşirik)",
"displayName-count-one": "Belçika frankı (deyşirik)",
"displayName-count-other": "Belçika frankı (deyşirik)",
symbol: "BEC"
},
BEF: {
displayName: "Belçika Frankı",
"displayName-count-one": "Belçika frankı",
"displayName-count-other": "Belçika frankı",
symbol: "BEF"
},
BEL: {
displayName: "Belçika Frankı (finans)",
"displayName-count-one": "Belçika frankı (finans)",
"displayName-count-other": "Belçika frankı (finans)",
symbol: "BEL"
},
BGL: {
displayName: "Bolqarıstan Levası",
"displayName-count-one": "Bolqarıstan levası",
"displayName-count-other": "Bolqarıstan levası",
symbol: "BGL"
},
BGM: {
displayName: "BGM",
symbol: "BGM"
},
BGN: {
displayName: "Bolqarıstan Levi",
"displayName-count-one": "Bolqarıstan levi",
"displayName-count-other": "Bolqarıstan levi",
symbol: "BGN"
},
BGO: {
displayName: "BGO",
symbol: "BGO"
},
BHD: {
displayName: "Bəhreyn Dinarı",
"displayName-count-one": "Bəhreyn dinarı",
"displayName-count-other": "Bəhreyn dinarı",
symbol: "BHD"
},
BIF: {
displayName: "Burundi Frankı",
"displayName-count-one": "Burundi frankı",
"displayName-count-other": "Burundi frankı",
symbol: "BIF"
},
BMD: {
displayName: "Bermuda Dolları",
"displayName-count-one": "Bermuda dolları",
"displayName-count-other": "Bermuda dolları",
symbol: "BMD",
"symbol-alt-narrow": "$"
},
BND: {
displayName: "Bruney Dolları",
"displayName-count-one": "Bruney dolları",
"displayName-count-other": "Bruney dolları",
symbol: "BND",
"symbol-alt-narrow": "$"
},
BOB: {
displayName: "Boliviya Bolivianosu",
"displayName-count-one": "Boliviya bolivianosu",
"displayName-count-other": "Boliviya bolivianosu",
symbol: "BOB",
"symbol-alt-narrow": "Bs"
},
BOL: {
displayName: "BOL",
symbol: "BOL"
},
BOP: {
displayName: "Boliviya pesosu",
"displayName-count-one": "Boliviya pesosu",
"displayName-count-other": "Boliviya pesosu",
symbol: "BOP"
},
BOV: {
displayName: "Boliviya mvdolı",
"displayName-count-one": "Boliviya mvdolı",
"displayName-count-other": "Boliviya mvdolı",
symbol: "BOV"
},
BRB: {
displayName: "Braziliya kruzeyro novası",
"displayName-count-one": "Braziliya kruzeyro novası",
"displayName-count-other": "Braziliya kruzeyro novası",
symbol: "BRB"
},
BRC: {
displayName: "Braziliya kruzadosu",
"displayName-count-one": "Braziliya kruzadosu",
"displayName-count-other": "Braziliya kruzadosu",
symbol: "BRC"
},
BRE: {
displayName: "Braziliya kruzeyrosu (1990–1993)",
"displayName-count-one": "Braziliya kruzeyrosu (1990–1993)",
"displayName-count-other": "Braziliya kruzeyrosu (1990–1993)",
symbol: "BRE"
},
BRL: {
displayName: "Braziliya Realı",
"displayName-count-one": "Braziliya realı",
"displayName-count-other": "Braziliya realı",
symbol: "R$",
"symbol-alt-narrow": "R$"
},
BRN: {
displayName: "Braziliya kruzado novası",
"displayName-count-one": "Braziliya kruzado novası",
"displayName-count-other": "Braziliya kruzado novası",
symbol: "BRN"
},
BRR: {
displayName: "Braziliya kruzeyrosu",
"displayName-count-one": "Braziliya kruzeyrosu",
"displayName-count-other": "Braziliya kruzeyrosu",
symbol: "BRR"
},
BRZ: {
displayName: "BRZ",
symbol: "BRZ"
},
BSD: {
displayName: "Bahama Dolları",
"displayName-count-one": "Bahama dolları",
"displayName-count-other": "Bahama dolları",
symbol: "BSD",
"symbol-alt-narrow": "$"
},
BTN: {
displayName: "Butan Nqultrumu",
"displayName-count-one": "Butan nqultrumu",
"displayName-count-other": "Butan nqultrumu",
symbol: "BTN"
},
BUK: {
displayName: "Burmis Kyatı",
"displayName-count-one": "Burmis kyatı",
"displayName-count-other": "Burmis kyatı",
symbol: "BUK"
},
BWP: {
displayName: "Botsvana Pulası",
"displayName-count-one": "Botsvana pulası",
"displayName-count-other": "Botsvana pulası",
symbol: "BWP",
"symbol-alt-narrow": "P"
},
BYB: {
displayName: "Belarus Yeni Rublu (1994–1999)",
"displayName-count-one": "Belarus yeni rublu (1994–1999)",
"displayName-count-other": "Belarus yeni rublu (1994–1999)",
symbol: "BYB"
},
BYN: {
displayName: "Belarus Rublu",
"displayName-count-one": "Belarus rublu",
"displayName-count-other": "Belarus rublu",
symbol: "BYN",
"symbol-alt-narrow": "р."
},
BYR: {
displayName: "Belarus Rublu (2000–2016)",
"displayName-count-one": "Belarus rublu (2000–2016)",
"displayName-count-other": "Belarus rublu (2000–2016)",
symbol: "BYR"
},
BZD: {
displayName: "Beliz Dolları",
"displayName-count-one": "Beliz dolları",
"displayName-count-other": "Beliz dolları",
symbol: "BZD",
"symbol-alt-narrow": "$"
},
CAD: {
displayName: "Kanada Dolları",
"displayName-count-one": "Kanada dolları",
"displayName-count-other": "Kanada dolları",
symbol: "CA$",
"symbol-alt-narrow": "$"
},
CDF: {
displayName: "Konqo Frankı",
"displayName-count-one": "Konqo frankı",
"displayName-count-other": "Konqo frankı",
symbol: "CDF"
},
CHE: {
displayName: "WIR Avro",
"displayName-count-one": "WIR avro",
"displayName-count-other": "WIR avro",
symbol: "CHE"
},
CHF: {
displayName: "İsveçrə Frankı",
"displayName-count-one": "İsveçrə frankı",
"displayName-count-other": "İsveçrə frankı",
symbol: "CHF"
},
CHW: {
displayName: "WIR Frankası",
"displayName-count-one": "WIR frankası",
"displayName-count-other": "WIR frankası",
symbol: "CHW"
},
CLE: {
displayName: "CLE",
symbol: "CLE"
},
CLF: {
displayName: "CLF",
symbol: "CLF"
},
CLP: {
displayName: "Çili Pesosu",
"displayName-count-one": "Çili pesosu",
"displayName-count-other": "Çili pesosu",
symbol: "CLP",
"symbol-alt-narrow": "$"
},
CNY: {
displayName: "Çin Yuanı",
"displayName-count-one": "Çin yuanı",
"displayName-count-other": "Çin yuanı",
symbol: "CN¥",
"symbol-alt-narrow": "¥"
},
COP: {
displayName: "Kolumbiya Pesosu",
"displayName-count-one": "Kolombiya pesosu",
"displayName-count-other": "Kolombiya pesosu",
symbol: "COP",
"symbol-alt-narrow": "$"
},
COU: {
displayName: "COU",
symbol: "COU"
},
CRC: {
displayName: "Kosta Rika Kolonu",
"displayName-count-one": "Kosta Rika kolonu",
"displayName-count-other": "Kosta Rika kolonu",
symbol: "CRC",
"symbol-alt-narrow": "₡"
},
CSD: {
displayName: "Serbiya Dinarı (2002–2006)",
"displayName-count-one": "Serbiya dinarı (2002–2006)",
"displayName-count-other": "Serbiya dinarı (2002–2006)",
symbol: "CSD"
},
CSK: {
displayName: "Çexoslavakiya Korunası",
"displayName-count-one": "Çexoslavakiya korunası",
"displayName-count-other": "Çexoslavakiya korunası",
symbol: "CSK"
},
CUC: {
displayName: "Kuba Çevrilən Pesosu",
"displayName-count-one": "Kuba çevrilən pesosu",
"displayName-count-other": "Kuba çevrilən pesosu",
symbol: "CUC",
"symbol-alt-narrow": "$"
},
CUP: {
displayName: "Kuba Pesosu",
"displayName-count-one": "Kuba pesosu",
"displayName-count-other": "Kuba pesosu",
symbol: "CUP",
"symbol-alt-narrow": "$"
},
CVE: {
displayName: "Kape Verde Eskudosu",
"displayName-count-one": "Kape Verde eskudosu",
"displayName-count-other": "Kape Verde eskudosu",
symbol: "CVE"
},
CYP: {
displayName: "Kipr Paundu",
"displayName-count-one": "Kipr paundu",
"displayName-count-other": "Kipr paundu",
symbol: "CYP"
},
CZK: {
displayName: "Çexiya Korunası",
"displayName-count-one": "Çexiya korunası",
"displayName-count-other": "Çexiya korunası",
symbol: "CZK",
"symbol-alt-narrow": "Kč"
},
DDM: {
displayName: "Şərq Almaniya Ostmarkı",
"displayName-count-one": "Şərq Almaniya ostmarkı",
"displayName-count-other": "Şərq Almaniya ostmarkı",
symbol: "DDM"
},
DEM: {
displayName: "Alman Markası",
"displayName-count-one": "Alman markası",
"displayName-count-other": "Alman markası",
symbol: "DEM"
},
DJF: {
displayName: "Cibuti Frankı",
"displayName-count-one": "Cibuti frankı",
"displayName-count-other": "Cibuti frankı",
symbol: "DJF"
},
DKK: {
displayName: "Danimarka Kronu",
"displayName-count-one": "Danimarka kronu",
"displayName-count-other": "Danimarka kronu",
symbol: "DKK",
"symbol-alt-narrow": "kr"
},
DOP: {
displayName: "Dominika Pesosu",
"displayName-count-one": "Dominika pesosu",
"displayName-count-other": "Dominika pesosu",
symbol: "DOP",
"symbol-alt-narrow": "$"
},
DZD: {
displayName: "Əlcəzair Dinarı",
"displayName-count-one": "Əlcəzair dinarı",
"displayName-count-other": "Əlcəzair dinarı",
symbol: "DZD"
},
ECS: {
displayName: "Ekvador Sukresi",
"displayName-count-one": "Ekvador sukresi",
"displayName-count-other": "Ekvador sukresi",
symbol: "ECS"
},
ECV: {
displayName: "ECV",
symbol: "ECV"
},
EEK: {
displayName: "Estoniya Krunu",
"displayName-count-one": "Estoniya krunu",
"displayName-count-other": "Estoniya krunu",
symbol: "EEK"
},
EGP: {
displayName: "Misir Funtu",
"displayName-count-one": "Misir funtu",
"displayName-count-other": "Misir funtu",
symbol: "EGP",
"symbol-alt-narrow": "E£"
},
ERN: {
displayName: "Eritreya Nakfası",
"displayName-count-one": "Eritreya nakfası",
"displayName-count-other": "Eritreya nakfası",
symbol: "ERN"
},
ESA: {
displayName: "İspan Pesetası (A account)",
"displayName-count-one": "İspan pesetası (A account)",
"displayName-count-other": "İspan pesetası (A account)",
symbol: "ESA"
},
ESB: {
displayName: "İspan Pesetası (dəyşirik)",
"displayName-count-one": "İspan pesetası (dəyşirik)",
"displayName-count-other": "İspan pesetası (dəyşirik)",
symbol: "ESB"
},
ESP: {
displayName: "İspan Pesetası",
"displayName-count-one": "İspan pesetası",
"displayName-count-other": "İspan pesetası",
symbol: "ESP",
"symbol-alt-narrow": "₧"
},
ETB: {
displayName: "Efiopiya Bırrı",
"displayName-count-one": "Efiopiya bırrı",
"displayName-count-other": "Efiopiya bırrı",
symbol: "ETB"
},
EUR: {
displayName: "Avro",
"displayName-count-one": "Avro",
"displayName-count-other": "Avro",
symbol: "€",
"symbol-alt-narrow": "€"
},
FIM: {
displayName: "Fin Markası",
"displayName-count-one": "Fin markası",
"displayName-count-other": "Fin markası",
symbol: "FIM"
},
FJD: {
displayName: "Fici Dolları",
"displayName-count-one": "Fici dolları",
"displayName-count-other": "Fici dolları",
symbol: "FJD",
"symbol-alt-narrow": "$"
},
FKP: {
displayName: "Folklend Adaları Funtu",
"displayName-count-one": "Folklend Adaları funtu",
"displayName-count-other": "Folklend Adaları funtu",
symbol: "FKP",
"symbol-alt-narrow": "£"
},
FRF: {
displayName: "Fransız Markası",
"displayName-count-one": "Fransız markası",
"displayName-count-other": "Fransız markası",
symbol: "FRF"
},
GBP: {
displayName: "Britaniya Funt",
"displayName-count-one": "Britaniya funt",
"displayName-count-other": "Britaniya funt",
symbol: "£",
"symbol-alt-narrow": "£"
},
GEK: {
displayName: "Gürcüstan Kupon Lariti",
"displayName-count-one": "Gürcüstan kupon lariti",
"displayName-count-other": "Gürcüstan kupon lariti",
symbol: "GEK"
},
GEL: {
displayName: "Gürcüstan Larisi",
"displayName-count-one": "Gürcüstan larisi",
"displayName-count-other": "Gürcüstan larisi",
symbol: "GEL",
"symbol-alt-narrow": "₾",
"symbol-alt-variant": "₾"
},
GHC: {
displayName: "Qana Sedisi (1979–2007)",
"displayName-count-one": "Qana sedisi (1979–2007)",
"displayName-count-other": "Qana sedisi (1979–2007)",
symbol: "GHC"
},
GHS: {
displayName: "Qana Sedisi",
"displayName-count-one": "Qana sedisi",
"displayName-count-other": "Qana sedisi",
symbol: "GHS"
},
GIP: {
displayName: "Gibraltar Funtu",
"displayName-count-one": "Gibraltar funtu",
"displayName-count-other": "Gibraltar funtu",
symbol: "GIP",
"symbol-alt-narrow": "£"
},
GMD: {
displayName: "Qambiya Dalasisi",
"displayName-count-one": "Qambiya dalasisi",
"displayName-count-other": "Qambiya dalasisi",
symbol: "GMD"
},
GNF: {
displayName: "Qvineya Frankı",
"displayName-count-one": "Qvineya frankı",
"displayName-count-other": "Qvineya frankı",
symbol: "GNF",
"symbol-alt-narrow": "FG"
},
GNS: {
displayName: "Qvineya Sulisi",
"displayName-count-one": "Qvineya sulisi",
"displayName-count-other": "Qvineya sulisi",
symbol: "GNS"
},
GQE: {
displayName: "Ekvatoriya Gvineya Ekvele Quneanası",
"displayName-count-one": "Ekvatoriya Gvineya ekvele quneanası",
"displayName-count-other": "Ekvatoriya Gvineya ekvele quneanası",
symbol: "GQE"
},
GRD: {
displayName: "Yunan Draçması",
"displayName-count-one": "Yunan draxması",
"displayName-count-other": "Yunan draxması",
symbol: "GRD"
},
GTQ: {
displayName: "Qvatemala Küetzalı",
"displayName-count-one": "Qvatemala küetzalı",
"displayName-count-other": "Qvatemala küetzalı",
symbol: "GTQ",
"symbol-alt-narrow": "Q"
},
GWE: {
displayName: "Portugal Qvineya Eskudosu",
"displayName-count-one": "Portugal Qvineya eskudosu",
"displayName-count-other": "Portugal Qvineya eskudosu",
symbol: "GWE"
},
GWP: {
displayName: "Qvineya-Bisau Pesosu",
"displayName-count-one": "Qvineya-Bisau pesosu",
"displayName-count-other": "Qvineya-Bisau pesosu",
symbol: "GWP"
},
GYD: {
displayName: "Qayana Dolları",
"displayName-count-one": "Qayana dolları",
"displayName-count-other": "Qayana dolları",
symbol: "GYD",
"symbol-alt-narrow": "$"
},
HKD: {
displayName: "Honq Konq Dolları",
"displayName-count-one": "Honq Konq dolları",
"displayName-count-other": "Honq Konq dolları",
symbol: "HK$",
"symbol-alt-narrow": "$"
},
HNL: {
displayName: "Honduras Lempirası",
"displayName-count-one": "Honduras lempirası",
"displayName-count-other": "Honduras lempirası",
symbol: "HNL",
"symbol-alt-narrow": "L"
},
HRD: {
displayName: "Xorvatiya Dinarı",
"displayName-count-one": "Xorvatiya dinarı",
"displayName-count-other": "Xorvatiya dinarı",
symbol: "HRD"
},
HRK: {
displayName: "Xorvatiya Kunası",
"displayName-count-one": "Xorvatiya kunası",
"displayName-count-other": "Xorvatiya kunası",
symbol: "HRK",
"symbol-alt-narrow": "kn"
},
HTG: {
displayName: "Haiti Qourdu",
"displayName-count-one": "Haiti qourdu",
"displayName-count-other": "Haiti qourdu",
symbol: "HTG"
},
HUF: {
displayName: "Macarıstan Forinti",
"displayName-count-one": "Macarıstan forinti",
"displayName-count-other": "Macarıstan forinti",
symbol: "HUF",
"symbol-alt-narrow": "Ft"
},
IDR: {
displayName: "İndoneziya Rupisi",
"displayName-count-one": "İndoneziya rupisi",
"displayName-count-other": "İndoneziya rupisi",
symbol: "IDR",
"symbol-alt-narrow": "Rp"
},
IEP: {
displayName: "İrlandiya Paundu",
"displayName-count-one": "İrlandiya paundu",
"displayName-count-other": "İrlandiya paundu",
symbol: "IEP"
},
ILP: {
displayName: "İzrail Paundu",
"displayName-count-one": "İzrail paundu",
"displayName-count-other": "İzrail paundu",
symbol: "ILP"
},
ILR: {
displayName: "İsrail Şekeli (1980–1985)",
"displayName-count-one": "İsrail şekeli (1980–1985)",
"displayName-count-other": "İsrail şekeli (1980–1985)"
},
ILS: {
displayName: "İsrail Yeni Şekeli",
"displayName-count-one": "İsrail yeni şekeli",
"displayName-count-other": "İsrail yeni şekeli",
symbol: "₪",
"symbol-alt-narrow": "₪"
},
INR: {
displayName: "Hindistan Rupisi",
"displayName-count-one": "Hindistan rupisi",
"displayName-count-other": "Hindistan rupisi",
symbol: "₹",
"symbol-alt-narrow": "₹"
},
IQD: {
displayName: "İraq Dinarı",
"displayName-count-one": "İraq dinarı",
"displayName-count-other": "İraq dinarı",
symbol: "IQD"
},
IRR: {
displayName: "İran Rialı",
"displayName-count-one": "İran rialı",
"displayName-count-other": "İran rialı",
symbol: "IRR"
},
ISJ: {
displayName: "İslandiya Kronu (1918–1981)",
"displayName-count-one": "İslandiya kronu (1918–1981)",
"displayName-count-other": "İslandiya kronu (1918–1981)"
},
ISK: {
displayName: "İslandiya Kronu",
"displayName-count-one": "İslandiya kronu",
"displayName-count-other": "İslandiya kronu",
symbol: "ISK",
"symbol-alt-narrow": "kr"
},
ITL: {
displayName: "İtaliya Lirası",
"displayName-count-one": "İtaliya lirası",
"displayName-count-other": "İtaliya lirası",
symbol: "ITL"
},
JMD: {
displayName: "Yamayka Dolları",
"displayName-count-one": "Yamayka dolları",
"displayName-count-other": "Yamayka dolları",
symbol: "JMD",
"symbol-alt-narrow": "$"
},
JOD: {
displayName: "İordaniya Dinarı",
"displayName-count-one": "İordaniya dinarı",
"displayName-count-other": "İordaniya dinarı",
symbol: "JOD"
},
JPY: {
displayName: "Yaponiya Yeni",
"displayName-count-one": "Yaponiya yeni",
"displayName-count-other": "Yaponiya yeni",
symbol: "JP¥",
"symbol-alt-narrow": "¥"
},
KES: {
displayName: "Keniya Şillinqi",
"displayName-count-one": "Keniya şillinqi",
"displayName-count-other": "Keniya şillinqi",
symbol: "KES"
},
KGS: {
displayName: "Kırğızıstan Somu",
"displayName-count-one": "Kırğızıstan somu",
"displayName-count-other": "Kırğızıstan somu",
symbol: "KGS"
},
KHR: {
displayName: "Kamboca Rieli",
"displayName-count-one": "Kamboca rieli",
"displayName-count-other": "Kamboca rieli",
symbol: "KHR",
"symbol-alt-narrow": "៛"
},
KMF: {
displayName: "Komor Frankı",
"displayName-count-one": "Komor frankı",
"displayName-count-other": "Komor frankı",
symbol: "KMF",
"symbol-alt-narrow": "CF"
},
KPW: {
displayName: "Şimali Koreya Vonu",
"displayName-count-one": "Şimali Koreya vonu",
"displayName-count-other": "Şimali Koreya vonu",
symbol: "KPW",
"symbol-alt-narrow": "₩"
},
KRH: {
displayName: "KRH",
symbol: "KRH"
},
KRO: {
displayName: "KRO",
symbol: "KRO"
},
KRW: {
displayName: "Cənubi Koreya Vonu",
"displayName-count-one": "Cənubi Koreya vonu",
"displayName-count-other": "Cənubi Koreya vonu",
symbol: "₩",
"symbol-alt-narrow": "₩"
},
KWD: {
displayName: "Küveyt Dinarı",
"displayName-count-one": "Küveyt dinarı",
"displayName-count-other": "Küveyt dinarı",
symbol: "KWD"
},
KYD: {
displayName: "Kayman Adaları Dolları",
"displayName-count-one": "Kayman Adaları dolları",
"displayName-count-other": "Kayman Adaları dolları",
symbol: "KYD",
"symbol-alt-narrow": "$"
},
KZT: {
displayName: "Qazaxıstan Tengesi",
"displayName-count-one": "Qazaxıstan tengesi",
"displayName-count-other": "Qazaxıstan tengesi",
symbol: "KZT",
"symbol-alt-narrow": "₸"
},
LAK: {
displayName: "Laos Kipi",
"displayName-count-one": "Laos kipi",
"displayName-count-other": "Laos kipi",
symbol: "LAK",
"symbol-alt-narrow": "₭"
},
LBP: {
displayName: "Livan Funtu",
"displayName-count-one": "Livan funtu",
"displayName-count-other": "Livan funtu",
symbol: "LBP",
"symbol-alt-narrow": "L£"
},
LKR: {
displayName: "Şri Lanka Rupisi",
"displayName-count-one": "Şri Lanka rupisi",
"displayName-count-other": "Şri Lanka rupisi",
symbol: "LKR",
"symbol-alt-narrow": "Rs"
},
LRD: {
displayName: "Liberiya Dolları",
"displayName-count-one": "Liberiya dolları",
"displayName-count-other": "Liberiya dolları",
symbol: "LRD",
"symbol-alt-narrow": "$"
},
LSL: {
displayName: "Lesoto Lotisi",
"displayName-count-one": "Lesoto lotisi",
"displayName-count-other": "Lesoto lotisi",
symbol: "LSL"
},
LTL: {
displayName: "Litva Liti",
"displayName-count-one": "Litva liti",
"displayName-count-other": "Litva liti",
symbol: "LTL",
"symbol-alt-narrow": "Lt"
},
LTT: {
displayName: "Litva Talonası",
"displayName-count-one": "Litva talonası",
"displayName-count-other": "Litva talonası",
symbol: "LTT"
},
LUC: {
displayName: "Luksemburq Frankası (dəyişik)",
"displayName-count-one": "Luksemburq dəyişik frankası",
"displayName-count-other": "Luksemburq dəyişik frankası",
symbol: "LUC"
},
LUF: {
displayName: "Luksemburq Frankası",
"displayName-count-one": "Luksemburq frankası",
"displayName-count-other": "Luksemburq frankası",
symbol: "LUF"
},
LUL: {
displayName: "Luksemburq Frankası (finans)",
"displayName-count-one": "Luksemburq finans frankası",
"displayName-count-other": "Luksemburq finans frankası",
symbol: "LUL"
},
LVL: {
displayName: "Latviya Latı",
"displayName-count-one": "Latviya latı",
"displayName-count-other": "Latviya latı",
symbol: "LVL",
"symbol-alt-narrow": "Ls"
},
LVR: {
displayName: "Latviya Rublu",
"displayName-count-one": "Latviya rublu",
"displayName-count-other": "Latviya rublu",
symbol: "LVR"
},
LYD: {
displayName: "Liviya Dinarı",
"displayName-count-one": "Liviya dinarı",
"displayName-count-other": "Liviya dinarı",
symbol: "LYD"
},
MAD: {
displayName: "Mərakeş Dirhəmi",
"displayName-count-one": "Mərakeş dirhəmi",
"displayName-count-other": "Mərakeş dirhəmi",
symbol: "MAD"
},
MAF: {
displayName: "Mərakeş Frankası",
"displayName-count-one": "Mərakeş frankası",
"displayName-count-other": "Mərakeş frankası",
symbol: "MAF"
},
MCF: {
displayName: "MCF",
symbol: "MCF"
},
MDC: {
displayName: "MDC",
symbol: "MDC"
},
MDL: {
displayName: "Moldova Leyi",
"displayName-count-one": "Moldova leyi",
"displayName-count-other": "Moldova leyi",
symbol: "MDL"
},
MGA: {
displayName: "Madaqaskar Ariarisi",
"displayName-count-one": "Madaqaskar ariarisi",
"displayName-count-other": "Madaqaskar ariarisi",
symbol: "MGA",
"symbol-alt-narrow": "Ar"
},
MGF: {
displayName: "Madaqaskar Frankası",
"displayName-count-one": "Madaqaskar frankası",
"displayName-count-other": "Madaqaskar frankası",
symbol: "MGF"
},
MKD: {
displayName: "Makedoniya Dinarı",
"displayName-count-one": "Makedoniya dinarı",
"displayName-count-other": "Makedoniya dinarı",
symbol: "MKD"
},
MKN: {
displayName: "Makedoniya Dinarı (1992–1993)",
"displayName-count-one": "Makedoniya dinarı (1992–1993)",
"displayName-count-other": "Makedoniya dinarı (1992–1993)",
symbol: "MKN"
},
MLF: {
displayName: "Mali Frankı",
"displayName-count-one": "Mali frankı",
"displayName-count-other": "Mali frankı",
symbol: "MLF"
},
MMK: {
displayName: "Myanma Kiyatı",
"displayName-count-one": "Myanmar kiyatı",
"displayName-count-other": "Myanmar kiyatı",
symbol: "MMK",
"symbol-alt-narrow": "K"
},
MNT: {
displayName: "Monqoliya Tuqriki",
"displayName-count-one": "Monqoliya tuqriki",
"displayName-count-other": "Monqoliya tuqriki",
symbol: "MNT",
"symbol-alt-narrow": "₮"
},
MOP: {
displayName: "Makao Patakası",
"displayName-count-one": "Makao patakası",
"displayName-count-other": "Makao patakası",
symbol: "MOP"
},
MRO: {
displayName: "Mavritaniya Ugiyası",
"displayName-count-one": "Mavritaniya ugiyası",
"displayName-count-other": "Mavritaniya ugiyası",
symbol: "MRO"
},
MTL: {
displayName: "MTL",
symbol: "MTL"
},
MTP: {
displayName: "Maltiz Paundu",
"displayName-count-one": "Maltiz paundu",
"displayName-count-other": "Maltiz paundu",
symbol: "MTP"
},
MUR: {
displayName: "Mavriki Rupisi",
"displayName-count-one": "Mavriki rupisi",
"displayName-count-other": "Mavriki rupisi",
symbol: "MUR",
"symbol-alt-narrow": "Rs"
},
MVR: {
displayName: "Maldiv Rufiyası",
"displayName-count-one": "Maldiv rufiyası",
"displayName-count-other": "Maldiv rufiyası",
symbol: "MVR"
},
MWK: {
displayName: "Malavi Kvaçası",
"displayName-count-one": "Malavi kvaçası",
"displayName-count-other": "Malavi kvaçası",
symbol: "MWK"
},
MXN: {
displayName: "Meksika Pesosu",
"displayName-count-one": "Meksika pesosu",
"displayName-count-other": "Meksika pesosu",
symbol: "MX$",
"symbol-alt-narrow": "$"
},
MXP: {
displayName: "Meksika gümüş pesosu",
"displayName-count-one": "Meksika gümüş pesosu",
"displayName-count-other": "Meksika gümüş pesosu",
symbol: "MXP"
},
MXV: {
displayName: "MXV",
symbol: "MXV"
},
MYR: {
displayName: "Malayziya Ringiti",
"displayName-count-one": "Malayziya ringiti",
"displayName-count-other": "Malayziya ringiti",
symbol: "MYR",
"symbol-alt-narrow": "RM"
},
MZE: {
displayName: "Mozambik Eskudosu",
"displayName-count-one": "Mozambik eskudosu",
"displayName-count-other": "Mozambik eskudosu",
symbol: "MZE"
},
MZM: {
displayName: "Mozambik Metikalı (1980–2006)",
"displayName-count-one": "Mozambik metikalı (1980–2006)",
"displayName-count-other": "Mozambik metikalı (1980–2006)",
symbol: "MZM"
},
MZN: {
displayName: "Mozambik Metikalı",
"displayName-count-one": "Mozambik metikalı",
"displayName-count-other": "Mozambik metikalı",
symbol: "MZN"
},
NAD: {
displayName: "Namibiya Dolları",
"displayName-count-one": "Namibiya dolları",
"displayName-count-other": "Namibiya dolları",
symbol: "NAD",
"symbol-alt-narrow": "$"
},
NGN: {
displayName: "Nigeriya Nairası",
"displayName-count-one": "Nigeriya nairası",
"displayName-count-other": "Nigeriya nairası",
symbol: "NGN",
"symbol-alt-narrow": "₦"
},
NIC: {
displayName: "Nikaraqua kordobu",
"displayName-count-one": "Nikaraqua kordobu",
"displayName-count-other": "Nikaraqua kordobu",
symbol: "NIC"
},
NIO: {
displayName: "Nikaraqua Kordobası",
"displayName-count-one": "Nikaraqua kordobası",
"displayName-count-other": "Nikaraqua kordobası",
symbol: "NIO",
"symbol-alt-narrow": "C$"
},
NLG: {
displayName: "Hollandiya Gilderi",
"displayName-count-one": "Hollandiya gilderi",
"displayName-count-other": "Hollandiya gilderi",
symbol: "NLG"
},
NOK: {
displayName: "Norveç Kronu",
"displayName-count-one": "Norveç kronu",
"displayName-count-other": "Norveç kronu",
symbol: "NOK",
"symbol-alt-narrow": "kr"
},
NPR: {
displayName: "Nepal Rupisi",
"displayName-count-one": "Nepal rupisi",
"displayName-count-other": "Nepal rupisi",
symbol: "NPR",
"symbol-alt-narrow": "Rs"
},
NZD: {
displayName: "Yeni Zelandiya Dolları",
"displayName-count-one": "Yeni Zelandiya dolları",
"displayName-count-other": "Yeni Zelandiya dolları",
symbol: "NZ$",
"symbol-alt-narrow": "$"
},
OMR: {
displayName: "Oman Rialı",
"displayName-count-one": "Oman rialı",
"displayName-count-other": "Oman rialı",
symbol: "OMR"
},
PAB: {
displayName: "Panama Balboası",
"displayName-count-one": "Panama balboası",
"displayName-count-other": "Panama balboası",
symbol: "PAB"
},
PEI: {
displayName: "Peru Inti",
"displayName-count-one": "Peru inti",
"displayName-count-other": "Peru inti",
symbol: "PEI"
},
PEN: {
displayName: "Peru Solu",
"displayName-count-one": "Peru solu",
"displayName-count-other": "Peru solu",
symbol: "PEN"
},
PES: {
displayName: "Peru Solu (1863–1965)",
"displayName-count-one": "Peru solu (1863–1965)",
"displayName-count-other": "Peru solu (1863–1965)",
symbol: "PES"
},
PGK: {
displayName: "Papua Yeni Qvineya Kinası",
"displayName-count-one": "Papua Yeni Qvineya kinası",
"displayName-count-other": "Papua Yeni Qvineya kinası",
symbol: "PGK"
},
PHP: {
displayName: "Filippin Pesosu",
"displayName-count-one": "Filippin pesosu",
"displayName-count-other": "Filippin pesosu",
symbol: "PHP",
"symbol-alt-narrow": "₱"
},
PKR: {
displayName: "Pakistan Rupisi",
"displayName-count-one": "Pakistan rupisi",
"displayName-count-other": "Pakistan rupisi",
symbol: "PKR",
"symbol-alt-narrow": "Rs"
},
PLN: {
displayName: "Polşa Zlotısı",
"displayName-count-one": "Polşa zlotısı",
"displayName-count-other": "Polşa zlotısı",
symbol: "PLN",
"symbol-alt-narrow": "zł"
},
PLZ: {
displayName: "Polşa Zlotısı (1950–1995)",
"displayName-count-one": "Polşa zlotısı (1950–1995)",
"displayName-count-other": "Polşa zlotısı (1950–1995)",
symbol: "PLZ"
},
PTE: {
displayName: "Portuqal Eskudosu",
"displayName-count-one": "Portuqal eskudosu",
"displayName-count-other": "Portuqal eskudosu",
symbol: "PTE"
},
PYG: {
displayName: "Paraqvay Quaranisi",
"displayName-count-one": "Paraqvay quaranisi",
"displayName-count-other": "Paraqvay quaranisi",
symbol: "PYG",
"symbol-alt-narrow": "₲"
},
QAR: {
displayName: "Qatar Rialı",
"displayName-count-one": "Qatar rialı",
"displayName-count-other": "Qatar rialı",
symbol: "QAR"
},
RHD: {
displayName: "Rodezian Dolları",
"displayName-count-one": "Rodezian dolları",
"displayName-count-other": "Rodezian dolları",
symbol: "RHD"
},
ROL: {
displayName: "Rumıniya Leyi (1952–2006)",
"displayName-count-one": "Rumıniya leyi (1952–2006)",
"displayName-count-other": "Rumıniya leyi (1952–2006)",
symbol: "ROL"
},
RON: {
displayName: "Rumıniya Leyi",
"displayName-count-one": "Rumıniya leyi",
"displayName-count-other": "Rumıniya leyi",
symbol: "RON",
"symbol-alt-narrow": "ley"
},
RSD: {
displayName: "Serbiya Dinarı",
"displayName-count-one": "Serbiya dinarı",
"displayName-count-other": "Serbiya dinarı",
symbol: "RSD"
},
RUB: {
displayName: "Rusiya Rublu",
"displayName-count-one": "Rusiya rublu",
"displayName-count-other": "Rusiya rublu",
symbol: "RUB",
"symbol-alt-narrow": "₽"
},
RUR: {
displayName: "Rusiya Rublu (1991–1998)",
"displayName-count-one": "Rusiya rublu (1991–1998)",
"displayName-count-other": "Rusiya rublu (1991–1998)",
symbol: "RUR",
"symbol-alt-narrow": "р."
},
RWF: {
displayName: "Ruanda Frankı",
"displayName-count-one": "Ruanda frankı",
"displayName-count-other": "Ruanda frankı",
symbol: "RWF",
"symbol-alt-narrow": "RF"
},
SAR: {
displayName: "Səudiyyə Riyalı",
"displayName-count-one": "Səudiyyə riyalı",
"displayName-count-other": "Səudiyyə riyalı",
symbol: "SAR"
},
SBD: {
displayName: "Solomon Adaları Dolları",
"displayName-count-one": "Solomon Adaları dolları",
"displayName-count-other": "Solomon Adaları dolları",
symbol: "SBD",
"symbol-alt-narrow": "$"
},
SCR: {
displayName: "Seyşel Rupisi",
"displayName-count-one": "Seyşel rupisi",
"displayName-count-other": "Seyşel rupisi",
symbol: "SCR"
},
SDD: {
displayName: "SDD",
symbol: "SDD"
},
SDG: {
displayName: "Sudan Funtu",
"displayName-count-one": "Sudan funtu",
"displayName-count-other": "Sudan funtu",
symbol: "SDG"
},
SDP: {
displayName: "SDP",
symbol: "SDP"
},
SEK: {
displayName: "İsveç Kronu",
"displayName-count-one": "İsveç kronu",
"displayName-count-other": "İsveç kronu",
symbol: "SEK",
"symbol-alt-narrow": "kr"
},
SGD: {
displayName: "Sinqapur Dolları",
"displayName-count-one": "Sinqapur dolları",
"displayName-count-other": "Sinqapur dolları",
symbol: "SGD",
"symbol-alt-narrow": "$"
},
SHP: {
displayName: "Müqəddəs Yelena Funtu",
"displayName-count-one": "Müqəddəs Yelena funtu",
"displayName-count-other": "Müqəddəs Yelena funtu",
symbol: "SHP",
"symbol-alt-narrow": "£"
},
SIT: {
displayName: "Sloveniya Toları",
"displayName-count-one": "Sloveniya toları",
"displayName-count-other": "Sloveniya toları",
symbol: "SIT"
},
SKK: {
displayName: "Slovak Korunası",
"displayName-count-one": "Slovak korunası",
"displayName-count-other": "Slovak korunası",
symbol: "SKK"
},
SLL: {
displayName: "Sierra Leon Leonu",
"displayName-count-one": "Sierra Leon leonu",
"displayName-count-other": "Sierra Leon leonu",
symbol: "SLL"
},
SOS: {
displayName: "Somali Şillinqi",
"displayName-count-one": "Somali şillinqi",
"displayName-count-other": "Somali şillinqi",
symbol: "SOS"
},
SRD: {
displayName: "Surinam Dolları",
"displayName-count-one": "Surinam dolları",
"displayName-count-other": "Surinam dolları",
symbol: "SRD",
"symbol-alt-narrow": "$"
},
SRG: {
displayName: "SRG",
symbol: "SRG"
},
SSP: {
displayName: "Cənubi Sudan Funtu",
"displayName-count-one": "Cənubi Sudan funtu",
"displayName-count-other": "Cənubi Sudan funtu",
symbol: "SSP",
"symbol-alt-narrow": "£"
},
STD: {
displayName: "San Tom və Prinsip Dobrası",
"displayName-count-one": "San Tom və Prinsip dobrası",
"displayName-count-other": "San Tom və Prinsip dobrası",
symbol: "STD",
"symbol-alt-narrow": "Db"
},
SUR: {
displayName: "Sovet Rublu",
"displayName-count-one": "Sovet rublu",
"displayName-count-other": "Sovet rublu",
symbol: "SUR"
},
SVC: {
displayName: "El Salvador kolonu",
"displayName-count-one": "El Salvador kolonu",
"displayName-count-other": "El Salvador kolonu",
symbol: "SVC"
},
SYP: {
displayName: "Suriya Funtu",
"displayName-count-one": "Suriya funtu",
"displayName-count-other": "Suriya funtu",
symbol: "SYP",
"symbol-alt-narrow": "S£"
},
SZL: {
displayName: "Svazilend Lilangenini",
"displayName-count-one": "Svazilend lilangenini",
"displayName-count-other": "Svazilend emalangenini",
symbol: "SZL"
},
THB: {
displayName: "Tayland Batı",
"displayName-count-one": "Tayland batı",
"displayName-count-other": "Tayland batı",
symbol: "฿",
"symbol-alt-narrow": "฿"
},
TJR: {
displayName: "Tacikistan Rublu",
"displayName-count-one": "Tacikistan rublu",
"displayName-count-other": "Tacikistan rublu",
symbol: "TJR"
},
TJS: {
displayName: "Tacikistan Somonisi",
"displayName-count-one": "Tacikistan somonisi",
"displayName-count-other": "Tacikistan somonisi",
symbol: "TJS"
},
TMM: {
displayName: "Türkmənistan Manatı (1993–2009)",
"displayName-count-one": "Türkmənistan manatı (1993–2009)",
"displayName-count-other": "Türkmənistan manatı (1993–2009)",
symbol: "TMM"
},
TMT: {
displayName: "Türkmənistan Manatı",
"displayName-count-one": "Türkmənistan manatı",
"displayName-count-other": "Türkmənistan manatı",
symbol: "TMT"
},
TND: {
displayName: "Tunis Dinarı",
"displayName-count-one": "Tunis dinarı",
"displayName-count-other": "Tunis dinarı",
symbol: "TND"
},
TOP: {
displayName: "Tonqa Panqası",
"displayName-count-one": "Tonqa panqası",
"displayName-count-other": "Tonqa panqası",
symbol: "TOP",
"symbol-alt-narrow": "T$"
},
TPE: {
displayName: "Timor Eskudu",
"displayName-count-one": "Timor eskudu",
"displayName-count-other": "Timor eskudu",
symbol: "TPE"
},
TRL: {
displayName: "Türkiyə Lirəsi (1922–2005)",
"displayName-count-one": "Türkiyə lirəsi (1922–2005)",
"displayName-count-other": "Türkiyə lirəsi (1922–2005)",
symbol: "TRL"
},
TRY: {
displayName: "Türkiyə Lirəsi",
"displayName-count-one": "Türkiyə lirəsi",
"displayName-count-other": "Türkiyə lirəsi",
symbol: "TRY",
"symbol-alt-narrow": "₺",
"symbol-alt-variant": "TL"
},
TTD: {
displayName: "Trinidad və Tobaqo Dolları",
"displayName-count-one": "Trinidad və Tobaqo dolları",
"displayName-count-other": "Trinidad və Tobaqo dolları",
symbol: "TTD",
"symbol-alt-narrow": "$"
},
TWD: {
displayName: "Tayvan Yeni Dolları",
"displayName-count-one": "Tayvan yeni dolları",
"displayName-count-other": "Tayvan yeni dolları",
symbol: "NT$",
"symbol-alt-narrow": "NT$"
},
TZS: {
displayName: "Tanzaniya Şillinqi",
"displayName-count-one": "Tanzaniya şillinqi",
"displayName-count-other": "Tanzaniya şillinqi",
symbol: "TZS"
},
UAH: {
displayName: "Ukrayna Qrivnası",
"displayName-count-one": "Ukrayna qrivnası",
"displayName-count-other": "Ukrayna qrivnası",
symbol: "UAH",
"symbol-alt-narrow": "₴"
},
UAK: {
displayName: "Ukrayna Karbovenesası",
"displayName-count-one": "Ukrayna karbovenesası",
"displayName-count-other": "Ukrayna karbovenesası",
symbol: "UAK"
},
UGS: {
displayName: "Uqanda Şillinqi (1966–1987)",
"displayName-count-one": "Uqanda şillinqi (1966–1987)",
"displayName-count-other": "Uqanda şillinqi (1966–1987)",
symbol: "UGS"
},
UGX: {
displayName: "Uqanda Şillinqi",
"displayName-count-one": "Uqanda şillinqi",
"displayName-count-other": "Uqanda şillinqi",
symbol: "UGX"
},
USD: {
displayName: "ABŞ Dolları",
"displayName-count-one": "ABŞ dolları",
"displayName-count-other": "ABŞ dolları",
symbol: "US$",
"symbol-alt-narrow": "$"
},
USN: {
displayName: "ABŞ dolları (yeni gün)",
"displayName-count-one": "ABŞ dolları (yeni gün)",
"displayName-count-other": "ABŞ dolları (yeni gün)",
symbol: "USN"
},
USS: {
displayName: "ABŞ dolları (həmin gün)",
"displayName-count-one": "ABŞ dolları (həmin gün)",
"displayName-count-other": "ABŞ dolları (həmin gün)",
symbol: "USS"
},
UYI: {
displayName: "Uruqvay pesosu Unidades Indexadas",
"displayName-count-one": "Uruqvay pesosu unidades indexadas",
"displayName-count-other": "Uruqvay pesosu unidades indexadas",
symbol: "UYI"
},
UYP: {
displayName: "Uruqvay Pesosu (1975–1993)",
"displayName-count-one": "Uruqvay pesosu (1975–1993)",
"displayName-count-other": "Uruqvay pesosu (1975–1993)",
symbol: "UYP"
},
UYU: {
displayName: "Uruqvay Pesosu",
"displayName-count-one": "Uruqvay pesosu",
"displayName-count-other": "Uruqvay pesosu",
symbol: "UYU",
"symbol-alt-narrow": "$"
},
UZS: {
displayName: "Özbəkistan Somu",
"displayName-count-one": "Özbəkistan somu",
"displayName-count-other": "Özbəkistan somu",
symbol: "UZS"
},
VEB: {
displayName: "Venesuela Bolivarı (1871–2008)",
"displayName-count-one": "Venesuela bolivarı (1871–2008)",
"displayName-count-other": "Venesuela bolivarı (1871–2008)",
symbol: "VEB"
},
VEF: {
displayName: "Venesuela Bolivarı",
"displayName-count-one": "Venesuela bolivarı",
"displayName-count-other": "Venesuela bolivarı",
symbol: "VEF",
"symbol-alt-narrow": "Bs"
},
VND: {
displayName: "Vyetnam Donqu",
"displayName-count-one": "Vyetnam donqu",
"displayName-count-other": "Vyetnam donqu",
symbol: "₫",
"symbol-alt-narrow": "₫"
},
VNN: {
displayName: "Vyetnam Donqu (1978–1985)",
"displayName-count-one": "Vyetnam donqu (1978–1985)",
"displayName-count-other": "Vyetnam donqu (1978–1985)",
symbol: "VNN"
},
VUV: {
displayName: "Vanuatu Vatusu",
"displayName-count-one": "Vanuatu vatusu",
"displayName-count-other": "Vanuatu vatusu",
symbol: "VUV"
},
WST: {
displayName: "Samoa Talası",
"displayName-count-one": "Samoa talası",
"displayName-count-other": "Samoa talası",
symbol: "WST"
},
XAF: {
displayName: "Kamerun Frankı",
"displayName-count-one": "Kamerun frankı",
"displayName-count-other": "Kamerun frankı",
symbol: "FCFA"
},
XAG: {
displayName: "gümüş",
"displayName-count-one": "gümüş",
"displayName-count-other": "gümüş",
symbol: "XAG"
},
XAU: {
displayName: "qızıl",
"displayName-count-one": "qızıl",
"displayName-count-other": "qızıl",
symbol: "XAU"
},
XBA: {
displayName: "XBA",
symbol: "XBA"
},
XBB: {
displayName: "XBB",
symbol: "XBB"
},
XBC: {
displayName: "XBC",
symbol: "XBC"
},
XBD: {
displayName: "XBD",
symbol: "XBD"
},
XCD: {
displayName: "Şərqi Karib Dolları",
"displayName-count-one": "Şərqi Karib dolları",
"displayName-count-other": "Şərqi Karib dolları",
symbol: "EC$",
"symbol-alt-narrow": "$"
},
XDR: {
displayName: "XDR",
symbol: "XDR"
},
XEU: {
displayName: "XEU",
symbol: "XEU"
},
XFO: {
displayName: "Fransız Gızıl Frankı",
"displayName-count-one": "Fransız gızıl frankı",
"displayName-count-other": "Fransız gızıl frankı",
symbol: "XFO"
},
XFU: {
displayName: "Fransız UİC Frankı",
"displayName-count-one": "Fransız UİC frankı",
"displayName-count-other": "Fransız UİC frankı",
symbol: "XFU"
},
XOF: {
displayName: "Fil Dişi Sahili Frankı",
"displayName-count-one": "Fil Dişi Sahili frankı",
"displayName-count-other": "Fil Dişi Sahili frankı",
symbol: "CFA"
},
XPD: {
displayName: "Palladium",
"displayName-count-one": "Palladium",
"displayName-count-other": "Palladium",
symbol: "XPD"
},
XPF: {
displayName: "Fransız Polineziyası Frankı",
"displayName-count-one": "Fransız Polineziyası frankı",
"displayName-count-other": "Fransız Polineziyası frankı",
symbol: "CFPF"
},
XPT: {
displayName: "Platinum",
"displayName-count-one": "platinum",
"displayName-count-other": "platinum",
symbol: "XPT"
},
XRE: {
displayName: "XRE",
symbol: "XRE"
},
XSU: {
displayName: "XSU",
symbol: "XSU"
},
XTS: {
displayName: "XTS",
symbol: "XTS"
},
XUA: {
displayName: "XUA",
symbol: "XUA"
},
XXX: {
displayName: "Naməlum Valyuta",
"displayName-count-one": "(naməlum valyuta vahidi)",
"displayName-count-other": "(naməlum valyuta)",
symbol: "XXX"
},
YDD: {
displayName: "Yəmən Dinarı",
"displayName-count-one": "Yəmən dinarı",
"displayName-count-other": "Yəmən dinarı",
symbol: "YDD"
},
YER: {
displayName: "Yəmən Rialı",
"displayName-count-one": "Yəmən rialı",
"displayName-count-other": "Yəmən rialı",
symbol: "YER"
},
YUD: {
displayName: "Yuqoslaviya Dinarı (1966–1990)",
"displayName-count-one": "Yuqoslaviya dinarı (1966–1990)",
"displayName-count-other": "Yuqoslaviya dinarı (1966–1990)",
symbol: "YUD"
},
YUM: {
displayName: "Yuqoslaviya Yeni Dinarı (1994–2002)",
"displayName-count-one": "Yuqoslaviya yeni dinarı (1994–2002)",
"displayName-count-other": "Yuqoslaviya yeni dinarı (1994–2002)",
symbol: "YUM"
},
YUN: {
displayName: "Yuqoslaviya Dinarı (1990–1992)",
"displayName-count-one": "Yuqoslaviya dinarı (1990–1992)",
"displayName-count-other": "Yuqoslaviya dinarı (1990–1992)",
symbol: "YUN"
},
YUR: {
displayName: "YUR",
symbol: "YUR"
},
ZAL: {
displayName: "Cənubi Afrika Randı (finans)",
"displayName-count-one": "Cənubi Afrika randı (finans)",
"displayName-count-other": "Cənubi Afrika randı (finans)",
symbol: "ZAL"
},
ZAR: {
displayName: "Cənubi Afrika Randı",
"displayName-count-one": "Cənubi Afrika randı",
"displayName-count-other": "Cənubi Afrika randı",
symbol: "ZAR",
"symbol-alt-narrow": "R"
},
ZMK: {
displayName: "Zambiya Kvaçası (1968–2012)",
"displayName-count-one": "Zambiya kvaçası (1968–2012)",
"displayName-count-other": "Zambiya kvaçası (1968–2012)",
symbol: "ZMK"
},
ZMW: {
displayName: "Zambiya Kvaçası",
"displayName-count-one": "Zambiya kvaçası",
"displayName-count-other": "Zambiya kvaçası",
symbol: "ZMW",
"symbol-alt-narrow": "ZK"
},
ZRN: {
displayName: "Zair Yeni Zairi (1993–1998)",
"displayName-count-one": "Zair yeni zairi (1993–1998)",
"displayName-count-other": "Zair yeni zairi (1993–1998)",
symbol: "ZRN"
},
ZRZ: {
displayName: "Zair Zairi (1971–1993)",
"displayName-count-one": "Zair zairi (1971–1993)",
"displayName-count-other": "Zair zairi (1971–1993)",
symbol: "ZRZ"
},
ZWD: {
displayName: "Zimbabve Dolları (1980–2008)",
"displayName-count-one": "Zimbabve dolları (1980–2008)",
"displayName-count-other": "Zimbabve dolları (1980–2008)",
symbol: "ZWD"
},
ZWL: {
displayName: "Zimbabve Dolları (2009)",
"displayName-count-one": "Zimbabve dolları (2009)",
"displayName-count-other": "Zimbabve dolları (2009)",
symbol: "ZWL"
},
ZWR: {
displayName: "Zimbabve Dolları (2008)",
"displayName-count-one": "Zimbabve dolları (2008)",
"displayName-count-other": "Zimbabve dolları (2008)",
symbol: "ZWR"
}
},
localeCurrency: "AZN"
},
calendar: {
patterns: {
d: "dd.MM.y",
D: "d MMMM y, EEEE",
m: "d MMM",
M: "MMMM d",
y: "MMM y",
Y: "MMMM y",
F: "d MMMM y, EEEE HH:mm:ss",
g: "dd.MM.y HH:mm",
G: "dd.MM.y HH:mm:ss",
t: "HH:mm",
T: "HH:mm:ss",
s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss",
u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'"
},
dateTimeFormats: {
full: "{1} {0}",
long: "{1} {0}",
medium: "{1} {0}",
short: "{1} {0}",
availableFormats: {
d: "d",
E: "ccc",
Ed: "d E",
Ehm: "E h:mm a",
EHm: "E HH:mm",
Ehms: "E h:mm:ss a",
EHms: "E HH:mm:ss",
Gy: "G y",
GyMMM: "G MMM y",
GyMMMd: "G d MMM y",
GyMMMEd: "G d MMM y, E",
h: "h a",
H: "HH",
hm: "h:mm a",
Hm: "HH:mm",
hms: "h:mm:ss a",
Hms: "HH:mm:ss",
hmsv: "h:mm:ss a v",
Hmsv: "HH:mm:ss v",
hmv: "h:mm a v",
Hmv: "HH:mm v",
M: "L",
Md: "dd.MM",
MEd: "dd.MM, E",
MMM: "LLL",
MMMd: "d MMM",
MMMEd: "d MMM, E",
MMMMd: "MMMM d",
"MMMMW-count-one": "MMM, W 'həftə'",
"MMMMW-count-other": "MMM, W 'həftə'",
ms: "mm:ss",
y: "y",
yM: "MM.y",
yMd: "dd.MM.y",
yMEd: "dd.MM.y, E",
yMMM: "MMM y",
yMMMd: "d MMM y",
yMMMEd: "d MMM y, E",
yMMMM: "MMMM y",
yQQQ: "y QQQ",
yQQQQ: "y QQQQ",
"yw-count-one": "y, w 'həftə'",
"yw-count-other": "y, w 'həftə'"
}
},
timeFormats: {
full: "HH:mm:ss zzzz",
long: "HH:mm:ss z",
medium: "HH:mm:ss",
short: "HH:mm"
},
dateFormats: {
full: "d MMMM y, EEEE",
long: "d MMMM y",
medium: "d MMM y",
short: "dd.MM.yy"
},
days: {
format: {
abbreviated: [
"B.",
"B.E.",
"Ç.A.",
"Ç.",
"C.A.",
"C.",
"Ş."
],
narrow: [
"7",
"1",
"2",
"3",
"4",
"5",
"6"
],
short: [
"B.",
"B.E.",
"Ç.A.",
"Ç.",
"C.A.",
"C.",
"Ş."
],
wide: [
"bazar",
"bazar ertəsi",
"çərşənbə axşamı",
"çərşənbə",
"cümə axşamı",
"cümə",
"şənbə"
]
},
"stand-alone": {
abbreviated: [
"B.",
"B.E.",
"Ç.A.",
"Ç.",
"C.A.",
"C.",
"Ş."
],
narrow: [
"7",
"1",
"2",
"3",
"4",
"5",
"6"
],
short: [
"B.",
"B.E.",
"Ç.A.",
"Ç.",
"C.A.",
"C.",
"Ş."
],
wide: [
"bazar",
"bazar ertəsi",
"çərşənbə axşamı",
"çərşənbə",
"cümə axşamı",
"cümə",
"şənbə"
]
}
},
months: {
format: {
abbreviated: [
"yan",
"fev",
"mar",
"apr",
"may",
"iyn",
"iyl",
"avq",
"sen",
"okt",
"noy",
"dek"
],
narrow: [
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"11",
"12"
],
wide: [
"yanvar",
"fevral",
"mart",
"aprel",
"may",
"iyun",
"iyul",
"avqust",
"sentyabr",
"oktyabr",
"noyabr",
"dekabr"
]
},
"stand-alone": {
abbreviated: [
"yan",
"fev",
"mar",
"apr",
"may",
"iyn",
"iyl",
"avq",
"sen",
"okt",
"noy",
"dek"
],
narrow: [
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"11",
"12"
],
wide: [
"Yanvar",
"Fevral",
"Mart",
"Aprel",
"May",
"İyun",
"İyul",
"Avqust",
"Sentyabr",
"Oktyabr",
"Noyabr",
"Dekabr"
]
}
},
quarters: {
format: {
abbreviated: [
"1-ci kv.",
"2-ci kv.",
"3-cü kv.",
"4-cü kv."
],
narrow: [
"1",
"2",
"3",
"4"
],
wide: [
"1-ci kvartal",
"2-ci kvartal",
"3-cü kvartal",
"4-cü kvartal"
]
},
"stand-alone": {
abbreviated: [
"1-ci kv.",
"2-ci kv.",
"3-cü kv.",
"4-cü kv."
],
narrow: [
"1",
"2",
"3",
"4"
],
wide: [
"1-ci kvartal",
"2-ci kvartal",
"3-cü kvartal",
"4-cü kvartal"
]
}
},
dayPeriods: {
format: {
abbreviated: {
midnight: "gecəyarı",
am: "AM",
noon: "günorta",
pm: "PM",
morning1: "sübh",
morning2: "səhər",
afternoon1: "gündüz",
evening1: "axşamüstü",
night1: "axşam",
night2: "gecə"
},
narrow: {
midnight: "gecəyarı",
am: "a",
noon: "g",
pm: "p",
morning1: "sübh",
morning2: "səhər",
afternoon1: "gündüz",
evening1: "axşamüstü",
night1: "axşam",
night2: "gecə"
},
wide: {
midnight: "gecəyarı",
am: "AM",
noon: "günorta",
pm: "PM",
morning1: "sübh",
morning2: "səhər",
afternoon1: "gündüz",
evening1: "axşamüstü",
night1: "axşam",
night2: "gecə"
}
},
"stand-alone": {
abbreviated: {
midnight: "gecəyarı",
am: "AM",
noon: "günorta",
pm: "PM",
morning1: "sübh",
morning2: "səhər",
afternoon1: "gündüz",
evening1: "axşamüstü",
night1: "axşam",
night2: "gecə"
},
narrow: {
midnight: "gecəyarı",
am: "AM",
noon: "günorta",
pm: "PM",
morning1: "sübh",
morning2: "səhər",
afternoon1: "gündüz",
evening1: "axşamüstü",
night1: "axşam",
night2: "gecə"
},
wide: {
midnight: "gecəyarı",
am: "AM",
noon: "günorta",
pm: "PM",
morning1: "sübh",
morning2: "səhər",
afternoon1: "gündüz",
evening1: "axşamüstü",
night1: "axşam",
night2: "gecə"
}
}
},
eras: {
format: {
wide: {
0: "eramızdan əvvəl",
1: "yeni era",
"0-alt-variant": "bizim eradan əvvəl",
"1-alt-variant": "bizim era"
},
abbreviated: {
0: "e.ə.",
1: "y.e.",
"0-alt-variant": "b.e.ə.",
"1-alt-variant": "b.e."
},
narrow: {
0: "e.ə.",
1: "y.e.",
"0-alt-variant": "b.e.ə.",
"1-alt-variant": "b.e."
}
}
},
gmtFormat: "GMT{0}",
gmtZeroFormat: "GMT",
dateFields: {
era: {
wide: "Era",
short: "Era",
narrow: "Era"
},
year: {
wide: "İl",
short: "il",
narrow: "il"
},
quarter: {
wide: "Rüb",
short: "rüb",
narrow: "rüb"
},
month: {
wide: "Ay",
short: "ay",
narrow: "ay"
},
week: {
wide: "Həftə",
short: "həftə",
narrow: "həftə"
},
weekOfMonth: {
wide: "Week Of Month",
short: "Week Of Month",
narrow: "Week Of Month"
},
day: {
wide: "Gün",
short: "Gün",
narrow: "Gün"
},
dayOfYear: {
wide: "Day Of Year",
short: "Day Of Year",
narrow: "Day Of Year"
},
weekday: {
wide: "Həftənin Günü",
short: "Həftənin Günü",
narrow: "Həftənin Günü"
},
weekdayOfMonth: {
wide: "Weekday Of Month",
short: "Weekday Of Month",
narrow: "Weekday Of Month"
},
dayperiod: {
short: "AM/PM",
wide: "AM/PM",
narrow: "AM/PM"
},
hour: {
wide: "Saat",
short: "saat",
narrow: "saat"
},
minute: {
wide: "Dəqiqə",
short: "dəq.",
narrow: "dəq."
},
second: {
wide: "Saniyə",
short: "san.",
narrow: "san."
},
zone: {
wide: "Saat Qurşağı",
short: "Saat Qurşağı",
narrow: "Saat Qurşağı"
}
}
},
firstDay: 1,
likelySubtags: {
az: "az-Latn-AZ"
}
});
|
console.log(URL_FILE_SERVER);
var lastID = 0;
var getLastId = function() {
return lastID;
};
var loadNextFile = function() {
console.log(URL_FILE_SERVER + lastID);
$.ajax({
url: URL_FILE_SERVER + getLastId(),
dataType: 'json',
method: "GET",
success: function(result) {
console.log(result)
lastID = parseInt(result.lastId);
$('#conteudo').append(result.html);
if ($("#conteudo .imagem").length <= 10) {
loadNextFile();
}
},
error: function(e) {
console.log("ERROR:");
console.log(e);
}
})
};
$(function() {
if ($("#conteudo .imagem").length <= 1) {
loadNextFile();
}
var win = $(window);
// Each time the user scrolls
win.scroll(function() {
// End of the document reached?
if ($(document).height() - win.height() == win.scrollTop()) {
//$('#loading').show();
console.log("SCOLL");
loadNextFile();
}
});
}); |
'use strict';
// NIVEL CRUD
var Model = require('../../models/model');
// (para agregar un nuevo conservacion)
// GET /conservacion
exports.getForm = function (req, res) {
var conservacion = Model.Conservacion.build();
res.render('web/conservacion/add', { conservacion: conservacion});
};
// Rutas que terminan en /conservacion
// POST /conservacion
exports.create = function (req, res) {
// bodyParser debe hacer la magia
var conservacion = req.body.conservacion;
var condicionesSeguridad = req.body.condicionesSeguridad;
var conservacion = Model.Conservacion.build({
conservacion: conservacion,
condicionesSeguridad: condicionesSeguridad
});
conservacion.add(function (success) {
res.redirect( '/web/conservacion');
},
function (err) {
res.redirect( '/web/conservacion');
// res.send(err);
});
};
// (trae todos los conservacion)
// GET /conservacion
exports.listPag = function (req, res) {
var conservacion = Model.Conservacion.build();
console.log('GET Paginado pre Select');
var limitPage = 10;
if (currentPage == null ) {
var currentPage = 1;
var initial = 0;
var offset = initial+limitPage;
} else {
var currentPage = req.params.currentPage;
var initial = currentPage*limitPage;
var offset = initial+limitPage;
}
conservacion.retrievePag(initial, offset, limitPage, currentPage, function (conservacion) {
if (conservacion) {
var totalPage = conservacion.count/limitPage;
var count = conservacion.count
res.render('web/conservacion/list.ejs', {
conservaciones: conservacion.rows,
activePage: currentPage,
totalPage: totalPage,
count: count,
limitPage: limitPage
});
} else {
res.send(401, 'No se encontraron Conservaciones');
}
}, function (error) {
console.log(error);
res.send('Conservacion no encontrado');
});
};
// Rutas que terminan en /conservacion/:conservacionId
// PUT /conservacion/:conservacionId
// Actualiza conservacion
exports.update = function (req, res) {
var conservacion = Model.Conservacion.build();
conservacion.id = req.body.id;
conservacion.conservacion = req.body.conservacion;
conservacion.condicionesSeguridad = req.body.condicionesSeguridad;
conservacion.updateById(conservacion.id, function (success) {
console.log(success);
if (success) {
res.redirect('/web/conservacion');
} else {
console.log(success);
res.send(401, 'Conservacion no encontrado');
}
}, function (error) {
console.log(error);
res.send('Conservacion no encontrado');
});
};
// GET /conservacion/:conservacionId
// Toma un conservacion por id
exports.read = function (req, res) {
var conservacion = Model.Conservacion.build();
conservacion.retrieveById(req.params.conservacionId, function (conservacionq) {
if (conservacionq) {
res.render('web/conservacion/edit', {conservacion:conservacionq});
} else {
res.send(401, 'Conservacion no encontrado');
}
}, function (error) {
res.send('Conservacion no encontrado');
});
};
// DELETE /conservacion/conservacionId
// Borra el conservacionId
exports.delete = function (req, res) {
var conservacion = Model.Conservacion.build();
conservacion.removeById(req.params.conservacionId, function (conservacion) {
if (conservacion) {
res.redirect( '/web/conservacion');
} else {
res.send(401, 'Conservacion no encontrado');
}
}, function (error) {
res.send('Conservacion no encontrado');
});
};
|
// @flow
const UnnamedFunction = require('./components/UnnamedFunction').default;
module.exports = {
name: 'function fixture',
component: UnnamedFunction,
props: {}
};
|
'use strict';
var _ = require('lodash');
var $ = require('preconditions').singleton();
var Uuid = require('uuid');
var log = require('npmlog');
log.debug = log.verbose;
log.disableColor();
var Bitcore = require('bitcore-lib');
var Common = require('../common');
var Constants = Common.Constants;
var Defaults = Common.Defaults;
var TxProposalLegacy = require('./txproposal_legacy');
var TxProposalAction = require('./txproposalaction');
function TxProposal() {};
TxProposal.create = function(opts) {
opts = opts || {};
var x = new TxProposal();
x.version = 3;
var now = Date.now();
x.createdOn = Math.floor(now / 1000);
x.id = _.padLeft(now, 14, '0') + Uuid.v4();
x.walletId = opts.walletId;
x.creatorId = opts.creatorId;
x.message = opts.message;
x.payProUrl = opts.payProUrl;
x.changeAddress = opts.changeAddress;
x.setInputs(opts.inputs);
x.outputs = _.map(opts.outputs, function(output) {
return _.pick(output, ['amount', 'toAddress', 'message']);
});
x.outputOrder = _.shuffle(_.range(x.outputs.length + 1));
x.walletM = opts.walletM;
x.walletN = opts.walletN;
x.requiredSignatures = x.walletM;
x.requiredRejections = Math.min(x.walletM, x.walletN - x.walletM + 1),
x.status = 'temporary';
x.actions = [];
x.fee = null;
x.feePerKb = opts.feePerKb;
x.excludeUnconfirmedUtxos = opts.excludeUnconfirmedUtxos;
x.addressType = opts.addressType || (x.walletN > 1 ? Constants.SCRIPT_TYPES.P2SH : Constants.SCRIPT_TYPES.P2PKH);
$.checkState(_.contains(_.values(Constants.SCRIPT_TYPES), x.addressType));
x.customData = opts.customData;
x.amount = x.getTotalAmount();
try {
x.network = opts.network || Bitcore.Address(x.outputs[0].toAddress).toObject().network;
} catch (ex) {}
$.checkState(_.contains(_.values(Constants.NETWORKS), x.network));
return x;
};
TxProposal.fromObj = function(obj) {
if (!(obj.version >= 3)) {
return TxProposalLegacy.fromObj(obj);
}
var x = new TxProposal();
x.version = obj.version;
x.createdOn = obj.createdOn;
x.id = obj.id;
x.walletId = obj.walletId;
x.creatorId = obj.creatorId;
x.outputs = obj.outputs;
x.amount = obj.amount;
x.message = obj.message;
x.payProUrl = obj.payProUrl;
x.changeAddress = obj.changeAddress;
x.inputs = obj.inputs;
x.walletM = obj.walletM;
x.walletN = obj.walletN;
x.requiredSignatures = obj.requiredSignatures;
x.requiredRejections = obj.requiredRejections;
x.status = obj.status;
x.txid = obj.txid;
x.broadcastedOn = obj.broadcastedOn;
x.inputPaths = obj.inputPaths;
x.actions = _.map(obj.actions, function(action) {
return TxProposalAction.fromObj(action);
});
x.outputOrder = obj.outputOrder;
x.fee = obj.fee;
x.network = obj.network;
x.feePerKb = obj.feePerKb;
x.excludeUnconfirmedUtxos = obj.excludeUnconfirmedUtxos;
x.addressType = obj.addressType;
x.customData = obj.customData;
x.proposalSignature = obj.proposalSignature;
x.proposalSignaturePubKey = obj.proposalSignaturePubKey;
x.proposalSignaturePubKeySig = obj.proposalSignaturePubKeySig;
return x;
};
TxProposal.prototype.toObject = function() {
var x = _.cloneDeep(this);
x.isPending = this.isPending();
return x;
};
TxProposal.prototype.setInputs = function(inputs) {
this.inputs = inputs || [];
this.inputPaths = _.pluck(inputs, 'path') || [];
};
TxProposal.prototype._updateStatus = function() {
if (this.status != 'pending') return;
if (this.isRejected()) {
this.status = 'rejected';
} else if (this.isAccepted()) {
this.status = 'accepted';
}
};
TxProposal.prototype._buildTx = function() {
var self = this;
var t = new Bitcore.Transaction();
$.checkState(_.contains(_.values(Constants.SCRIPT_TYPES), self.addressType));
switch (self.addressType) {
case Constants.SCRIPT_TYPES.P2SH:
_.each(self.inputs, function(i) {
t.from(i, i.publicKeys, self.requiredSignatures);
});
break;
case Constants.SCRIPT_TYPES.P2PKH:
t.from(self.inputs);
break;
}
_.each(self.outputs, function(o) {
$.checkState(o.script || o.toAddress, 'Output should have either toAddress or script specified');
if (o.script) {
t.addOutput(new Bitcore.Transaction.Output({
script: o.script,
satoshis: o.amount
}));
} else {
t.to(o.toAddress, o.amount);
}
});
t.fee(self.fee);
t.change(self.changeAddress.address);
// Shuffle outputs for improved privacy
if (t.outputs.length > 1) {
var outputOrder = _.reject(self.outputOrder, function(order) {
return order >= t.outputs.length;
});
$.checkState(t.outputs.length == outputOrder.length);
t.sortOutputs(function(outputs) {
return _.map(outputOrder, function(i) {
return outputs[i];
});
});
}
// Validate inputs vs outputs independently of Bitcore
var totalInputs = _.sum(self.inputs, 'satoshis');
var totalOutputs = _.sum(t.outputs, 'satoshis');
$.checkState(totalInputs - totalOutputs <= Defaults.MAX_TX_FEE);
return t;
};
TxProposal.prototype._getCurrentSignatures = function() {
var acceptedActions = _.filter(this.actions, {
type: 'accept'
});
return _.map(acceptedActions, function(x) {
return {
signatures: x.signatures,
xpub: x.xpub,
};
});
};
TxProposal.prototype.getBitcoreTx = function() {
var self = this;
var t = this._buildTx();
var sigs = this._getCurrentSignatures();
_.each(sigs, function(x) {
self._addSignaturesToBitcoreTx(t, x.signatures, x.xpub);
});
return t;
};
TxProposal.prototype.getRawTx = function() {
var t = this.getBitcoreTx();
return t.uncheckedSerialize();
};
TxProposal.prototype.getEstimatedSize = function() {
// Note: found empirically based on all multisig P2SH inputs and within m & n allowed limits.
var safetyMargin = 0.05;
var walletM = this.requiredSignatures;
var overhead = 4 + 4 + 9 + 9;
var inputSize = walletM * 72 + this.walletN * 36 + 44;
var outputSize = 34;
var nbInputs = this.inputs.length;
var nbOutputs = (_.isArray(this.outputs) ? Math.max(1, this.outputs.length) : 1) + 1;
var size = overhead + inputSize * nbInputs + outputSize * nbOutputs;
return parseInt((size * (1 + safetyMargin)).toFixed(0));
};
TxProposal.prototype.estimateFee = function() {
var fee = this.feePerKb * this.getEstimatedSize() / 1000;
this.fee = parseInt(fee.toFixed(0));
};
/**
* getTotalAmount
*
* @return {Number} total amount of all outputs excluding change output
*/
TxProposal.prototype.getTotalAmount = function() {
return _.sum(this.outputs, 'amount');
};
/**
* getActors
*
* @return {String[]} copayerIds that performed actions in this proposal (accept / reject)
*/
TxProposal.prototype.getActors = function() {
return _.pluck(this.actions, 'copayerId');
};
/**
* getApprovers
*
* @return {String[]} copayerIds that approved the tx proposal (accept)
*/
TxProposal.prototype.getApprovers = function() {
return _.pluck(
_.filter(this.actions, {
type: 'accept'
}), 'copayerId');
};
/**
* getActionBy
*
* @param {String} copayerId
* @return {Object} type / createdOn
*/
TxProposal.prototype.getActionBy = function(copayerId) {
return _.find(this.actions, {
copayerId: copayerId
});
};
TxProposal.prototype.addAction = function(copayerId, type, comment, signatures, xpub) {
var action = TxProposalAction.create({
copayerId: copayerId,
type: type,
signatures: signatures,
xpub: xpub,
comment: comment,
});
this.actions.push(action);
this._updateStatus();
};
TxProposal.prototype._addSignaturesToBitcoreTx = function(tx, signatures, xpub) {
var self = this;
if (signatures.length != this.inputs.length)
throw new Error('Number of signatures does not match number of inputs');
var i = 0,
x = new Bitcore.HDPublicKey(xpub);
_.each(signatures, function(signatureHex) {
var input = self.inputs[i];
try {
var signature = Bitcore.crypto.Signature.fromString(signatureHex);
var pub = x.derive(self.inputPaths[i]).publicKey;
var s = {
inputIndex: i,
signature: signature,
sigtype: Bitcore.crypto.Signature.SIGHASH_ALL,
publicKey: pub,
};
tx.inputs[i].addSignature(tx, s);
i++;
} catch (e) {};
});
if (i != tx.inputs.length)
throw new Error('Wrong signatures');
};
TxProposal.prototype.sign = function(copayerId, signatures, xpub) {
try {
// Tests signatures are OK
var tx = this.getBitcoreTx();
this._addSignaturesToBitcoreTx(tx, signatures, xpub);
this.addAction(copayerId, 'accept', null, signatures, xpub);
if (this.status == 'accepted') {
this.raw = tx.uncheckedSerialize();
this.txid = tx.id;
}
return true;
} catch (e) {
log.debug(e);
return false;
}
};
TxProposal.prototype.reject = function(copayerId, reason) {
this.addAction(copayerId, 'reject', reason);
};
TxProposal.prototype.isTemporary = function() {
return this.status == 'temporary';
};
TxProposal.prototype.isPending = function() {
return !_.contains(['temporary', 'broadcasted', 'rejected'], this.status);
};
TxProposal.prototype.isAccepted = function() {
var votes = _.countBy(this.actions, 'type');
return votes['accept'] >= this.requiredSignatures;
};
TxProposal.prototype.isRejected = function() {
var votes = _.countBy(this.actions, 'type');
return votes['reject'] >= this.requiredRejections;
};
TxProposal.prototype.isBroadcasted = function() {
return this.status == 'broadcasted';
};
TxProposal.prototype.setBroadcasted = function() {
$.checkState(this.txid);
this.status = 'broadcasted';
this.broadcastedOn = Math.floor(Date.now() / 1000);
};
module.exports = TxProposal;
|
import {MemberApi} from './api/member-api';
export class SignUp {
static inject() { return [MemberApi]; }
constructor(memberApi) {
this.heading = "Sign Up";
this.memberApi = memberApi;
this.passwordsMatch = true;
this.errors = [];
this.successMessage = '';
// Member fields
this.member = {
firstName: '',
lastName: '',
email: '',
password: ''
};
this.confirmPassword = '';
}
checkPasswordsMatch() {
this.passwordsMatch = this.member.password == this.confirmPassword;
}
signUp() {
this.errors = [];
this.successMessage = '';
this.memberApi.addMember(this.member).then(function(response) {
this.successMessage = 'New member saved.'; // This should redirect to login screen, or a message to check email for activation link.
this.clearEntries();
}.bind(this)).catch(function(err) {
if (err.content.error.details != null) {
for (var key in err.content.error.details.messages) {
this.errors.push(err.content.error.details.messages[key]);
}
} else {
this.errors.push(err.content.error.message);
}
console.log(this.errors);
}.bind(this));
}
clearEntries() {
this.member.firstName = '';
this.member.lastName = '';
this.member.email = '';
this.member.password = '';
this.confirmPassword = '';
this.checkPasswordsMatch();
}
clearErrors() {
this.errors = [];
this.successMessage = '';
}
clearAll() {
this.clearEntries();
this.clearErrors();
}
}
|
function Year(year) {
this.year = year;
this.isLeap = function () {
return (this.year % 100 == 0 && this.year % 400 == 0) || (this.year % 100 != 0 && this.year % 4 == 0);
}
}
module.exports = Year;
|
// dependencies
var async = require('async');
var should = require('should');
// libraries
var config = require('./../../config');
var gtfs = require('./../../../');
var downloadScript = require('../../../scripts/download');
// test support
var databaseTestSupport = require('./../../support/database')(config);
var db;
// setup fixtures
var agenciesFixtures = [{ agency_key: 'caltrain', url: __dirname + '/../../fixture/caltrain_20120824_0333.zip'}];
var agency_key = agenciesFixtures[0].agency_key;
config.agencies = agenciesFixtures;
describe('gtfs.getStopsByRoute(): ', function(){
before(function(done){
async.series({
connectToDb: function(next){
databaseTestSupport.connect(function(err, _db){
db = _db;
next();
});
}
}, function(){
done();
})
});
after(function(done) {
async.series({
teardownDatabase: function(next){
databaseTestSupport.teardown(next);
},
closeDb: function(next){
databaseTestSupport.close(next);
}
}, function(){
done();
});
});
beforeEach(function(done){
async.series({
teardownDatabase: function(next){
databaseTestSupport.teardown(next);
},
executeDownloadScript: function(next){
downloadScript(config, next);
}
}, function(err, res){
done();
});
});
it('should return error and empty array if no stops exists for given agency, route and direction', function(done){
async.series({
teardownDatabase: function(next){
databaseTestSupport.teardown(next);
}
},function(){
var agency_key = 'non_existing_agency';
var route_id = 'non_existing_route_id';
var direction_id = '0';
gtfs.getStopsByRoute(agency_key, route_id, direction_id, function(err, stops){
should.exist(err);
should.exist(stops);
stops.should.have.length(0);
done();
});
});
});
it('should return array of stops if it exists for given agency, route and direction', function(done){
var agency_key = 'caltrain';
var route_id = 'ct_local_20120701';
var direction_id = '0';
var expectedStopIds = [
'San Jose Caltrain',
'Santa Clara Caltrain',
'Lawrence Caltrain',
'Sunnyvale Caltrain',
'Mountain View Caltrain',
'San Antonio Caltrain',
'California Ave Caltrain',
'Palo Alto Caltrain',
'Menlo Park Caltrain',
'Atherton Caltrain',
'Redwood City Caltrain',
'San Carlos Caltrain',
'Belmont Caltrain',
'Hillsdale Caltrain',
'Hayward Park Caltrain',
'San Mateo Caltrain',
'Burlingame Caltrain',
'Broadway Caltrain',
'Millbrae Caltrain',
'San Bruno Caltrain',
'So. San Francisco Caltrain',
'Bayshore Caltrain',
'22nd Street Caltrain',
'San Francisco Caltrain'
];
gtfs.getStopsByRoute(agency_key, route_id, direction_id, function(err, stops){
should.not.exist(err);
should.exist(stops);
stops.should.have.length(24);
for (var i in stops){
var stop = stops[i];
expectedStopIds[i].should.equal(stop.stop_id, 'The order of stops are expected to be the same');
}
done();
});
});
it('should return array of stops if it exists for given agency, route and direction (opposite direction)', function(done){
var agency_key = 'caltrain';
var route_id = 'ct_local_20120701';
var direction_id = '1';
var expectedStopIds = [
'San Francisco Caltrain',
'22nd Street Caltrain',
'Bayshore Caltrain',
'So. San Francisco Caltrain',
'San Bruno Caltrain',
'Millbrae Caltrain',
'Burlingame Caltrain',
'San Mateo Caltrain',
'Hayward Park Caltrain',
'Hillsdale Caltrain',
'Belmont Caltrain',
'San Carlos Caltrain',
'Redwood City Caltrain',
'Menlo Park Caltrain',
'Palo Alto Caltrain',
'California Ave Caltrain',
'San Antonio Caltrain',
'Mountain View Caltrain',
'Sunnyvale Caltrain',
'Lawrence Caltrain',
'Santa Clara Caltrain',
'College Park Caltrain',
'San Jose Caltrain',
'Tamien Caltrain',
'Capitol Caltrain',
'Blossom Hill Caltrain',
'Morgan Hill Caltrain',
'San Martin Caltrain',
'Gilroy Caltrain'
];
gtfs.getStopsByRoute(agency_key, route_id, direction_id, function(err, stops){
should.not.exist(err);
should.exist(stops);
stops.should.have.length(29);
for (var i in stops){
var stop = stops[i];
expectedStopIds[i].should.equal(stop.stop_id, 'The order of stops are expected to be the same');
}
done();
});
});
it('should return array of all stops for all directions if it exists for given agency and route (without specifying direction)', function(done){
var agency_key = 'caltrain';
var route_id = 'ct_local_20120701';
var expectedResults = {
0: {
direction_id: 0,
stops_count: 24,
stops: [
'San Jose Caltrain',
'Santa Clara Caltrain',
'Lawrence Caltrain',
'Sunnyvale Caltrain',
'Mountain View Caltrain',
'San Antonio Caltrain',
'California Ave Caltrain',
'Palo Alto Caltrain',
'Menlo Park Caltrain',
'Atherton Caltrain',
'Redwood City Caltrain',
'San Carlos Caltrain',
'Belmont Caltrain',
'Hillsdale Caltrain',
'Hayward Park Caltrain',
'San Mateo Caltrain',
'Burlingame Caltrain',
'Broadway Caltrain',
'Millbrae Caltrain',
'San Bruno Caltrain',
'So. San Francisco Caltrain',
'Bayshore Caltrain',
'22nd Street Caltrain',
'San Francisco Caltrain'
]
},
1: {
direction_id: 1,
stops_count: 29,
stops: [
'San Francisco Caltrain',
'22nd Street Caltrain',
'Bayshore Caltrain',
'So. San Francisco Caltrain',
'San Bruno Caltrain',
'Millbrae Caltrain',
'Burlingame Caltrain',
'San Mateo Caltrain',
'Hayward Park Caltrain',
'Hillsdale Caltrain',
'Belmont Caltrain',
'San Carlos Caltrain',
'Redwood City Caltrain',
'Menlo Park Caltrain',
'Palo Alto Caltrain',
'California Ave Caltrain',
'San Antonio Caltrain',
'Mountain View Caltrain',
'Sunnyvale Caltrain',
'Lawrence Caltrain',
'Santa Clara Caltrain',
'College Park Caltrain',
'San Jose Caltrain',
'Tamien Caltrain',
'Capitol Caltrain',
'Blossom Hill Caltrain',
'Morgan Hill Caltrain',
'San Martin Caltrain',
'Gilroy Caltrain'
]
}
};
gtfs.getStopsByRoute(agency_key, route_id, function(err, results){
should.not.exist(err);
should.exist(results);
results.should.have.length(2, 'Should have 2 directions');
for (var i in results){
var row = results[i];
row.should.have.property('direction_id');
row.should.have.property('stops');
row.stops.should.have.length(expectedResults[row.direction_id].stops_count);
for (var k in row.stops){
var stop = row.stops[k];
expectedResults[row.direction_id].stops[k].should.equal(stop.stop_id, 'The order of stops are expected to be the same');
}
}
done();
});
});
});
|
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* Ninja Physics. The Ninja Physics system was created in Flash by Metanet Software and ported to JavaScript by Richard Davey.
*
* It allows for AABB and Circle to Tile collision. Tiles can be any of 34 different types, including slopes, convex and concave shapes.
*
* It does what it does very well, but is ripe for expansion and optimisation. Here are some features that I'd love to see the community add:
*
* * AABB to AABB collision
* * AABB to Circle collision
* * AABB and Circle 'immovable' property support
* * n-way collision, so an AABB/Circle could pass through a tile from below and land upon it.
* * QuadTree or spatial grid for faster Body vs. Tile Group look-ups.
* * Optimise the internal vector math and reduce the quantity of temporary vars created.
* * Expand Gravity and Bounce to allow for separate x/y axis values.
* * Support Bodies linked to Sprites that don't have anchor set to 0.5
*
* Feel free to attempt any of the above and submit a Pull Request with your code! Be sure to include test cases proving they work.
*
* @class Phaser.Physics.Ninja
* @constructor
* @param {Phaser.Game} game - reference to the current game instance.
*/
Phaser.Physics.Ninja = function (game) {
/**
* @property {Phaser.Game} game - Local reference to game.
*/
this.game = game;
/**
* @property {Phaser.Time} time - Local reference to game.time.
*/
this.time = this.game.time;
/**
* @property {number} gravity - The World gravity setting.
*/
this.gravity = 0.2;
/**
* @property {Phaser.Rectangle} bounds - The bounds inside of which the physics world exists. Defaults to match the world bounds.
*/
this.bounds = new Phaser.Rectangle(0, 0, game.world.width, game.world.height);
/**
* @property {number} maxObjects - Used by the QuadTree to set the maximum number of objects per quad.
*/
this.maxObjects = 10;
/**
* @property {number} maxLevels - Used by the QuadTree to set the maximum number of iteration levels.
*/
this.maxLevels = 4;
/**
* @property {Phaser.QuadTree} quadTree - The world QuadTree.
*/
this.quadTree = new Phaser.QuadTree(this.game.world.bounds.x, this.game.world.bounds.y, this.game.world.bounds.width, this.game.world.bounds.height, this.maxObjects, this.maxLevels);
// By default we want the bounds the same size as the world bounds
this.setBoundsToWorld();
};
Phaser.Physics.Ninja.prototype.constructor = Phaser.Physics.Ninja;
Phaser.Physics.Ninja.prototype = {
/**
* This will create a Ninja Physics AABB body on the given game object. Its dimensions will match the width and height of the object at the point it is created.
* A game object can only have 1 physics body active at any one time, and it can't be changed until the object is destroyed.
*
* @method Phaser.Physics.Ninja#enableAABB
* @param {object|array|Phaser.Group} object - The game object to create the physics body on. Can also be an array or Group of objects, a body will be created on every child that has a `body` property.
* @param {boolean} [children=true] - Should a body be created on all children of this object? If true it will recurse down the display list as far as it can go.
*/
enableAABB: function (object, children) {
this.enable(object, 1, 0, 0, children);
},
/**
* This will create a Ninja Physics Circle body on the given game object.
* A game object can only have 1 physics body active at any one time, and it can't be changed until the object is destroyed.
*
* @method Phaser.Physics.Ninja#enableCircle
* @param {object|array|Phaser.Group} object - The game object to create the physics body on. Can also be an array or Group of objects, a body will be created on every child that has a `body` property.
* @param {number} radius - The radius of the Circle.
* @param {boolean} [children=true] - Should a body be created on all children of this object? If true it will recurse down the display list as far as it can go.
*/
enableCircle: function (object, radius, children) {
this.enable(object, 2, 0, radius, children);
},
/**
* This will create a Ninja Physics Tile body on the given game object. There are 34 different types of tile you can create, including 45 degree slopes,
* convex and concave circles and more. The id parameter controls which Tile type is created, but you can also change it at run-time.
* Note that for all degree based tile types they need to have an equal width and height. If the given object doesn't have equal width and height it will use the width.
* A game object can only have 1 physics body active at any one time, and it can't be changed until the object is destroyed.
*
* @method Phaser.Physics.Ninja#enableTile
* @param {object|array|Phaser.Group} object - The game object to create the physics body on. Can also be an array or Group of objects, a body will be created on every child that has a `body` property.
* @param {number} [id=1] - The type of Tile this will use, i.e. Phaser.Physics.Ninja.Tile.SLOPE_45DEGpn, Phaser.Physics.Ninja.Tile.CONVEXpp, etc.
* @param {boolean} [children=true] - Should a body be created on all children of this object? If true it will recurse down the display list as far as it can go.
*/
enableTile: function (object, id, children) {
this.enable(object, 3, id, 0, children);
},
/**
* This will create a Ninja Physics body on the given game object or array of game objects.
* A game object can only have 1 physics body active at any one time, and it can't be changed until the object is destroyed.
*
* @method Phaser.Physics.Ninja#enable
* @param {object|array|Phaser.Group} object - The game object to create the physics body on. Can also be an array or Group of objects, a body will be created on every child that has a `body` property.
* @param {number} [type=1] - The type of Ninja shape to create. 1 = AABB, 2 = Circle or 3 = Tile.
* @param {number} [id=1] - If this body is using a Tile shape, you can set the Tile id here, i.e. Phaser.Physics.Ninja.Tile.SLOPE_45DEGpn, Phaser.Physics.Ninja.Tile.CONVEXpp, etc.
* @param {number} [radius=0] - If this body is using a Circle shape this controls the radius.
* @param {boolean} [children=true] - Should a body be created on all children of this object? If true it will recurse down the display list as far as it can go.
*/
enable: function (object, type, id, radius, children) {
if (typeof type === 'undefined') { type = 1; }
if (typeof id === 'undefined') { id = 1; }
if (typeof radius === 'undefined') { radius = 0; }
if (typeof children === 'undefined') { children = true; }
if (Array.isArray(object))
{
var i = object.length;
while (i--)
{
if (object[i] instanceof Phaser.Group)
{
// If it's a Group then we do it on the children regardless
this.enable(object[i].children, type, id, radius, children);
}
else
{
this.enableBody(object[i], type, id, radius);
if (children && object[i].hasOwnProperty('children') && object[i].children.length > 0)
{
this.enable(object[i], type, id, radius, true);
}
}
}
}
else
{
if (object instanceof Phaser.Group)
{
// If it's a Group then we do it on the children regardless
this.enable(object.children, type, id, radius, children);
}
else
{
this.enableBody(object, type, id, radius);
if (children && object.hasOwnProperty('children') && object.children.length > 0)
{
this.enable(object.children, type, id, radius, true);
}
}
}
},
/**
* Creates a Ninja Physics body on the given game object.
* A game object can only have 1 physics body active at any one time, and it can't be changed until the body is nulled.
*
* @method Phaser.Physics.Ninja#enableBody
* @param {object} object - The game object to create the physics body on. A body will only be created if this object has a null `body` property.
*/
enableBody: function (object, type, id, radius) {
if (object.hasOwnProperty('body') && object.body === null)
{
object.body = new Phaser.Physics.Ninja.Body(this, object, type, id, radius);
object.anchor.set(0.5);
}
},
/**
* Updates the size of this physics world.
*
* @method Phaser.Physics.Ninja#setBounds
* @param {number} x - Top left most corner of the world.
* @param {number} y - Top left most corner of the world.
* @param {number} width - New width of the world. Can never be smaller than the Game.width.
* @param {number} height - New height of the world. Can never be smaller than the Game.height.
*/
setBounds: function (x, y, width, height) {
this.bounds.setTo(x, y, width, height);
},
/**
* Updates the size of this physics world to match the size of the game world.
*
* @method Phaser.Physics.Ninja#setBoundsToWorld
*/
setBoundsToWorld: function () {
this.bounds.setTo(this.game.world.bounds.x, this.game.world.bounds.y, this.game.world.bounds.width, this.game.world.bounds.height);
},
/**
* Clears all physics bodies from the given TilemapLayer that were created with `World.convertTilemap`.
*
* @method Phaser.Physics.Ninja#clearTilemapLayerBodies
* @param {Phaser.Tilemap} map - The Tilemap to get the map data from.
* @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to map.currentLayer.
*/
clearTilemapLayerBodies: function (map, layer) {
layer = map.getLayer(layer);
var i = map.layers[layer].bodies.length;
while (i--)
{
map.layers[layer].bodies[i].destroy();
}
map.layers[layer].bodies.length = [];
},
/**
* Goes through all tiles in the given Tilemap and TilemapLayer and converts those set to collide into physics tiles.
* Only call this *after* you have specified all of the tiles you wish to collide with calls like Tilemap.setCollisionBetween, etc.
* Every time you call this method it will destroy any previously created bodies and remove them from the world.
* Therefore understand it's a very expensive operation and not to be done in a core game update loop.
*
* In Ninja the Tiles have an ID from 0 to 33, where 0 is 'empty', 1 is a full tile, 2 is a 45-degree slope, etc. You can find the ID
* list either at the very bottom of `Tile.js`, or in a handy visual reference in the `resources/Ninja Physics Debug Tiles` folder in the repository.
* The slopeMap parameter is an array that controls how the indexes of the tiles in your tilemap data will map to the Ninja Tile IDs.
* For example if you had 6 tiles in your tileset: Imagine the first 4 should be converted into fully solid Tiles and the other 2 are 45-degree slopes.
* Your slopeMap array would look like this: `[ 1, 1, 1, 1, 2, 3 ]`.
* Where each element of the array is a tile in your tilemap and the resulting Ninja Tile it should create.
*
* @method Phaser.Physics.Ninja#convertTilemap
* @param {Phaser.Tilemap} map - The Tilemap to get the map data from.
* @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to map.currentLayer.
* @param {object} [slopeMap] - The tilemap index to Tile ID map.
* @return {array} An array of the Phaser.Physics.Ninja.Tile objects that were created.
*/
convertTilemap: function (map, layer, slopeMap) {
layer = map.getLayer(layer);
// If the bodies array is already populated we need to nuke it
this.clearTilemapLayerBodies(map, layer);
for (var y = 0, h = map.layers[layer].height; y < h; y++)
{
for (var x = 0, w = map.layers[layer].width; x < w; x++)
{
var tile = map.layers[layer].data[y][x];
if (tile && slopeMap.hasOwnProperty(tile.index))
{
var body = new Phaser.Physics.Ninja.Body(this, null, 3, slopeMap[tile.index], 0, tile.worldX + tile.centerX, tile.worldY + tile.centerY, tile.width, tile.height);
map.layers[layer].bodies.push(body);
}
}
}
return map.layers[layer].bodies;
},
/**
* Checks for overlaps between two game objects. The objects can be Sprites, Groups or Emitters.
* You can perform Sprite vs. Sprite, Sprite vs. Group and Group vs. Group overlap checks.
* Unlike collide the objects are NOT automatically separated or have any physics applied, they merely test for overlap results.
* The second parameter can be an array of objects, of differing types.
*
* @method Phaser.Physics.Ninja#overlap
* @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter} object1 - The first object to check. Can be an instance of Phaser.Sprite, Phaser.Group or Phaser.Particles.Emitter.
* @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|array} object2 - The second object or array of objects to check. Can be Phaser.Sprite, Phaser.Group or Phaser.Particles.Emitter.
* @param {function} [overlapCallback=null] - An optional callback function that is called if the objects overlap. The two objects will be passed to this function in the same order in which you specified them.
* @param {function} [processCallback=null] - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then overlapCallback will only be called if processCallback returns true.
* @param {object} [callbackContext] - The context in which to run the callbacks.
* @returns {boolean} True if an overlap occured otherwise false.
*/
overlap: function (object1, object2, overlapCallback, processCallback, callbackContext) {
overlapCallback = overlapCallback || null;
processCallback = processCallback || null;
callbackContext = callbackContext || overlapCallback;
this._result = false;
this._total = 0;
if (Array.isArray(object2))
{
for (var i = 0, len = object2.length; i < len; i++)
{
this.collideHandler(object1, object2[i], overlapCallback, processCallback, callbackContext, true);
}
}
else
{
this.collideHandler(object1, object2, overlapCallback, processCallback, callbackContext, true);
}
return (this._total > 0);
},
/**
* Checks for collision between two game objects. You can perform Sprite vs. Sprite, Sprite vs. Group, Group vs. Group, Sprite vs. Tilemap Layer or Group vs. Tilemap Layer collisions.
* The second parameter can be an array of objects, of differing types.
* The objects are also automatically separated. If you don't require separation then use ArcadePhysics.overlap instead.
* An optional processCallback can be provided. If given this function will be called when two sprites are found to be colliding. It is called before any separation takes place,
* giving you the chance to perform additional checks. If the function returns true then the collision and separation is carried out. If it returns false it is skipped.
* The collideCallback is an optional function that is only called if two sprites collide. If a processCallback has been set then it needs to return true for collideCallback to be called.
*
* @method Phaser.Physics.Ninja#collide
* @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.TilemapLayer} object1 - The first object to check. Can be an instance of Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter, or Phaser.TilemapLayer.
* @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.TilemapLayer|array} object2 - The second object or array of objects to check. Can be Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter or Phaser.TilemapLayer.
* @param {function} [collideCallback=null] - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them.
* @param {function} [processCallback=null] - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them.
* @param {object} [callbackContext] - The context in which to run the callbacks.
* @returns {boolean} True if a collision occured otherwise false.
*/
collide: function (object1, object2, collideCallback, processCallback, callbackContext) {
collideCallback = collideCallback || null;
processCallback = processCallback || null;
callbackContext = callbackContext || collideCallback;
this._result = false;
this._total = 0;
if (Array.isArray(object2))
{
for (var i = 0, len = object2.length; i < len; i++)
{
this.collideHandler(object1, object2[i], collideCallback, processCallback, callbackContext, false);
}
}
else
{
this.collideHandler(object1, object2, collideCallback, processCallback, callbackContext, false);
}
return (this._total > 0);
},
/**
* Internal collision handler.
*
* @method Phaser.Physics.Ninja#collideHandler
* @private
* @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.TilemapLayer} object1 - The first object to check. Can be an instance of Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter, or Phaser.TilemapLayer.
* @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.TilemapLayer} object2 - The second object to check. Can be an instance of Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter or Phaser.TilemapLayer. Can also be an array of objects to check.
* @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them.
* @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them.
* @param {object} callbackContext - The context in which to run the callbacks.
* @param {boolean} overlapOnly - Just run an overlap or a full collision.
*/
collideHandler: function (object1, object2, collideCallback, processCallback, callbackContext, overlapOnly) {
// Only collide valid objects
if (typeof object2 === 'undefined' && (object1.type === Phaser.GROUP || object1.type === Phaser.EMITTER))
{
this.collideGroupVsSelf(object1, collideCallback, processCallback, callbackContext, overlapOnly);
return;
}
if (object1 && object2 && object1.exists && object2.exists)
{
// SPRITES
if (object1.type == Phaser.SPRITE || object1.type == Phaser.TILESPRITE)
{
if (object2.type == Phaser.SPRITE || object2.type == Phaser.TILESPRITE)
{
this.collideSpriteVsSprite(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly);
}
else if (object2.type == Phaser.GROUP || object2.type == Phaser.EMITTER)
{
this.collideSpriteVsGroup(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly);
}
else if (object2.type == Phaser.TILEMAPLAYER)
{
this.collideSpriteVsTilemapLayer(object1, object2, collideCallback, processCallback, callbackContext);
}
}
// GROUPS
else if (object1.type == Phaser.GROUP)
{
if (object2.type == Phaser.SPRITE || object2.type == Phaser.TILESPRITE)
{
this.collideSpriteVsGroup(object2, object1, collideCallback, processCallback, callbackContext, overlapOnly);
}
else if (object2.type == Phaser.GROUP || object2.type == Phaser.EMITTER)
{
this.collideGroupVsGroup(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly);
}
else if (object2.type == Phaser.TILEMAPLAYER)
{
this.collideGroupVsTilemapLayer(object1, object2, collideCallback, processCallback, callbackContext);
}
}
// TILEMAP LAYERS
else if (object1.type == Phaser.TILEMAPLAYER)
{
if (object2.type == Phaser.SPRITE || object2.type == Phaser.TILESPRITE)
{
this.collideSpriteVsTilemapLayer(object2, object1, collideCallback, processCallback, callbackContext);
}
else if (object2.type == Phaser.GROUP || object2.type == Phaser.EMITTER)
{
this.collideGroupVsTilemapLayer(object2, object1, collideCallback, processCallback, callbackContext);
}
}
// EMITTER
else if (object1.type == Phaser.EMITTER)
{
if (object2.type == Phaser.SPRITE || object2.type == Phaser.TILESPRITE)
{
this.collideSpriteVsGroup(object2, object1, collideCallback, processCallback, callbackContext, overlapOnly);
}
else if (object2.type == Phaser.GROUP || object2.type == Phaser.EMITTER)
{
this.collideGroupVsGroup(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly);
}
else if (object2.type == Phaser.TILEMAPLAYER)
{
this.collideGroupVsTilemapLayer(object1, object2, collideCallback, processCallback, callbackContext);
}
}
}
},
/**
* An internal function. Use Phaser.Physics.Ninja.collide instead.
*
* @method Phaser.Physics.Ninja#collideSpriteVsSprite
* @private
*/
collideSpriteVsSprite: function (sprite1, sprite2, collideCallback, processCallback, callbackContext, overlapOnly) {
if (this.separate(sprite1.body, sprite2.body, processCallback, callbackContext, overlapOnly))
{
if (collideCallback)
{
collideCallback.call(callbackContext, sprite1, sprite2);
}
this._total++;
}
},
/**
* An internal function. Use Phaser.Physics.Ninja.collide instead.
*
* @method Phaser.Physics.Ninja#collideSpriteVsGroup
* @private
*/
collideSpriteVsGroup: function (sprite, group, collideCallback, processCallback, callbackContext, overlapOnly) {
if (group.length === 0)
{
return;
}
// What is the sprite colliding with in the quadtree?
// this.quadTree.clear();
// this.quadTree = new Phaser.QuadTree(this.game.world.bounds.x, this.game.world.bounds.y, this.game.world.bounds.width, this.game.world.bounds.height, this.maxObjects, this.maxLevels);
// this.quadTree.populate(group);
// this._potentials = this.quadTree.retrieve(sprite);
for (var i = 0, len = group.children.length; i < len; i++)
{
// We have our potential suspects, are they in this group?
if (group.children[i].exists && group.children[i].body && this.separate(sprite.body, group.children[i].body, processCallback, callbackContext, overlapOnly))
{
if (collideCallback)
{
collideCallback.call(callbackContext, sprite, group.children[i]);
}
this._total++;
}
}
},
/**
* An internal function. Use Phaser.Physics.Ninja.collide instead.
*
* @method Phaser.Physics.Ninja#collideGroupVsSelf
* @private
*/
collideGroupVsSelf: function (group, collideCallback, processCallback, callbackContext, overlapOnly) {
if (group.length === 0)
{
return;
}
var len = group.children.length;
for (var i = 0; i < len; i++)
{
for (var j = i + 1; j <= len; j++)
{
if (group.children[i] && group.children[j] && group.children[i].exists && group.children[j].exists)
{
this.collideSpriteVsSprite(group.children[i], group.children[j], collideCallback, processCallback, callbackContext, overlapOnly);
}
}
}
},
/**
* An internal function. Use Phaser.Physics.Ninja.collide instead.
*
* @method Phaser.Physics.Ninja#collideGroupVsGroup
* @private
*/
collideGroupVsGroup: function (group1, group2, collideCallback, processCallback, callbackContext, overlapOnly) {
if (group1.length === 0 || group2.length === 0)
{
return;
}
for (var i = 0, len = group1.children.length; i < len; i++)
{
if (group1.children[i].exists)
{
this.collideSpriteVsGroup(group1.children[i], group2, collideCallback, processCallback, callbackContext, overlapOnly);
}
}
},
/**
* The core separation function to separate two physics bodies.
* @method Phaser.Physics.Ninja#separate
* @param {Phaser.Physics.Ninja.Body} body1 - The Body object to separate.
* @param {Phaser.Physics.Ninja.Body} body2 - The Body object to separate.
* @returns {boolean} Returns true if the bodies collided, otherwise false.
*/
separate: function (body1, body2) {
if (body1.type !== Phaser.Physics.NINJA || body2.type !== Phaser.Physics.NINJA)
{
return false;
}
if (body1.aabb && body2.aabb)
{
return body1.aabb.collideAABBVsAABB(body2.aabb);
}
if (body1.aabb && body2.tile)
{
return body1.aabb.collideAABBVsTile(body2.tile);
}
if (body1.tile && body2.aabb)
{
return body2.aabb.collideAABBVsTile(body1.tile);
}
if (body1.circle && body2.tile)
{
return body1.circle.collideCircleVsTile(body2.tile);
}
if (body1.tile && body2.circle)
{
return body2.circle.collideCircleVsTile(body1.tile);
}
}
};
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* The Physics Body is linked to a single Sprite. All physics operations should be performed against the body rather than
* the Sprite itself. For example you can set the velocity, bounce values etc all on the Body.
*
* @class Phaser.Physics.Ninja.Body
* @constructor
* @param {Phaser.Physics.Ninja} system - The physics system this Body belongs to.
* @param {Phaser.Sprite} sprite - The Sprite object this physics body belongs to.
* @param {number} [type=1] - The type of Ninja shape to create. 1 = AABB, 2 = Circle or 3 = Tile.
* @param {number} [id=1] - If this body is using a Tile shape, you can set the Tile id here, i.e. Phaser.Physics.Ninja.Tile.SLOPE_45DEGpn, Phaser.Physics.Ninja.Tile.CONVEXpp, etc.
* @param {number} [radius=16] - If this body is using a Circle shape this controls the radius.
* @param {number} [x=0] - The x coordinate of this Body. This is only used if a sprite is not provided.
* @param {number} [y=0] - The y coordinate of this Body. This is only used if a sprite is not provided.
* @param {number} [width=0] - The width of this Body. This is only used if a sprite is not provided.
* @param {number} [height=0] - The height of this Body. This is only used if a sprite is not provided.
*/
Phaser.Physics.Ninja.Body = function (system, sprite, type, id, radius, x, y, width, height) {
sprite = sprite || null;
if (typeof type === 'undefined') { type = 1; }
if (typeof id === 'undefined') { id = 1; }
if (typeof radius === 'undefined') { radius = 16; }
/**
* @property {Phaser.Sprite} sprite - Reference to the parent Sprite.
*/
this.sprite = sprite;
/**
* @property {Phaser.Game} game - Local reference to game.
*/
this.game = system.game;
/**
* @property {number} type - The type of physics system this body belongs to.
*/
this.type = Phaser.Physics.NINJA;
/**
* @property {Phaser.Physics.Ninja} system - The parent physics system.
*/
this.system = system;
/**
* @property {Phaser.Physics.Ninja.AABB} aabb - The AABB object this body is using for collision.
*/
this.aabb = null;
/**
* @property {Phaser.Physics.Ninja.Tile} tile - The Tile object this body is using for collision.
*/
this.tile = null;
/**
* @property {Phaser.Physics.Ninja.Circle} circle - The Circle object this body is using for collision.
*/
this.circle = null;
/**
* @property {object} shape - A local reference to the body shape.
*/
this.shape = null;
// Setting drag to 0 and friction to 0 means you get a normalised speed (px psec)
/**
* @property {number} drag - The drag applied to this object as it moves.
* @default
*/
this.drag = 1;
/**
* @property {number} friction - The friction applied to this object as it moves.
* @default
*/
this.friction = 0.05;
/**
* @property {number} gravityScale - How much of the world gravity should be applied to this object? 1 = all of it, 0.5 = 50%, etc.
* @default
*/
this.gravityScale = 1;
/**
* @property {number} bounce - The bounciness of this object when it collides. A value between 0 and 1. We recommend setting it to 0.999 to avoid jittering.
* @default
*/
this.bounce = 0.3;
/**
* @property {Phaser.Point} velocity - The velocity in pixels per second sq. of the Body.
*/
this.velocity = new Phaser.Point();
/**
* @property {number} facing - A const reference to the direction the Body is traveling or facing.
* @default
*/
this.facing = Phaser.NONE;
/**
* @property {boolean} immovable - An immovable Body will not receive any impacts from other bodies. Not fully implemented.
* @default
*/
this.immovable = false;
/**
* A Body can be set to collide against the World bounds automatically and rebound back into the World if this is set to true. Otherwise it will leave the World.
* @property {boolean} collideWorldBounds - Should the Body collide with the World bounds?
*/
this.collideWorldBounds = true;
/**
* Set the checkCollision properties to control which directions collision is processed for this Body.
* For example checkCollision.up = false means it won't collide when the collision happened while moving up.
* @property {object} checkCollision - An object containing allowed collision.
*/
this.checkCollision = { none: false, any: true, up: true, down: true, left: true, right: true };
/**
* This object is populated with boolean values when the Body collides with another.
* touching.up = true means the collision happened to the top of this Body for example.
* @property {object} touching - An object containing touching results.
*/
this.touching = { none: true, up: false, down: false, left: false, right: false };
/**
* This object is populated with previous touching values from the bodies previous collision.
* @property {object} wasTouching - An object containing previous touching results.
*/
this.wasTouching = { none: true, up: false, down: false, left: false, right: false };
/**
* @property {number} maxSpeed - The maximum speed this body can travel at (taking drag and friction into account)
* @default
*/
this.maxSpeed = 8;
if (sprite)
{
x = sprite.x;
y = sprite.y;
width = sprite.width;
height = sprite.height;
if (sprite.anchor.x === 0)
{
x += (sprite.width * 0.5);
}
if (sprite.anchor.y === 0)
{
y += (sprite.height * 0.5);
}
}
if (type === 1)
{
this.aabb = new Phaser.Physics.Ninja.AABB(this, x, y, width, height);
this.shape = this.aabb;
}
else if (type === 2)
{
this.circle = new Phaser.Physics.Ninja.Circle(this, x, y, radius);
this.shape = this.circle;
}
else if (type === 3)
{
this.tile = new Phaser.Physics.Ninja.Tile(this, x, y, width, height, id);
this.shape = this.tile;
}
};
Phaser.Physics.Ninja.Body.prototype = {
/**
* Internal method.
*
* @method Phaser.Physics.Ninja.Body#preUpdate
* @protected
*/
preUpdate: function () {
// Store and reset collision flags
this.wasTouching.none = this.touching.none;
this.wasTouching.up = this.touching.up;
this.wasTouching.down = this.touching.down;
this.wasTouching.left = this.touching.left;
this.wasTouching.right = this.touching.right;
this.touching.none = true;
this.touching.up = false;
this.touching.down = false;
this.touching.left = false;
this.touching.right = false;
this.shape.integrate();
if (this.collideWorldBounds)
{
this.shape.collideWorldBounds();
}
},
/**
* Internal method.
*
* @method Phaser.Physics.Ninja.Body#postUpdate
* @protected
*/
postUpdate: function () {
if (this.sprite)
{
if (this.sprite.type === Phaser.TILESPRITE)
{
// TileSprites don't use their anchor property, so we need to adjust the coordinates
this.sprite.x = this.shape.pos.x - this.shape.xw;
this.sprite.y = this.shape.pos.y - this.shape.yw;
}
else
{
this.sprite.x = this.shape.pos.x;
this.sprite.y = this.shape.pos.y;
}
}
if (this.velocity.x < 0)
{
this.facing = Phaser.LEFT;
}
else if (this.velocity.x > 0)
{
this.facing = Phaser.RIGHT;
}
if (this.velocity.y < 0)
{
this.facing = Phaser.UP;
}
else if (this.velocity.y > 0)
{
this.facing = Phaser.DOWN;
}
},
/**
* Stops all movement of this body.
*
* @method Phaser.Physics.Ninja.Body#setZeroVelocity
*/
setZeroVelocity: function () {
this.shape.oldpos.x = this.shape.pos.x;
this.shape.oldpos.y = this.shape.pos.y;
},
/**
* Moves the Body forwards based on its current angle and the given speed.
* The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms).
*
* @method Phaser.Physics.Body#moveTo
* @param {number} speed - The speed at which it should move forwards.
* @param {number} angle - The angle in which it should move, given in degrees.
*/
moveTo: function (speed, angle) {
var magnitude = speed * this.game.time.physicsElapsed;
var angle = this.game.math.degToRad(angle);
this.shape.pos.x = this.shape.oldpos.x + (magnitude * Math.cos(angle));
this.shape.pos.y = this.shape.oldpos.y + (magnitude * Math.sin(angle));
},
/**
* Moves the Body backwards based on its current angle and the given speed.
* The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms).
*
* @method Phaser.Physics.Body#moveBackward
* @param {number} speed - The speed at which it should move backwards.
* @param {number} angle - The angle in which it should move, given in degrees.
*/
moveFrom: function (speed, angle) {
var magnitude = -speed * this.game.time.physicsElapsed;
var angle = this.game.math.degToRad(angle);
this.shape.pos.x = this.shape.oldpos.x + (magnitude * Math.cos(angle));
this.shape.pos.y = this.shape.oldpos.y + (magnitude * Math.sin(angle));
},
/**
* If this Body is dynamic then this will move it to the left by setting its x velocity to the given speed.
* The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms).
*
* @method Phaser.Physics.Body#moveLeft
* @param {number} speed - The speed at which it should move to the left, in pixels per second.
*/
moveLeft: function (speed) {
var fx = -speed * this.game.time.physicsElapsed;
this.shape.pos.x = this.shape.oldpos.x + Math.min(this.maxSpeed, Math.max(-this.maxSpeed, this.shape.pos.x - this.shape.oldpos.x + fx));
},
/**
* If this Body is dynamic then this will move it to the right by setting its x velocity to the given speed.
* The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms).
*
* @method Phaser.Physics.Body#moveRight
* @param {number} speed - The speed at which it should move to the right, in pixels per second.
*/
moveRight: function (speed) {
var fx = speed * this.game.time.physicsElapsed;
this.shape.pos.x = this.shape.oldpos.x + Math.min(this.maxSpeed, Math.max(-this.maxSpeed, this.shape.pos.x - this.shape.oldpos.x + fx));
},
/**
* If this Body is dynamic then this will move it up by setting its y velocity to the given speed.
* The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms).
*
* @method Phaser.Physics.Body#moveUp
* @param {number} speed - The speed at which it should move up, in pixels per second.
*/
moveUp: function (speed) {
var fx = -speed * this.game.time.physicsElapsed;
this.shape.pos.y = this.shape.oldpos.y + Math.min(this.maxSpeed, Math.max(-this.maxSpeed, this.shape.pos.y - this.shape.oldpos.y + fx));
},
/**
* If this Body is dynamic then this will move it down by setting its y velocity to the given speed.
* The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms).
*
* @method Phaser.Physics.Body#moveDown
* @param {number} speed - The speed at which it should move down, in pixels per second.
*/
moveDown: function (speed) {
var fx = speed * this.game.time.physicsElapsed;
this.shape.pos.y = this.shape.oldpos.y + Math.min(this.maxSpeed, Math.max(-this.maxSpeed, this.shape.pos.y - this.shape.oldpos.y + fx));
},
/**
* Resets all Body values and repositions on the Sprite.
*
* @method Phaser.Physics.Ninja.Body#reset
*/
reset: function () {
this.velocity.set(0);
this.shape.pos.x = this.sprite.x;
this.shape.pos.y = this.sprite.y;
this.shape.oldpos.copyFrom(this.shape.pos);
},
/**
* Returns the absolute delta x value.
*
* @method Phaser.Physics.Ninja.Body#deltaAbsX
* @return {number} The absolute delta value.
*/
deltaAbsX: function () {
return (this.deltaX() > 0 ? this.deltaX() : -this.deltaX());
},
/**
* Returns the absolute delta y value.
*
* @method Phaser.Physics.Ninja.Body#deltaAbsY
* @return {number} The absolute delta value.
*/
deltaAbsY: function () {
return (this.deltaY() > 0 ? this.deltaY() : -this.deltaY());
},
/**
* Returns the delta x value. The difference between Body.x now and in the previous step.
*
* @method Phaser.Physics.Ninja.Body#deltaX
* @return {number} The delta value. Positive if the motion was to the right, negative if to the left.
*/
deltaX: function () {
return this.shape.pos.x - this.shape.oldpos.x;
},
/**
* Returns the delta y value. The difference between Body.y now and in the previous step.
*
* @method Phaser.Physics.Ninja.Body#deltaY
* @return {number} The delta value. Positive if the motion was downwards, negative if upwards.
*/
deltaY: function () {
return this.shape.pos.y - this.shape.oldpos.y;
},
/**
* Destroys this body's reference to the sprite and system, and destroys its shape.
*
* @method Phaser.Physics.Ninja.Body#destroy
*/
destroy: function() {
this.sprite = null;
this.system = null;
this.aabb = null;
this.tile = null;
this.circle = null;
this.shape.destroy();
this.shape = null;
}
};
/**
* @name Phaser.Physics.Ninja.Body#x
* @property {number} x - The x position.
*/
Object.defineProperty(Phaser.Physics.Ninja.Body.prototype, "x", {
get: function () {
return this.shape.pos.x;
},
set: function (value) {
this.shape.pos.x = value;
}
});
/**
* @name Phaser.Physics.Ninja.Body#y
* @property {number} y - The y position.
*/
Object.defineProperty(Phaser.Physics.Ninja.Body.prototype, "y", {
get: function () {
return this.shape.pos.y;
},
set: function (value) {
this.shape.pos.y = value;
}
});
/**
* @name Phaser.Physics.Ninja.Body#width
* @property {number} width - The width of this Body
* @readonly
*/
Object.defineProperty(Phaser.Physics.Ninja.Body.prototype, "width", {
get: function () {
return this.shape.width;
}
});
/**
* @name Phaser.Physics.Ninja.Body#height
* @property {number} height - The height of this Body
* @readonly
*/
Object.defineProperty(Phaser.Physics.Ninja.Body.prototype, "height", {
get: function () {
return this.shape.height;
}
});
/**
* @name Phaser.Physics.Ninja.Body#bottom
* @property {number} bottom - The bottom value of this Body (same as Body.y + Body.height)
* @readonly
*/
Object.defineProperty(Phaser.Physics.Ninja.Body.prototype, "bottom", {
get: function () {
return this.shape.pos.y + this.shape.yw;
}
});
/**
* @name Phaser.Physics.Ninja.Body#right
* @property {number} right - The right value of this Body (same as Body.x + Body.width)
* @readonly
*/
Object.defineProperty(Phaser.Physics.Ninja.Body.prototype, "right", {
get: function () {
return this.shape.pos.x + this.shape.xw;
}
});
/**
* @name Phaser.Physics.Ninja.Body#speed
* @property {number} speed - The speed of this Body
* @readonly
*/
Object.defineProperty(Phaser.Physics.Ninja.Body.prototype, "speed", {
get: function () {
return Math.sqrt(this.shape.velocity.x * this.shape.velocity.x + this.shape.velocity.y * this.shape.velocity.y);
}
});
/**
* @name Phaser.Physics.Ninja.Body#angle
* @property {number} angle - The angle of this Body
* @readonly
*/
Object.defineProperty(Phaser.Physics.Ninja.Body.prototype, "angle", {
get: function () {
return Math.atan2(this.shape.velocity.y, this.shape.velocity.x);
}
});
/**
* Render Sprite's Body.
*
* @method Phaser.Physics.Ninja.Body#render
* @param {object} context - The context to render to.
* @param {Phaser.Physics.Ninja.Body} body - The Body to render.
* @param {string} [color='rgba(0,255,0,0.4)'] - color of the debug shape to be rendered. (format is css color string).
* @param {boolean} [filled=true] - Render the shape as a filled (default, true) or a stroked (false)
*/
Phaser.Physics.Ninja.Body.render = function(context, body, color, filled) {
color = color || 'rgba(0,255,0,0.4)';
if (typeof filled === 'undefined')
{
filled = true;
}
if (body.aabb || body.circle)
{
body.shape.render(context, body.game.camera.x, body.game.camera.y, color, filled);
}
};
/* jshint camelcase: false */
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* Ninja Physics AABB constructor.
* Note: This class could be massively optimised and reduced in size. I leave that challenge up to you.
*
* @class Phaser.Physics.Ninja.AABB
* @constructor
* @param {Phaser.Physics.Ninja.Body} body - The body that owns this shape.
* @param {number} x - The x coordinate to create this shape at.
* @param {number} y - The y coordinate to create this shape at.
* @param {number} width - The width of this AABB.
* @param {number} height - The height of this AABB.
*/
Phaser.Physics.Ninja.AABB = function (body, x, y, width, height) {
/**
* @property {Phaser.Physics.Ninja.Body} system - A reference to the body that owns this shape.
*/
this.body = body;
/**
* @property {Phaser.Physics.Ninja} system - A reference to the physics system.
*/
this.system = body.system;
/**
* @property {Phaser.Point} pos - The position of this object.
*/
this.pos = new Phaser.Point(x, y);
/**
* @property {Phaser.Point} oldpos - The position of this object in the previous update.
*/
this.oldpos = new Phaser.Point(x, y);
/**
* @property {number} xw - Half the width.
* @readonly
*/
this.xw = Math.abs(width / 2);
/**
* @property {number} xw - Half the height.
* @readonly
*/
this.yw = Math.abs(height / 2);
/**
* @property {number} width - The width.
* @readonly
*/
this.width = width;
/**
* @property {number} height - The height.
* @readonly
*/
this.height = height;
/**
* @property {number} oH - Internal var.
* @private
*/
this.oH = 0;
/**
* @property {number} oV - Internal var.
* @private
*/
this.oV = 0;
/**
* @property {Phaser.Point} velocity - The velocity of this object.
*/
this.velocity = new Phaser.Point();
/**
* @property {object} aabbTileProjections - All of the collision response handlers.
*/
this.aabbTileProjections = {};
this.aabbTileProjections[Phaser.Physics.Ninja.Tile.TYPE_FULL] = this.projAABB_Full;
this.aabbTileProjections[Phaser.Physics.Ninja.Tile.TYPE_45DEG] = this.projAABB_45Deg;
this.aabbTileProjections[Phaser.Physics.Ninja.Tile.TYPE_CONCAVE] = this.projAABB_Concave;
this.aabbTileProjections[Phaser.Physics.Ninja.Tile.TYPE_CONVEX] = this.projAABB_Convex;
this.aabbTileProjections[Phaser.Physics.Ninja.Tile.TYPE_22DEGs] = this.projAABB_22DegS;
this.aabbTileProjections[Phaser.Physics.Ninja.Tile.TYPE_22DEGb] = this.projAABB_22DegB;
this.aabbTileProjections[Phaser.Physics.Ninja.Tile.TYPE_67DEGs] = this.projAABB_67DegS;
this.aabbTileProjections[Phaser.Physics.Ninja.Tile.TYPE_67DEGb] = this.projAABB_67DegB;
this.aabbTileProjections[Phaser.Physics.Ninja.Tile.TYPE_HALF] = this.projAABB_Half;
};
Phaser.Physics.Ninja.AABB.prototype.constructor = Phaser.Physics.Ninja.AABB;
Phaser.Physics.Ninja.AABB.COL_NONE = 0;
Phaser.Physics.Ninja.AABB.COL_AXIS = 1;
Phaser.Physics.Ninja.AABB.COL_OTHER = 2;
Phaser.Physics.Ninja.AABB.prototype = {
/**
* Updates this AABBs position.
*
* @method Phaser.Physics.Ninja.AABB#integrate
*/
integrate: function () {
var px = this.pos.x;
var py = this.pos.y;
// integrate
this.pos.x += (this.body.drag * this.pos.x) - (this.body.drag * this.oldpos.x);
this.pos.y += (this.body.drag * this.pos.y) - (this.body.drag * this.oldpos.y) + (this.system.gravity * this.body.gravityScale);
// store
this.velocity.set(this.pos.x - px, this.pos.y - py);
this.oldpos.set(px, py);
},
/**
* Process a world collision and apply the resulting forces.
*
* @method Phaser.Physics.Ninja.AABB#reportCollisionVsWorld
* @param {number} px - The tangent velocity
* @param {number} py - The tangent velocity
* @param {number} dx - Collision normal
* @param {number} dy - Collision normal
* @param {number} obj - Object this AABB collided with
*/
reportCollisionVsWorld: function (px, py, dx, dy) {
var p = this.pos;
var o = this.oldpos;
// Calc velocity
var vx = p.x - o.x;
var vy = p.y - o.y;
// Find component of velocity parallel to collision normal
var dp = (vx * dx + vy * dy);
var nx = dp * dx; //project velocity onto collision normal
var ny = dp * dy; //nx,ny is normal velocity
var tx = vx - nx; //px,py is tangent velocity
var ty = vy - ny;
// We only want to apply collision response forces if the object is travelling into, and not out of, the collision
var b, bx, by, fx, fy;
if (dp < 0)
{
fx = tx * this.body.friction;
fy = ty * this.body.friction;
b = 1 + this.body.bounce;
bx = (nx * b);
by = (ny * b);
if (dx === 1)
{
this.body.touching.left = true;
}
else if (dx === -1)
{
this.body.touching.right = true;
}
if (dy === 1)
{
this.body.touching.up = true;
}
else if (dy === -1)
{
this.body.touching.down = true;
}
}
else
{
// Moving out of collision, do not apply forces
bx = by = fx = fy = 0;
}
// Project object out of collision
p.x += px;
p.y += py;
// Apply bounce+friction impulses which alter velocity
o.x += px + bx + fx;
o.y += py + by + fy;
},
reverse: function () {
var vx = this.pos.x - this.oldpos.x;
var vy = this.pos.y - this.oldpos.y;
if (this.oldpos.x < this.pos.x)
{
this.oldpos.x = this.pos.x + vx;
// this.oldpos.x = this.pos.x + (vx + 1 + this.body.bounce);
}
else if (this.oldpos.x > this.pos.x)
{
this.oldpos.x = this.pos.x - vx;
// this.oldpos.x = this.pos.x - (vx + 1 + this.body.bounce);
}
if (this.oldpos.y < this.pos.y)
{
this.oldpos.y = this.pos.y + vy;
// this.oldpos.y = this.pos.y + (vy + 1 + this.body.bounce);
}
else if (this.oldpos.y > this.pos.y)
{
this.oldpos.y = this.pos.y - vy;
// this.oldpos.y = this.pos.y - (vy + 1 + this.body.bounce);
}
},
/**
* Process a body collision and apply the resulting forces. Still very much WIP and doesn't work fully. Feel free to fix!
*
* @method Phaser.Physics.Ninja.AABB#reportCollisionVsBody
* @param {number} px - The tangent velocity
* @param {number} py - The tangent velocity
* @param {number} dx - Collision normal
* @param {number} dy - Collision normal
* @param {number} obj - Object this AABB collided with
*/
reportCollisionVsBody: function (px, py, dx, dy, obj) {
var vx1 = this.pos.x - this.oldpos.x; // Calc velocity of this object
var vy1 = this.pos.y - this.oldpos.y;
var dp1 = (vx1 * dx + vy1 * dy); // Find component of velocity parallel to collision normal
// We only want to apply collision response forces if the object is travelling into, and not out of, the collision
if (this.body.immovable && obj.body.immovable)
{
// Split the separation then return, no forces applied as they come to a stand-still
px *= 0.5;
py *= 0.5;
this.pos.add(px, py);
this.oldpos.set(this.pos.x, this.pos.y);
obj.pos.subtract(px, py);
obj.oldpos.set(obj.pos.x, obj.pos.y);
return;
}
else if (!this.body.immovable && !obj.body.immovable)
{
// separate
px *= 0.5;
py *= 0.5;
this.pos.add(px, py);
obj.pos.subtract(px, py);
if (dp1 < 0)
{
this.reverse();
obj.reverse();
}
}
else if (!this.body.immovable)
{
this.pos.subtract(px, py);
if (dp1 < 0)
{
this.reverse();
}
}
else if (!obj.body.immovable)
{
obj.pos.subtract(px, py);
if (dp1 < 0)
{
obj.reverse();
}
}
},
/**
* Collides this AABB against the world bounds.
*
* @method Phaser.Physics.Ninja.AABB#collideWorldBounds
*/
collideWorldBounds: function () {
var dx = this.system.bounds.x - (this.pos.x - this.xw);
if (0 < dx)
{
this.reportCollisionVsWorld(dx, 0, 1, 0, null);
}
else
{
dx = (this.pos.x + this.xw) - this.system.bounds.right;
if (0 < dx)
{
this.reportCollisionVsWorld(-dx, 0, -1, 0, null);
}
}
var dy = this.system.bounds.y - (this.pos.y - this.yw);
if (0 < dy)
{
this.reportCollisionVsWorld(0, dy, 0, 1, null);
}
else
{
dy = (this.pos.y + this.yw) - this.system.bounds.bottom;
if (0 < dy)
{
this.reportCollisionVsWorld(0, -dy, 0, -1, null);
}
}
},
/**
* Collides this AABB against a AABB.
*
* @method Phaser.Physics.Ninja.AABB#collideAABBVsAABB
* @param {Phaser.Physics.Ninja.AABB} aabb - The AABB to collide against.
*/
collideAABBVsAABB: function (aabb) {
var pos = this.pos;
var c = aabb;
var tx = c.pos.x;
var ty = c.pos.y;
var txw = c.xw;
var tyw = c.yw;
var dx = pos.x - tx;//tile->obj delta
var px = (txw + this.xw) - Math.abs(dx);//penetration depth in x
if (0 < px)
{
var dy = pos.y - ty;//tile->obj delta
var py = (tyw + this.yw) - Math.abs(dy);//pen depth in y
if (0 < py)
{
//object may be colliding with tile; call tile-specific collision function
//calculate projection vectors
if (px < py)
{
//project in x
if (dx < 0)
{
//project to the left
px *= -1;
py = 0;
}
else
{
//proj to right
py = 0;
}
}
else
{
//project in y
if (dy < 0)
{
//project up
px = 0;
py *= -1;
}
else
{
//project down
px = 0;
}
}
var l = Math.sqrt(px * px + py * py);
this.reportCollisionVsBody(px, py, px / l, py / l, c);
return Phaser.Physics.Ninja.AABB.COL_AXIS;
}
}
return false;
},
/**
* Collides this AABB against a Tile.
*
* @method Phaser.Physics.Ninja.AABB#collideAABBVsTile
* @param {Phaser.Physics.Ninja.Tile} tile - The Tile to collide against.
*/
collideAABBVsTile: function (tile) {
var dx = this.pos.x - tile.pos.x; // tile->obj delta
var px = (tile.xw + this.xw) - Math.abs(dx); // penetration depth in x
if (0 < px)
{
var dy = this.pos.y - tile.pos.y; // tile->obj delta
var py = (tile.yw + this.yw) - Math.abs(dy); // pen depth in y
if (0 < py)
{
// Calculate projection vectors
if (px < py)
{
// Project in x
if (dx < 0)
{
// Project to the left
px *= -1;
py = 0;
}
else
{
// Project to the right
py = 0;
}
}
else
{
// Project in y
if (dy < 0)
{
// Project up
px = 0;
py *= -1;
}
else
{
// Project down
px = 0;
}
}
// Object may be colliding with tile; call tile-specific collision function
return this.resolveTile(px, py, this, tile);
}
}
return false;
},
/**
* Resolves tile collision.
*
* @method Phaser.Physics.Ninja.AABB#resolveTile
* @param {number} x - Penetration depth on the x axis.
* @param {number} y - Penetration depth on the y axis.
* @param {Phaser.Physics.Ninja.AABB} body - The AABB involved in the collision.
* @param {Phaser.Physics.Ninja.Tile} tile - The Tile involved in the collision.
* @return {boolean} True if the collision was processed, otherwise false.
*/
resolveTile: function (x, y, body, tile) {
if (0 < tile.id)
{
return this.aabbTileProjections[tile.type](x, y, body, tile);
}
else
{
// console.warn("Ninja.AABB.resolveTile was called with an empty (or unknown) tile!: id=" + tile.id + ")");
return false;
}
},
/**
* Resolves Full tile collision.
*
* @method Phaser.Physics.Ninja.AABB#projAABB_Full
* @param {number} x - Penetration depth on the x axis.
* @param {number} y - Penetration depth on the y axis.
* @param {Phaser.Physics.Ninja.AABB} obj - The AABB involved in the collision.
* @param {Phaser.Physics.Ninja.Tile} t - The Tile involved in the collision.
* @return {number} The result of the collision.
*/
projAABB_Full: function (x, y, obj, t) {
var l = Math.sqrt(x * x + y * y);
obj.reportCollisionVsWorld(x, y, x / l, y / l, t);
return Phaser.Physics.Ninja.AABB.COL_AXIS;
},
/**
* Resolves Half tile collision.
*
* @method Phaser.Physics.Ninja.AABB#projAABB_Half
* @param {number} x - Penetration depth on the x axis.
* @param {number} y - Penetration depth on the y axis.
* @param {Phaser.Physics.Ninja.AABB} obj - The AABB involved in the collision.
* @param {Phaser.Physics.Ninja.Tile} t - The Tile involved in the collision.
* @return {number} The result of the collision.
*/
projAABB_Half: function (x, y, obj, t) {
//signx or signy must be 0; the other must be -1 or 1
//calculate the projection vector for the half-edge, and then
//(if collision is occuring) pick the minimum
var sx = t.signx;
var sy = t.signy;
var ox = (obj.pos.x - (sx*obj.xw)) - t.pos.x;//this gives is the coordinates of the innermost
var oy = (obj.pos.y - (sy*obj.yw)) - t.pos.y;//point on the AABB, relative to the tile center
//we perform operations analogous to the 45deg tile, except we're using
//an axis-aligned slope instead of an angled one..
//if the dotprod of (ox,oy) and (sx,sy) is negative, the corner is in the slope
//and we need toproject it out by the magnitude of the projection of (ox,oy) onto (sx,sy)
var dp = (ox*sx) + (oy*sy);
if (dp < 0)
{
//collision; project delta onto slope and use this to displace the object
sx *= -dp;//(sx,sy) is now the projection vector
sy *= -dp;
var lenN = Math.sqrt(sx*sx + sy*sy);
var lenP = Math.sqrt(x*x + y*y);
if (lenP < lenN)
{
//project along axis; note that we're assuming that this tile is horizontal OR vertical
//relative to the AABB's current tile, and not diagonal OR the current tile.
obj.reportCollisionVsWorld(x,y,x/lenP, y/lenP, t);
return Phaser.Physics.Ninja.AABB.COL_AXIS;
}
else
{
//note that we could use -= instead of -dp
obj.reportCollisionVsWorld(sx,sy,t.signx, t.signy, t);
return Phaser.Physics.Ninja.AABB.COL_OTHER;
}
}
return Phaser.Physics.Ninja.AABB.COL_NONE;
},
/**
* Resolves 45 Degree tile collision.
*
* @method Phaser.Physics.Ninja.AABB#projAABB_45Deg
* @param {number} x - Penetration depth on the x axis.
* @param {number} y - Penetration depth on the y axis.
* @param {Phaser.Physics.Ninja.AABB} obj - The AABB involved in the collision.
* @param {Phaser.Physics.Ninja.Tile} t - The Tile involved in the collision.
* @return {number} The result of the collision.
*/
projAABB_45Deg: function (x, y, obj, t) {
var signx = t.signx;
var signy = t.signy;
var ox = (obj.pos.x - (signx*obj.xw)) - t.pos.x;//this gives is the coordinates of the innermost
var oy = (obj.pos.y - (signy*obj.yw)) - t.pos.y;//point on the AABB, relative to the tile center
var sx = t.sx;
var sy = t.sy;
//if the dotprod of (ox,oy) and (sx,sy) is negative, the corner is in the slope
//and we need toproject it out by the magnitude of the projection of (ox,oy) onto (sx,sy)
var dp = (ox*sx) + (oy*sy);
if (dp < 0)
{
//collision; project delta onto slope and use this to displace the object
sx *= -dp;//(sx,sy) is now the projection vector
sy *= -dp;
var lenN = Math.sqrt(sx*sx + sy*sy);
var lenP = Math.sqrt(x*x + y*y);
if (lenP < lenN)
{
//project along axis
obj.reportCollisionVsWorld(x,y,x/lenP, y/lenP, t);
return Phaser.Physics.Ninja.AABB.COL_AXIS;
}
else
{
//project along slope
obj.reportCollisionVsWorld(sx,sy,t.sx,t.sy);
return Phaser.Physics.Ninja.AABB.COL_OTHER;
}
}
return Phaser.Physics.Ninja.AABB.COL_NONE;
},
/**
* Resolves 22 Degree tile collision.
*
* @method Phaser.Physics.Ninja.AABB#projAABB_22DegS
* @param {number} x - Penetration depth on the x axis.
* @param {number} y - Penetration depth on the y axis.
* @param {Phaser.Physics.Ninja.AABB} obj - The AABB involved in the collision.
* @param {Phaser.Physics.Ninja.Tile} t - The Tile involved in the collision.
* @return {number} The result of the collision.
*/
projAABB_22DegS: function (x, y, obj, t) {
var signx = t.signx;
var signy = t.signy;
//first we need to check to make sure we're colliding with the slope at all
var py = obj.pos.y - (signy*obj.yw);
var penY = t.pos.y - py;//this is the vector from the innermost point on the box to the highest point on
//the tile; if it is positive, this means the box is above the tile and
//no collision is occuring
if (0 < (penY*signy))
{
var ox = (obj.pos.x - (signx*obj.xw)) - (t.pos.x + (signx*t.xw));//this gives is the coordinates of the innermost
var oy = (obj.pos.y - (signy*obj.yw)) - (t.pos.y - (signy*t.yw));//point on the AABB, relative to a point on the slope
var sx = t.sx;//get slope unit normal
var sy = t.sy;
//if the dotprod of (ox,oy) and (sx,sy) is negative, the corner is in the slope
//and we need toproject it out by the magnitude of the projection of (ox,oy) onto (sx,sy)
var dp = (ox*sx) + (oy*sy);
if (dp < 0)
{
//collision; project delta onto slope and use this to displace the object
sx *= -dp;//(sx,sy) is now the projection vector
sy *= -dp;
var lenN = Math.sqrt(sx*sx + sy*sy);
var lenP = Math.sqrt(x*x + y*y);
var aY = Math.abs(penY);
if (lenP < lenN)
{
if (aY < lenP)
{
obj.reportCollisionVsWorld(0, penY, 0, penY/aY, t);
return Phaser.Physics.Ninja.AABB.COL_OTHER;
}
else
{
obj.reportCollisionVsWorld(x,y,x/lenP, y/lenP, t);
return Phaser.Physics.Ninja.AABB.COL_AXIS;
}
}
else
{
if (aY < lenN)
{
obj.reportCollisionVsWorld(0, penY, 0, penY/aY, t);
return Phaser.Physics.Ninja.AABB.COL_OTHER;
}
else
{
obj.reportCollisionVsWorld(sx,sy,t.sx,t.sy,t);
return Phaser.Physics.Ninja.AABB.COL_OTHER;
}
}
}
}
//if we've reached this point, no collision has occured
return Phaser.Physics.Ninja.AABB.COL_NONE;
},
/**
* Resolves 22 Degree tile collision.
*
* @method Phaser.Physics.Ninja.AABB#projAABB_22DegB
* @param {number} x - Penetration depth on the x axis.
* @param {number} y - Penetration depth on the y axis.
* @param {Phaser.Physics.Ninja.AABB} obj - The AABB involved in the collision.
* @param {Phaser.Physics.Ninja.Tile} t - The Tile involved in the collision.
* @return {number} The result of the collision.
*/
projAABB_22DegB: function (x, y, obj, t) {
var signx = t.signx;
var signy = t.signy;
var ox = (obj.pos.x - (signx*obj.xw)) - (t.pos.x - (signx*t.xw));//this gives is the coordinates of the innermost
var oy = (obj.pos.y - (signy*obj.yw)) - (t.pos.y + (signy*t.yw));//point on the AABB, relative to a point on the slope
var sx = t.sx;//get slope unit normal
var sy = t.sy;
//if the dotprod of (ox,oy) and (sx,sy) is negative, the corner is in the slope
//and we need toproject it out by the magnitude of the projection of (ox,oy) onto (sx,sy)
var dp = (ox*sx) + (oy*sy);
if (dp < 0)
{
//collision; project delta onto slope and use this to displace the object
sx *= -dp;//(sx,sy) is now the projection vector
sy *= -dp;
var lenN = Math.sqrt(sx*sx + sy*sy);
var lenP = Math.sqrt(x*x + y*y);
if (lenP < lenN)
{
obj.reportCollisionVsWorld(x,y,x/lenP, y/lenP, t);
return Phaser.Physics.Ninja.AABB.COL_AXIS;
}
else
{
obj.reportCollisionVsWorld(sx,sy,t.sx,t.sy,t);
return Phaser.Physics.Ninja.AABB.COL_OTHER;
}
}
return Phaser.Physics.Ninja.AABB.COL_NONE;
},
/**
* Resolves 67 Degree tile collision.
*
* @method Phaser.Physics.Ninja.AABB#projAABB_67DegS
* @param {number} x - Penetration depth on the x axis.
* @param {number} y - Penetration depth on the y axis.
* @param {Phaser.Physics.Ninja.AABB} obj - The AABB involved in the collision.
* @param {Phaser.Physics.Ninja.Tile} t - The Tile involved in the collision.
* @return {number} The result of the collision.
*/
projAABB_67DegS: function (x, y, obj, t) {
var signx = t.signx;
var signy = t.signy;
var px = obj.pos.x - (signx*obj.xw);
var penX = t.pos.x - px;
if (0 < (penX*signx))
{
var ox = (obj.pos.x - (signx*obj.xw)) - (t.pos.x - (signx*t.xw));//this gives is the coordinates of the innermost
var oy = (obj.pos.y - (signy*obj.yw)) - (t.pos.y + (signy*t.yw));//point on the AABB, relative to a point on the slope
var sx = t.sx;//get slope unit normal
var sy = t.sy;
//if the dotprod of (ox,oy) and (sx,sy) is negative, the corner is in the slope
//and we need to project it out by the magnitude of the projection of (ox,oy) onto (sx,sy)
var dp = (ox*sx) + (oy*sy);
if (dp < 0)
{
//collision; project delta onto slope and use this to displace the object
sx *= -dp;//(sx,sy) is now the projection vector
sy *= -dp;
var lenN = Math.sqrt(sx*sx + sy*sy);
var lenP = Math.sqrt(x*x + y*y);
var aX = Math.abs(penX);
if (lenP < lenN)
{
if (aX < lenP)
{
obj.reportCollisionVsWorld(penX, 0, penX/aX, 0, t);
return Phaser.Physics.Ninja.AABB.COL_OTHER;
}
else
{
obj.reportCollisionVsWorld(x,y,x/lenP, y/lenP, t);
return Phaser.Physics.Ninja.AABB.COL_AXIS;
}
}
else
{
if (aX < lenN)
{
obj.reportCollisionVsWorld(penX, 0, penX/aX, 0, t);
return Phaser.Physics.Ninja.AABB.COL_OTHER;
}
else
{
obj.reportCollisionVsWorld(sx,sy,t.sx,t.sy,t);
return Phaser.Physics.Ninja.AABB.COL_OTHER;
}
}
}
}
//if we've reached this point, no collision has occured
return Phaser.Physics.Ninja.AABB.COL_NONE;
},
/**
* Resolves 67 Degree tile collision.
*
* @method Phaser.Physics.Ninja.AABB#projAABB_67DegB
* @param {number} x - Penetration depth on the x axis.
* @param {number} y - Penetration depth on the y axis.
* @param {Phaser.Physics.Ninja.AABB} obj - The AABB involved in the collision.
* @param {Phaser.Physics.Ninja.Tile} t - The Tile involved in the collision.
* @return {number} The result of the collision.
*/
projAABB_67DegB: function (x, y, obj, t) {
var signx = t.signx;
var signy = t.signy;
var ox = (obj.pos.x - (signx*obj.xw)) - (t.pos.x + (signx*t.xw));//this gives is the coordinates of the innermost
var oy = (obj.pos.y - (signy*obj.yw)) - (t.pos.y - (signy*t.yw));//point on the AABB, relative to a point on the slope
var sx = t.sx;//get slope unit normal
var sy = t.sy;
//if the dotprod of (ox,oy) and (sx,sy) is negative, the corner is in the slope
//and we need toproject it out by the magnitude of the projection of (ox,oy) onto (sx,sy)
var dp = (ox*sx) + (oy*sy);
if (dp < 0)
{
//collision; project delta onto slope and use this to displace the object
sx *= -dp;//(sx,sy) is now the projection vector
sy *= -dp;
var lenN = Math.sqrt(sx*sx + sy*sy);
var lenP = Math.sqrt(x*x + y*y);
if (lenP < lenN)
{
obj.reportCollisionVsWorld(x,y,x/lenP, y/lenP, t);
return Phaser.Physics.Ninja.AABB.COL_AXIS;
}
else
{
obj.reportCollisionVsWorld(sx,sy,t.sx,t.sy,t);
return Phaser.Physics.Ninja.AABB.COL_OTHER;
}
}
return Phaser.Physics.Ninja.AABB.COL_NONE;
},
/**
* Resolves Convex tile collision.
*
* @method Phaser.Physics.Ninja.AABB#projAABB_Convex
* @param {number} x - Penetration depth on the x axis.
* @param {number} y - Penetration depth on the y axis.
* @param {Phaser.Physics.Ninja.AABB} obj - The AABB involved in the collision.
* @param {Phaser.Physics.Ninja.Tile} t - The Tile involved in the collision.
* @return {number} The result of the collision.
*/
projAABB_Convex: function (x, y, obj, t) {
//if distance from "innermost" corner of AABB is less than than tile radius,
//collision is occuring and we need to project
var signx = t.signx;
var signy = t.signy;
var ox = (obj.pos.x - (signx * obj.xw)) - (t.pos.x - (signx * t.xw));//(ox,oy) is the vector from the circle center to
var oy = (obj.pos.y - (signy * obj.yw)) - (t.pos.y - (signy * t.yw));//the AABB
var len = Math.sqrt(ox * ox + oy * oy);
var twid = t.xw * 2;
var rad = Math.sqrt(twid * twid + 0);//this gives us the radius of a circle centered on the tile's corner and extending to the opposite edge of the tile;
//note that this should be precomputed at compile-time since it's constant
var pen = rad - len;
if (((signx * ox) < 0) || ((signy * oy) < 0))
{
//the test corner is "outside" the 1/4 of the circle we're interested in
var lenP = Math.sqrt(x * x + y * y);
obj.reportCollisionVsWorld(x, y, x / lenP, y / lenP, t);
return Phaser.Physics.Ninja.AABB.COL_AXIS;//we need to report
}
else if (0 < pen)
{
//project along corner->circle vector
ox /= len;
oy /= len;
obj.reportCollisionVsWorld(ox * pen, oy * pen, ox, oy, t);
return Phaser.Physics.Ninja.AABB.COL_OTHER;
}
return Phaser.Physics.Ninja.AABB.COL_NONE;
},
/**
* Resolves Concave tile collision.
*
* @method Phaser.Physics.Ninja.AABB#projAABB_Concave
* @param {number} x - Penetration depth on the x axis.
* @param {number} y - Penetration depth on the y axis.
* @param {Phaser.Physics.Ninja.AABB} obj - The AABB involved in the collision.
* @param {Phaser.Physics.Ninja.Tile} t - The Tile involved in the collision.
* @return {number} The result of the collision.
*/
projAABB_Concave: function (x, y, obj, t) {
//if distance from "innermost" corner of AABB is further than tile radius,
//collision is occuring and we need to project
var signx = t.signx;
var signy = t.signy;
var ox = (t.pos.x + (signx * t.xw)) - (obj.pos.x - (signx * obj.xw));//(ox,oy) is the vector form the innermost AABB corner to the
var oy = (t.pos.y + (signy * t.yw)) - (obj.pos.y - (signy * obj.yw));//circle's center
var twid = t.xw * 2;
var rad = Math.sqrt(twid * twid + 0);//this gives us the radius of a circle centered on the tile's corner and extending to the opposite edge of the tile;
//note that this should be precomputed at compile-time since it's constant
var len = Math.sqrt(ox * ox + oy * oy);
var pen = len - rad;
if (0 < pen)
{
//collision; we need to either project along the axes, or project along corner->circlecenter vector
var lenP = Math.sqrt(x * x + y * y);
if (lenP < pen)
{
//it's shorter to move along axis directions
obj.reportCollisionVsWorld(x, y, x / lenP, y / lenP, t);
return Phaser.Physics.Ninja.AABB.COL_AXIS;
}
else
{
//project along corner->circle vector
ox /= len;//len should never be 0, since if it IS 0, rad should be > than len
oy /= len;//and we should never reach here
obj.reportCollisionVsWorld(ox * pen, oy * pen, ox, oy, t);
return Phaser.Physics.Ninja.AABB.COL_OTHER;
}
}
return Phaser.Physics.Ninja.AABB.COL_NONE;
},
/**
* Destroys this AABB's reference to Body and System
*
* @method Phaser.Physics.Ninja.AABB#destroy
*/
destroy: function() {
this.body = null;
this.system = null;
},
/**
* Render this AABB for debugging purposes.
*
* @method Phaser.Physics.Ninja.AABB#render
* @param {object} context - The context to render to.
* @param {number} xOffset - X offset from AABB's position to render at.
* @param {number} yOffset - Y offset from AABB's position to render at.
* @param {string} color - color of the debug shape to be rendered. (format is css color string).
* @param {boolean} filled - Render the shape as solid (true) or hollow (false).
*/
render: function(context, xOffset, yOffset, color, filled) {
var left = this.pos.x - this.xw - xOffset;
var top = this.pos.y - this.yw - yOffset;
if (filled)
{
context.fillStyle = color;
context.fillRect(left, top, this.width, this.height);
}
else
{
context.strokeStyle = color;
context.strokeRect(left, top, this.width, this.height);
}
}
};
/* jshint camelcase: false */
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* Ninja Physics Tile constructor.
* A Tile is defined by its width, height and type. It's type can include slope data, such as 45 degree slopes, or convex slopes.
* Understand that for any type including a slope (types 2 to 29) the Tile must be SQUARE, i.e. have an equal width and height.
* Also note that as Tiles are primarily used for levels they have gravity disabled and world bounds collision disabled by default.
*
* Note: This class could be massively optimised and reduced in size. I leave that challenge up to you.
*
* @class Phaser.Physics.Ninja.Tile
* @constructor
* @param {Phaser.Physics.Ninja.Body} body - The body that owns this shape.
* @param {number} x - The x coordinate to create this shape at.
* @param {number} y - The y coordinate to create this shape at.
* @param {number} width - The width of this AABB.
* @param {number} height - The height of this AABB.
* @param {number} [type=1] - The type of Ninja shape to create. 1 = AABB, 2 = Circle or 3 = Tile.
*/
Phaser.Physics.Ninja.Tile = function (body, x, y, width, height, type) {
if (typeof type === 'undefined') { type = Phaser.Physics.Ninja.Tile.EMPTY; }
/**
* @property {Phaser.Physics.Ninja.Body} system - A reference to the body that owns this shape.
*/
this.body = body;
/**
* @property {Phaser.Physics.Ninja} system - A reference to the physics system.
*/
this.system = body.system;
/**
* @property {number} id - The ID of this Tile.
* @readonly
*/
this.id = type;
/**
* @property {number} type - The type of this Tile.
* @readonly
*/
this.type = Phaser.Physics.Ninja.Tile.TYPE_EMPTY;
/**
* @property {Phaser.Point} pos - The position of this object.
*/
this.pos = new Phaser.Point(x, y);
/**
* @property {Phaser.Point} oldpos - The position of this object in the previous update.
*/
this.oldpos = new Phaser.Point(x, y);
if (this.id > 1 && this.id < 30)
{
// Tile Types 2 to 29 require square tile dimensions, so use the width as the base
height = width;
}
/**
* @property {number} xw - Half the width.
* @readonly
*/
this.xw = Math.abs(width / 2);
/**
* @property {number} xw - Half the height.
* @readonly
*/
this.yw = Math.abs(height / 2);
/**
* @property {number} width - The width.
* @readonly
*/
this.width = width;
/**
* @property {number} height - The height.
* @readonly
*/
this.height = height;
/**
* @property {Phaser.Point} velocity - The velocity of this object.
*/
this.velocity = new Phaser.Point();
/**
* @property {number} signx - Internal var.
* @private
*/
this.signx = 0;
/**
* @property {number} signy - Internal var.
* @private
*/
this.signy = 0;
/**
* @property {number} sx - Internal var.
* @private
*/
this.sx = 0;
/**
* @property {number} sy - Internal var.
* @private
*/
this.sy = 0;
// By default Tiles disable gravity and world bounds collision
this.body.gravityScale = 0;
this.body.collideWorldBounds = false;
if (this.id > 0)
{
this.setType(this.id);
}
};
Phaser.Physics.Ninja.Tile.prototype.constructor = Phaser.Physics.Ninja.Tile;
Phaser.Physics.Ninja.Tile.prototype = {
/**
* Updates this objects position.
*
* @method Phaser.Physics.Ninja.Tile#integrate
*/
integrate: function () {
var px = this.pos.x;
var py = this.pos.y;
this.pos.x += (this.body.drag * this.pos.x) - (this.body.drag * this.oldpos.x);
this.pos.y += (this.body.drag * this.pos.y) - (this.body.drag * this.oldpos.y) + (this.system.gravity * this.body.gravityScale);
this.velocity.set(this.pos.x - px, this.pos.y - py);
this.oldpos.set(px, py);
},
/**
* Tiles cannot collide with the world bounds, it's up to you to keep them where you want them. But we need this API stub to satisfy the Body.
*
* @method Phaser.Physics.Ninja.Tile#collideWorldBounds
*/
collideWorldBounds: function () {
var dx = this.system.bounds.x - (this.pos.x - this.xw);
if (0 < dx)
{
this.reportCollisionVsWorld(dx, 0, 1, 0, null);
}
else
{
dx = (this.pos.x + this.xw) - this.system.bounds.right;
if (0 < dx)
{
this.reportCollisionVsWorld(-dx, 0, -1, 0, null);
}
}
var dy = this.system.bounds.y - (this.pos.y - this.yw);
if (0 < dy)
{
this.reportCollisionVsWorld(0, dy, 0, 1, null);
}
else
{
dy = (this.pos.y + this.yw) - this.system.bounds.bottom;
if (0 < dy)
{
this.reportCollisionVsWorld(0, -dy, 0, -1, null);
}
}
},
/**
* Process a world collision and apply the resulting forces.
*
* @method Phaser.Physics.Ninja.Tile#reportCollisionVsWorld
* @param {number} px - The tangent velocity
* @param {number} py - The tangent velocity
* @param {number} dx - Collision normal
* @param {number} dy - Collision normal
* @param {number} obj - Object this Tile collided with
*/
reportCollisionVsWorld: function (px, py, dx, dy) {
var p = this.pos;
var o = this.oldpos;
// Calc velocity
var vx = p.x - o.x;
var vy = p.y - o.y;
// Find component of velocity parallel to collision normal
var dp = (vx * dx + vy * dy);
var nx = dp * dx; //project velocity onto collision normal
var ny = dp * dy; //nx,ny is normal velocity
var tx = vx - nx; //px,py is tangent velocity
var ty = vy - ny;
// We only want to apply collision response forces if the object is travelling into, and not out of, the collision
var b, bx, by, fx, fy;
if (dp < 0)
{
fx = tx * this.body.friction;
fy = ty * this.body.friction;
b = 1 + this.body.bounce;
bx = (nx * b);
by = (ny * b);
if (dx === 1)
{
this.body.touching.left = true;
}
else if (dx === -1)
{
this.body.touching.right = true;
}
if (dy === 1)
{
this.body.touching.up = true;
}
else if (dy === -1)
{
this.body.touching.down = true;
}
}
else
{
// Moving out of collision, do not apply forces
bx = by = fx = fy = 0;
}
// Project object out of collision
p.x += px;
p.y += py;
// Apply bounce+friction impulses which alter velocity
o.x += px + bx + fx;
o.y += py + by + fy;
},
/**
* Tiles cannot collide with the world bounds, it's up to you to keep them where you want them. But we need this API stub to satisfy the Body.
*
* @method Phaser.Physics.Ninja.Tile#setType
* @param {number} id - The type of Tile this will use, i.e. Phaser.Physics.Ninja.Tile.SLOPE_45DEGpn, Phaser.Physics.Ninja.Tile.CONVEXpp, etc.
*/
setType: function (id) {
if (id === Phaser.Physics.Ninja.Tile.EMPTY)
{
this.clear();
}
else
{
this.id = id;
this.updateType();
}
return this;
},
/**
* Sets this tile to be empty.
*
* @method Phaser.Physics.Ninja.Tile#clear
*/
clear: function () {
this.id = Phaser.Physics.Ninja.Tile.EMPTY;
this.updateType();
},
/**
* Destroys this Tiles reference to Body and System.
*
* @method Phaser.Physics.Ninja.Tile#destroy
*/
destroy: function () {
this.body = null;
this.system = null;
},
/**
* This converts a tile from implicitly-defined (via id), to explicit (via properties).
* Don't call directly, instead of setType.
*
* @method Phaser.Physics.Ninja.Tile#updateType
* @private
*/
updateType: function () {
if (this.id === 0)
{
//EMPTY
this.type = Phaser.Physics.Ninja.Tile.TYPE_EMPTY;
this.signx = 0;
this.signy = 0;
this.sx = 0;
this.sy = 0;
return true;
}
//tile is non-empty; collide
if (this.id < Phaser.Physics.Ninja.Tile.TYPE_45DEG)
{
//FULL
this.type = Phaser.Physics.Ninja.Tile.TYPE_FULL;
this.signx = 0;
this.signy = 0;
this.sx = 0;
this.sy = 0;
}
else if (this.id < Phaser.Physics.Ninja.Tile.TYPE_CONCAVE)
{
// 45deg
this.type = Phaser.Physics.Ninja.Tile.TYPE_45DEG;
if (this.id == Phaser.Physics.Ninja.Tile.SLOPE_45DEGpn)
{
this.signx = 1;
this.signy = -1;
this.sx = this.signx / Math.SQRT2;//get slope _unit_ normal
this.sy = this.signy / Math.SQRT2;//since normal is (1,-1), length is sqrt(1*1 + -1*-1) = sqrt(2)
}
else if (this.id == Phaser.Physics.Ninja.Tile.SLOPE_45DEGnn)
{
this.signx = -1;
this.signy = -1;
this.sx = this.signx / Math.SQRT2;//get slope _unit_ normal
this.sy = this.signy / Math.SQRT2;//since normal is (1,-1), length is sqrt(1*1 + -1*-1) = sqrt(2)
}
else if (this.id == Phaser.Physics.Ninja.Tile.SLOPE_45DEGnp)
{
this.signx = -1;
this.signy = 1;
this.sx = this.signx / Math.SQRT2;//get slope _unit_ normal
this.sy = this.signy / Math.SQRT2;//since normal is (1,-1), length is sqrt(1*1 + -1*-1) = sqrt(2)
}
else if (this.id == Phaser.Physics.Ninja.Tile.SLOPE_45DEGpp)
{
this.signx = 1;
this.signy = 1;
this.sx = this.signx / Math.SQRT2;//get slope _unit_ normal
this.sy = this.signy / Math.SQRT2;//since normal is (1,-1), length is sqrt(1*1 + -1*-1) = sqrt(2)
}
else
{
return false;
}
}
else if (this.id < Phaser.Physics.Ninja.Tile.TYPE_CONVEX)
{
// Concave
this.type = Phaser.Physics.Ninja.Tile.TYPE_CONCAVE;
if (this.id == Phaser.Physics.Ninja.Tile.CONCAVEpn)
{
this.signx = 1;
this.signy = -1;
this.sx = 0;
this.sy = 0;
}
else if (this.id == Phaser.Physics.Ninja.Tile.CONCAVEnn)
{
this.signx = -1;
this.signy = -1;
this.sx = 0;
this.sy = 0;
}
else if (this.id == Phaser.Physics.Ninja.Tile.CONCAVEnp)
{
this.signx = -1;
this.signy = 1;
this.sx = 0;
this.sy = 0;
}
else if (this.id == Phaser.Physics.Ninja.Tile.CONCAVEpp)
{
this.signx = 1;
this.signy = 1;
this.sx = 0;
this.sy = 0;
}
else
{
return false;
}
}
else if (this.id < Phaser.Physics.Ninja.Tile.TYPE_22DEGs)
{
// Convex
this.type = Phaser.Physics.Ninja.Tile.TYPE_CONVEX;
if (this.id == Phaser.Physics.Ninja.Tile.CONVEXpn)
{
this.signx = 1;
this.signy = -1;
this.sx = 0;
this.sy = 0;
}
else if (this.id == Phaser.Physics.Ninja.Tile.CONVEXnn)
{
this.signx = -1;
this.signy = -1;
this.sx = 0;
this.sy = 0;
}
else if (this.id == Phaser.Physics.Ninja.Tile.CONVEXnp)
{
this.signx = -1;
this.signy = 1;
this.sx = 0;
this.sy = 0;
}
else if (this.id == Phaser.Physics.Ninja.Tile.CONVEXpp)
{
this.signx = 1;
this.signy = 1;
this.sx = 0;
this.sy = 0;
}
else
{
return false;
}
}
else if (this.id < Phaser.Physics.Ninja.Tile.TYPE_22DEGb)
{
// 22deg small
this.type = Phaser.Physics.Ninja.Tile.TYPE_22DEGs;
if (this.id == Phaser.Physics.Ninja.Tile.SLOPE_22DEGpnS)
{
this.signx = 1;
this.signy = -1;
var slen = Math.sqrt(2 * 2 + 1 * 1);
this.sx = (this.signx * 1) / slen;
this.sy = (this.signy * 2) / slen;
}
else if (this.id == Phaser.Physics.Ninja.Tile.SLOPE_22DEGnnS)
{
this.signx = -1;
this.signy = -1;
var slen = Math.sqrt(2 * 2 + 1 * 1);
this.sx = (this.signx * 1) / slen;
this.sy = (this.signy * 2) / slen;
}
else if (this.id == Phaser.Physics.Ninja.Tile.SLOPE_22DEGnpS)
{
this.signx = -1;
this.signy = 1;
var slen = Math.sqrt(2 * 2 + 1 * 1);
this.sx = (this.signx * 1) / slen;
this.sy = (this.signy * 2) / slen;
}
else if (this.id == Phaser.Physics.Ninja.Tile.SLOPE_22DEGppS)
{
this.signx = 1;
this.signy = 1;
var slen = Math.sqrt(2 * 2 + 1 * 1);
this.sx = (this.signx * 1) / slen;
this.sy = (this.signy * 2) / slen;
}
else
{
return false;
}
}
else if (this.id < Phaser.Physics.Ninja.Tile.TYPE_67DEGs)
{
// 22deg big
this.type = Phaser.Physics.Ninja.Tile.TYPE_22DEGb;
if (this.id == Phaser.Physics.Ninja.Tile.SLOPE_22DEGpnB)
{
this.signx = 1;
this.signy = -1;
var slen = Math.sqrt(2 * 2 + 1 * 1);
this.sx = (this.signx * 1) / slen;
this.sy = (this.signy * 2) / slen;
}
else if (this.id == Phaser.Physics.Ninja.Tile.SLOPE_22DEGnnB)
{
this.signx = -1;
this.signy = -1;
var slen = Math.sqrt(2 * 2 + 1 * 1);
this.sx = (this.signx * 1) / slen;
this.sy = (this.signy * 2) / slen;
}
else if (this.id == Phaser.Physics.Ninja.Tile.SLOPE_22DEGnpB)
{
this.signx = -1;
this.signy = 1;
var slen = Math.sqrt(2 * 2 + 1 * 1);
this.sx = (this.signx * 1) / slen;
this.sy = (this.signy * 2) / slen;
}
else if (this.id == Phaser.Physics.Ninja.Tile.SLOPE_22DEGppB)
{
this.signx = 1;
this.signy = 1;
var slen = Math.sqrt(2 * 2 + 1 * 1);
this.sx = (this.signx * 1) / slen;
this.sy = (this.signy * 2) / slen;
}
else
{
return false;
}
}
else if (this.id < Phaser.Physics.Ninja.Tile.TYPE_67DEGb)
{
// 67deg small
this.type = Phaser.Physics.Ninja.Tile.TYPE_67DEGs;
if (this.id == Phaser.Physics.Ninja.Tile.SLOPE_67DEGpnS)
{
this.signx = 1;
this.signy = -1;
var slen = Math.sqrt(2 * 2 + 1 * 1);
this.sx = (this.signx * 2) / slen;
this.sy = (this.signy * 1) / slen;
}
else if (this.id == Phaser.Physics.Ninja.Tile.SLOPE_67DEGnnS)
{
this.signx = -1;
this.signy = -1;
var slen = Math.sqrt(2 * 2 + 1 * 1);
this.sx = (this.signx * 2) / slen;
this.sy = (this.signy * 1) / slen;
}
else if (this.id == Phaser.Physics.Ninja.Tile.SLOPE_67DEGnpS)
{
this.signx = -1;
this.signy = 1;
var slen = Math.sqrt(2 * 2 + 1 * 1);
this.sx = (this.signx * 2) / slen;
this.sy = (this.signy * 1) / slen;
}
else if (this.id == Phaser.Physics.Ninja.Tile.SLOPE_67DEGppS)
{
this.signx = 1;
this.signy = 1;
var slen = Math.sqrt(2 * 2 + 1 * 1);
this.sx = (this.signx * 2) / slen;
this.sy = (this.signy * 1) / slen;
}
else
{
return false;
}
}
else if (this.id < Phaser.Physics.Ninja.Tile.TYPE_HALF)
{
// 67deg big
this.type = Phaser.Physics.Ninja.Tile.TYPE_67DEGb;
if (this.id == Phaser.Physics.Ninja.Tile.SLOPE_67DEGpnB)
{
this.signx = 1;
this.signy = -1;
var slen = Math.sqrt(2 * 2 + 1 * 1);
this.sx = (this.signx * 2) / slen;
this.sy = (this.signy * 1) / slen;
}
else if (this.id == Phaser.Physics.Ninja.Tile.SLOPE_67DEGnnB)
{
this.signx = -1;
this.signy = -1;
var slen = Math.sqrt(2 * 2 + 1 * 1);
this.sx = (this.signx * 2) / slen;
this.sy = (this.signy * 1) / slen;
}
else if (this.id == Phaser.Physics.Ninja.Tile.SLOPE_67DEGnpB)
{
this.signx = -1;
this.signy = 1;
var slen = Math.sqrt(2 * 2 + 1 * 1);
this.sx = (this.signx * 2) / slen;
this.sy = (this.signy * 1) / slen;
}
else if (this.id == Phaser.Physics.Ninja.Tile.SLOPE_67DEGppB)
{
this.signx = 1;
this.signy = 1;
var slen = Math.sqrt(2 * 2 + 1 * 1);
this.sx = (this.signx * 2) / slen;
this.sy = (this.signy * 1) / slen;
}
else
{
return false;
}
}
else
{
// Half-full tile
this.type = Phaser.Physics.Ninja.Tile.TYPE_HALF;
if (this.id == Phaser.Physics.Ninja.Tile.HALFd)
{
this.signx = 0;
this.signy = -1;
this.sx = this.signx;
this.sy = this.signy;
}
else if (this.id == Phaser.Physics.Ninja.Tile.HALFu)
{
this.signx = 0;
this.signy = 1;
this.sx = this.signx;
this.sy = this.signy;
}
else if (this.id == Phaser.Physics.Ninja.Tile.HALFl)
{
this.signx = 1;
this.signy = 0;
this.sx = this.signx;
this.sy = this.signy;
}
else if (this.id == Phaser.Physics.Ninja.Tile.HALFr)
{
this.signx = -1;
this.signy = 0;
this.sx = this.signx;
this.sy = this.signy;
}
else
{
return false;
}
}
}
};
/**
* @name Phaser.Physics.Ninja.Tile#x
* @property {number} x - The x position.
*/
Object.defineProperty(Phaser.Physics.Ninja.Tile.prototype, "x", {
get: function () {
return this.pos.x - this.xw;
},
set: function (value) {
this.pos.x = value;
}
});
/**
* @name Phaser.Physics.Ninja.Tile#y
* @property {number} y - The y position.
*/
Object.defineProperty(Phaser.Physics.Ninja.Tile.prototype, "y", {
get: function () {
return this.pos.y - this.yw;
},
set: function (value) {
this.pos.y = value;
}
});
/**
* @name Phaser.Physics.Ninja.Tile#bottom
* @property {number} bottom - The bottom value of this Body (same as Body.y + Body.height)
* @readonly
*/
Object.defineProperty(Phaser.Physics.Ninja.Tile.prototype, "bottom", {
get: function () {
return this.pos.y + this.yw;
}
});
/**
* @name Phaser.Physics.Ninja.Tile#right
* @property {number} right - The right value of this Body (same as Body.x + Body.width)
* @readonly
*/
Object.defineProperty(Phaser.Physics.Ninja.Tile.prototype, "right", {
get: function () {
return this.pos.x + this.xw;
}
});
Phaser.Physics.Ninja.Tile.EMPTY = 0;
Phaser.Physics.Ninja.Tile.FULL = 1;//fullAABB tile
Phaser.Physics.Ninja.Tile.SLOPE_45DEGpn = 2;//45-degree triangle, whose normal is (+ve,-ve)
Phaser.Physics.Ninja.Tile.SLOPE_45DEGnn = 3;//(+ve,+ve)
Phaser.Physics.Ninja.Tile.SLOPE_45DEGnp = 4;//(-ve,+ve)
Phaser.Physics.Ninja.Tile.SLOPE_45DEGpp = 5;//(-ve,-ve)
Phaser.Physics.Ninja.Tile.CONCAVEpn = 6;//1/4-circle cutout
Phaser.Physics.Ninja.Tile.CONCAVEnn = 7;
Phaser.Physics.Ninja.Tile.CONCAVEnp = 8;
Phaser.Physics.Ninja.Tile.CONCAVEpp = 9;
Phaser.Physics.Ninja.Tile.CONVEXpn = 10;//1/4/circle
Phaser.Physics.Ninja.Tile.CONVEXnn = 11;
Phaser.Physics.Ninja.Tile.CONVEXnp = 12;
Phaser.Physics.Ninja.Tile.CONVEXpp = 13;
Phaser.Physics.Ninja.Tile.SLOPE_22DEGpnS = 14;//22.5 degree slope
Phaser.Physics.Ninja.Tile.SLOPE_22DEGnnS = 15;
Phaser.Physics.Ninja.Tile.SLOPE_22DEGnpS = 16;
Phaser.Physics.Ninja.Tile.SLOPE_22DEGppS = 17;
Phaser.Physics.Ninja.Tile.SLOPE_22DEGpnB = 18;
Phaser.Physics.Ninja.Tile.SLOPE_22DEGnnB = 19;
Phaser.Physics.Ninja.Tile.SLOPE_22DEGnpB = 20;
Phaser.Physics.Ninja.Tile.SLOPE_22DEGppB = 21;
Phaser.Physics.Ninja.Tile.SLOPE_67DEGpnS = 22;//67.5 degree slope
Phaser.Physics.Ninja.Tile.SLOPE_67DEGnnS = 23;
Phaser.Physics.Ninja.Tile.SLOPE_67DEGnpS = 24;
Phaser.Physics.Ninja.Tile.SLOPE_67DEGppS = 25;
Phaser.Physics.Ninja.Tile.SLOPE_67DEGpnB = 26;
Phaser.Physics.Ninja.Tile.SLOPE_67DEGnnB = 27;
Phaser.Physics.Ninja.Tile.SLOPE_67DEGnpB = 28;
Phaser.Physics.Ninja.Tile.SLOPE_67DEGppB = 29;
Phaser.Physics.Ninja.Tile.HALFd = 30;//half-full tiles
Phaser.Physics.Ninja.Tile.HALFr = 31;
Phaser.Physics.Ninja.Tile.HALFu = 32;
Phaser.Physics.Ninja.Tile.HALFl = 33;
Phaser.Physics.Ninja.Tile.TYPE_EMPTY = 0;
Phaser.Physics.Ninja.Tile.TYPE_FULL = 1;
Phaser.Physics.Ninja.Tile.TYPE_45DEG = 2;
Phaser.Physics.Ninja.Tile.TYPE_CONCAVE = 6;
Phaser.Physics.Ninja.Tile.TYPE_CONVEX = 10;
Phaser.Physics.Ninja.Tile.TYPE_22DEGs = 14;
Phaser.Physics.Ninja.Tile.TYPE_22DEGb = 18;
Phaser.Physics.Ninja.Tile.TYPE_67DEGs = 22;
Phaser.Physics.Ninja.Tile.TYPE_67DEGb = 26;
Phaser.Physics.Ninja.Tile.TYPE_HALF = 30;
/* jshint camelcase: false */
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* Ninja Physics Circle constructor.
* Note: This class could be massively optimised and reduced in size. I leave that challenge up to you.
*
* @class Phaser.Physics.Ninja.Circle
* @constructor
* @param {Phaser.Physics.Ninja.Body} body - The body that owns this shape.
* @param {number} x - The x coordinate to create this shape at.
* @param {number} y - The y coordinate to create this shape at.
* @param {number} radius - The radius of this Circle.
*/
Phaser.Physics.Ninja.Circle = function (body, x, y, radius) {
/**
* @property {Phaser.Physics.Ninja.Body} system - A reference to the body that owns this shape.
*/
this.body = body;
/**
* @property {Phaser.Physics.Ninja} system - A reference to the physics system.
*/
this.system = body.system;
/**
* @property {Phaser.Point} pos - The position of this object.
*/
this.pos = new Phaser.Point(x, y);
/**
* @property {Phaser.Point} oldpos - The position of this object in the previous update.
*/
this.oldpos = new Phaser.Point(x, y);
/**
* @property {number} radius - The radius of this circle shape.
*/
this.radius = radius;
/**
* @property {number} xw - Half the width.
* @readonly
*/
this.xw = radius;
/**
* @property {number} xw - Half the height.
* @readonly
*/
this.yw = radius;
/**
* @property {number} width - The width.
* @readonly
*/
this.width = radius * 2;
/**
* @property {number} height - The height.
* @readonly
*/
this.height = radius * 2;
/**
* @property {number} oH - Internal var.
* @private
*/
this.oH = 0;
/**
* @property {number} oV - Internal var.
* @private
*/
this.oV = 0;
/**
* @property {Phaser.Point} velocity - The velocity of this object.
*/
this.velocity = new Phaser.Point();
/**
* @property {object} circleTileProjections - All of the collision response handlers.
*/
this.circleTileProjections = {};
this.circleTileProjections[Phaser.Physics.Ninja.Tile.TYPE_FULL] = this.projCircle_Full;
this.circleTileProjections[Phaser.Physics.Ninja.Tile.TYPE_45DEG] = this.projCircle_45Deg;
this.circleTileProjections[Phaser.Physics.Ninja.Tile.TYPE_CONCAVE] = this.projCircle_Concave;
this.circleTileProjections[Phaser.Physics.Ninja.Tile.TYPE_CONVEX] = this.projCircle_Convex;
this.circleTileProjections[Phaser.Physics.Ninja.Tile.TYPE_22DEGs] = this.projCircle_22DegS;
this.circleTileProjections[Phaser.Physics.Ninja.Tile.TYPE_22DEGb] = this.projCircle_22DegB;
this.circleTileProjections[Phaser.Physics.Ninja.Tile.TYPE_67DEGs] = this.projCircle_67DegS;
this.circleTileProjections[Phaser.Physics.Ninja.Tile.TYPE_67DEGb] = this.projCircle_67DegB;
this.circleTileProjections[Phaser.Physics.Ninja.Tile.TYPE_HALF] = this.projCircle_Half;
};
Phaser.Physics.Ninja.Circle.prototype.constructor = Phaser.Physics.Ninja.Circle;
Phaser.Physics.Ninja.Circle.COL_NONE = 0;
Phaser.Physics.Ninja.Circle.COL_AXIS = 1;
Phaser.Physics.Ninja.Circle.COL_OTHER = 2;
Phaser.Physics.Ninja.Circle.prototype = {
/**
* Updates this Circles position.
*
* @method Phaser.Physics.Ninja.Circle#integrate
*/
integrate: function () {
var px = this.pos.x;
var py = this.pos.y;
// integrate
this.pos.x += (this.body.drag * this.pos.x) - (this.body.drag * this.oldpos.x);
this.pos.y += (this.body.drag * this.pos.y) - (this.body.drag * this.oldpos.y) + (this.system.gravity * this.body.gravityScale);
// store
this.velocity.set(this.pos.x - px, this.pos.y - py);
this.oldpos.set(px, py);
},
/**
* Process a world collision and apply the resulting forces.
*
* @method Phaser.Physics.Ninja.Circle#reportCollisionVsWorld
* @param {number} px - The tangent velocity
* @param {number} py - The tangent velocity
* @param {number} dx - Collision normal
* @param {number} dy - Collision normal
* @param {number} obj - Object this Circle collided with
*/
reportCollisionVsWorld: function (px, py, dx, dy) {
var p = this.pos;
var o = this.oldpos;
// Calc velocity
var vx = p.x - o.x;
var vy = p.y - o.y;
// Find component of velocity parallel to collision normal
var dp = (vx * dx + vy * dy);
var nx = dp * dx; //project velocity onto collision normal
var ny = dp * dy; //nx,ny is normal velocity
var tx = vx - nx; //px,py is tangent velocity
var ty = vy - ny;
// We only want to apply collision response forces if the object is travelling into, and not out of, the collision
var b, bx, by, fx, fy;
if (dp < 0)
{
fx = tx * this.body.friction;
fy = ty * this.body.friction;
b = 1 + this.body.bounce;
bx = (nx * b);
by = (ny * b);
if (dx === 1)
{
this.body.touching.left = true;
}
else if (dx === -1)
{
this.body.touching.right = true;
}
if (dy === 1)
{
this.body.touching.up = true;
}
else if (dy === -1)
{
this.body.touching.down = true;
}
}
else
{
// Moving out of collision, do not apply forces
bx = by = fx = fy = 0;
}
// Project object out of collision
p.x += px;
p.y += py;
// Apply bounce+friction impulses which alter velocity
o.x += px + bx + fx;
o.y += py + by + fy;
},
/**
* Collides this Circle against the world bounds.
*
* @method Phaser.Physics.Ninja.Circle#collideWorldBounds
*/
collideWorldBounds: function () {
var dx = this.system.bounds.x - (this.pos.x - this.radius);
if (0 < dx)
{
this.reportCollisionVsWorld(dx, 0, 1, 0, null);
}
else
{
dx = (this.pos.x + this.radius) - this.system.bounds.right;
if (0 < dx)
{
this.reportCollisionVsWorld(-dx, 0, -1, 0, null);
}
}
var dy = this.system.bounds.y - (this.pos.y - this.radius);
if (0 < dy)
{
this.reportCollisionVsWorld(0, dy, 0, 1, null);
}
else
{
dy = (this.pos.y + this.radius) - this.system.bounds.bottom;
if (0 < dy)
{
this.reportCollisionVsWorld(0, -dy, 0, -1, null);
}
}
},
/**
* Collides this Circle with a Tile.
*
* @method Phaser.Physics.Ninja.Circle#collideCircleVsTile
* @param {Phaser.Physics.Ninja.Tile} t - The Tile involved in the collision.
* @return {boolean} True if they collide, otherwise false.
*/
collideCircleVsTile: function (tile) {
var pos = this.pos;
var r = this.radius;
var c = tile;
var tx = c.pos.x;
var ty = c.pos.y;
var txw = c.xw;
var tyw = c.yw;
var dx = pos.x - tx; // tile->obj delta
var px = (txw + r) - Math.abs(dx); // penetration depth in x
if (0 < px)
{
var dy = pos.y - ty; // tile->obj delta
var py = (tyw + r) - Math.abs(dy); // pen depth in y
if (0 < py)
{
// object may be colliding with tile
// determine grid/voronoi region of circle center
this.oH = 0;
this.oV = 0;
if (dx < -txw)
{
// circle is on left side of tile
this.oH = -1;
}
else if (txw < dx)
{
// circle is on right side of tile
this.oH = 1;
}
if (dy < -tyw)
{
// circle is on top side of tile
this.oV = -1;
}
else if (tyw < dy)
{
// circle is on bottom side of tile
this.oV = 1;
}
return this.resolveCircleTile(px, py, this.oH, this.oV, this, c);
}
}
},
/**
* Resolves tile collision.
*
* @method Phaser.Physics.Ninja.Circle#resolveCircleTile
* @param {number} x - Penetration depth on the x axis.
* @param {number} y - Penetration depth on the y axis.
* @param {number} oH - Grid / voronoi region.
* @param {number} oV - Grid / voronoi region.
* @param {Phaser.Physics.Ninja.Circle} obj - The Circle involved in the collision.
* @param {Phaser.Physics.Ninja.Tile} t - The Tile involved in the collision.
* @return {number} The result of the collision.
*/
resolveCircleTile: function (x, y, oH, oV, obj, t) {
if (0 < t.id)
{
return this.circleTileProjections[t.type](x, y, oH, oV, obj, t);
}
else
{
return false;
}
},
/**
* Resolves Full tile collision.
*
* @method Phaser.Physics.Ninja.Circle#projCircle_Full
* @param {number} x - Penetration depth on the x axis.
* @param {number} y - Penetration depth on the y axis.
* @param {number} oH - Grid / voronoi region.
* @param {number} oV - Grid / voronoi region.
* @param {Phaser.Physics.Ninja.Circle} obj - The Circle involved in the collision.
* @param {Phaser.Physics.Ninja.Tile} t - The Tile involved in the collision.
* @return {number} The result of the collision.
*/
projCircle_Full: function (x, y, oH, oV, obj, t) {
//if we're colliding vs. the current cell, we need to project along the
//smallest penetration vector.
//if we're colliding vs. horiz. or vert. neighb, we simply project horiz/vert
//if we're colliding diagonally, we need to collide vs. tile corner
if (oH === 0)
{
if (oV === 0)
{
//collision with current cell
if (x < y)
{
//penetration in x is smaller; project in x
var dx = obj.pos.x - t.pos.x;//get sign for projection along x-axis
//NOTE: should we handle the delta === 0 case?! and how? (project towards oldpos?)
if (dx < 0)
{
obj.reportCollisionVsWorld(-x, 0, -1, 0, t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
else
{
obj.reportCollisionVsWorld(x, 0, 1, 0, t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
}
else
{
//penetration in y is smaller; project in y
var dy = obj.pos.y - t.pos.y;//get sign for projection along y-axis
//NOTE: should we handle the delta === 0 case?! and how? (project towards oldpos?)
if (dy < 0)
{
obj.reportCollisionVsWorld(0, -y, 0, -1, t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
else
{
obj.reportCollisionVsWorld(0, y, 0, 1, t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
}
}
else
{
//collision with vertical neighbor
obj.reportCollisionVsWorld(0, y * oV, 0, oV, t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
}
else if (oV === 0)
{
//collision with horizontal neighbor
obj.reportCollisionVsWorld(x * oH, 0, oH, 0, t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
else
{
//diagonal collision
//get diag vertex position
var vx = t.pos.x + (oH * t.xw);
var vy = t.pos.y + (oV * t.yw);
var dx = obj.pos.x - vx;//calc vert->circle vector
var dy = obj.pos.y - vy;
var len = Math.sqrt(dx * dx + dy * dy);
var pen = obj.radius - len;
if (0 < pen)
{
//vertex is in the circle; project outward
if (len === 0)
{
//project out by 45deg
dx = oH / Math.SQRT2;
dy = oV / Math.SQRT2;
}
else
{
dx /= len;
dy /= len;
}
obj.reportCollisionVsWorld(dx * pen, dy * pen, dx, dy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
return Phaser.Physics.Ninja.Circle.COL_NONE;
},
/**
* Resolves 45 Degree tile collision.
*
* @method Phaser.Physics.Ninja.Circle#projCircle_45Deg
* @param {number} x - Penetration depth on the x axis.
* @param {number} y - Penetration depth on the y axis.
* @param {number} oH - Grid / voronoi region.
* @param {number} oV - Grid / voronoi region.
* @param {Phaser.Physics.Ninja.Circle} obj - The Circle involved in the collision.
* @param {Phaser.Physics.Ninja.Tile} t - The Tile involved in the collision.
* @return {number} The result of the collision.
*/
projCircle_45Deg: function (x, y, oH, oV, obj, t) {
//if we're colliding diagonally:
// -if obj is in the diagonal pointed to by the slope normal: we can't collide, do nothing
// -else, collide vs. the appropriate vertex
//if obj is in this tile: perform collision as for aabb-ve-45deg
//if obj is horiz OR very neighb in direction of slope: collide only vs. slope
//if obj is horiz or vert neigh against direction of slope: collide vs. face
var signx = t.signx;
var signy = t.signy;
var lenP;
if (oH === 0)
{
if (oV === 0)
{
//colliding with current tile
var sx = t.sx;
var sy = t.sy;
var ox = (obj.pos.x - (sx * obj.radius)) - t.pos.x;//this gives is the coordinates of the innermost
var oy = (obj.pos.y - (sy * obj.radius)) - t.pos.y;//point on the circle, relative to the tile center
//if the dotprod of (ox,oy) and (sx,sy) is negative, the innermost point is in the slope
//and we need toproject it out by the magnitude of the projection of (ox,oy) onto (sx,sy)
var dp = (ox * sx) + (oy * sy);
if (dp < 0)
{
//collision; project delta onto slope and use this as the slope penetration vector
sx *= -dp;//(sx,sy) is now the penetration vector
sy *= -dp;
//find the smallest axial projection vector
if (x < y)
{
//penetration in x is smaller
lenP = x;
y = 0;
//get sign for projection along x-axis
if ((obj.pos.x - t.pos.x) < 0)
{
x *= -1;
}
}
else
{
//penetration in y is smaller
lenP = y;
x = 0;
//get sign for projection along y-axis
if ((obj.pos.y - t.pos.y) < 0)
{
y *= -1;
}
}
var lenN = Math.sqrt(sx * sx + sy * sy);
if (lenP < lenN)
{
obj.reportCollisionVsWorld(x, y, x / lenP, y / lenP, t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
else
{
obj.reportCollisionVsWorld(sx, sy, t.sx, t.sy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
}
else
{
//colliding vertically
if ((signy * oV) < 0)
{
//colliding with face/edge
obj.reportCollisionVsWorld(0, y * oV, 0, oV, t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
else
{
//we could only be colliding vs the slope OR a vertex
//look at the vector form the closest vert to the circle to decide
var sx = t.sx;
var sy = t.sy;
var ox = obj.pos.x - (t.pos.x - (signx * t.xw));//this gives is the coordinates of the innermost
var oy = obj.pos.y - (t.pos.y + (oV * t.yw));//point on the circle, relative to the closest tile vert
//if the component of (ox,oy) parallel to the normal's righthand normal
//has the same sign as the slope of the slope (the sign of the slope's slope is signx*signy)
//then we project by the vertex, otherwise by the normal.
//note that this is simply a VERY tricky/weird method of determining
//if the circle is in side the slope/face's voronoi region, or that of the vertex.
var perp = (ox * -sy) + (oy * sx);
if (0 < (perp * signx * signy))
{
//collide vs. vertex
var len = Math.sqrt(ox * ox + oy * oy);
var pen = obj.radius - len;
if (0 < pen)
{
//note: if len=0, then perp=0 and we'll never reach here, so don't worry about div-by-0
ox /= len;
oy /= len;
obj.reportCollisionVsWorld(ox * pen, oy * pen, ox, oy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
else
{
//collide vs. slope
//if the component of (ox,oy) parallel to the normal is less than the circle radius, we're
//penetrating the slope. note that this method of penetration calculation doesn't hold
//in general (i.e it won't work if the circle is in the slope), but works in this case
//because we know the circle is in a neighboring cell
var dp = (ox * sx) + (oy * sy);
var pen = obj.radius - Math.abs(dp);//note: we don't need the abs because we know the dp will be positive, but just in case..
if (0 < pen)
{
//collision; circle out along normal by penetration amount
obj.reportCollisionVsWorld(sx * pen, sy * pen, sx, sy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
}
}
}
else if (oV === 0)
{
//colliding horizontally
if ((signx * oH) < 0)
{
//colliding with face/edge
obj.reportCollisionVsWorld(x * oH, 0, oH, 0, t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
else
{
//we could only be colliding vs the slope OR a vertex
//look at the vector form the closest vert to the circle to decide
var sx = t.sx;
var sy = t.sy;
var ox = obj.pos.x - (t.pos.x + (oH * t.xw));//this gives is the coordinates of the innermost
var oy = obj.pos.y - (t.pos.y - (signy * t.yw));//point on the circle, relative to the closest tile vert
//if the component of (ox,oy) parallel to the normal's righthand normal
//has the same sign as the slope of the slope (the sign of the slope's slope is signx*signy)
//then we project by the normal, otherwise by the vertex.
//(NOTE: this is the opposite logic of the vertical case;
// for vertical, if the perp prod and the slope's slope agree, it's outside.
// for horizontal, if the perp prod and the slope's slope agree, circle is inside.
// ..but this is only a property of flahs' coord system (i.e the rules might swap
// in righthanded systems))
//note that this is simply a VERY tricky/weird method of determining
//if the circle is in side the slope/face's voronio region, or that of the vertex.
var perp = (ox * -sy) + (oy * sx);
if ((perp * signx * signy) < 0)
{
//collide vs. vertex
var len = Math.sqrt(ox * ox + oy * oy);
var pen = obj.radius - len;
if (0 < pen)
{
//note: if len=0, then perp=0 and we'll never reach here, so don't worry about div-by-0
ox /= len;
oy /= len;
obj.reportCollisionVsWorld(ox * pen, oy * pen, ox, oy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
else
{
//collide vs. slope
//if the component of (ox,oy) parallel to the normal is less than the circle radius, we're
//penetrating the slope. note that this method of penetration calculation doesn't hold
//in general (i.e it won't work if the circle is in the slope), but works in this case
//because we know the circle is in a neighboring cell
var dp = (ox * sx) + (oy * sy);
var pen = obj.radius - Math.abs(dp);//note: we don't need the abs because we know the dp will be positive, but just in case..
if (0 < pen)
{
//collision; circle out along normal by penetration amount
obj.reportCollisionVsWorld(sx * pen, sy * pen, sx, sy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
}
}
else
{
//colliding diagonally
if (0 < ((signx * oH) + (signy * oV)))
{
//the dotprod of slope normal and cell offset is strictly positive,
//therefore obj is in the diagonal neighb pointed at by the normal, and
//it cannot possibly reach/touch/penetrate the slope
return Phaser.Physics.Ninja.Circle.COL_NONE;
}
else
{
//collide vs. vertex
//get diag vertex position
var vx = t.pos.x + (oH * t.xw);
var vy = t.pos.y + (oV * t.yw);
var dx = obj.pos.x - vx;//calc vert->circle vector
var dy = obj.pos.y - vy;
var len = Math.sqrt(dx * dx + dy * dy);
var pen = obj.radius - len;
if (0 < pen)
{
//vertex is in the circle; project outward
if (len === 0)
{
//project out by 45deg
dx = oH / Math.SQRT2;
dy = oV / Math.SQRT2;
}
else
{
dx /= len;
dy /= len;
}
obj.reportCollisionVsWorld(dx * pen, dy * pen, dx, dy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
}
return Phaser.Physics.Ninja.Circle.COL_NONE;
},
/**
* Resolves Concave tile collision.
*
* @method Phaser.Physics.Ninja.Circle#projCircle_Concave
* @param {number} x - Penetration depth on the x axis.
* @param {number} y - Penetration depth on the y axis.
* @param {number} oH - Grid / voronoi region.
* @param {number} oV - Grid / voronoi region.
* @param {Phaser.Physics.Ninja.Circle} obj - The Circle involved in the collision.
* @param {Phaser.Physics.Ninja.Tile} t - The Tile involved in the collision.
* @return {number} The result of the collision.
*/
projCircle_Concave: function (x, y, oH, oV, obj, t) {
//if we're colliding diagonally:
// -if obj is in the diagonal pointed to by the slope normal: we can't collide, do nothing
// -else, collide vs. the appropriate vertex
//if obj is in this tile: perform collision as for aabb
//if obj is horiz OR very neighb in direction of slope: collide vs vert
//if obj is horiz or vert neigh against direction of slope: collide vs. face
var signx = t.signx;
var signy = t.signy;
var lenP;
if (oH === 0)
{
if (oV === 0)
{
//colliding with current tile
var ox = (t.pos.x + (signx * t.xw)) - obj.pos.x;//(ox,oy) is the vector from the circle to
var oy = (t.pos.y + (signy * t.yw)) - obj.pos.y;//tile-circle's center
var twid = t.xw * 2;
var trad = Math.sqrt(twid * twid + 0);//this gives us the radius of a circle centered on the tile's corner and extending to the opposite edge of the tile;
//note that this should be precomputed at compile-time since it's constant
var len = Math.sqrt(ox * ox + oy * oy);
var pen = (len + obj.radius) - trad;
if (0 < pen)
{
//find the smallest axial projection vector
if (x < y)
{
//penetration in x is smaller
lenP = x;
y = 0;
//get sign for projection along x-axis
if ((obj.pos.x - t.pos.x) < 0)
{
x *= -1;
}
}
else
{
//penetration in y is smaller
lenP = y;
x = 0;
//get sign for projection along y-axis
if ((obj.pos.y - t.pos.y) < 0)
{
y *= -1;
}
}
if (lenP < pen)
{
obj.reportCollisionVsWorld(x, y, x / lenP, y / lenP, t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
else
{
//we can assume that len >0, because if we're here then
//(len + obj.radius) > trad, and since obj.radius <= trad
//len MUST be > 0
ox /= len;
oy /= len;
obj.reportCollisionVsWorld(ox * pen, oy * pen, ox, oy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
else
{
return Phaser.Physics.Ninja.Circle.COL_NONE;
}
}
else
{
//colliding vertically
if ((signy * oV) < 0)
{
//colliding with face/edge
obj.reportCollisionVsWorld(0, y * oV, 0, oV, t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
else
{
//we could only be colliding vs the vertical tip
//get diag vertex position
var vx = t.pos.x - (signx * t.xw);
var vy = t.pos.y + (oV * t.yw);
var dx = obj.pos.x - vx;//calc vert->circle vector
var dy = obj.pos.y - vy;
var len = Math.sqrt(dx * dx + dy * dy);
var pen = obj.radius - len;
if (0 < pen)
{
//vertex is in the circle; project outward
if (len === 0)
{
//project out vertically
dx = 0;
dy = oV;
}
else
{
dx /= len;
dy /= len;
}
obj.reportCollisionVsWorld(dx * pen, dy * pen, dx, dy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
}
}
else if (oV === 0)
{
//colliding horizontally
if ((signx * oH) < 0)
{
//colliding with face/edge
obj.reportCollisionVsWorld(x * oH, 0, oH, 0, t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
else
{
//we could only be colliding vs the horizontal tip
//get diag vertex position
var vx = t.pos.x + (oH * t.xw);
var vy = t.pos.y - (signy * t.yw);
var dx = obj.pos.x - vx;//calc vert->circle vector
var dy = obj.pos.y - vy;
var len = Math.sqrt(dx * dx + dy * dy);
var pen = obj.radius - len;
if (0 < pen)
{
//vertex is in the circle; project outward
if (len === 0)
{
//project out horizontally
dx = oH;
dy = 0;
}
else
{
dx /= len;
dy /= len;
}
obj.reportCollisionVsWorld(dx * pen, dy * pen, dx, dy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
}
else
{
//colliding diagonally
if (0 < ((signx * oH) + (signy * oV)))
{
//the dotprod of slope normal and cell offset is strictly positive,
//therefore obj is in the diagonal neighb pointed at by the normal, and
//it cannot possibly reach/touch/penetrate the slope
return Phaser.Physics.Ninja.Circle.COL_NONE;
}
else
{
//collide vs. vertex
//get diag vertex position
var vx = t.pos.x + (oH * t.xw);
var vy = t.pos.y + (oV * t.yw);
var dx = obj.pos.x - vx;//calc vert->circle vector
var dy = obj.pos.y - vy;
var len = Math.sqrt(dx * dx + dy * dy);
var pen = obj.radius - len;
if (0 < pen)
{
//vertex is in the circle; project outward
if (len === 0)
{
//project out by 45deg
dx = oH / Math.SQRT2;
dy = oV / Math.SQRT2;
}
else
{
dx /= len;
dy /= len;
}
obj.reportCollisionVsWorld(dx * pen, dy * pen, dx, dy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
}
return Phaser.Physics.Ninja.Circle.COL_NONE;
},
/**
* Resolves Convex tile collision.
*
* @method Phaser.Physics.Ninja.Circle#projCircle_Convex
* @param {number} x - Penetration depth on the x axis.
* @param {number} y - Penetration depth on the y axis.
* @param {number} oH - Grid / voronoi region.
* @param {number} oV - Grid / voronoi region.
* @param {Phaser.Physics.Ninja.Circle} obj - The Circle involved in the collision.
* @param {Phaser.Physics.Ninja.Tile} t - The Tile involved in the collision.
* @return {number} The result of the collision.
*/
projCircle_Convex: function (x, y, oH, oV, obj, t) {
//if the object is horiz AND/OR vertical neighbor in the normal (signx,signy)
//direction, collide vs. tile-circle only.
//if we're colliding diagonally:
// -else, collide vs. the appropriate vertex
//if obj is in this tile: perform collision as for aabb
//if obj is horiz or vert neigh against direction of slope: collide vs. face
var signx = t.signx;
var signy = t.signy;
var lenP;
if (oH === 0)
{
if (oV === 0)
{
//colliding with current tile
var ox = obj.pos.x - (t.pos.x - (signx * t.xw));//(ox,oy) is the vector from the tile-circle to
var oy = obj.pos.y - (t.pos.y - (signy * t.yw));//the circle's center
var twid = t.xw * 2;
var trad = Math.sqrt(twid * twid + 0);//this gives us the radius of a circle centered on the tile's corner and extending to the opposite edge of the tile;
//note that this should be precomputed at compile-time since it's constant
var len = Math.sqrt(ox * ox + oy * oy);
var pen = (trad + obj.radius) - len;
if (0 < pen)
{
//find the smallest axial projection vector
if (x < y)
{
//penetration in x is smaller
lenP = x;
y = 0;
//get sign for projection along x-axis
if ((obj.pos.x - t.pos.x) < 0)
{
x *= -1;
}
}
else
{
//penetration in y is smaller
lenP = y;
x = 0;
//get sign for projection along y-axis
if ((obj.pos.y - t.pos.y) < 0)
{
y *= -1;
}
}
if (lenP < pen)
{
obj.reportCollisionVsWorld(x, y, x / lenP, y / lenP, t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
else
{
//note: len should NEVER be === 0, because if it is,
//projeciton by an axis shoudl always be shorter, and we should
//never arrive here
ox /= len;
oy /= len;
obj.reportCollisionVsWorld(ox * pen, oy * pen, ox, oy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
}
else
{
//colliding vertically
if ((signy * oV) < 0)
{
//colliding with face/edge
obj.reportCollisionVsWorld(0, y * oV, 0, oV, t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
else
{
//obj in neighboring cell pointed at by tile normal;
//we could only be colliding vs the tile-circle surface
var ox = obj.pos.x - (t.pos.x - (signx * t.xw));//(ox,oy) is the vector from the tile-circle to
var oy = obj.pos.y - (t.pos.y - (signy * t.yw));//the circle's center
var twid = t.xw * 2;
var trad = Math.sqrt(twid * twid + 0);//this gives us the radius of a circle centered on the tile's corner and extending to the opposite edge of the tile;
//note that this should be precomputed at compile-time since it's constant
var len = Math.sqrt(ox * ox + oy * oy);
var pen = (trad + obj.radius) - len;
if (0 < pen)
{
//note: len should NEVER be === 0, because if it is,
//obj is not in a neighboring cell!
ox /= len;
oy /= len;
obj.reportCollisionVsWorld(ox * pen, oy * pen, ox, oy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
}
}
else if (oV === 0)
{
//colliding horizontally
if ((signx * oH) < 0)
{
//colliding with face/edge
obj.reportCollisionVsWorld(x * oH, 0, oH, 0, t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
else
{
//obj in neighboring cell pointed at by tile normal;
//we could only be colliding vs the tile-circle surface
var ox = obj.pos.x - (t.pos.x - (signx * t.xw));//(ox,oy) is the vector from the tile-circle to
var oy = obj.pos.y - (t.pos.y - (signy * t.yw));//the circle's center
var twid = t.xw * 2;
var trad = Math.sqrt(twid * twid + 0);//this gives us the radius of a circle centered on the tile's corner and extending to the opposite edge of the tile;
//note that this should be precomputed at compile-time since it's constant
var len = Math.sqrt(ox * ox + oy * oy);
var pen = (trad + obj.radius) - len;
if (0 < pen)
{
//note: len should NEVER be === 0, because if it is,
//obj is not in a neighboring cell!
ox /= len;
oy /= len;
obj.reportCollisionVsWorld(ox * pen, oy * pen, ox, oy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
}
else
{
//colliding diagonally
if (0 < ((signx * oH) + (signy * oV)))
{
//obj in diag neighb cell pointed at by tile normal;
//we could only be colliding vs the tile-circle surface
var ox = obj.pos.x - (t.pos.x - (signx * t.xw));//(ox,oy) is the vector from the tile-circle to
var oy = obj.pos.y - (t.pos.y - (signy * t.yw));//the circle's center
var twid = t.xw * 2;
var trad = Math.sqrt(twid * twid + 0);//this gives us the radius of a circle centered on the tile's corner and extending to the opposite edge of the tile;
//note that this should be precomputed at compile-time since it's constant
var len = Math.sqrt(ox * ox + oy * oy);
var pen = (trad + obj.radius) - len;
if (0 < pen)
{
//note: len should NEVER be === 0, because if it is,
//obj is not in a neighboring cell!
ox /= len;
oy /= len;
obj.reportCollisionVsWorld(ox * pen, oy * pen, ox, oy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
else
{
//collide vs. vertex
//get diag vertex position
var vx = t.pos.x + (oH * t.xw);
var vy = t.pos.y + (oV * t.yw);
var dx = obj.pos.x - vx;//calc vert->circle vector
var dy = obj.pos.y - vy;
var len = Math.sqrt(dx * dx + dy * dy);
var pen = obj.radius - len;
if (0 < pen)
{
//vertex is in the circle; project outward
if (len === 0)
{
//project out by 45deg
dx = oH / Math.SQRT2;
dy = oV / Math.SQRT2;
}
else
{
dx /= len;
dy /= len;
}
obj.reportCollisionVsWorld(dx * pen, dy * pen, dx, dy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
}
return Phaser.Physics.Ninja.Circle.COL_NONE;
},
/**
* Resolves Half tile collision.
*
* @method Phaser.Physics.Ninja.Circle#projCircle_Half
* @param {number} x - Penetration depth on the x axis.
* @param {number} y - Penetration depth on the y axis.
* @param {number} oH - Grid / voronoi region.
* @param {number} oV - Grid / voronoi region.
* @param {Phaser.Physics.Ninja.Circle} obj - The Circle involved in the collision.
* @param {Phaser.Physics.Ninja.Tile} t - The Tile involved in the collision.
* @return {number} The result of the collision.
*/
projCircle_Half: function (x,y,oH,oV,obj,t) {
//if obj is in a neighbor pointed at by the halfedge normal,
//we'll never collide (i.e if the normal is (0,1) and the obj is in the DL.D, or R neighbors)
//
//if obj is in a neigbor perpendicular to the halfedge normal, it might
//collide with the halfedge-vertex, or with the halfedge side.
//
//if obj is in a neigb pointing opposite the halfedge normal, obj collides with edge
//
//if obj is in a diagonal (pointing away from the normal), obj collides vs vertex
//
//if obj is in the halfedge cell, it collides as with aabb
var signx = t.signx;
var signy = t.signy;
var celldp = (oH*signx + oV*signy);//this tells us about the configuration of cell-offset relative to tile normal
if (0 < celldp)
{
//obj is in "far" (pointed-at-by-normal) neighbor of halffull tile, and will never hit
return Phaser.Physics.Ninja.Circle.COL_NONE;
}
else if (oH === 0)
{
if (oV === 0)
{
//colliding with current tile
var r = obj.radius;
var ox = (obj.pos.x - (signx*r)) - t.pos.x;//this gives is the coordinates of the innermost
var oy = (obj.pos.y - (signy*r)) - t.pos.y;//point on the circle, relative to the tile center
//we perform operations analogous to the 45deg tile, except we're using
//an axis-aligned slope instead of an angled one..
var sx = signx;
var sy = signy;
//if the dotprod of (ox,oy) and (sx,sy) is negative, the corner is in the slope
//and we need toproject it out by the magnitude of the projection of (ox,oy) onto (sx,sy)
var dp = (ox*sx) + (oy*sy);
if (dp < 0)
{
//collision; project delta onto slope and use this to displace the object
sx *= -dp;//(sx,sy) is now the projection vector
sy *= -dp;
var lenN = Math.sqrt(sx*sx + sy*sy);
var lenP = Math.sqrt(x*x + y*y);
if (lenP < lenN)
{
obj.reportCollisionVsWorld(x,y,x/lenP, y/lenP,t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
else
{
obj.reportCollisionVsWorld(sx,sy,t.signx,t.signy);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
return true;
}
}
else
{
//colliding vertically
if (celldp === 0)
{
var dx = obj.pos.x - t.pos.x;
//we're in a cell perpendicular to the normal, and can collide vs. halfedge vertex
//or halfedge side
if ((dx*signx) < 0)
{
//collision with halfedge side
obj.reportCollisionVsWorld(0,y*oV,0,oV,t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
else
{
//collision with halfedge vertex
var dy = obj.pos.y - (t.pos.y + oV*t.yw);//(dx,dy) is now the vector from the appropriate halfedge vertex to the circle
var len = Math.sqrt(dx*dx + dy*dy);
var pen = obj.radius - len;
if (0 < pen)
{
//vertex is in the circle; project outward
if (len === 0)
{
//project out by 45deg
dx = signx / Math.SQRT2;
dy = oV / Math.SQRT2;
}
else
{
dx /= len;
dy /= len;
}
obj.reportCollisionVsWorld(dx*pen, dy*pen, dx, dy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
}
else
{
//due to the first conditional (celldp >0), we know we're in the cell "opposite" the normal, and so
//we can only collide with the cell edge
//collision with vertical neighbor
obj.reportCollisionVsWorld(0,y*oV,0,oV,t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
}
}
else if (oV === 0)
{
//colliding horizontally
if (celldp === 0)
{
var dy = obj.pos.y - t.pos.y;
//we're in a cell perpendicular to the normal, and can collide vs. halfedge vertex
//or halfedge side
if ((dy*signy) < 0)
{
//collision with halfedge side
obj.reportCollisionVsWorld(x*oH,0,oH,0,t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
else
{
//collision with halfedge vertex
var dx = obj.pos.x - (t.pos.x + oH*t.xw);//(dx,dy) is now the vector from the appropriate halfedge vertex to the circle
var len = Math.sqrt(dx*dx + dy*dy);
var pen = obj.radius - len;
if (0 < pen)
{
//vertex is in the circle; project outward
if (len === 0)
{
//project out by 45deg
dx = signx / Math.SQRT2;
dy = oV / Math.SQRT2;
}
else
{
dx /= len;
dy /= len;
}
obj.reportCollisionVsWorld(dx*pen, dy*pen, dx, dy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
}
else
{
//due to the first conditional (celldp >0), we know w're in the cell "opposite" the normal, and so
//we can only collide with the cell edge
obj.reportCollisionVsWorld(x*oH, 0, oH, 0, t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
}
else
{
//colliding diagonally; we know, due to the initial (celldp >0) test which has failed
//if we've reached this point, that we're in a diagonal neighbor on the non-normal side, so
//we could only be colliding with the cell vertex, if at all.
//get diag vertex position
var vx = t.pos.x + (oH*t.xw);
var vy = t.pos.y + (oV*t.yw);
var dx = obj.pos.x - vx;//calc vert->circle vector
var dy = obj.pos.y - vy;
var len = Math.sqrt(dx*dx + dy*dy);
var pen = obj.radius - len;
if (0 < pen)
{
//vertex is in the circle; project outward
if (len === 0)
{
//project out by 45deg
dx = oH / Math.SQRT2;
dy = oV / Math.SQRT2;
}
else
{
dx /= len;
dy /= len;
}
obj.reportCollisionVsWorld(dx*pen, dy*pen, dx, dy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
return Phaser.Physics.Ninja.Circle.COL_NONE;
},
/**
* Resolves 22 Degree tile collision.
*
* @method Phaser.Physics.Ninja.Circle#projCircle_22DegS
* @param {number} x - Penetration depth on the x axis.
* @param {number} y - Penetration depth on the y axis.
* @param {number} oH - Grid / voronoi region.
* @param {number} oV - Grid / voronoi region.
* @param {Phaser.Physics.Ninja.Circle} obj - The Circle involved in the collision.
* @param {Phaser.Physics.Ninja.Tile} t - The Tile involved in the collision.
* @return {number} The result of the collision.
*/
projCircle_22DegS: function (x,y,oH,oV,obj,t) {
//if the object is in a cell pointed at by signy, no collision will ever occur
//otherwise,
//
//if we're colliding diagonally:
// -collide vs. the appropriate vertex
//if obj is in this tile: collide vs slope or vertex
//if obj is horiz neighb in direction of slope: collide vs. slope or vertex
//if obj is horiz neighb against the slope:
// if (distance in y from circle to 90deg corner of tile < 1/2 tileheight, collide vs. face)
// else(collide vs. corner of slope) (vert collision with a non-grid-aligned vert)
//if obj is vert neighb against direction of slope: collide vs. face
var lenP;
var signx = t.signx;
var signy = t.signy;
if (0 < (signy*oV))
{
//object will never collide vs tile, it can't reach that far
return Phaser.Physics.Ninja.Circle.COL_NONE;
}
else if (oH === 0)
{
if (oV === 0)
{
//colliding with current tile
//we could only be colliding vs the slope OR a vertex
//look at the vector form the closest vert to the circle to decide
var sx = t.sx;
var sy = t.sy;
var r = obj.radius;
var ox = obj.pos.x - (t.pos.x - (signx*t.xw));//this gives is the coordinates of the innermost
var oy = obj.pos.y - t.pos.y;//point on the circle, relative to the tile corner
//if the component of (ox,oy) parallel to the normal's righthand normal
//has the same sign as the slope of the slope (the sign of the slope's slope is signx*signy)
//then we project by the vertex, otherwise by the normal or axially.
//note that this is simply a VERY tricky/weird method of determining
//if the circle is in side the slope/face's voronio region, or that of the vertex.
var perp = (ox*-sy) + (oy*sx);
if (0 < (perp*signx*signy))
{
//collide vs. vertex
var len = Math.sqrt(ox*ox + oy*oy);
var pen = r - len;
if (0 < pen)
{
//note: if len=0, then perp=0 and we'll never reach here, so don't worry about div-by-0
ox /= len;
oy /= len;
obj.reportCollisionVsWorld(ox*pen, oy*pen, ox, oy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
else
{
//collide vs. slope or vs axis
ox -= r*sx;//this gives us the vector from
oy -= r*sy;//a point on the slope to the innermost point on the circle
//if the dotprod of (ox,oy) and (sx,sy) is negative, the point on the circle is in the slope
//and we need toproject it out by the magnitude of the projection of (ox,oy) onto (sx,sy)
var dp = (ox*sx) + (oy*sy);
if (dp < 0)
{
//collision; project delta onto slope and use this to displace the object
sx *= -dp;//(sx,sy) is now the projection vector
sy *= -dp;
var lenN = Math.sqrt(sx*sx + sy*sy);
//find the smallest axial projection vector
if (x < y)
{
//penetration in x is smaller
lenP = x;
y = 0;
//get sign for projection along x-axis
if ((obj.pos.x - t.pos.x) < 0)
{
x *= -1;
}
}
else
{
//penetration in y is smaller
lenP = y;
x = 0;
//get sign for projection along y-axis
if ((obj.pos.y - t.pos.y)< 0)
{
y *= -1;
}
}
if (lenP < lenN)
{
obj.reportCollisionVsWorld(x,y,x/lenP, y/lenP, t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
else
{
obj.reportCollisionVsWorld(sx,sy,t.sx,t.sy,t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
}
}
else
{
//colliding vertically; we can assume that (signy*oV) < 0
//due to the first conditional far above
obj.reportCollisionVsWorld(0,y*oV, 0, oV, t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
}
else if (oV === 0)
{
//colliding horizontally
if ((signx*oH) < 0)
{
//colliding with face/edge OR with corner of wedge, depending on our position vertically
//collide vs. vertex
//get diag vertex position
var vx = t.pos.x - (signx*t.xw);
var vy = t.pos.y;
var dx = obj.pos.x - vx;//calc vert->circle vector
var dy = obj.pos.y - vy;
if ((dy*signy) < 0)
{
//colliding vs face
obj.reportCollisionVsWorld(x*oH, 0, oH, 0, t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
else
{
//colliding vs. vertex
var len = Math.sqrt(dx*dx + dy*dy);
var pen = obj.radius - len;
if (0 < pen)
{
//vertex is in the circle; project outward
if (len === 0)
{
//project out by 45deg
dx = oH / Math.SQRT2;
dy = oV / Math.SQRT2;
}
else
{
dx /= len;
dy /= len;
}
obj.reportCollisionVsWorld(dx*pen, dy*pen, dx, dy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
}
else
{
//we could only be colliding vs the slope OR a vertex
//look at the vector form the closest vert to the circle to decide
var sx = t.sx;
var sy = t.sy;
var ox = obj.pos.x - (t.pos.x + (oH*t.xw));//this gives is the coordinates of the innermost
var oy = obj.pos.y - (t.pos.y - (signy*t.yw));//point on the circle, relative to the closest tile vert
//if the component of (ox,oy) parallel to the normal's righthand normal
//has the same sign as the slope of the slope (the sign of the slope's slope is signx*signy)
//then we project by the normal, otherwise by the vertex.
//(NOTE: this is the opposite logic of the vertical case;
// for vertical, if the perp prod and the slope's slope agree, it's outside.
// for horizontal, if the perp prod and the slope's slope agree, circle is inside.
// ..but this is only a property of flahs' coord system (i.e the rules might swap
// in righthanded systems))
//note that this is simply a VERY tricky/weird method of determining
//if the circle is in side the slope/face's voronio region, or that of the vertex.
var perp = (ox*-sy) + (oy*sx);
if ((perp*signx*signy) < 0)
{
//collide vs. vertex
var len = Math.sqrt(ox*ox + oy*oy);
var pen = obj.radius - len;
if (0 < pen)
{
//note: if len=0, then perp=0 and we'll never reach here, so don't worry about div-by-0
ox /= len;
oy /= len;
obj.reportCollisionVsWorld(ox*pen, oy*pen, ox, oy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
else
{
//collide vs. slope
//if the component of (ox,oy) parallel to the normal is less than the circle radius, we're
//penetrating the slope. note that this method of penetration calculation doesn't hold
//in general (i.e it won't work if the circle is in the slope), but works in this case
//because we know the circle is in a neighboring cell
var dp = (ox*sx) + (oy*sy);
var pen = obj.radius - Math.abs(dp);//note: we don't need the abs because we know the dp will be positive, but just in case..
if (0 < pen)
{
//collision; circle out along normal by penetration amount
obj.reportCollisionVsWorld(sx*pen, sy*pen, sx, sy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
}
}
else
{
//colliding diagonally; due to the first conditional above,
//obj is vertically offset against slope, and offset in either direction horizontally
//collide vs. vertex
//get diag vertex position
var vx = t.pos.x + (oH*t.xw);
var vy = t.pos.y + (oV*t.yw);
var dx = obj.pos.x - vx;//calc vert->circle vector
var dy = obj.pos.y - vy;
var len = Math.sqrt(dx*dx + dy*dy);
var pen = obj.radius - len;
if (0 < pen)
{
//vertex is in the circle; project outward
if (len === 0)
{
//project out by 45deg
dx = oH / Math.SQRT2;
dy = oV / Math.SQRT2;
}
else
{
dx /= len;
dy /= len;
}
obj.reportCollisionVsWorld(dx*pen, dy*pen, dx, dy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
return Phaser.Physics.Ninja.Circle.COL_NONE;
},
/**
* Resolves 22 Degree tile collision.
*
* @method Phaser.Physics.Ninja.Circle#projCircle_22DegB
* @param {number} x - Penetration depth on the x axis.
* @param {number} y - Penetration depth on the y axis.
* @param {number} oH - Grid / voronoi region.
* @param {number} oV - Grid / voronoi region.
* @param {Phaser.Physics.Ninja.Circle} obj - The Circle involved in the collision.
* @param {Phaser.Physics.Ninja.Tile} t - The Tile involved in the collision.
* @return {number} The result of the collision.
*/
projCircle_22DegB: function (x,y,oH, oV, obj,t) {
//if we're colliding diagonally:
// -if we're in the cell pointed at by the normal, collide vs slope, else
// collide vs. the appropriate corner/vertex
//
//if obj is in this tile: collide as with aabb
//
//if obj is horiz or vertical neighbor AGAINST the slope: collide with edge
//
//if obj is horiz neighb in direction of slope: collide vs. slope or vertex or edge
//
//if obj is vert neighb in direction of slope: collide vs. slope or vertex
var lenP;
var signx = t.signx;
var signy = t.signy;
if (oH === 0)
{
if (oV === 0)
{
//colliding with current cell
var sx = t.sx;
var sy = t.sy;
var r = obj.radius;
var ox = (obj.pos.x - (sx*r)) - (t.pos.x - (signx*t.xw));//this gives is the coordinates of the innermost
var oy = (obj.pos.y - (sy*r)) - (t.pos.y + (signy*t.yw));//point on the AABB, relative to a point on the slope
//if the dotprod of (ox,oy) and (sx,sy) is negative, the point on the circle is in the slope
//and we need toproject it out by the magnitude of the projection of (ox,oy) onto (sx,sy)
var dp = (ox*sx) + (oy*sy);
if (dp < 0)
{
//collision; project delta onto slope and use this to displace the object
sx *= -dp;//(sx,sy) is now the projection vector
sy *= -dp;
var lenN = Math.sqrt(sx*sx + sy*sy);
//find the smallest axial projection vector
if (x < y)
{
//penetration in x is smaller
lenP = x;
y = 0;
//get sign for projection along x-axis
if ((obj.pos.x - t.pos.x) < 0)
{
x *= -1;
}
}
else
{
//penetration in y is smaller
lenP = y;
x = 0;
//get sign for projection along y-axis
if ((obj.pos.y - t.pos.y)< 0)
{
y *= -1;
}
}
if (lenP < lenN)
{
obj.reportCollisionVsWorld(x, y, x/lenP, y/lenP, t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
else
{
obj.reportCollisionVsWorld(sx, sy, t.sx, t.sy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
}
else
{
//colliding vertically
if ((signy*oV) < 0)
{
//colliding with face/edge
obj.reportCollisionVsWorld(0, y*oV, 0, oV, t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
else
{
//we could only be colliding vs the slope OR a vertex
//look at the vector form the closest vert to the circle to decide
var sx = t.sx;
var sy = t.sy;
var ox = obj.pos.x - (t.pos.x - (signx*t.xw));//this gives is the coordinates of the innermost
var oy = obj.pos.y - (t.pos.y + (signy*t.yw));//point on the circle, relative to the closest tile vert
//if the component of (ox,oy) parallel to the normal's righthand normal
//has the same sign as the slope of the slope (the sign of the slope's slope is signx*signy)
//then we project by the vertex, otherwise by the normal.
//note that this is simply a VERY tricky/weird method of determining
//if the circle is in side the slope/face's voronio region, or that of the vertex.
var perp = (ox*-sy) + (oy*sx);
if (0 < (perp*signx*signy))
{
//collide vs. vertex
var len = Math.sqrt(ox*ox + oy*oy);
var pen = obj.radius - len;
if (0 < pen)
{
//note: if len=0, then perp=0 and we'll never reach here, so don't worry about div-by-0
ox /= len;
oy /= len;
obj.reportCollisionVsWorld(ox*pen, oy*pen, ox, oy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
else
{
//collide vs. slope
//if the component of (ox,oy) parallel to the normal is less than the circle radius, we're
//penetrating the slope. note that this method of penetration calculation doesn't hold
//in general (i.e it won't work if the circle is in the slope), but works in this case
//because we know the circle is in a neighboring cell
var dp = (ox*sx) + (oy*sy);
var pen = obj.radius - Math.abs(dp);//note: we don't need the abs because we know the dp will be positive, but just in case..
if (0 < pen)
{
//collision; circle out along normal by penetration amount
obj.reportCollisionVsWorld(sx*pen, sy*pen,sx, sy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
}
}
}
else if (oV === 0)
{
//colliding horizontally
if ((signx*oH) < 0)
{
//colliding with face/edge
obj.reportCollisionVsWorld(x*oH, 0, oH, 0, t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
else
{
//colliding with edge, slope, or vertex
var ox = obj.pos.x - (t.pos.x + (signx*t.xw));//this gives is the coordinates of the innermost
var oy = obj.pos.y - t.pos.y;//point on the circle, relative to the closest tile vert
if ((oy*signy) < 0)
{
//we're colliding with the halfface
obj.reportCollisionVsWorld(x*oH, 0, oH, 0, t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
else
{
//colliding with the vertex or slope
var sx = t.sx;
var sy = t.sy;
//if the component of (ox,oy) parallel to the normal's righthand normal
//has the same sign as the slope of the slope (the sign of the slope's slope is signx*signy)
//then we project by the slope, otherwise by the vertex.
//note that this is simply a VERY tricky/weird method of determining
//if the circle is in side the slope/face's voronio region, or that of the vertex.
var perp = (ox*-sy) + (oy*sx);
if ((perp*signx*signy) < 0)
{
//collide vs. vertex
var len = Math.sqrt(ox*ox + oy*oy);
var pen = obj.radius - len;
if (0 < pen)
{
//note: if len=0, then perp=0 and we'll never reach here, so don't worry about div-by-0
ox /= len;
oy /= len;
obj.reportCollisionVsWorld(ox*pen, oy*pen, ox, oy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
else
{
//collide vs. slope
//if the component of (ox,oy) parallel to the normal is less than the circle radius, we're
//penetrating the slope. note that this method of penetration calculation doesn't hold
//in general (i.e it won't work if the circle is in the slope), but works in this case
//because we know the circle is in a neighboring cell
var dp = (ox*sx) + (oy*sy);
var pen = obj.radius - Math.abs(dp);//note: we don't need the abs because we know the dp will be positive, but just in case..
if (0 < pen)
{
//collision; circle out along normal by penetration amount
obj.reportCollisionVsWorld(sx*pen, sy*pen, t.sx, t.sy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
}
}
}
else
{
//colliding diagonally
if ( 0 < ((signx*oH) + (signy*oV)) )
{
//the dotprod of slope normal and cell offset is strictly positive,
//therefore obj is in the diagonal neighb pointed at by the normal.
//collide vs slope
//we should really precalc this at compile time, but for now, fuck it
var slen = Math.sqrt(2*2 + 1*1);//the raw slope is (-2,-1)
var sx = (signx*1) / slen;//get slope _unit_ normal;
var sy = (signy*2) / slen;//raw RH normal is (1,-2)
var r = obj.radius;
var ox = (obj.pos.x - (sx*r)) - (t.pos.x - (signx*t.xw));//this gives is the coordinates of the innermost
var oy = (obj.pos.y - (sy*r)) - (t.pos.y + (signy*t.yw));//point on the circle, relative to a point on the slope
//if the dotprod of (ox,oy) and (sx,sy) is negative, the point on the circle is in the slope
//and we need toproject it out by the magnitude of the projection of (ox,oy) onto (sx,sy)
var dp = (ox*sx) + (oy*sy);
if (dp < 0)
{
//collision; project delta onto slope and use this to displace the object
//(sx,sy)*-dp is the projection vector
obj.reportCollisionVsWorld(-sx*dp, -sy*dp, t.sx, t.sy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
return Phaser.Physics.Ninja.Circle.COL_NONE;
}
else
{
//collide vs the appropriate vertex
var vx = t.pos.x + (oH*t.xw);
var vy = t.pos.y + (oV*t.yw);
var dx = obj.pos.x - vx;//calc vert->circle vector
var dy = obj.pos.y - vy;
var len = Math.sqrt(dx*dx + dy*dy);
var pen = obj.radius - len;
if (0 < pen)
{
//vertex is in the circle; project outward
if (len === 0)
{
//project out by 45deg
dx = oH / Math.SQRT2;
dy = oV / Math.SQRT2;
}
else
{
dx /= len;
dy /= len;
}
obj.reportCollisionVsWorld(dx*pen, dy*pen, dx, dy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
}
return Phaser.Physics.Ninja.Circle.COL_NONE;
},
/**
* Resolves 67 Degree tile collision.
*
* @method Phaser.Physics.Ninja.Circle#projCircle_67DegS
* @param {number} x - Penetration depth on the x axis.
* @param {number} y - Penetration depth on the y axis.
* @param {number} oH - Grid / voronoi region.
* @param {number} oV - Grid / voronoi region.
* @param {Phaser.Physics.Ninja.Circle} obj - The Circle involved in the collision.
* @param {Phaser.Physics.Ninja.Tile} t - The Tile involved in the collision.
* @return {number} The result of the collision.
*/
projCircle_67DegS: function (x,y,oH,oV,obj,t) {
//if the object is in a cell pointed at by signx, no collision will ever occur
//otherwise,
//
//if we're colliding diagonally:
// -collide vs. the appropriate vertex
//if obj is in this tile: collide vs slope or vertex or axis
//if obj is vert neighb in direction of slope: collide vs. slope or vertex
//if obj is vert neighb against the slope:
// if (distance in y from circle to 90deg corner of tile < 1/2 tileheight, collide vs. face)
// else(collide vs. corner of slope) (vert collision with a non-grid-aligned vert)
//if obj is horiz neighb against direction of slope: collide vs. face
var signx = t.signx;
var signy = t.signy;
if (0 < (signx*oH))
{
//object will never collide vs tile, it can't reach that far
return Phaser.Physics.Ninja.Circle.COL_NONE;
}
else if (oH === 0)
{
if (oV === 0)
{
//colliding with current tile
//we could only be colliding vs the slope OR a vertex
//look at the vector form the closest vert to the circle to decide
var lenP;
var sx = t.sx;
var sy = t.sy;
var r = obj.radius;
var ox = obj.pos.x - t.pos.x;//this gives is the coordinates of the innermost
var oy = obj.pos.y - (t.pos.y - (signy*t.yw));//point on the circle, relative to the tile corner
//if the component of (ox,oy) parallel to the normal's righthand normal
//has the same sign as the slope of the slope (the sign of the slope's slope is signx*signy)
//then we project by the normal or axis, otherwise by the corner/vertex
//note that this is simply a VERY tricky/weird method of determining
//if the circle is in side the slope/face's voronoi region, or that of the vertex.
var perp = (ox*-sy) + (oy*sx);
if ((perp*signx*signy) < 0)
{
//collide vs. vertex
var len = Math.sqrt(ox*ox + oy*oy);
var pen = r - len;
if (0 < pen)
{
//note: if len=0, then perp=0 and we'll never reach here, so don't worry about div-by-0
ox /= len;
oy /= len;
obj.reportCollisionVsWorld(ox*pen, oy*pen, ox, oy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
else
{
//collide vs. slope or vs axis
ox -= r*sx;//this gives us the vector from
oy -= r*sy;//a point on the slope to the innermost point on the circle
//if the dotprod of (ox,oy) and (sx,sy) is negative, the point on the circle is in the slope
//and we need toproject it out by the magnitude of the projection of (ox,oy) onto (sx,sy)
var dp = (ox*sx) + (oy*sy);
if (dp < 0)
{
//collision; project delta onto slope and use this to displace the object
sx *= -dp;//(sx,sy) is now the projection vector
sy *= -dp;
var lenN = Math.sqrt(sx*sx + sy*sy);
//find the smallest axial projection vector
if (x < y)
{
//penetration in x is smaller
lenP = x;
y = 0;
//get sign for projection along x-axis
if ((obj.pos.x - t.pos.x) < 0)
{
x *= -1;
}
}
else
{
//penetration in y is smaller
lenP = y;
x = 0;
//get sign for projection along y-axis
if ((obj.pos.y - t.pos.y)< 0)
{
y *= -1;
}
}
if (lenP < lenN)
{
obj.reportCollisionVsWorld(x,y,x/lenP, y/lenP, t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
else
{
obj.reportCollisionVsWorld(sx,sy,t.sx,t.sy,t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
}
}
else
{
//colliding vertically
if ((signy*oV) < 0)
{
//colliding with face/edge OR with corner of wedge, depending on our position vertically
//collide vs. vertex
//get diag vertex position
var vx = t.pos.x;
var vy = t.pos.y - (signy*t.yw);
var dx = obj.pos.x - vx;//calc vert->circle vector
var dy = obj.pos.y - vy;
if ((dx*signx) < 0)
{
//colliding vs face
obj.reportCollisionVsWorld(0, y*oV, 0, oV, t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
else
{
//colliding vs. vertex
var len = Math.sqrt(dx*dx + dy*dy);
var pen = obj.radius - len;
if (0 < pen)
{
//vertex is in the circle; project outward
if (len === 0)
{
//project out by 45deg
dx = oH / Math.SQRT2;
dy = oV / Math.SQRT2;
}
else
{
dx /= len;
dy /= len;
}
obj.reportCollisionVsWorld(dx*pen, dy*pen, dx, dy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
}
else
{
//we could only be colliding vs the slope OR a vertex
//look at the vector form the closest vert to the circle to decide
var sx = t.sx;
var sy = t.sy;
var ox = obj.pos.x - (t.pos.x - (signx*t.xw));//this gives is the coordinates of the innermost
var oy = obj.pos.y - (t.pos.y + (oV*t.yw));//point on the circle, relative to the closest tile vert
//if the component of (ox,oy) parallel to the normal's righthand normal
//has the same sign as the slope of the slope (the sign of the slope's slope is signx*signy)
//then we project by the vertex, otherwise by the normal.
//note that this is simply a VERY tricky/weird method of determining
//if the circle is in side the slope/face's voronio region, or that of the vertex.
var perp = (ox*-sy) + (oy*sx);
if (0 < (perp*signx*signy))
{
//collide vs. vertex
var len = Math.sqrt(ox*ox + oy*oy);
var pen = obj.radius - len;
if (0 < pen)
{
//note: if len=0, then perp=0 and we'll never reach here, so don't worry about div-by-0
ox /= len;
oy /= len;
obj.reportCollisionVsWorld(ox*pen, oy*pen, ox, oy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
else
{
//collide vs. slope
//if the component of (ox,oy) parallel to the normal is less than the circle radius, we're
//penetrating the slope. note that this method of penetration calculation doesn't hold
//in general (i.e it won't work if the circle is in the slope), but works in this case
//because we know the circle is in a neighboring cell
var dp = (ox*sx) + (oy*sy);
var pen = obj.radius - Math.abs(dp);//note: we don't need the abs because we know the dp will be positive, but just in case..
if (0 < pen)
{
//collision; circle out along normal by penetration amount
obj.reportCollisionVsWorld(sx*pen, sy*pen, t.sx, t.sy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
}
}
}
else if (oV === 0)
{
//colliding horizontally; we can assume that (signy*oV) < 0
//due to the first conditional far above
obj.reportCollisionVsWorld(x*oH, 0, oH, 0, t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
else
{
//colliding diagonally; due to the first conditional above,
//obj is vertically offset against slope, and offset in either direction horizontally
//collide vs. vertex
//get diag vertex position
var vx = t.pos.x + (oH*t.xw);
var vy = t.pos.y + (oV*t.yw);
var dx = obj.pos.x - vx;//calc vert->circle vector
var dy = obj.pos.y - vy;
var len = Math.sqrt(dx*dx + dy*dy);
var pen = obj.radius - len;
if (0 < pen)
{
//vertex is in the circle; project outward
if (len === 0)
{
//project out by 45deg
dx = oH / Math.SQRT2;
dy = oV / Math.SQRT2;
}
else
{
dx /= len;
dy /= len;
}
obj.reportCollisionVsWorld(dx*pen, dy*pen, dx, dy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
return Phaser.Physics.Ninja.Circle.COL_NONE;
},
/**
* Resolves 67 Degree tile collision.
*
* @method Phaser.Physics.Ninja.Circle#projCircle_67DegB
* @param {number} x - Penetration depth on the x axis.
* @param {number} y - Penetration depth on the y axis.
* @param {number} oH - Grid / voronoi region.
* @param {number} oV - Grid / voronoi region.
* @param {Phaser.Physics.Ninja.Circle} obj - The Circle involved in the collision.
* @param {Phaser.Physics.Ninja.Tile} t - The Tile involved in the collision.
* @return {number} The result of the collision.
*/
projCircle_67DegB: function (x,y,oH, oV, obj,t) {
//if we're colliding diagonally:
// -if we're in the cell pointed at by the normal, collide vs slope, else
// collide vs. the appropriate corner/vertex
//
//if obj is in this tile: collide as with aabb
//
//if obj is horiz or vertical neighbor AGAINST the slope: collide with edge
//
//if obj is vert neighb in direction of slope: collide vs. slope or vertex or halfedge
//
//if obj is horiz neighb in direction of slope: collide vs. slope or vertex
var signx = t.signx;
var signy = t.signy;
if (oH === 0)
{
if (oV === 0)
{
//colliding with current cell
var lenP;
var sx = t.sx;
var sy = t.sy;
var r = obj.radius;
var ox = (obj.pos.x - (sx*r)) - (t.pos.x + (signx*t.xw));//this gives is the coordinates of the innermost
var oy = (obj.pos.y - (sy*r)) - (t.pos.y - (signy*t.yw));//point on the AABB, relative to a point on the slope
//if the dotprod of (ox,oy) and (sx,sy) is negative, the point on the circle is in the slope
//and we need toproject it out by the magnitude of the projection of (ox,oy) onto (sx,sy)
var dp = (ox*sx) + (oy*sy);
if (dp < 0)
{
//collision; project delta onto slope and use this to displace the object
sx *= -dp;//(sx,sy) is now the projection vector
sy *= -dp;
var lenN = Math.sqrt(sx*sx + sy*sy);
//find the smallest axial projection vector
if (x < y)
{
//penetration in x is smaller
lenP = x;
y = 0;
//get sign for projection along x-axis
if ((obj.pos.x - t.pos.x) < 0)
{
x *= -1;
}
}
else
{
//penetration in y is smaller
lenP = y;
x = 0;
//get sign for projection along y-axis
if ((obj.pos.y - t.pos.y)< 0)
{
y *= -1;
}
}
if (lenP < lenN)
{
obj.reportCollisionVsWorld(x,y,x/lenP, y/lenP, t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
else
{
obj.reportCollisionVsWorld(sx, sy, t.sx, t.sy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
}
else
{
//colliding vertically
if ((signy*oV) < 0)
{
//colliding with face/edge
obj.reportCollisionVsWorld(0, y*oV, 0, oV, t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
else
{
//colliding with edge, slope, or vertex
var ox = obj.pos.x - t.pos.x;//this gives is the coordinates of the innermost
var oy = obj.pos.y - (t.pos.y + (signy*t.yw));//point on the circle, relative to the closest tile vert
if ((ox*signx) < 0)
{
//we're colliding with the halfface
obj.reportCollisionVsWorld(0, y*oV, 0, oV, t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
else
{
//colliding with the vertex or slope
var sx = t.sx;
var sy = t.sy;
//if the component of (ox,oy) parallel to the normal's righthand normal
//has the same sign as the slope of the slope (the sign of the slope's slope is signx*signy)
//then we project by the vertex, otherwise by the slope.
//note that this is simply a VERY tricky/weird method of determining
//if the circle is in side the slope/face's voronio region, or that of the vertex.
var perp = (ox*-sy) + (oy*sx);
if (0 < (perp*signx*signy))
{
//collide vs. vertex
var len = Math.sqrt(ox*ox + oy*oy);
var pen = obj.radius - len;
if (0 < pen)
{
//note: if len=0, then perp=0 and we'll never reach here, so don't worry about div-by-0
ox /= len;
oy /= len;
obj.reportCollisionVsWorld(ox*pen, oy*pen, ox, oy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
else
{
//collide vs. slope
//if the component of (ox,oy) parallel to the normal is less than the circle radius, we're
//penetrating the slope. note that this method of penetration calculation doesn't hold
//in general (i.e it won't work if the circle is in the slope), but works in this case
//because we know the circle is in a neighboring cell
var dp = (ox*sx) + (oy*sy);
var pen = obj.radius - Math.abs(dp);//note: we don't need the abs because we know the dp will be positive, but just in case..
if (0 < pen)
{
//collision; circle out along normal by penetration amount
obj.reportCollisionVsWorld(sx*pen, sy*pen, sx, sy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
}
}
}
}
else if (oV === 0)
{
//colliding horizontally
if ((signx*oH) < 0)
{
//colliding with face/edge
obj.reportCollisionVsWorld(x*oH, 0, oH, 0, t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
else
{
//we could only be colliding vs the slope OR a vertex
//look at the vector form the closest vert to the circle to decide
var slen = Math.sqrt(2*2 + 1*1);//the raw slope is (-2,-1)
var sx = (signx*2) / slen;//get slope _unit_ normal;
var sy = (signy*1) / slen;//raw RH normal is (1,-2)
var ox = obj.pos.x - (t.pos.x + (signx*t.xw));//this gives is the coordinates of the innermost
var oy = obj.pos.y - (t.pos.y - (signy*t.yw));//point on the circle, relative to the closest tile vert
//if the component of (ox,oy) parallel to the normal's righthand normal
//has the same sign as the slope of the slope (the sign of the slope's slope is signx*signy)
//then we project by the slope, otherwise by the vertex.
//note that this is simply a VERY tricky/weird method of determining
//if the circle is in side the slope/face's voronio region, or that of the vertex.
var perp = (ox*-sy) + (oy*sx);
if ((perp*signx*signy) < 0)
{
//collide vs. vertex
var len = Math.sqrt(ox*ox + oy*oy);
var pen = obj.radius - len;
if (0 < pen)
{
//note: if len=0, then perp=0 and we'll never reach here, so don't worry about div-by-0
ox /= len;
oy /= len;
obj.reportCollisionVsWorld(ox*pen, oy*pen, ox, oy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
else
{
//collide vs. slope
//if the component of (ox,oy) parallel to the normal is less than the circle radius, we're
//penetrating the slope. note that this method of penetration calculation doesn't hold
//in general (i.e it won't work if the circle is in the slope), but works in this case
//because we know the circle is in a neighboring cell
var dp = (ox*sx) + (oy*sy);
var pen = obj.radius - Math.abs(dp);//note: we don't need the abs because we know the dp will be positive, but just in case..
if (0 < pen)
{
//collision; circle out along normal by penetration amount
obj.reportCollisionVsWorld(sx*pen, sy*pen, t.sx, t.sy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
}
}
else
{
//colliding diagonally
if ( 0 < ((signx*oH) + (signy*oV)) )
{
//the dotprod of slope normal and cell offset is strictly positive,
//therefore obj is in the diagonal neighb pointed at by the normal.
//collide vs slope
var sx = t.sx;
var sy = t.sy;
var r = obj.radius;
var ox = (obj.pos.x - (sx*r)) - (t.pos.x + (signx*t.xw));//this gives is the coordinates of the innermost
var oy = (obj.pos.y - (sy*r)) - (t.pos.y - (signy*t.yw));//point on the circle, relative to a point on the slope
//if the dotprod of (ox,oy) and (sx,sy) is negative, the point on the circle is in the slope
//and we need toproject it out by the magnitude of the projection of (ox,oy) onto (sx,sy)
var dp = (ox*sx) + (oy*sy);
if (dp < 0)
{
//collision; project delta onto slope and use this to displace the object
//(sx,sy)*-dp is the projection vector
obj.reportCollisionVsWorld(-sx*dp, -sy*dp, t.sx, t.sy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
return Phaser.Physics.Ninja.Circle.COL_NONE;
}
else
{
//collide vs the appropriate vertex
var vx = t.pos.x + (oH*t.xw);
var vy = t.pos.y + (oV*t.yw);
var dx = obj.pos.x - vx;//calc vert->circle vector
var dy = obj.pos.y - vy;
var len = Math.sqrt(dx*dx + dy*dy);
var pen = obj.radius - len;
if (0 < pen)
{
//vertex is in the circle; project outward
if (len === 0)
{
//project out by 45deg
dx = oH / Math.SQRT2;
dy = oV / Math.SQRT2;
}
else
{
dx /= len;
dy /= len;
}
obj.reportCollisionVsWorld(dx*pen, dy*pen, dx, dy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
}
return Phaser.Physics.Ninja.Circle.COL_NONE;
},
/**
* Destroys this Circle's reference to Body and System
*
* @method Phaser.Physics.Ninja.Circle#destroy
*/
destroy: function() {
this.body = null;
this.system = null;
},
/**
* Render this circle for debugging purposes.
*
* @method Phaser.Physics.Ninja.Circle#render
* @param {object} context - The context to render to.
* @param {number} xOffset - X offset from circle's position to render at.
* @param {number} yOffset - Y offset from circle's position to render at.
* @param {string} color - color of the debug shape to be rendered. (format is css color string).
* @param {boolean} filled - Render the shape as solid (true) or hollow (false).
*/
render: function(context, xOffset, yOffset, color, filled) {
var x = this.pos.x - xOffset;
var y = this.pos.y - yOffset;
context.beginPath();
context.arc(x, y, this.radius, 0, 2 * Math.PI, false);
if (filled)
{
context.fillStyle = color;
context.fill();
}
else
{
context.strokeStyle = color;
context.stroke();
}
}
};
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const chalk = require("chalk");
const utils_1 = require("../../utils");
const index_1 = require("./index");
const index_2 = require("../../http/index");
/**
* @description Registers application routes.
*
* @export
* @class RouteRegister
*/
class RouteRegister {
constructor(components, injectables, application) {
this.components = components;
this.injectables = injectables;
this.application = application;
this.initialize();
}
/**
* @description - Registers application routes.
*
* @private
*
* @memberOf RouteRegister
*/
initialize() {
for (let component of this.components) {
// Retrive the component metadata. This will be used to get the
// component configuration for things like "routeUrl" and "method".
let metadata = Reflect.getMetadata('unison:component', component);
for (let method of utils_1.ClassMethods(component)) {
if (Reflect.hasMetadata('unison:route', new component(), method)) {
// Get the route metadata.
let routeMetadata = Reflect.getMetadata('unison:route', new component(), method);
let permissions = [];
// Get the route permissions.
let routePermissions = Reflect.getMetadata('unison:permissions', new component(), method);
if (metadata.routes !== undefined && metadata.routes.permissions !== undefined)
permissions.push(...metadata.routes.permissions);
if (routePermissions !== undefined)
permissions.push(...routePermissions);
// Generate the method that the route will use.
let defaultMethod = (routeMetadata.method || metadata.routes.method || 'get');
// Generate the uri that the route will use.
let uri = utils_1.GenerateURI(metadata.routes.baseUrl || '', routeMetadata.route);
// Register express route.
this.application[defaultMethod](uri, (request, response) => {
// Check if any of the required params are missing.
let required = new index_1.RouteRequired().verify(request, Reflect.getMetadata('unison:required-headers', new component(), method), Reflect.getMetadata('unison:required-body', new component(), method), Reflect.getMetadata('unison:required-query', new component(), method));
if (required.length > 0)
return response
.status(index_2.Status.ClientError.BadRequest)
.json(required);
new index_1.PermissionsHandler()
.verify(request, response, permissions, this.injectables)
.then(success => {
let dependencies = [];
if (Reflect.hasMetadata('design:paramtypes', component)) {
for (let dependency of Reflect.getMetadata('design:paramtypes', component))
dependencies.push(this.injectables[utils_1.ClassName(dependency)]);
}
new component(...dependencies)[method](request, response)
.catch(error => { });
})
.catch(error => { });
});
this.logRoute(uri, defaultMethod);
}
}
}
}
logRoute(url, method) {
switch (method) {
case index_2.Method.GET:
console.log(`${chalk.green(method.toUpperCase())} - ${chalk.italic(url)}`);
break;
case index_2.Method.POST:
console.log(`${chalk.cyan(method.toUpperCase())} - ${chalk.italic(url)}`);
break;
case index_2.Method.DELETE:
console.log(`${chalk.red(method.toUpperCase())} - ${chalk.italic(url)}`);
break;
default:
console.log(`${chalk.black(method.toUpperCase())} - ${chalk.italic(url)}`);
break;
}
}
}
exports.RouteRegister = RouteRegister;
|
Given an array of n distinct integers sorted in ascending order, write a function that returns a Fixed Point in the array, if there is any Fixed Point present in array, else returns -1. Fixed Point in an array is an index i such that arr[i] is equal to i. Note that integers in array can be negative. Examples:Asked by rajk Method 1 (Linear Search)
Linearly search for an index i such that arr[i] == i. Return the first such index found. Thanks to pm for suggesting this solution.Time Complexity: O(n)
Method 2 (Binary Search)
First check whether middle element is Fixed Point or not. If it is, then return it; otherwise check whether index of middle element is greater than value at the index. If index is greater, then Fixed Point(s) lies on the right side of the middle point (obviously only if there is a Fixed Point). Else the Fixed Point(s) lies on left side.Algorithmic Paradigm: Divide & Conquer
Time Complexity: O(Logn)Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.Tags: Divide and Conquer |
import { moduleFor, test } from 'ember-qunit';
moduleFor('route:foo/bar', 'Unit | Route | foo/bar', {
// Specify the other units that are required for this test.
// needs: ['controller:foo']
});
test('it exists', function (assert) {
let route = this.subject();
assert.ok(route);
});
|
import React, {PropTypes} from "react";
import {bindActionCreators} from "redux";
import {connect} from "react-redux";
import * as contextualMenuActions from "../../actions/contextualMenuActions";
import {
Button,
ContextualMenu,
DirectionalHint,
IconName
} from "office-ui-fabric-react";
/**
* Contextual Menu Demo
*/
const ContextualMenuDemo = (props) => {
let {showContextualMenu} = props;
// Method to hide the contextual menu
let hide = () => {
// Hide the contextual menu
props.actions.hide();
}
// The button click event
let onClick = (event) => {
// Disable postback
event.preventDefault();
// Show the contextual menu
props.actions.show();
};
// Render the component
return (
<div>
<Button
id="targetElement"
onClick={event => onClick(event)}
>Show Menu</Button>
{
showContextualMenu && <ContextualMenu
showFocuOnMount={true}
target="#targetElement"
onDismiss={hide}
directionalHint={DirectionalHint.bottomRightEdge}
items={[
{
key: 'newItem',
iconProps: {
iconName: IconName.Add
},
subMenuProps: {
items: [
{
key: 'emailMessage',
name: 'Email message',
title: 'Create an email'
},
{
key: 'calendarEvent',
name: 'Calendar event',
title: 'Create a calendar event',
}
],
},
name: 'New'
},
{
key: 'upload',
onClick: () => {
this.setState({ showCallout: true });
},
iconProps: {
iconName: IconName.Upload,
style: {
color: 'salmon'
}
},
name: 'Upload (Custom Color)',
title: 'Upload a file'
},
{
key: 'divider_1',
name: '-',
},
{
key: 'rename',
name: 'Rename'
},
{
key: 'properties',
name: 'Properties'
},
{
key: 'disabled',
name: 'Disabled item',
disabled: true,
},
{
key: 'divider_2',
name: '-',
},
{
key: 'share',
iconProps: {
iconName: IconName.Share
},
subMenuProps: {
items: [
{
key: 'sharetoemail',
name: 'Share to Email',
iconProps: {
iconName: IconName.Mail
},
},
{
key: 'sharetofacebook',
name: 'Share to Facebook',
},
{
key: 'sharetotwitter',
name: 'Share to Twitter',
iconProps: {
iconName: IconName.Share
},
subMenuProps: {
items: [
{
key: 'sharetoemail_1',
name: 'Share to Email',
title: 'Share to Email',
iconProps: {
iconName: IconName.Mail
},
},
{
key: 'sharetofacebook_1',
name: 'Share to Facebook',
title: 'Share to Facebook',
},
{
key: 'sharetotwitter_1',
name: 'Share to Twitter',
title: 'Share to Twitter',
iconProps: {
iconName: IconName.Share
}
},
],
},
},
],
},
name: 'Share'
},
{
key: 'print',
iconProps: {
iconName: IconName.Print
},
name: 'Print'
},
{
key: 'music',
iconProps: {
iconName: IconName.MusicInCollectionFill
},
name: 'Music',
},
{
key: 'divider_3',
name: '-',
},
{
key: 'Dattabase',
name: 'Go to Dattabase',
href: 'http://dattabase.com'
}
]}
/>
}
</div>
);
};
/**
* Properties
*/
ContextualMenuDemo.propTypes = {
showContextualMenu: PropTypes.bool
};
/**
* Connections
*/
export default connect(
/**
* State to Property Mapper
*/
(state, ownProps) => {
return {
showContextualMenu: state.contextualMenu.showContextualMenu,
};
},
/**
* Actions Mapper
*/
(dispatch) => {
return {
actions: bindActionCreators(contextualMenuActions, dispatch)
};
}
)(ContextualMenuDemo); |
/*!
* jQuery Mobile v@VERSION
* http://jquerymobile.com/
*
* Copyright 2011, jQuery Project
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*/
// This is code that can be used as a simple bookmarklet for timing
// the load, enhancment, and transition of a changePage() request.
(function( $, window, undefined ) {
function getTime() {
return ( new Date() ).getTime();
}
var startChange, stopChange, startLoad, stopLoad, startEnhance, stopEnhance, startTransition, stopTransition, lock = 0;
$( document )
.bind( "pagebeforechange", function( e, data) {
if ( typeof data.toPage === "string" ) {
startChange = stopChange = startLoad = stopLoad = startEnhance = stopEnhance = startTransition = stopTransition = getTime();
}
})
.bind( "pagebeforeload", function() {
startLoad = stopLoad = getTime();
})
.bind( "pagebeforecreate", function() {
if ( ++lock === 1 ) {
stopLoad = startEnhance = stopEnhance = getTime();
}
})
.bind( "pageinit", function() {
if ( --lock === 0 ) {
stopEnhance = getTime();
}
})
.bind( "pagebeforeshow", function() {
startTransition = stopTransition = getTime();
})
.bind( "pageshow", function() {
stopTransition = getTime();
})
.bind( "pagechange", function( e, data ) {
if ( typeof data.toPage === "object" ) {
stopChange = getTime();
alert("load + processing: " + ( stopLoad - startLoad )
+ "\nenhance: " + ( stopEnhance - startEnhance )
+ "\ntransition: " + ( stopTransition - startTransition )
+ "\ntotalTime: " + ( stopChange - startChange ) );
startChange = stopChange = startLoad = stopLoad = startEnhance = stopEnhance = startTransition = stopTransition = 0;
}
});
})( jQuery, window );
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.