code stringlengths 2 1.05M | repo_name stringlengths 5 114 | path stringlengths 4 991 | language stringclasses 1 value | license stringclasses 15 values | size int32 2 1.05M |
|---|---|---|---|---|---|
var formInstance = (
<Form>
<Input placeholder="验证成功" label="验证成功" validation="success" />
<Input placeholder="验证警告" label="验证警告" validation="warning" />
<Input placeholder="验证失败" label="验证失败" validation="error" />
<FormGroup validation="success">
<label>单选按钮:</label>
<Input type="radio" label="男" inline />
<Input type="radio" label="女" inline />
</FormGroup>
</Form>
);
React.render(formInstance, mountNode);
| Node-X/amazeui-react | docs/form/06-field-state.js | JavaScript | mit | 517 |
// randomColor by David Merfield under the CC0 license
// https://github.com/davidmerfield/randomColor/
;(function(root, factory) {
// Support AMD
if (typeof define === 'function' && define.amd) {
define([], factory);
// Support CommonJS
} else if (typeof exports === 'object') {
var randomColor = factory();
// Support NodeJS & Component, which allow module.exports to be a function
if (typeof module === 'object' && module && module.exports) {
exports = module.exports = randomColor;
}
// Support CommonJS 1.1.1 spec
exports.randomColor = randomColor;
// Support vanilla script loading
} else {
root.randomColor = factory();
}
}(this, function() {
// Seed to get repeatable colors
var seed = null;
// Shared color dictionary
var colorDictionary = {};
// Populate the color dictionary
loadColorBounds();
var randomColor = function (options) {
options = options || {};
// Check if there is a seed and ensure it's an
// integer. Otherwise, reset the seed value.
if (options.seed && options.seed === parseInt(options.seed, 10)) {
seed = options.seed;
// A string was passed as a seed
} else if (typeof options.seed === 'string') {
seed = stringToInteger(options.seed);
// Something was passed as a seed but it wasn't an integer or string
} else if (options.seed !== undefined && options.seed !== null) {
throw new TypeError('The seed value must be an integer or string');
// No seed, reset the value outside.
} else {
seed = null;
}
var H,S,B;
// Check if we need to generate multiple colors
if (options.count !== null && options.count !== undefined) {
var totalColors = options.count,
colors = [];
options.count = null;
while (totalColors > colors.length) {
// Since we're generating multiple colors,
// incremement the seed. Otherwise we'd just
// generate the same color each time...
if (seed && options.seed) options.seed += 1;
colors.push(randomColor(options));
}
options.count = totalColors;
return colors;
}
// First we pick a hue (H)
H = pickHue(options);
// Then use H to determine saturation (S)
S = pickSaturation(H, options);
// Then use S and H to determine brightness (B).
B = pickBrightness(H, S, options);
// Then we return the HSB color in the desired format
return setFormat([H,S,B], options);
};
function pickHue (options) {
var hueRange = getHueRange(options.hue),
hue = randomWithin(hueRange);
// Instead of storing red as two seperate ranges,
// we group them, using negative numbers
if (hue < 0) {hue = 360 + hue;}
return hue;
}
function pickSaturation (hue, options) {
if (options.luminosity === 'random') {
return randomWithin([0,100]);
}
if (options.hue === 'monochrome') {
return 0;
}
var saturationRange = getSaturationRange(hue);
var sMin = saturationRange[0],
sMax = saturationRange[1];
switch (options.luminosity) {
case 'bright':
sMin = 55;
break;
case 'dark':
sMin = sMax - 10;
break;
case 'light':
sMax = 55;
break;
}
return randomWithin([sMin, sMax]);
}
function pickBrightness (H, S, options) {
var bMin = getMinimumBrightness(H, S),
bMax = 100;
switch (options.luminosity) {
case 'dark':
bMax = bMin + 20;
break;
case 'light':
bMin = (bMax + bMin)/2;
break;
case 'random':
bMin = 0;
bMax = 100;
break;
}
return randomWithin([bMin, bMax]);
}
function setFormat (hsv, options) {
switch (options.format) {
case 'hsvArray':
return hsv;
case 'hslArray':
return HSVtoHSL(hsv);
case 'hsl':
var hsl = HSVtoHSL(hsv);
return 'hsl('+hsl[0]+', '+hsl[1]+'%, '+hsl[2]+'%)';
case 'hsla':
var hslColor = HSVtoHSL(hsv);
return 'hsla('+hslColor[0]+', '+hslColor[1]+'%, '+hslColor[2]+'%, ' + Math.random() + ')';
case 'rgbArray':
return HSVtoRGB(hsv);
case 'rgb':
var rgb = HSVtoRGB(hsv);
return 'rgb(' + rgb.join(', ') + ')';
case 'rgba':
var rgbColor = HSVtoRGB(hsv);
return 'rgba(' + rgbColor.join(', ') + ', ' + Math.random() + ')';
default:
return HSVtoHex(hsv);
}
}
function getMinimumBrightness(H, S) {
var lowerBounds = getColorInfo(H).lowerBounds;
for (var i = 0; i < lowerBounds.length - 1; i++) {
var s1 = lowerBounds[i][0],
v1 = lowerBounds[i][1];
var s2 = lowerBounds[i+1][0],
v2 = lowerBounds[i+1][1];
if (S >= s1 && S <= s2) {
var m = (v2 - v1)/(s2 - s1),
b = v1 - m*s1;
return m*S + b;
}
}
return 0;
}
function getHueRange (colorInput) {
if (typeof parseInt(colorInput) === 'number') {
var number = parseInt(colorInput);
if (number < 360 && number > 0) {
return [number, number];
}
}
if (typeof colorInput === 'string') {
if (colorDictionary[colorInput]) {
var color = colorDictionary[colorInput];
if (color.hueRange) {return color.hueRange;}
}
}
return [0,360];
}
function getSaturationRange (hue) {
return getColorInfo(hue).saturationRange;
}
function getColorInfo (hue) {
// Maps red colors to make picking hue easier
if (hue >= 334 && hue <= 360) {
hue-= 360;
}
for (var colorName in colorDictionary) {
var color = colorDictionary[colorName];
if (color.hueRange &&
hue >= color.hueRange[0] &&
hue <= color.hueRange[1]) {
return colorDictionary[colorName];
}
} return 'Color not found';
}
function randomWithin (range) {
if (seed === null) {
return Math.floor(range[0] + Math.random()*(range[1] + 1 - range[0]));
} else {
//Seeded random algorithm from http://indiegamr.com/generate-repeatable-random-numbers-in-js/
var max = range[1] || 1;
var min = range[0] || 0;
seed = (seed * 9301 + 49297) % 233280;
var rnd = seed / 233280.0;
return Math.floor(min + rnd * (max - min));
}
}
function HSVtoHex (hsv){
var rgb = HSVtoRGB(hsv);
function componentToHex(c) {
var hex = c.toString(16);
return hex.length == 1 ? '0' + hex : hex;
}
var hex = '#' + componentToHex(rgb[0]) + componentToHex(rgb[1]) + componentToHex(rgb[2]);
return hex;
}
function defineColor (name, hueRange, lowerBounds) {
var sMin = lowerBounds[0][0],
sMax = lowerBounds[lowerBounds.length - 1][0],
bMin = lowerBounds[lowerBounds.length - 1][1],
bMax = lowerBounds[0][1];
colorDictionary[name] = {
hueRange: hueRange,
lowerBounds: lowerBounds,
saturationRange: [sMin, sMax],
brightnessRange: [bMin, bMax]
};
}
function loadColorBounds () {
defineColor(
'monochrome',
null,
[[0,0],[100,0]]
);
defineColor(
'red',
[-26,18],
[[20,100],[30,92],[40,89],[50,85],[60,78],[70,70],[80,60],[90,55],[100,50]]
);
defineColor(
'orange',
[19,46],
[[20,100],[30,93],[40,88],[50,86],[60,85],[70,70],[100,70]]
);
defineColor(
'yellow',
[47,62],
[[25,100],[40,94],[50,89],[60,86],[70,84],[80,82],[90,80],[100,75]]
);
defineColor(
'green',
[63,178],
[[30,100],[40,90],[50,85],[60,81],[70,74],[80,64],[90,50],[100,40]]
);
defineColor(
'blue',
[179, 257],
[[20,100],[30,86],[40,80],[50,74],[60,60],[70,52],[80,44],[90,39],[100,35]]
);
defineColor(
'purple',
[258, 282],
[[20,100],[30,87],[40,79],[50,70],[60,65],[70,59],[80,52],[90,45],[100,42]]
);
defineColor(
'pink',
[283, 334],
[[20,100],[30,90],[40,86],[60,84],[80,80],[90,75],[100,73]]
);
}
function HSVtoRGB (hsv) {
// this doesn't work for the values of 0 and 360
// here's the hacky fix
var h = hsv[0];
if (h === 0) {h = 1;}
if (h === 360) {h = 359;}
// Rebase the h,s,v values
h = h/360;
var s = hsv[1]/100,
v = hsv[2]/100;
var h_i = Math.floor(h*6),
f = h * 6 - h_i,
p = v * (1 - s),
q = v * (1 - f*s),
t = v * (1 - (1 - f)*s),
r = 256,
g = 256,
b = 256;
switch(h_i) {
case 0: r = v; g = t; b = p; break;
case 1: r = q; g = v; b = p; break;
case 2: r = p; g = v; b = t; break;
case 3: r = p; g = q; b = v; break;
case 4: r = t; g = p; b = v; break;
case 5: r = v; g = p; b = q; break;
}
var result = [Math.floor(r*255), Math.floor(g*255), Math.floor(b*255)];
return result;
}
function HSVtoHSL (hsv) {
var h = hsv[0],
s = hsv[1]/100,
v = hsv[2]/100,
k = (2-s)*v;
return [
h,
Math.round(s*v / (k<1 ? k : 2-k) * 10000) / 100,
k/2 * 100
];
}
function stringToInteger (string) {
var total = 0
for (var i = 0; i !== string.length; i++) {
if (total >= Number.MAX_SAFE_INTEGER) break;
total += string.charCodeAt(i)
}
return total
}
return randomColor;
}));
| CraigBanach/voting-app | views/home/poll/randomcolor/randomColor.js | JavaScript | mit | 9,464 |
// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// License: GNU General Public License v3. See license.txt
erpnext.SMSManager = function SMSManager(doc) {
var me = this;
this.setup = function() {
var default_msg = {
'Lead' : '',
'Opportunity' : 'Your enquiry has been logged into the system. Ref No: ' + doc.name,
'Quotation' : 'Quotation ' + doc.name + ' has been sent via email. Thanks!',
'Sales Order' : 'Sales Order ' + doc.name + ' has been created against '
+ (doc.quotation_no ? ('Quote No:' + doc.quotation_no) : '')
+ (doc.po_no ? (' for your PO: ' + doc.po_no) : ''),
'Delivery Note' : 'Items has been delivered against delivery note: ' + doc.name
+ (doc.po_no ? (' for your PO: ' + doc.po_no) : ''),
'Sales Invoice': 'Invoice ' + doc.name + ' has been sent via email '
+ (doc.po_no ? (' for your PO: ' + doc.po_no) : ''),
'Material Request' : 'Material Request ' + doc.name + ' has been raised in the system',
'Purchase Order' : 'Purchase Order ' + doc.name + ' has been sent via email',
'Purchase Receipt' : 'Items has been received against purchase receipt: ' + doc.name
}
if (in_list(['Sales Order', 'Delivery Note', 'Sales Invoice'], doc.doctype))
this.show(doc.contact_person, 'Customer', doc.customer, '', default_msg[doc.doctype]);
else if (doc.doctype === 'Quotation')
this.show(doc.contact_person, 'Customer', doc.party_name, '', default_msg[doc.doctype]);
else if (in_list(['Purchase Order', 'Purchase Receipt'], doc.doctype))
this.show(doc.contact_person, 'Supplier', doc.supplier, '', default_msg[doc.doctype]);
else if (doc.doctype == 'Lead')
this.show('', '', '', doc.mobile_no, default_msg[doc.doctype]);
else if (doc.doctype == 'Opportunity')
this.show('', '', '', doc.contact_no, default_msg[doc.doctype]);
else if (doc.doctype == 'Material Request')
this.show('', '', '', '', default_msg[doc.doctype]);
};
this.get_contact_number = function(contact, ref_doctype, ref_name) {
frappe.call({
method: "frappe.core.doctype.sms_settings.sms_settings.get_contact_number",
args: {
contact_name: contact,
ref_doctype: ref_doctype,
ref_name: ref_name
},
callback: function(r) {
if(r.exc) { frappe.msgprint(r.exc); return; }
me.number = r.message;
me.show_dialog();
}
});
};
this.show = function(contact, ref_doctype, ref_name, mobile_nos, message) {
this.message = message;
if (mobile_nos) {
me.number = mobile_nos;
me.show_dialog();
} else if (contact){
this.get_contact_number(contact, ref_doctype, ref_name)
} else {
me.show_dialog();
}
}
this.show_dialog = function() {
if(!me.dialog)
me.make_dialog();
me.dialog.set_values({
'message': me.message,
'number': me.number
})
me.dialog.show();
}
this.make_dialog = function() {
var d = new frappe.ui.Dialog({
title: 'Send SMS',
width: 400,
fields: [
{fieldname:'number', fieldtype:'Data', label:'Mobile Number', reqd:1},
{fieldname:'message', fieldtype:'Text', label:'Message', reqd:1},
{fieldname:'send', fieldtype:'Button', label:'Send'}
]
})
d.fields_dict.send.input.onclick = function() {
var btn = d.fields_dict.send.input;
var v = me.dialog.get_values();
if(v) {
$(btn).set_working();
frappe.call({
method: "frappe.core.doctype.sms_settings.sms_settings.send_sms",
args: {
receiver_list: [v.number],
msg: v.message
},
callback: function(r) {
$(btn).done_working();
if(r.exc) {frappe.msgprint(r.exc); return; }
me.dialog.hide();
}
});
}
}
this.dialog = d;
}
this.setup();
}
| mhbu50/erpnext | erpnext/public/js/sms_manager.js | JavaScript | gpl-3.0 | 3,678 |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
var gTestfile = 'regress-441477-01.js';
//-----------------------------------------------------------------------------
var BUGNUMBER = 441477-01;
var summary = '';
var actual = 'No Exception';
var expect = 'No Exception';
//-----------------------------------------------------------------------------
test();
//-----------------------------------------------------------------------------
function test()
{
enterFunc ('test');
printBugNumber(BUGNUMBER);
printStatus (summary);
try
{
for (i = 0; i < 5;)
{
if (i > 5)
throw "bad";
i++;
continue;
}
}
catch(ex)
{
actual = ex + '';
}
reportCompare(expect, actual, summary);
exitFunc ('test');
}
| sainaen/rhino | testsrc/tests/ecma_3/Regress/regress-441477-01.js | JavaScript | mpl-2.0 | 1,005 |
import React from 'react';
import { Provider } from 'react-redux';
import PropTypes from 'prop-types';
import configureStore from '../store/configureStore';
import { BrowserRouter, Route } from 'react-router-dom';
import { ScrollContext } from 'react-router-scroll-4';
import UI from '../features/ui';
import { fetchCustomEmojis } from '../actions/custom_emojis';
import { hydrateStore } from '../actions/store';
import { connectUserStream } from '../actions/streaming';
import { IntlProvider, addLocaleData } from 'react-intl';
import { getLocale } from '../locales';
import initialState from '../initial_state';
import ErrorBoundary from '../components/error_boundary';
const { localeData, messages } = getLocale();
addLocaleData(localeData);
export const store = configureStore();
const hydrateAction = hydrateStore(initialState);
store.dispatch(hydrateAction);
store.dispatch(fetchCustomEmojis());
const createIdentityContext = state => ({
signedIn: !!state.meta.me,
accountId: state.meta.me,
accessToken: state.meta.access_token,
});
export default class Mastodon extends React.PureComponent {
static propTypes = {
locale: PropTypes.string.isRequired,
};
static childContextTypes = {
identity: PropTypes.shape({
signedIn: PropTypes.bool.isRequired,
accountId: PropTypes.string,
accessToken: PropTypes.string,
}).isRequired,
};
identity = createIdentityContext(initialState);
getChildContext() {
return {
identity: this.identity,
};
}
componentDidMount() {
if (this.identity.signedIn) {
this.disconnect = store.dispatch(connectUserStream());
}
}
componentWillUnmount () {
if (this.disconnect) {
this.disconnect();
this.disconnect = null;
}
}
shouldUpdateScroll (prevRouterProps, { location }) {
return !(location.state?.mastodonModalKey && location.state?.mastodonModalKey !== prevRouterProps?.location?.state?.mastodonModalKey);
}
render () {
const { locale } = this.props;
return (
<IntlProvider locale={locale} messages={messages}>
<Provider store={store}>
<ErrorBoundary>
<BrowserRouter basename='/web'>
<ScrollContext shouldUpdateScroll={this.shouldUpdateScroll}>
<Route path='/' component={UI} />
</ScrollContext>
</BrowserRouter>
</ErrorBoundary>
</Provider>
</IntlProvider>
);
}
}
| Ryanaka/mastodon | app/javascript/mastodon/containers/mastodon.js | JavaScript | agpl-3.0 | 2,454 |
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
*/
'use strict';
/* global chrome */
var ports = {};
chrome.runtime.onConnect.addListener(function(port) {
var tab = null;
var name = null;
if (isNumeric(port.name)) {
tab = port.name;
name = 'devtools';
installContentScript(+port.name);
} else {
tab = port.sender.tab.id;
name = 'content-script';
}
if (!ports[tab]) {
ports[tab] = {
devtools: null,
'content-script': null,
};
}
ports[tab][name] = port;
if (ports[tab].devtools && ports[tab]['content-script']) {
doublePipe(ports[tab].devtools, ports[tab]['content-script']);
}
});
function isNumeric(str: string): boolean {
return +str + '' === str;
}
function installContentScript(tabId: number) {
chrome.tabs.executeScript(tabId, {file: '/build/contentScript.js'}, function() {
});
}
function doublePipe(one, two) {
one.onMessage.addListener(lOne);
function lOne(message) {
// console.log('dv -> rep', message);
two.postMessage(message);
}
two.onMessage.addListener(lTwo);
function lTwo(message) {
// console.log('rep -> dv', message);
one.postMessage(message);
}
function shutdown() {
one.onMessage.removeListener(lOne);
two.onMessage.removeListener(lTwo);
one.disconnect();
two.disconnect();
}
one.onDisconnect.addListener(shutdown);
two.onDisconnect.addListener(shutdown);
}
| mcanthony/react-devtools | shells/chrome/src/background.js | JavaScript | bsd-3-clause | 1,679 |
module.exports={A:{A:{"2":"H E G C B WB","36":"A"},B:{"36":"D u g I J"},C:{"1":"0 1 2 3 4 5 6 n o p q r s t y K","2":"UB x F L H E G C B A D u g I J Y SB RB","36":"O e P Q R S T U V W X v Z a b c d N f M h i j k l m"},D:{"1":"0 1 2 3 4 5 6 h i j k l m n o p q r s t y K GB AB CB VB DB EB","2":"F L H E G C B A D u g I J Y O e P Q R S T U V W X v Z a b c d N f M"},E:{"2":"9 F L H E G C B A FB HB IB JB KB LB MB"},F:{"1":"U V W X v Z a b c d N f M h i j k l m n o p q r s t","2":"7 8 C A D I J Y O e P Q R S T NB OB PB QB TB w"},G:{"2":"9 G A BB z XB YB ZB aB bB cB dB eB"},H:{"2":"fB"},I:{"2":"x F K gB hB iB jB z kB lB"},J:{"2":"E B"},K:{"1":"M","2":"7 8 B A D w"},L:{"1":"AB"},M:{"1":"K"},N:{"2":"B","36":"A"},O:{"1":"mB"},P:{"1":"L","16":"F"},Q:{"2":"nB"},R:{"1":"oB"}},B:5,C:"Screen Orientation"};
| mytkdals93/golfpass | public/framework/node_modules/caniuse-lite/data/features/screen-orientation.js | JavaScript | mit | 802 |
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './Footer.css';
import Link from '../Link';
function Footer() {
return (
<div className={s.root}>
<div className={s.container}>
<span className={s.text}>© Your Company</span>
<span className={s.spacer}>·</span>
<Link className={s.link} to="/">Home</Link>
<span className={s.spacer}>·</span>
<Link className={s.link} to="/privacy">Privacy</Link>
<span className={s.spacer}>·</span>
<Link className={s.link} to="/not-found">Not Found</Link>
</div>
</div>
);
}
export default withStyles(s)(Footer);
| zerubeus/voicifix | src/components/Footer/Footer.js | JavaScript | mit | 951 |
var path = require('path');
var package = require('./package');
var webpack = require('webpack');
var ProgressPlugin = require('webpack/lib/ProgressPlugin');
var inspect = require('util').inspect;
var Busboy = require('busboy');
var chalk = require('chalk');
var webpackMiddleware = require('webpack-dev-middleware');
var webpackConfig = require('./webpack.config');
var webpackCompiler = webpack(webpackConfig);
var handler;
webpackCompiler.apply(new ProgressPlugin(function(percentage, msg) {
var stream = process.stderr;
if (stream.isTTY && percentage < 0.71) {
stream.cursorTo(0);
stream.write('📦 ' + chalk.magenta(msg));
stream.clearLine(1);
} else if (percentage === 1) {
console.log(chalk.green('\nwebpack: bundle build is now finished.'));
}
}));
// {{ settings for nico
exports.site = {
name: package.title,
description: package.description,
repo: package.repository.url,
issues: package.bugs.url
};
// PRODUCTION
if (process.env.NODE_ENV === 'PRODUCTION') {
exports.minimized = '.min';
}
exports.package = package;
exports.theme = 'site';
exports.source = process.cwd();
exports.output = path.join(process.cwd(), '_site');
exports.permalink = '{{directory}}/{{filename}}';
exports.ignorefilter = function(filepath, subdir) {
var extname = path.extname(filepath);
if (extname === '.tmp' || extname === '.bak') {
return false;
}
if (/\.DS_Store/.test(filepath)) {
return false;
}
if (/^(_site|_theme|node_modules|site|\.idea)/.test(subdir)) {
return false;
}
return true;
};
exports.middlewares = [
{
name: 'upload',
filter: /upload\.do?$/,
handle: function(req, res, next) {
if (req.method === 'POST') {
var busboy = new Busboy({headers: req.headers});
busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
console.log('File [' + fieldname + ']: filename: ' + filename + ', encoding: ' + encoding + ', mimetype: ' + mimetype);
file.on('data', function(data) {
console.log('File [' + fieldname + '] got ' + data.length + ' bytes');
});
file.on('end', function() {
console.log('File [' + fieldname + '] Finished');
});
});
busboy.on('field', function(fieldname, val, fieldnameTruncated, valTruncated) {
console.log('Field [' + fieldname + ']: value: ' + inspect(val));
});
busboy.on('finish', function() {
console.log('Done parsing form!');
//res.writeHead(303, { Connection: 'close', Location: '/' });
res.end(JSON.stringify({
'status': 'success',
'url': '/example.file'
}));
});
req.pipe(busboy);
}
}
},
{
name: 'webpackDevMiddleware',
filter: /\.(js|css)(\.map)?$/,
handle: function(req, res, next) {
handler = handler || webpackMiddleware(webpackCompiler, {
publicPath: '/dist/',
lazy: false,
watchOptions: {
aggregateTimeout: 300,
poll: true
},
noInfo: true
});
try {
return handler(req, res, next);
} catch(e) {}
}
}];
exports.writers = [
'nico-jsx.PageWriter',
'nico-jsx.StaticWriter',
'nico-jsx.FileWriter'
];
// end settings }}
process.on('uncaughtException', function(err) {
console.log(err);
});
| samlin08/ant-design | nico.js | JavaScript | mit | 3,338 |
import demand from 'must';
import { columnsParser, sortParser, filtersParser, filterParser, createFilterObject } from '../index';
import sinon from 'sinon';
describe('<List> query parsers', function () {
beforeEach(function () {
this.fields = {
name: {
path: 'name',
paths: {
first: 'name.first',
last: 'name.last',
full: 'name.full',
},
type: 'name',
label: 'Name',
size: 'full',
required: true,
hasFilterMethod: true,
defaultValue: {
first: '',
last: '',
},
},
email: {
path: 'email',
type: 'email',
label: 'Email',
size: 'full',
required: true,
defaultValue: {
email: '',
},
},
};
this.currentList = {
fields: this.fields,
defaultColumns: { columns: '__DEFAULT_COLUMNS__' },
defaultSort: { sort: '__DEFAULT_SORT__' },
expandColumns: sinon.spy(),
expandSort: sinon.spy(),
};
this.path = 'name';
this.value = { value: 'a', mode: 'contains', inverted: false };
this.filter = Object.assign({}, { path: this.path }, this.value);
});
describe('columnsParser()', function () {
describe('If an empty columns array is added', function () {
it('should call expandColumns with default columns', function () {
const columns = [];
columnsParser(columns, this.currentList);
const result = this.currentList.expandColumns.getCall(0).args[0];
demand(result).eql(this.currentList.defaultColumns);
});
});
describe('If the input columns are undefined', function () {
it('should call expandColumns with default columns', function () {
const columns = void 0;
columnsParser(columns, this.currentList);
const result = this.currentList.expandColumns.getCall(0).args[0];
demand(result).eql(this.currentList.defaultColumns);
});
});
describe('If currentList does not exist', function () {
it('throws an Error', function () {
const columns = ['name', 'email'];
let e = void 0;
try {
columnsParser(columns, null);
} catch (error) {
e = error;
}
demand(e.message).eql('No currentList selected');
});
});
});
describe('sortParser()', function () {
describe('If no path is specified', function () {
it('should return the default sort object', function () {
const path = void 0;
sortParser(path, this.currentList);
const result = this.currentList.expandSort.getCall(0).args[0];
demand(result).eql(this.currentList.defaultSort);
});
});
describe('If currentList does not exist', function () {
it('throws an Error', function () {
const path = 'email';
let e = void 0;
try {
sortParser(path, null);
} catch (error) {
e = error;
}
demand(e.message).eql('No currentList selected');
});
});
});
describe('createFilterObject()', function () {
describe('If prvided with a valid path and a valid currentList', function () {
it('returns an object with a field [object Object], and the passed in value', function () {
const expectedFilter = this.currentList.fields[this.path];
const expectedResult = { field: expectedFilter, value: this.value };
demand(createFilterObject(this.path, this.value, this.currentList.fields)).eql(expectedResult);
});
});
describe('If provided with an invalid path', function () {
it('returns undefined', function () {
const expectedResult = void 0;
demand(createFilterObject(null, null, this.currentList)).eql(expectedResult);
});
});
describe('If provided with an invalid currentListFields', function () {
it('returns undefined', function () {
const expectedResult = void 0;
demand(createFilterObject(this.path, this.value, {})).eql(expectedResult);
});
});
describe('If provided with a null value for currentListFields', function () {
it('returns undefined', function () {
const expectedResult = void 0;
demand(createFilterObject(this.path, this.value, null)).eql(expectedResult);
});
});
describe('If provided with any value that is not a plain object', function () {
it('returns undefined', function () {
const expectedResult = void 0;
demand(createFilterObject(this.path, this.value, 'currentListFields')).eql(expectedResult);
});
});
});
describe('filtersParser()', function () {
describe('Given no matching fields are found', function () {
it('returns an empty array', function () {
const invalidFilter = 'jemena';
const expectedResult = [];
const filters = [invalidFilter];
demand(filtersParser(filters, this.currentList)).eql(expectedResult);
});
});
describe('Given no filters are passed into the function', function () {
it('returns an empty array', function () {
const expectedResult = [];
demand(filtersParser(null, this.currentList)).eql(expectedResult);
});
});
describe('Given an array of filters', function () {
it('returns an array of filters', function () {
const filter = Object.assign(
{},
{ path: 'name' },
this.value
);
const filters = [filter];
const expectedResult = [{
field: this.currentList.fields[filter.path],
value: this.value,
}];
demand(filtersParser(filters, this.currentList)).eql(expectedResult);
});
});
describe('Given a valid stringified filters array', function () {
it('returns an array of filters', function () {
const filter = Object.assign(
{},
{ path: 'name' },
this.value
);
const filters = [filter];
const stringifiedFilters = JSON.stringify(filters);
const expectedResult = [{
field: this.currentList.fields[filter.path],
value: this.value,
}];
demand(filtersParser(stringifiedFilters, this.currentList)).eql(expectedResult);
});
});
describe('If provided with an invalid stringified filters array', function () {
it('returns an empty array', function () {
const stringifiedFilters = 'jemena';
const expectedResult = [];
demand(filtersParser(stringifiedFilters, this.currentList)).eql(expectedResult);
});
});
});
describe('filterParser()', function () {
beforeEach(function () {
const firstEntry = { field: this.currentList.fields[this.path], value: this.value };
const secondEntry = { field: this.currentList.fields.email, value: this.value };
this.activeFilters = [firstEntry, secondEntry];
this.addedFilter = { path: this.filter.path, value: this.value };
});
describe('Given a valid filter object with a path and value', function () {
it('returns an expanded filter object', function () {
const expectedResult = { field: this.currentList.fields[this.path], value: this.value };
demand(filterParser(this.addedFilter, this.activeFilters, this.currentList)).eql(expectedResult);
});
});
describe('Given that activeFilters is not an array', function () {
it('throws an error', function () {
const invalidActiveFilters = 'hello there';
let e = void 0;
try {
filterParser(this.addedFilter, invalidActiveFilters, this.currentList);
} catch (error) {
e = error;
}
demand(e.message).eql('activeFilters must be an array');
});
});
describe('Given that currentList is not a valid object', function () {
it('throws an error', function () {
let e = void 0;
const invalidList = void 0;
try {
filterParser({}, this.activeFilters, invalidList);
} catch (error) {
e = error;
}
demand(e.message).eql('No currentList selected');
});
});
describe('Given that the filter does not exist in activeFilters', function () {
describe('Given that currentList is not an object of the shape that we expect', function () {
it('returns undefined', function () {
const expectedResult = void 0;
const badList = {
someKey: 'some value',
someOtherKey: 'some other value',
};
demand(filterParser(this.addedFilter, [], badList)).eql(expectedResult);
});
});
});
});
});
| trentmillar/keystone | admin/client/App/parsers/tests/index.test.js | JavaScript | mit | 7,962 |
tinyMCE.addI18n('sk.simple',{
bold_desc:"Tu\u010Dn\u00FD text (Ctrl+B)",
italic_desc:"\u0160ikm\u00FD text (kurz\u00EDva) (Ctrl+I)",
underline_desc:"Pod\u010Diarknut\u00FD text (Ctrl+U)",
striketrough_desc:"Pre\u0161krtnut\u00FD text",
bullist_desc:"Zoznam s odr\u00E1\u017Ekami",
numlist_desc:"\u010C\u00EDslovan\u00FD zoznam",
undo_desc:"Sp\u00E4\u0165 (Ctrl+Z)",
redo_desc:"Znovu (Ctrl+Y)",
cleanup_desc:"Vy\u010Disti\u0165 neupraven\u00FD k\u00F3d"
}); | skevy/django-tinymce | tinymce/media/tiny_mce/themes/simple/langs/sk.js | JavaScript | mit | 466 |
define("dojox/gfx/utils", ["dojo/_base/kernel","dojo/_base/lang","./_base", "dojo/_base/html","dojo/_base/array", "dojo/_base/window", "dojo/_base/json",
"dojo/_base/Deferred", "dojo/_base/sniff", "require","dojo/_base/config"],
function(kernel, lang, g, html, arr, win, jsonLib, Deferred, has, require, config){
var gu = g.utils = {};
lang.mixin(gu, {
forEach: function(
/*dojox/gfx/shape.Surface|dojox/gfx/shape.Shape*/ object,
/*Function|String|Array*/ f, /*Object?*/ o
){
// summary:
// Takes a shape or a surface and applies a function "f" to in the context of "o"
// (or global, if missing). If "shape" was a surface or a group, it applies the same
// function to all children recursively effectively visiting all shapes of the underlying scene graph.
// object:
// The gfx container to iterate.
// f:
// The function to apply.
// o:
// The scope.
o = o || kernel.global;
f.call(o, object);
if(object instanceof g.Surface || object instanceof g.Group){
arr.forEach(object.children, function(shape){
gu.forEach(shape, f, o);
});
}
},
serialize: function(object){
// summary:
// Takes a shape or a surface and returns a JSON-like object, which describes underlying shapes.
// object: dojox/gfx/shape.Surface|dojox/gfx/shape.Shape
// The container to serialize.
var t = {}, v, isSurface = object instanceof g.Surface;
if(isSurface || object instanceof g.Group){
t.children = arr.map(object.children, gu.serialize);
if(isSurface){
return t.children; // Array
}
}else{
t.shape = object.getShape();
}
if(object.getTransform){
v = object.getTransform();
if(v){ t.transform = v; }
}
if(object.getStroke){
v = object.getStroke();
if(v){ t.stroke = v; }
}
if(object.getFill){
v = object.getFill();
if(v){ t.fill = v; }
}
if(object.getFont){
v = object.getFont();
if(v){ t.font = v; }
}
return t; // Object
},
toJson: function(object, prettyPrint){
// summary:
// Works just like serialize() but returns a JSON string. If prettyPrint is true, the string is pretty-printed to make it more human-readable.
// object: dojox/gfx/shape.Surface|dojox/gfx/shape.Shape
// The container to serialize.
// prettyPrint: Boolean?
// Indicates whether the output string should be formatted.
// returns: String
return jsonLib.toJson(gu.serialize(object), prettyPrint); // String
},
deserialize: function(parent, object){
// summary:
// Takes a surface or a shape and populates it with an object produced by serialize().
// parent: dojox/gfx/shape.Surface|dojox/gfx/shape.Shape
// The destination container for the deserialized shapes.
// object: dojox/gfx/shape.Shape|Array
// The shapes to deserialize.
if(object instanceof Array){
return arr.map(object, lang.hitch(null, gu.deserialize, parent)); // Array
}
var shape = ("shape" in object) ? parent.createShape(object.shape) : parent.createGroup();
if("transform" in object){
shape.setTransform(object.transform);
}
if("stroke" in object){
shape.setStroke(object.stroke);
}
if("fill" in object){
shape.setFill(object.fill);
}
if("font" in object){
shape.setFont(object.font);
}
if("children" in object){
arr.forEach(object.children, lang.hitch(null, gu.deserialize, shape));
}
return shape; // dojox/gfx/shape.Shape
},
fromJson: function(parent, json){
// summary:
// Works just like deserialize() but takes a JSON representation of the object.
// parent: dojox/gfx/shape.Surface|dojox/gfx/shape.Shape
// The destination container for the deserialized shapes.
// json: String
// The shapes to deserialize.
return gu.deserialize(parent, jsonLib.fromJson(json)); // Array|dojox/gfx/shape.Shape
},
toSvg: function(/*dojox/gfx/shape.Surface*/surface){
// summary:
// Function to serialize a GFX surface to SVG text.
// description:
// Function to serialize a GFX surface to SVG text. The value of this output
// is that there are numerous serverside parser libraries that can render
// SVG into images in various formats. This provides a way that GFX objects
// can be captured in a known format and sent serverside for serialization
// into an image.
// surface:
// The GFX surface to serialize.
// returns:
// Deferred object that will be called when SVG serialization is complete.
//Since the init and even surface creation can be async, we need to
//return a deferred that will be called when content has serialized.
var deferred = new Deferred();
if(g.renderer === "svg"){
//If we're already in SVG mode, this is easy and quick.
try{
var svg = gu._cleanSvg(gu._innerXML(surface.rawNode));
deferred.callback(svg);
}catch(e){
deferred.errback(e);
}
}else{
//Okay, now we have to get creative with hidden iframes and the like to
//serialize SVG.
if (!gu._initSvgSerializerDeferred) {
gu._initSvgSerializer();
}
var jsonForm = gu.toJson(surface);
var serializer = function(){
try{
var sDim = surface.getDimensions();
var width = sDim.width;
var height = sDim.height;
//Create an attach point in the iframe for the contents.
var node = gu._gfxSvgProxy.document.createElement("div");
gu._gfxSvgProxy.document.body.appendChild(node);
//Set the node scaling.
win.withDoc(gu._gfxSvgProxy.document, function() {
html.style(node, "width", width);
html.style(node, "height", height);
}, this);
//Create temp surface to render object to and render.
var ts = gu._gfxSvgProxy[dojox._scopeName].gfx.createSurface(node, width, height);
//It's apparently possible that a suface creation is async, so we need to use
//the whenLoaded function. Probably not needed for SVG, but making it common
var draw = function(surface) {
try{
gu._gfxSvgProxy[dojox._scopeName].gfx.utils.fromJson(surface, jsonForm);
//Get contents and remove temp surface.
var svg = gu._cleanSvg(node.innerHTML);
surface.clear();
surface.destroy();
gu._gfxSvgProxy.document.body.removeChild(node);
deferred.callback(svg);
}catch(e){
deferred.errback(e);
}
};
ts.whenLoaded(null,draw);
}catch (ex) {
deferred.errback(ex);
}
};
//See if we can call it directly or pass it to the deferred to be
//called on initialization.
if(gu._initSvgSerializerDeferred.fired > 0){
serializer();
}else{
gu._initSvgSerializerDeferred.addCallback(serializer);
}
}
return deferred; //dojo.Deferred that will be called when serialization finishes.
},
//iFrame document used for handling SVG serialization.
_gfxSvgProxy: null,
//Serializer loaded.
_initSvgSerializerDeferred: null,
_svgSerializerInitialized: function() {
// summary:
// Internal function to call when the serializer init completed.
// tags:
// private
gu._initSvgSerializerDeferred.callback(true);
},
_initSvgSerializer: function(){
// summary:
// Internal function to initialize the hidden iframe where SVG rendering
// will occur.
// tags:
// private
if(!gu._initSvgSerializerDeferred){
gu._initSvgSerializerDeferred = new Deferred();
var f = win.doc.createElement("iframe");
html.style(f, {
display: "none",
position: "absolute",
width: "1em",
height: "1em",
top: "-10000px"
});
var intv;
if(has("ie")){
f.onreadystatechange = function(){
if(f.contentWindow.document.readyState == "complete"){
f.onreadystatechange = function() {};
intv = setInterval(function() {
if(f.contentWindow[kernel.scopeMap["dojo"][1]._scopeName] &&
f.contentWindow[kernel.scopeMap["dojox"][1]._scopeName].gfx &&
f.contentWindow[kernel.scopeMap["dojox"][1]._scopeName].gfx.utils){
clearInterval(intv);
f.contentWindow.parent[kernel.scopeMap["dojox"][1]._scopeName].gfx.utils._gfxSvgProxy = f.contentWindow;
f.contentWindow.parent[kernel.scopeMap["dojox"][1]._scopeName].gfx.utils._svgSerializerInitialized();
}
}, 50);
}
};
}else{
f.onload = function(){
f.onload = function() {};
intv = setInterval(function() {
if(f.contentWindow[kernel.scopeMap["dojo"][1]._scopeName] &&
f.contentWindow[kernel.scopeMap["dojox"][1]._scopeName].gfx &&
f.contentWindow[kernel.scopeMap["dojox"][1]._scopeName].gfx.utils){
clearInterval(intv);
f.contentWindow.parent[kernel.scopeMap["dojox"][1]._scopeName].gfx.utils._gfxSvgProxy = f.contentWindow;
f.contentWindow.parent[kernel.scopeMap["dojox"][1]._scopeName].gfx.utils._svgSerializerInitialized();
}
}, 50);
};
}
//We have to load the GFX SVG proxy frame. Default is to use the one packaged in dojox.
var uri = (config["dojoxGfxSvgProxyFrameUrl"]||require.toUrl("dojox/gfx/resources/gfxSvgProxyFrame.html"));
f.setAttribute("src", uri.toString());
win.body().appendChild(f);
}
},
_innerXML: function(/*Node*/node){
// summary:
// Implementation of MS's innerXML function, borrowed from dojox.xml.parser.
// node:
// The node from which to generate the XML text representation.
// tags:
// private
if(node.innerXML){
return node.innerXML; //String
}else if(node.xml){
return node.xml; //String
}else if(typeof XMLSerializer != "undefined"){
return (new XMLSerializer()).serializeToString(node); //String
}
return null;
},
_cleanSvg: function(svg) {
// summary:
// Internal function that cleans up artifacts in extracted SVG content.
// tags:
// private
if(svg){
//Make sure the namespace is set.
if(svg.indexOf("xmlns=\"http://www.w3.org/2000/svg\"") == -1){
svg = svg.substring(4, svg.length);
svg = "<svg xmlns=\"http://www.w3.org/2000/svg\"" + svg;
}
//Same for xmlns:xlink (missing in Chrome and Safari)
if(svg.indexOf("xmlns:xlink=\"http://www.w3.org/1999/xlink\"") == -1){
svg = svg.substring(4, svg.length);
svg = "<svg xmlns:xlink=\"http://www.w3.org/1999/xlink\"" + svg;
}
//and add namespace to href attribute if not done yet
//(FF 5+ adds xlink:href but not the xmlns def)
if(svg.indexOf("xlink:href") === -1){
svg = svg.replace(/href\s*=/g, "xlink:href=");
}
// in IE, <image are serialized as <img>
svg = svg.replace(/<img\b([^>]*)>/gi,"<image $1 />");
//Do some other cleanup, like stripping out the
//dojoGfx attributes and quoting ids.
svg = svg.replace(/\bdojoGfx\w*\s*=\s*(['"])\w*\1/g, "");
svg = svg.replace(/\b__gfxObject__\s*=\s*(['"])\w*\1/g, "");
svg = svg.replace(/[=]([^"']+?)(\s|>)/g,'="$1"$2');
}
return svg; //Cleaned SVG text.
}
});
return gu;
});
| ISTang/sitemap | web/public/libs/dojo/1.8.3/dojox/gfx/utils.js.uncompressed.js | JavaScript | gpl-2.0 | 11,072 |
describe('Controller: FileController', function() {
var $scope,
File;
beforeEach(module('Bastion.files', 'Bastion.test-mocks'));
beforeEach(inject(function($controller, $rootScope, MockResource) {
$scope = $rootScope.$new();
File = MockResource.$new();
$scope.$stateParams = {
fileId: 1
};
$controller('FileController', {
$scope: $scope,
File: File
});
}));
it('attaches file to scope', function() {
expect($scope.file).toBeDefined();
expect($scope.panel.loading).toBe(false);
});
});
| Katello/katello | engines/bastion_katello/test/files/details/file.controller.test.js | JavaScript | gpl-2.0 | 622 |
module.exports={A:{A:{"2":"J C G E B A VB"},B:{"2":"D Y g H L"},C:{"1":"m n o p q r s x y","2":"0 1 3 4 5 TB z F I J C G E u t RB QB","132":"L M N O P Q R S T U V W X v Z a b c d e f K h i j k l","164":"B A D Y g H"},D:{"1":"0 1 3 4 5 8 h i j k l m n o p q r s x y u t FB BB UB CB DB","2":"F I J C G E B A D Y g H L M N O P Q R S T U V W X v Z a b c d e f","66":"K"},E:{"2":"9 F I J C G E B A EB GB HB IB JB KB LB"},F:{"1":"U V W X v Z a b c d e f K h i j k l m n o p q r s","2":"6 7 E A D H L M N O P Q R S T MB NB OB PB SB w"},G:{"2":"2 9 G A AB WB XB YB ZB aB bB cB dB"},H:{"2":"eB"},I:{"1":"t","2":"2 z F fB gB hB iB jB kB"},J:{"2":"C B"},K:{"1":"K","2":"6 7 B A D w"},L:{"1":"8"},M:{"1":"u"},N:{"2":"B A"},O:{"132":"lB"},P:{"1":"F I"},Q:{"2":"mB"},R:{"1":"nB"}},B:4,C:"Battery Status API"};
| cleverswine/cleverswine-hugo | themes/semantic-cards/semantic/node_modules/caniuse-lite/data/features/battery-status.js | JavaScript | gpl-3.0 | 796 |
/*
* SERVER-6127 : $project uasserts if an expected nested field has a non object parent in a document
*
* This test validates the SERVER-6127 ticket. Return undefined when retrieving a field along a
* path, when the subpath does not exist (this is what happens when a field does not exist and
* there is no path). Previous it would uassert causing the aggregation to end.
*/
/*
* 1) Clear and create testing db
* 2) Run an aggregation that simply projects a two fields, one with a sub path one without
* 3) Assert that the result is what we expected
*/
// Clear db
db.s6127.drop();
// Populate db
db.s6127.save({a:1});
db.s6127.save({foo:2});
db.s6127.save({foo:{bar:3}});
// Aggregate checking the field foo and the path foo.bar
var s6127 = db.s6127.aggregate(
{ $project : {
_id : 0,
'foo.bar' : 1,
field : "$foo",
path : "$foo.bar"
}}
);
/*
* The first document should contain nothing as neither field exists, the second document should
* contain only field as it has a value in foo, but foo does not have a field bar so it cannot walk
* that path, the third document should have both the field and path as foo is an object which has
* a field bar
*/
var s6127result = [
{
},
{
field : 2
},
{
foo : {
bar : 3
},
field : {
bar : 3
},
path : 3
}
];
// Assert
assert.eq(s6127.result, s6127result, 's6127 failed');
| wvdd007/robomongo | src/third-party/mongodb/jstests/aggregation/bugs/server6127.js | JavaScript | gpl-3.0 | 1,497 |
/* @preserve
* Leaflet 1.6.0+Detached: 0c81bdf904d864fd12a286e3d1979f47aba17991.0c81bdf, a JS library for interactive maps. http://leafletjs.com
* (c) 2010-2019 Vladimir Agafonkin, (c) 2010-2011 CloudMade
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(factory((global.L = {})));
}(this, (function (exports) { 'use strict';
var version = "1.6.0+HEAD.0c81bdf";
/*
* @namespace Util
*
* Various utility functions, used by Leaflet internally.
*/
var freeze = Object.freeze;
Object.freeze = function (obj) { return obj; };
// @function extend(dest: Object, src?: Object): Object
// Merges the properties of the `src` object (or multiple objects) into `dest` object and returns the latter. Has an `L.extend` shortcut.
function extend(dest) {
var i, j, len, src;
for (j = 1, len = arguments.length; j < len; j++) {
src = arguments[j];
for (i in src) {
dest[i] = src[i];
}
}
return dest;
}
// @function create(proto: Object, properties?: Object): Object
// Compatibility polyfill for [Object.create](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/create)
var create = Object.create || (function () {
function F() {}
return function (proto) {
F.prototype = proto;
return new F();
};
})();
// @function bind(fn: Function, …): Function
// Returns a new function bound to the arguments passed, like [Function.prototype.bind](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function/bind).
// Has a `L.bind()` shortcut.
function bind(fn, obj) {
var slice = Array.prototype.slice;
if (fn.bind) {
return fn.bind.apply(fn, slice.call(arguments, 1));
}
var args = slice.call(arguments, 2);
return function () {
return fn.apply(obj, args.length ? args.concat(slice.call(arguments)) : arguments);
};
}
// @property lastId: Number
// Last unique ID used by [`stamp()`](#util-stamp)
var lastId = 0;
// @function stamp(obj: Object): Number
// Returns the unique ID of an object, assigning it one if it doesn't have it.
function stamp(obj) {
/*eslint-disable */
obj._leaflet_id = obj._leaflet_id || ++lastId;
return obj._leaflet_id;
/* eslint-enable */
}
// @function throttle(fn: Function, time: Number, context: Object): Function
// Returns a function which executes function `fn` with the given scope `context`
// (so that the `this` keyword refers to `context` inside `fn`'s code). The function
// `fn` will be called no more than one time per given amount of `time`. The arguments
// received by the bound function will be any arguments passed when binding the
// function, followed by any arguments passed when invoking the bound function.
// Has an `L.throttle` shortcut.
function throttle(fn, time, context) {
var lock, args, wrapperFn, later;
later = function () {
// reset lock and call if queued
lock = false;
if (args) {
wrapperFn.apply(context, args);
args = false;
}
};
wrapperFn = function () {
if (lock) {
// called too soon, queue to call later
args = arguments;
} else {
// call and lock until later
fn.apply(context, arguments);
setTimeout(later, time);
lock = true;
}
};
return wrapperFn;
}
// @function wrapNum(num: Number, range: Number[], includeMax?: Boolean): Number
// Returns the number `num` modulo `range` in such a way so it lies within
// `range[0]` and `range[1]`. The returned value will be always smaller than
// `range[1]` unless `includeMax` is set to `true`.
function wrapNum(x, range, includeMax) {
var max = range[1],
min = range[0],
d = max - min;
return x === max && includeMax ? x : ((x - min) % d + d) % d + min;
}
// @function falseFn(): Function
// Returns a function which always returns `false`.
function falseFn() { return false; }
// @function formatNum(num: Number, digits?: Number): Number
// Returns the number `num` rounded to `digits` decimals, or to 6 decimals by default.
function formatNum(num, digits) {
var pow = Math.pow(10, (digits === undefined ? 6 : digits));
return Math.round(num * pow) / pow;
}
// @function trim(str: String): String
// Compatibility polyfill for [String.prototype.trim](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/Trim)
function trim(str) {
return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, '');
}
// @function splitWords(str: String): String[]
// Trims and splits the string on whitespace and returns the array of parts.
function splitWords(str) {
return trim(str).split(/\s+/);
}
// @function setOptions(obj: Object, options: Object): Object
// Merges the given properties to the `options` of the `obj` object, returning the resulting options. See `Class options`. Has an `L.setOptions` shortcut.
function setOptions(obj, options) {
if (!obj.hasOwnProperty('options')) {
obj.options = obj.options ? create(obj.options) : {};
}
for (var i in options) {
obj.options[i] = options[i];
}
return obj.options;
}
// @function getParamString(obj: Object, existingUrl?: String, uppercase?: Boolean): String
// Converts an object into a parameter URL string, e.g. `{a: "foo", b: "bar"}`
// translates to `'?a=foo&b=bar'`. If `existingUrl` is set, the parameters will
// be appended at the end. If `uppercase` is `true`, the parameter names will
// be uppercased (e.g. `'?A=foo&B=bar'`)
function getParamString(obj, existingUrl, uppercase) {
var params = [];
for (var i in obj) {
params.push(encodeURIComponent(uppercase ? i.toUpperCase() : i) + '=' + encodeURIComponent(obj[i]));
}
return ((!existingUrl || existingUrl.indexOf('?') === -1) ? '?' : '&') + params.join('&');
}
var templateRe = /\{ *([\w_-]+) *\}/g;
// @function template(str: String, data: Object): String
// Simple templating facility, accepts a template string of the form `'Hello {a}, {b}'`
// and a data object like `{a: 'foo', b: 'bar'}`, returns evaluated string
// `('Hello foo, bar')`. You can also specify functions instead of strings for
// data values — they will be evaluated passing `data` as an argument.
function template(str, data) {
return str.replace(templateRe, function (str, key) {
var value = data[key];
if (value === undefined) {
throw new Error('No value provided for variable ' + str);
} else if (typeof value === 'function') {
value = value(data);
}
return value;
});
}
// @function isArray(obj): Boolean
// Compatibility polyfill for [Array.isArray](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray)
var isArray = Array.isArray || function (obj) {
return (Object.prototype.toString.call(obj) === '[object Array]');
};
// @function indexOf(array: Array, el: Object): Number
// Compatibility polyfill for [Array.prototype.indexOf](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf)
function indexOf(array, el) {
for (var i = 0; i < array.length; i++) {
if (array[i] === el) { return i; }
}
return -1;
}
// @property emptyImageUrl: String
// Data URI string containing a base64-encoded empty GIF image.
// Used as a hack to free memory from unused images on WebKit-powered
// mobile devices (by setting image `src` to this string).
var emptyImageUrl = 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=';
// inspired by http://paulirish.com/2011/requestanimationframe-for-smart-animating/
function getPrefixed(name) {
return window['webkit' + name] || window['moz' + name] || window['ms' + name];
}
var lastTime = 0;
// fallback for IE 7-8
function timeoutDefer(fn) {
var time = +new Date(),
timeToCall = Math.max(0, 16 - (time - lastTime));
lastTime = time + timeToCall;
return window.setTimeout(fn, timeToCall);
}
var requestFn = window.requestAnimationFrame || getPrefixed('RequestAnimationFrame') || timeoutDefer;
var cancelFn = window.cancelAnimationFrame || getPrefixed('CancelAnimationFrame') ||
getPrefixed('CancelRequestAnimationFrame') || function (id) { window.clearTimeout(id); };
// @function requestAnimFrame(fn: Function, context?: Object, immediate?: Boolean): Number
// Schedules `fn` to be executed when the browser repaints. `fn` is bound to
// `context` if given. When `immediate` is set, `fn` is called immediately if
// the browser doesn't have native support for
// [`window.requestAnimationFrame`](https://developer.mozilla.org/docs/Web/API/window/requestAnimationFrame),
// otherwise it's delayed. Returns a request ID that can be used to cancel the request.
function requestAnimFrame(fn, context, immediate) {
if (immediate && requestFn === timeoutDefer) {
fn.call(context);
} else {
return requestFn.call(window, bind(fn, context));
}
}
// @function cancelAnimFrame(id: Number): undefined
// Cancels a previous `requestAnimFrame`. See also [window.cancelAnimationFrame](https://developer.mozilla.org/docs/Web/API/window/cancelAnimationFrame).
function cancelAnimFrame(id) {
if (id) {
cancelFn.call(window, id);
}
}
var Util = (Object.freeze || Object)({
freeze: freeze,
extend: extend,
create: create,
bind: bind,
lastId: lastId,
stamp: stamp,
throttle: throttle,
wrapNum: wrapNum,
falseFn: falseFn,
formatNum: formatNum,
trim: trim,
splitWords: splitWords,
setOptions: setOptions,
getParamString: getParamString,
template: template,
isArray: isArray,
indexOf: indexOf,
emptyImageUrl: emptyImageUrl,
requestFn: requestFn,
cancelFn: cancelFn,
requestAnimFrame: requestAnimFrame,
cancelAnimFrame: cancelAnimFrame
});
// @class Class
// @aka L.Class
// @section
// @uninheritable
// Thanks to John Resig and Dean Edwards for inspiration!
function Class() {}
Class.extend = function (props) {
// @function extend(props: Object): Function
// [Extends the current class](#class-inheritance) given the properties to be included.
// Returns a Javascript function that is a class constructor (to be called with `new`).
var NewClass = function () {
// call the constructor
if (this.initialize) {
this.initialize.apply(this, arguments);
}
// call all constructor hooks
this.callInitHooks();
};
var parentProto = NewClass.__super__ = this.prototype;
var proto = create(parentProto);
proto.constructor = NewClass;
NewClass.prototype = proto;
// inherit parent's statics
for (var i in this) {
if (this.hasOwnProperty(i) && i !== 'prototype' && i !== '__super__') {
NewClass[i] = this[i];
}
}
// mix static properties into the class
if (props.statics) {
extend(NewClass, props.statics);
delete props.statics;
}
// mix includes into the prototype
if (props.includes) {
checkDeprecatedMixinEvents(props.includes);
extend.apply(null, [proto].concat(props.includes));
delete props.includes;
}
// merge options
if (proto.options) {
props.options = extend(create(proto.options), props.options);
}
// mix given properties into the prototype
extend(proto, props);
proto._initHooks = [];
// add method for calling all hooks
proto.callInitHooks = function () {
if (this._initHooksCalled) { return; }
if (parentProto.callInitHooks) {
parentProto.callInitHooks.call(this);
}
this._initHooksCalled = true;
for (var i = 0, len = proto._initHooks.length; i < len; i++) {
proto._initHooks[i].call(this);
}
};
return NewClass;
};
// @function include(properties: Object): this
// [Includes a mixin](#class-includes) into the current class.
Class.include = function (props) {
extend(this.prototype, props);
return this;
};
// @function mergeOptions(options: Object): this
// [Merges `options`](#class-options) into the defaults of the class.
Class.mergeOptions = function (options) {
extend(this.prototype.options, options);
return this;
};
// @function addInitHook(fn: Function): this
// Adds a [constructor hook](#class-constructor-hooks) to the class.
Class.addInitHook = function (fn) { // (Function) || (String, args...)
var args = Array.prototype.slice.call(arguments, 1);
var init = typeof fn === 'function' ? fn : function () {
this[fn].apply(this, args);
};
this.prototype._initHooks = this.prototype._initHooks || [];
this.prototype._initHooks.push(init);
return this;
};
function checkDeprecatedMixinEvents(includes) {
if (typeof L === 'undefined' || !L || !L.Mixin) { return; }
includes = isArray(includes) ? includes : [includes];
for (var i = 0; i < includes.length; i++) {
if (includes[i] === L.Mixin.Events) {
console.warn('Deprecated include of L.Mixin.Events: ' +
'this property will be removed in future releases, ' +
'please inherit from L.Evented instead.', new Error().stack);
}
}
}
/*
* @class Evented
* @aka L.Evented
* @inherits Class
*
* A set of methods shared between event-powered classes (like `Map` and `Marker`). Generally, events allow you to execute some function when something happens with an object (e.g. the user clicks on the map, causing the map to fire `'click'` event).
*
* @example
*
* ```js
* map.on('click', function(e) {
* alert(e.latlng);
* } );
* ```
*
* Leaflet deals with event listeners by reference, so if you want to add a listener and then remove it, define it as a function:
*
* ```js
* function onClick(e) { ... }
*
* map.on('click', onClick);
* map.off('click', onClick);
* ```
*/
var Events = {
/* @method on(type: String, fn: Function, context?: Object): this
* Adds a listener function (`fn`) to a particular event type of the object. You can optionally specify the context of the listener (object the this keyword will point to). You can also pass several space-separated types (e.g. `'click dblclick'`).
*
* @alternative
* @method on(eventMap: Object): this
* Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`
*/
on: function (types, fn, context) {
// types can be a map of types/handlers
if (typeof types === 'object') {
for (var type in types) {
// we don't process space-separated events here for performance;
// it's a hot path since Layer uses the on(obj) syntax
this._on(type, types[type], fn);
}
} else {
// types can be a string of space-separated words
types = splitWords(types);
for (var i = 0, len = types.length; i < len; i++) {
this._on(types[i], fn, context);
}
}
return this;
},
/* @method off(type: String, fn?: Function, context?: Object): this
* Removes a previously added listener function. If no function is specified, it will remove all the listeners of that particular event from the object. Note that if you passed a custom context to `on`, you must pass the same context to `off` in order to remove the listener.
*
* @alternative
* @method off(eventMap: Object): this
* Removes a set of type/listener pairs.
*
* @alternative
* @method off: this
* Removes all listeners to all events on the object. This includes implicitly attached events.
*/
off: function (types, fn, context) {
if (!types) {
// clear all listeners if called without arguments
delete this._events;
} else if (typeof types === 'object') {
for (var type in types) {
this._off(type, types[type], fn);
}
} else {
types = splitWords(types);
for (var i = 0, len = types.length; i < len; i++) {
this._off(types[i], fn, context);
}
}
return this;
},
// attach listener (without syntactic sugar now)
_on: function (type, fn, context) {
this._events = this._events || {};
/* get/init listeners for type */
var typeListeners = this._events[type];
if (!typeListeners) {
typeListeners = [];
this._events[type] = typeListeners;
}
if (context === this) {
// Less memory footprint.
context = undefined;
}
var newListener = {fn: fn, ctx: context},
listeners = typeListeners;
// check if fn already there
for (var i = 0, len = listeners.length; i < len; i++) {
if (listeners[i].fn === fn && listeners[i].ctx === context) {
return;
}
}
listeners.push(newListener);
},
_off: function (type, fn, context) {
var listeners,
i,
len;
if (!this._events) { return; }
listeners = this._events[type];
if (!listeners) {
return;
}
if (!fn) {
// Set all removed listeners to noop so they are not called if remove happens in fire
for (i = 0, len = listeners.length; i < len; i++) {
listeners[i].fn = falseFn;
}
// clear all listeners for a type if function isn't specified
delete this._events[type];
return;
}
if (context === this) {
context = undefined;
}
if (listeners) {
// find fn and remove it
for (i = 0, len = listeners.length; i < len; i++) {
var l = listeners[i];
if (l.ctx !== context) { continue; }
if (l.fn === fn) {
// set the removed listener to noop so that's not called if remove happens in fire
l.fn = falseFn;
if (this._firingCount) {
/* copy array in case events are being fired */
this._events[type] = listeners = listeners.slice();
}
listeners.splice(i, 1);
return;
}
}
}
},
// @method fire(type: String, data?: Object, propagate?: Boolean): this
// Fires an event of the specified type. You can optionally provide an data
// object — the first argument of the listener function will contain its
// properties. The event can optionally be propagated to event parents.
fire: function (type, data, propagate) {
if (!this.listens(type, propagate)) { return this; }
var event = extend({}, data, {
type: type,
target: this,
sourceTarget: data && data.sourceTarget || this
});
if (this._events) {
var listeners = this._events[type];
if (listeners) {
this._firingCount = (this._firingCount + 1) || 1;
for (var i = 0, len = listeners.length; i < len; i++) {
var l = listeners[i];
l.fn.call(l.ctx || this, event);
}
this._firingCount--;
}
}
if (propagate) {
// propagate the event to parents (set with addEventParent)
this._propagateEvent(event);
}
return this;
},
// @method listens(type: String): Boolean
// Returns `true` if a particular event type has any listeners attached to it.
listens: function (type, propagate) {
var listeners = this._events && this._events[type];
if (listeners && listeners.length) { return true; }
if (propagate) {
// also check parents for listeners if event propagates
for (var id in this._eventParents) {
if (this._eventParents[id].listens(type, propagate)) { return true; }
}
}
return false;
},
// @method once(…): this
// Behaves as [`on(…)`](#evented-on), except the listener will only get fired once and then removed.
once: function (types, fn, context) {
if (typeof types === 'object') {
for (var type in types) {
this.once(type, types[type], fn);
}
return this;
}
var handler = bind(function () {
this
.off(types, fn, context)
.off(types, handler, context);
}, this);
// add a listener that's executed once and removed after that
return this
.on(types, fn, context)
.on(types, handler, context);
},
// @method addEventParent(obj: Evented): this
// Adds an event parent - an `Evented` that will receive propagated events
addEventParent: function (obj) {
this._eventParents = this._eventParents || {};
this._eventParents[stamp(obj)] = obj;
return this;
},
// @method removeEventParent(obj: Evented): this
// Removes an event parent, so it will stop receiving propagated events
removeEventParent: function (obj) {
if (this._eventParents) {
delete this._eventParents[stamp(obj)];
}
return this;
},
_propagateEvent: function (e) {
for (var id in this._eventParents) {
this._eventParents[id].fire(e.type, extend({
layer: e.target,
propagatedFrom: e.target
}, e), true);
}
}
};
// aliases; we should ditch those eventually
// @method addEventListener(…): this
// Alias to [`on(…)`](#evented-on)
Events.addEventListener = Events.on;
// @method removeEventListener(…): this
// Alias to [`off(…)`](#evented-off)
// @method clearAllEventListeners(…): this
// Alias to [`off()`](#evented-off)
Events.removeEventListener = Events.clearAllEventListeners = Events.off;
// @method addOneTimeEventListener(…): this
// Alias to [`once(…)`](#evented-once)
Events.addOneTimeEventListener = Events.once;
// @method fireEvent(…): this
// Alias to [`fire(…)`](#evented-fire)
Events.fireEvent = Events.fire;
// @method hasEventListeners(…): Boolean
// Alias to [`listens(…)`](#evented-listens)
Events.hasEventListeners = Events.listens;
var Evented = Class.extend(Events);
/*
* @class Point
* @aka L.Point
*
* Represents a point with `x` and `y` coordinates in pixels.
*
* @example
*
* ```js
* var point = L.point(200, 300);
* ```
*
* All Leaflet methods and options that accept `Point` objects also accept them in a simple Array form (unless noted otherwise), so these lines are equivalent:
*
* ```js
* map.panBy([200, 300]);
* map.panBy(L.point(200, 300));
* ```
*
* Note that `Point` does not inherit from Leafet's `Class` object,
* which means new classes can't inherit from it, and new methods
* can't be added to it with the `include` function.
*/
function Point(x, y, round) {
// @property x: Number; The `x` coordinate of the point
this.x = (round ? Math.round(x) : x);
// @property y: Number; The `y` coordinate of the point
this.y = (round ? Math.round(y) : y);
}
var trunc = Math.trunc || function (v) {
return v > 0 ? Math.floor(v) : Math.ceil(v);
};
Point.prototype = {
// @method clone(): Point
// Returns a copy of the current point.
clone: function () {
return new Point(this.x, this.y);
},
// @method add(otherPoint: Point): Point
// Returns the result of addition of the current and the given points.
add: function (point) {
// non-destructive, returns a new point
return this.clone()._add(toPoint(point));
},
_add: function (point) {
// destructive, used directly for performance in situations where it's safe to modify existing point
this.x += point.x;
this.y += point.y;
return this;
},
// @method subtract(otherPoint: Point): Point
// Returns the result of subtraction of the given point from the current.
subtract: function (point) {
return this.clone()._subtract(toPoint(point));
},
_subtract: function (point) {
this.x -= point.x;
this.y -= point.y;
return this;
},
// @method divideBy(num: Number): Point
// Returns the result of division of the current point by the given number.
divideBy: function (num) {
return this.clone()._divideBy(num);
},
_divideBy: function (num) {
this.x /= num;
this.y /= num;
return this;
},
// @method multiplyBy(num: Number): Point
// Returns the result of multiplication of the current point by the given number.
multiplyBy: function (num) {
return this.clone()._multiplyBy(num);
},
_multiplyBy: function (num) {
this.x *= num;
this.y *= num;
return this;
},
// @method scaleBy(scale: Point): Point
// Multiply each coordinate of the current point by each coordinate of
// `scale`. In linear algebra terms, multiply the point by the
// [scaling matrix](https://en.wikipedia.org/wiki/Scaling_%28geometry%29#Matrix_representation)
// defined by `scale`.
scaleBy: function (point) {
return new Point(this.x * point.x, this.y * point.y);
},
// @method unscaleBy(scale: Point): Point
// Inverse of `scaleBy`. Divide each coordinate of the current point by
// each coordinate of `scale`.
unscaleBy: function (point) {
return new Point(this.x / point.x, this.y / point.y);
},
// @method round(): Point
// Returns a copy of the current point with rounded coordinates.
round: function () {
return this.clone()._round();
},
_round: function () {
this.x = Math.round(this.x);
this.y = Math.round(this.y);
return this;
},
// @method floor(): Point
// Returns a copy of the current point with floored coordinates (rounded down).
floor: function () {
return this.clone()._floor();
},
_floor: function () {
this.x = Math.floor(this.x);
this.y = Math.floor(this.y);
return this;
},
// @method ceil(): Point
// Returns a copy of the current point with ceiled coordinates (rounded up).
ceil: function () {
return this.clone()._ceil();
},
_ceil: function () {
this.x = Math.ceil(this.x);
this.y = Math.ceil(this.y);
return this;
},
// @method trunc(): Point
// Returns a copy of the current point with truncated coordinates (rounded towards zero).
trunc: function () {
return this.clone()._trunc();
},
_trunc: function () {
this.x = trunc(this.x);
this.y = trunc(this.y);
return this;
},
// @method distanceTo(otherPoint: Point): Number
// Returns the cartesian distance between the current and the given points.
distanceTo: function (point) {
point = toPoint(point);
var x = point.x - this.x,
y = point.y - this.y;
return Math.sqrt(x * x + y * y);
},
// @method equals(otherPoint: Point): Boolean
// Returns `true` if the given point has the same coordinates.
equals: function (point) {
point = toPoint(point);
return point.x === this.x &&
point.y === this.y;
},
// @method contains(otherPoint: Point): Boolean
// Returns `true` if both coordinates of the given point are less than the corresponding current point coordinates (in absolute values).
contains: function (point) {
point = toPoint(point);
return Math.abs(point.x) <= Math.abs(this.x) &&
Math.abs(point.y) <= Math.abs(this.y);
},
// @method toString(): String
// Returns a string representation of the point for debugging purposes.
toString: function () {
return 'Point(' +
formatNum(this.x) + ', ' +
formatNum(this.y) + ')';
}
};
// @factory L.point(x: Number, y: Number, round?: Boolean)
// Creates a Point object with the given `x` and `y` coordinates. If optional `round` is set to true, rounds the `x` and `y` values.
// @alternative
// @factory L.point(coords: Number[])
// Expects an array of the form `[x, y]` instead.
// @alternative
// @factory L.point(coords: Object)
// Expects a plain object of the form `{x: Number, y: Number}` instead.
function toPoint(x, y, round) {
if (x instanceof Point) {
return x;
}
if (isArray(x)) {
return new Point(x[0], x[1]);
}
if (x === undefined || x === null) {
return x;
}
if (typeof x === 'object' && 'x' in x && 'y' in x) {
return new Point(x.x, x.y);
}
return new Point(x, y, round);
}
/*
* @class Bounds
* @aka L.Bounds
*
* Represents a rectangular area in pixel coordinates.
*
* @example
*
* ```js
* var p1 = L.point(10, 10),
* p2 = L.point(40, 60),
* bounds = L.bounds(p1, p2);
* ```
*
* All Leaflet methods that accept `Bounds` objects also accept them in a simple Array form (unless noted otherwise), so the bounds example above can be passed like this:
*
* ```js
* otherBounds.intersects([[10, 10], [40, 60]]);
* ```
*
* Note that `Bounds` does not inherit from Leafet's `Class` object,
* which means new classes can't inherit from it, and new methods
* can't be added to it with the `include` function.
*/
function Bounds(a, b) {
if (!a) { return; }
var points = b ? [a, b] : a;
for (var i = 0, len = points.length; i < len; i++) {
this.extend(points[i]);
}
}
Bounds.prototype = {
// @method extend(point: Point): this
// Extends the bounds to contain the given point.
extend: function (point) { // (Point)
point = toPoint(point);
// @property min: Point
// The top left corner of the rectangle.
// @property max: Point
// The bottom right corner of the rectangle.
if (!this.min && !this.max) {
this.min = point.clone();
this.max = point.clone();
} else {
this.min.x = Math.min(point.x, this.min.x);
this.max.x = Math.max(point.x, this.max.x);
this.min.y = Math.min(point.y, this.min.y);
this.max.y = Math.max(point.y, this.max.y);
}
return this;
},
// @method getCenter(round?: Boolean): Point
// Returns the center point of the bounds.
getCenter: function (round) {
return new Point(
(this.min.x + this.max.x) / 2,
(this.min.y + this.max.y) / 2, round);
},
// @method getBottomLeft(): Point
// Returns the bottom-left point of the bounds.
getBottomLeft: function () {
return new Point(this.min.x, this.max.y);
},
// @method getTopRight(): Point
// Returns the top-right point of the bounds.
getTopRight: function () { // -> Point
return new Point(this.max.x, this.min.y);
},
// @method getTopLeft(): Point
// Returns the top-left point of the bounds (i.e. [`this.min`](#bounds-min)).
getTopLeft: function () {
return this.min; // left, top
},
// @method getBottomRight(): Point
// Returns the bottom-right point of the bounds (i.e. [`this.max`](#bounds-max)).
getBottomRight: function () {
return this.max; // right, bottom
},
// @method getSize(): Point
// Returns the size of the given bounds
getSize: function () {
return this.max.subtract(this.min);
},
// @method contains(otherBounds: Bounds): Boolean
// Returns `true` if the rectangle contains the given one.
// @alternative
// @method contains(point: Point): Boolean
// Returns `true` if the rectangle contains the given point.
contains: function (obj) {
var min, max;
if (typeof obj[0] === 'number' || obj instanceof Point) {
obj = toPoint(obj);
} else {
obj = toBounds(obj);
}
if (obj instanceof Bounds) {
min = obj.min;
max = obj.max;
} else {
min = max = obj;
}
return (min.x >= this.min.x) &&
(max.x <= this.max.x) &&
(min.y >= this.min.y) &&
(max.y <= this.max.y);
},
// @method intersects(otherBounds: Bounds): Boolean
// Returns `true` if the rectangle intersects the given bounds. Two bounds
// intersect if they have at least one point in common.
intersects: function (bounds) { // (Bounds) -> Boolean
bounds = toBounds(bounds);
var min = this.min,
max = this.max,
min2 = bounds.min,
max2 = bounds.max,
xIntersects = (max2.x >= min.x) && (min2.x <= max.x),
yIntersects = (max2.y >= min.y) && (min2.y <= max.y);
return xIntersects && yIntersects;
},
// @method overlaps(otherBounds: Bounds): Boolean
// Returns `true` if the rectangle overlaps the given bounds. Two bounds
// overlap if their intersection is an area.
overlaps: function (bounds) { // (Bounds) -> Boolean
bounds = toBounds(bounds);
var min = this.min,
max = this.max,
min2 = bounds.min,
max2 = bounds.max,
xOverlaps = (max2.x > min.x) && (min2.x < max.x),
yOverlaps = (max2.y > min.y) && (min2.y < max.y);
return xOverlaps && yOverlaps;
},
isValid: function () {
return !!(this.min && this.max);
}
};
// @factory L.bounds(corner1: Point, corner2: Point)
// Creates a Bounds object from two corners coordinate pairs.
// @alternative
// @factory L.bounds(points: Point[])
// Creates a Bounds object from the given array of points.
function toBounds(a, b) {
if (!a || a instanceof Bounds) {
return a;
}
return new Bounds(a, b);
}
/*
* @class LatLngBounds
* @aka L.LatLngBounds
*
* Represents a rectangular geographical area on a map.
*
* @example
*
* ```js
* var corner1 = L.latLng(40.712, -74.227),
* corner2 = L.latLng(40.774, -74.125),
* bounds = L.latLngBounds(corner1, corner2);
* ```
*
* All Leaflet methods that accept LatLngBounds objects also accept them in a simple Array form (unless noted otherwise), so the bounds example above can be passed like this:
*
* ```js
* map.fitBounds([
* [40.712, -74.227],
* [40.774, -74.125]
* ]);
* ```
*
* Caution: if the area crosses the antimeridian (often confused with the International Date Line), you must specify corners _outside_ the [-180, 180] degrees longitude range.
*
* Note that `LatLngBounds` does not inherit from Leafet's `Class` object,
* which means new classes can't inherit from it, and new methods
* can't be added to it with the `include` function.
*/
function LatLngBounds(corner1, corner2) { // (LatLng, LatLng) or (LatLng[])
if (!corner1) { return; }
var latlngs = corner2 ? [corner1, corner2] : corner1;
for (var i = 0, len = latlngs.length; i < len; i++) {
this.extend(latlngs[i]);
}
}
LatLngBounds.prototype = {
// @method extend(latlng: LatLng): this
// Extend the bounds to contain the given point
// @alternative
// @method extend(otherBounds: LatLngBounds): this
// Extend the bounds to contain the given bounds
extend: function (obj) {
var sw = this._southWest,
ne = this._northEast,
sw2, ne2;
if (obj instanceof LatLng) {
sw2 = obj;
ne2 = obj;
} else if (obj instanceof LatLngBounds) {
sw2 = obj._southWest;
ne2 = obj._northEast;
if (!sw2 || !ne2) { return this; }
} else {
return obj ? this.extend(toLatLng(obj) || toLatLngBounds(obj)) : this;
}
if (!sw && !ne) {
this._southWest = new LatLng(sw2.lat, sw2.lng);
this._northEast = new LatLng(ne2.lat, ne2.lng);
} else {
sw.lat = Math.min(sw2.lat, sw.lat);
sw.lng = Math.min(sw2.lng, sw.lng);
ne.lat = Math.max(ne2.lat, ne.lat);
ne.lng = Math.max(ne2.lng, ne.lng);
}
return this;
},
// @method pad(bufferRatio: Number): LatLngBounds
// Returns bounds created by extending or retracting the current bounds by a given ratio in each direction.
// For example, a ratio of 0.5 extends the bounds by 50% in each direction.
// Negative values will retract the bounds.
pad: function (bufferRatio) {
var sw = this._southWest,
ne = this._northEast,
heightBuffer = Math.abs(sw.lat - ne.lat) * bufferRatio,
widthBuffer = Math.abs(sw.lng - ne.lng) * bufferRatio;
return new LatLngBounds(
new LatLng(sw.lat - heightBuffer, sw.lng - widthBuffer),
new LatLng(ne.lat + heightBuffer, ne.lng + widthBuffer));
},
// @method getCenter(): LatLng
// Returns the center point of the bounds.
getCenter: function () {
return new LatLng(
(this._southWest.lat + this._northEast.lat) / 2,
(this._southWest.lng + this._northEast.lng) / 2);
},
// @method getSouthWest(): LatLng
// Returns the south-west point of the bounds.
getSouthWest: function () {
return this._southWest;
},
// @method getNorthEast(): LatLng
// Returns the north-east point of the bounds.
getNorthEast: function () {
return this._northEast;
},
// @method getNorthWest(): LatLng
// Returns the north-west point of the bounds.
getNorthWest: function () {
return new LatLng(this.getNorth(), this.getWest());
},
// @method getSouthEast(): LatLng
// Returns the south-east point of the bounds.
getSouthEast: function () {
return new LatLng(this.getSouth(), this.getEast());
},
// @method getWest(): Number
// Returns the west longitude of the bounds
getWest: function () {
return this._southWest.lng;
},
// @method getSouth(): Number
// Returns the south latitude of the bounds
getSouth: function () {
return this._southWest.lat;
},
// @method getEast(): Number
// Returns the east longitude of the bounds
getEast: function () {
return this._northEast.lng;
},
// @method getNorth(): Number
// Returns the north latitude of the bounds
getNorth: function () {
return this._northEast.lat;
},
// @method contains(otherBounds: LatLngBounds): Boolean
// Returns `true` if the rectangle contains the given one.
// @alternative
// @method contains (latlng: LatLng): Boolean
// Returns `true` if the rectangle contains the given point.
contains: function (obj) { // (LatLngBounds) or (LatLng) -> Boolean
if (typeof obj[0] === 'number' || obj instanceof LatLng || 'lat' in obj) {
obj = toLatLng(obj);
} else {
obj = toLatLngBounds(obj);
}
var sw = this._southWest,
ne = this._northEast,
sw2, ne2;
if (obj instanceof LatLngBounds) {
sw2 = obj.getSouthWest();
ne2 = obj.getNorthEast();
} else {
sw2 = ne2 = obj;
}
return (sw2.lat >= sw.lat) && (ne2.lat <= ne.lat) &&
(sw2.lng >= sw.lng) && (ne2.lng <= ne.lng);
},
// @method intersects(otherBounds: LatLngBounds): Boolean
// Returns `true` if the rectangle intersects the given bounds. Two bounds intersect if they have at least one point in common.
intersects: function (bounds) {
bounds = toLatLngBounds(bounds);
var sw = this._southWest,
ne = this._northEast,
sw2 = bounds.getSouthWest(),
ne2 = bounds.getNorthEast(),
latIntersects = (ne2.lat >= sw.lat) && (sw2.lat <= ne.lat),
lngIntersects = (ne2.lng >= sw.lng) && (sw2.lng <= ne.lng);
return latIntersects && lngIntersects;
},
// @method overlaps(otherBounds: Bounds): Boolean
// Returns `true` if the rectangle overlaps the given bounds. Two bounds overlap if their intersection is an area.
overlaps: function (bounds) {
bounds = toLatLngBounds(bounds);
var sw = this._southWest,
ne = this._northEast,
sw2 = bounds.getSouthWest(),
ne2 = bounds.getNorthEast(),
latOverlaps = (ne2.lat > sw.lat) && (sw2.lat < ne.lat),
lngOverlaps = (ne2.lng > sw.lng) && (sw2.lng < ne.lng);
return latOverlaps && lngOverlaps;
},
// @method toBBoxString(): String
// Returns a string with bounding box coordinates in a 'southwest_lng,southwest_lat,northeast_lng,northeast_lat' format. Useful for sending requests to web services that return geo data.
toBBoxString: function () {
return [this.getWest(), this.getSouth(), this.getEast(), this.getNorth()].join(',');
},
// @method equals(otherBounds: LatLngBounds, maxMargin?: Number): Boolean
// Returns `true` if the rectangle is equivalent (within a small margin of error) to the given bounds. The margin of error can be overridden by setting `maxMargin` to a small number.
equals: function (bounds, maxMargin) {
if (!bounds) { return false; }
bounds = toLatLngBounds(bounds);
return this._southWest.equals(bounds.getSouthWest(), maxMargin) &&
this._northEast.equals(bounds.getNorthEast(), maxMargin);
},
// @method isValid(): Boolean
// Returns `true` if the bounds are properly initialized.
isValid: function () {
return !!(this._southWest && this._northEast);
}
};
// TODO International date line?
// @factory L.latLngBounds(corner1: LatLng, corner2: LatLng)
// Creates a `LatLngBounds` object by defining two diagonally opposite corners of the rectangle.
// @alternative
// @factory L.latLngBounds(latlngs: LatLng[])
// Creates a `LatLngBounds` object defined by the geographical points it contains. Very useful for zooming the map to fit a particular set of locations with [`fitBounds`](#map-fitbounds).
function toLatLngBounds(a, b) {
if (a instanceof LatLngBounds) {
return a;
}
return new LatLngBounds(a, b);
}
/* @class LatLng
* @aka L.LatLng
*
* Represents a geographical point with a certain latitude and longitude.
*
* @example
*
* ```
* var latlng = L.latLng(50.5, 30.5);
* ```
*
* All Leaflet methods that accept LatLng objects also accept them in a simple Array form and simple object form (unless noted otherwise), so these lines are equivalent:
*
* ```
* map.panTo([50, 30]);
* map.panTo({lon: 30, lat: 50});
* map.panTo({lat: 50, lng: 30});
* map.panTo(L.latLng(50, 30));
* ```
*
* Note that `LatLng` does not inherit from Leaflet's `Class` object,
* which means new classes can't inherit from it, and new methods
* can't be added to it with the `include` function.
*/
function LatLng(lat, lng, alt) {
if (isNaN(lat) || isNaN(lng)) {
throw new Error('Invalid LatLng object: (' + lat + ', ' + lng + ')');
}
// @property lat: Number
// Latitude in degrees
this.lat = +lat;
// @property lng: Number
// Longitude in degrees
this.lng = +lng;
// @property alt: Number
// Altitude in meters (optional)
if (alt !== undefined) {
this.alt = +alt;
}
}
LatLng.prototype = {
// @method equals(otherLatLng: LatLng, maxMargin?: Number): Boolean
// Returns `true` if the given `LatLng` point is at the same position (within a small margin of error). The margin of error can be overridden by setting `maxMargin` to a small number.
equals: function (obj, maxMargin) {
if (!obj) { return false; }
obj = toLatLng(obj);
var margin = Math.max(
Math.abs(this.lat - obj.lat),
Math.abs(this.lng - obj.lng));
return margin <= (maxMargin === undefined ? 1.0E-9 : maxMargin);
},
// @method toString(): String
// Returns a string representation of the point (for debugging purposes).
toString: function (precision) {
return 'LatLng(' +
formatNum(this.lat, precision) + ', ' +
formatNum(this.lng, precision) + ')';
},
// @method distanceTo(otherLatLng: LatLng): Number
// Returns the distance (in meters) to the given `LatLng` calculated using the [Spherical Law of Cosines](https://en.wikipedia.org/wiki/Spherical_law_of_cosines).
distanceTo: function (other) {
return Earth.distance(this, toLatLng(other));
},
// @method wrap(): LatLng
// Returns a new `LatLng` object with the longitude wrapped so it's always between -180 and +180 degrees.
wrap: function () {
return Earth.wrapLatLng(this);
},
// @method toBounds(sizeInMeters: Number): LatLngBounds
// Returns a new `LatLngBounds` object in which each boundary is `sizeInMeters/2` meters apart from the `LatLng`.
toBounds: function (sizeInMeters) {
var latAccuracy = 180 * sizeInMeters / 40075017,
lngAccuracy = latAccuracy / Math.cos((Math.PI / 180) * this.lat);
return toLatLngBounds(
[this.lat - latAccuracy, this.lng - lngAccuracy],
[this.lat + latAccuracy, this.lng + lngAccuracy]);
},
clone: function () {
return new LatLng(this.lat, this.lng, this.alt);
}
};
// @factory L.latLng(latitude: Number, longitude: Number, altitude?: Number): LatLng
// Creates an object representing a geographical point with the given latitude and longitude (and optionally altitude).
// @alternative
// @factory L.latLng(coords: Array): LatLng
// Expects an array of the form `[Number, Number]` or `[Number, Number, Number]` instead.
// @alternative
// @factory L.latLng(coords: Object): LatLng
// Expects an plain object of the form `{lat: Number, lng: Number}` or `{lat: Number, lng: Number, alt: Number}` instead.
function toLatLng(a, b, c) {
if (a instanceof LatLng) {
return a;
}
if (isArray(a) && typeof a[0] !== 'object') {
if (a.length === 3) {
return new LatLng(a[0], a[1], a[2]);
}
if (a.length === 2) {
return new LatLng(a[0], a[1]);
}
return null;
}
if (a === undefined || a === null) {
return a;
}
if (typeof a === 'object' && 'lat' in a) {
return new LatLng(a.lat, 'lng' in a ? a.lng : a.lon, a.alt);
}
if (b === undefined) {
return null;
}
return new LatLng(a, b, c);
}
/*
* @namespace CRS
* @crs L.CRS.Base
* Object that defines coordinate reference systems for projecting
* geographical points into pixel (screen) coordinates and back (and to
* coordinates in other units for [WMS](https://en.wikipedia.org/wiki/Web_Map_Service) services). See
* [spatial reference system](http://en.wikipedia.org/wiki/Coordinate_reference_system).
*
* Leaflet defines the most usual CRSs by default. If you want to use a
* CRS not defined by default, take a look at the
* [Proj4Leaflet](https://github.com/kartena/Proj4Leaflet) plugin.
*
* Note that the CRS instances do not inherit from Leafet's `Class` object,
* and can't be instantiated. Also, new classes can't inherit from them,
* and methods can't be added to them with the `include` function.
*/
var CRS = {
// @method latLngToPoint(latlng: LatLng, zoom: Number): Point
// Projects geographical coordinates into pixel coordinates for a given zoom.
latLngToPoint: function (latlng, zoom) {
var projectedPoint = this.projection.project(latlng),
scale = this.scale(zoom);
return this.transformation._transform(projectedPoint, scale);
},
// @method pointToLatLng(point: Point, zoom: Number): LatLng
// The inverse of `latLngToPoint`. Projects pixel coordinates on a given
// zoom into geographical coordinates.
pointToLatLng: function (point, zoom) {
var scale = this.scale(zoom),
untransformedPoint = this.transformation.untransform(point, scale);
return this.projection.unproject(untransformedPoint);
},
// @method project(latlng: LatLng): Point
// Projects geographical coordinates into coordinates in units accepted for
// this CRS (e.g. meters for EPSG:3857, for passing it to WMS services).
project: function (latlng) {
return this.projection.project(latlng);
},
// @method unproject(point: Point): LatLng
// Given a projected coordinate returns the corresponding LatLng.
// The inverse of `project`.
unproject: function (point) {
return this.projection.unproject(point);
},
// @method scale(zoom: Number): Number
// Returns the scale used when transforming projected coordinates into
// pixel coordinates for a particular zoom. For example, it returns
// `256 * 2^zoom` for Mercator-based CRS.
scale: function (zoom) {
return 256 * Math.pow(2, zoom);
},
// @method zoom(scale: Number): Number
// Inverse of `scale()`, returns the zoom level corresponding to a scale
// factor of `scale`.
zoom: function (scale) {
return Math.log(scale / 256) / Math.LN2;
},
// @method getProjectedBounds(zoom: Number): Bounds
// Returns the projection's bounds scaled and transformed for the provided `zoom`.
getProjectedBounds: function (zoom) {
if (this.infinite) { return null; }
var b = this.projection.bounds,
s = this.scale(zoom),
min = this.transformation.transform(b.min, s),
max = this.transformation.transform(b.max, s);
return new Bounds(min, max);
},
// @method distance(latlng1: LatLng, latlng2: LatLng): Number
// Returns the distance between two geographical coordinates.
// @property code: String
// Standard code name of the CRS passed into WMS services (e.g. `'EPSG:3857'`)
//
// @property wrapLng: Number[]
// An array of two numbers defining whether the longitude (horizontal) coordinate
// axis wraps around a given range and how. Defaults to `[-180, 180]` in most
// geographical CRSs. If `undefined`, the longitude axis does not wrap around.
//
// @property wrapLat: Number[]
// Like `wrapLng`, but for the latitude (vertical) axis.
// wrapLng: [min, max],
// wrapLat: [min, max],
// @property infinite: Boolean
// If true, the coordinate space will be unbounded (infinite in both axes)
infinite: false,
// @method wrapLatLng(latlng: LatLng): LatLng
// Returns a `LatLng` where lat and lng has been wrapped according to the
// CRS's `wrapLat` and `wrapLng` properties, if they are outside the CRS's bounds.
wrapLatLng: function (latlng) {
var lng = this.wrapLng ? wrapNum(latlng.lng, this.wrapLng, true) : latlng.lng,
lat = this.wrapLat ? wrapNum(latlng.lat, this.wrapLat, true) : latlng.lat,
alt = latlng.alt;
return new LatLng(lat, lng, alt);
},
// @method wrapLatLngBounds(bounds: LatLngBounds): LatLngBounds
// Returns a `LatLngBounds` with the same size as the given one, ensuring
// that its center is within the CRS's bounds.
// Only accepts actual `L.LatLngBounds` instances, not arrays.
wrapLatLngBounds: function (bounds) {
var center = bounds.getCenter(),
newCenter = this.wrapLatLng(center),
latShift = center.lat - newCenter.lat,
lngShift = center.lng - newCenter.lng;
if (latShift === 0 && lngShift === 0) {
return bounds;
}
var sw = bounds.getSouthWest(),
ne = bounds.getNorthEast(),
newSw = new LatLng(sw.lat - latShift, sw.lng - lngShift),
newNe = new LatLng(ne.lat - latShift, ne.lng - lngShift);
return new LatLngBounds(newSw, newNe);
}
};
/*
* @namespace CRS
* @crs L.CRS.Earth
*
* Serves as the base for CRS that are global such that they cover the earth.
* Can only be used as the base for other CRS and cannot be used directly,
* since it does not have a `code`, `projection` or `transformation`. `distance()` returns
* meters.
*/
var Earth = extend({}, CRS, {
wrapLng: [-180, 180],
// Mean Earth Radius, as recommended for use by
// the International Union of Geodesy and Geophysics,
// see http://rosettacode.org/wiki/Haversine_formula
R: 6371000,
// distance between two geographical points using spherical law of cosines approximation
distance: function (latlng1, latlng2) {
var rad = Math.PI / 180,
lat1 = latlng1.lat * rad,
lat2 = latlng2.lat * rad,
sinDLat = Math.sin((latlng2.lat - latlng1.lat) * rad / 2),
sinDLon = Math.sin((latlng2.lng - latlng1.lng) * rad / 2),
a = sinDLat * sinDLat + Math.cos(lat1) * Math.cos(lat2) * sinDLon * sinDLon,
c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return this.R * c;
}
});
/*
* @namespace Projection
* @projection L.Projection.SphericalMercator
*
* Spherical Mercator projection — the most common projection for online maps,
* used by almost all free and commercial tile providers. Assumes that Earth is
* a sphere. Used by the `EPSG:3857` CRS.
*/
var earthRadius = 6378137;
var SphericalMercator = {
R: earthRadius,
MAX_LATITUDE: 85.0511287798,
project: function (latlng) {
var d = Math.PI / 180,
max = this.MAX_LATITUDE,
lat = Math.max(Math.min(max, latlng.lat), -max),
sin = Math.sin(lat * d);
return new Point(
this.R * latlng.lng * d,
this.R * Math.log((1 + sin) / (1 - sin)) / 2);
},
unproject: function (point) {
var d = 180 / Math.PI;
return new LatLng(
(2 * Math.atan(Math.exp(point.y / this.R)) - (Math.PI / 2)) * d,
point.x * d / this.R);
},
bounds: (function () {
var d = earthRadius * Math.PI;
return new Bounds([-d, -d], [d, d]);
})()
};
/*
* @class Transformation
* @aka L.Transformation
*
* Represents an affine transformation: a set of coefficients `a`, `b`, `c`, `d`
* for transforming a point of a form `(x, y)` into `(a*x + b, c*y + d)` and doing
* the reverse. Used by Leaflet in its projections code.
*
* @example
*
* ```js
* var transformation = L.transformation(2, 5, -1, 10),
* p = L.point(1, 2),
* p2 = transformation.transform(p), // L.point(7, 8)
* p3 = transformation.untransform(p2); // L.point(1, 2)
* ```
*/
// factory new L.Transformation(a: Number, b: Number, c: Number, d: Number)
// Creates a `Transformation` object with the given coefficients.
function Transformation(a, b, c, d) {
if (isArray(a)) {
// use array properties
this._a = a[0];
this._b = a[1];
this._c = a[2];
this._d = a[3];
return;
}
this._a = a;
this._b = b;
this._c = c;
this._d = d;
}
Transformation.prototype = {
// @method transform(point: Point, scale?: Number): Point
// Returns a transformed point, optionally multiplied by the given scale.
// Only accepts actual `L.Point` instances, not arrays.
transform: function (point, scale) { // (Point, Number) -> Point
return this._transform(point.clone(), scale);
},
// destructive transform (faster)
_transform: function (point, scale) {
scale = scale || 1;
point.x = scale * (this._a * point.x + this._b);
point.y = scale * (this._c * point.y + this._d);
return point;
},
// @method untransform(point: Point, scale?: Number): Point
// Returns the reverse transformation of the given point, optionally divided
// by the given scale. Only accepts actual `L.Point` instances, not arrays.
untransform: function (point, scale) {
scale = scale || 1;
return new Point(
(point.x / scale - this._b) / this._a,
(point.y / scale - this._d) / this._c);
}
};
// factory L.transformation(a: Number, b: Number, c: Number, d: Number)
// @factory L.transformation(a: Number, b: Number, c: Number, d: Number)
// Instantiates a Transformation object with the given coefficients.
// @alternative
// @factory L.transformation(coefficients: Array): Transformation
// Expects an coefficients array of the form
// `[a: Number, b: Number, c: Number, d: Number]`.
function toTransformation(a, b, c, d) {
return new Transformation(a, b, c, d);
}
/*
* @namespace CRS
* @crs L.CRS.EPSG3857
*
* The most common CRS for online maps, used by almost all free and commercial
* tile providers. Uses Spherical Mercator projection. Set in by default in
* Map's `crs` option.
*/
var EPSG3857 = extend({}, Earth, {
code: 'EPSG:3857',
projection: SphericalMercator,
transformation: (function () {
var scale = 0.5 / (Math.PI * SphericalMercator.R);
return toTransformation(scale, 0.5, -scale, 0.5);
}())
});
var EPSG900913 = extend({}, EPSG3857, {
code: 'EPSG:900913'
});
// @namespace SVG; @section
// There are several static functions which can be called without instantiating L.SVG:
// @function create(name: String): SVGElement
// Returns a instance of [SVGElement](https://developer.mozilla.org/docs/Web/API/SVGElement),
// corresponding to the class name passed. For example, using 'line' will return
// an instance of [SVGLineElement](https://developer.mozilla.org/docs/Web/API/SVGLineElement).
function svgCreate(name) {
return document.createElementNS('http://www.w3.org/2000/svg', name);
}
// @function pointsToPath(rings: Point[], closed: Boolean): String
// Generates a SVG path string for multiple rings, with each ring turning
// into "M..L..L.." instructions
function pointsToPath(rings, closed) {
var str = '',
i, j, len, len2, points, p;
for (i = 0, len = rings.length; i < len; i++) {
points = rings[i];
for (j = 0, len2 = points.length; j < len2; j++) {
p = points[j];
str += (j ? 'L' : 'M') + p.x + ' ' + p.y;
}
// closes the ring for polygons; "x" is VML syntax
str += closed ? (svg ? 'z' : 'x') : '';
}
// SVG complains about empty path strings
return str || 'M0 0';
}
/*
* @namespace Browser
* @aka L.Browser
*
* A namespace with static properties for browser/feature detection used by Leaflet internally.
*
* @example
*
* ```js
* if (L.Browser.ielt9) {
* alert('Upgrade your browser, dude!');
* }
* ```
*/
var style$1 = document.documentElement.style;
// @property ie: Boolean; `true` for all Internet Explorer versions (not Edge).
var ie = 'ActiveXObject' in window;
// @property ielt9: Boolean; `true` for Internet Explorer versions less than 9.
var ielt9 = ie && !document.addEventListener;
// @property edge: Boolean; `true` for the Edge web browser.
var edge = 'msLaunchUri' in navigator && !('documentMode' in document);
// @property webkit: Boolean;
// `true` for webkit-based browsers like Chrome and Safari (including mobile versions).
var webkit = userAgentContains('webkit');
// @property android: Boolean
// `true` for any browser running on an Android platform.
var android = userAgentContains('android');
// @property android23: Boolean; `true` for browsers running on Android 2 or Android 3.
var android23 = userAgentContains('android 2') || userAgentContains('android 3');
/* See https://stackoverflow.com/a/17961266 for details on detecting stock Android */
var webkitVer = parseInt(/WebKit\/([0-9]+)|$/.exec(navigator.userAgent)[1], 10); // also matches AppleWebKit
// @property androidStock: Boolean; `true` for the Android stock browser (i.e. not Chrome)
var androidStock = android && userAgentContains('Google') && webkitVer < 537 && !('AudioNode' in window);
// @property opera: Boolean; `true` for the Opera browser
var opera = !!window.opera;
// @property chrome: Boolean; `true` for the Chrome browser.
var chrome = userAgentContains('chrome');
// @property gecko: Boolean; `true` for gecko-based browsers like Firefox.
var gecko = userAgentContains('gecko') && !webkit && !opera && !ie;
// @property safari: Boolean; `true` for the Safari browser.
var safari = !chrome && userAgentContains('safari');
var phantom = userAgentContains('phantom');
// @property opera12: Boolean
// `true` for the Opera browser supporting CSS transforms (version 12 or later).
var opera12 = 'OTransition' in style$1;
// @property win: Boolean; `true` when the browser is running in a Windows platform
var win = navigator.platform.indexOf('Win') === 0;
// @property ie3d: Boolean; `true` for all Internet Explorer versions supporting CSS transforms.
var ie3d = ie && ('transition' in style$1);
// @property webkit3d: Boolean; `true` for webkit-based browsers supporting CSS transforms.
var webkit3d = ('WebKitCSSMatrix' in window) && ('m11' in new window.WebKitCSSMatrix()) && !android23;
// @property gecko3d: Boolean; `true` for gecko-based browsers supporting CSS transforms.
var gecko3d = 'MozPerspective' in style$1;
// @property any3d: Boolean
// `true` for all browsers supporting CSS transforms.
var any3d = !window.L_DISABLE_3D && (ie3d || webkit3d || gecko3d) && !opera12 && !phantom;
// @property mobile: Boolean; `true` for all browsers running in a mobile device.
var mobile = typeof orientation !== 'undefined' || userAgentContains('mobile');
// @property mobileWebkit: Boolean; `true` for all webkit-based browsers in a mobile device.
var mobileWebkit = mobile && webkit;
// @property mobileWebkit3d: Boolean
// `true` for all webkit-based browsers in a mobile device supporting CSS transforms.
var mobileWebkit3d = mobile && webkit3d;
// @property msPointer: Boolean
// `true` for browsers implementing the Microsoft touch events model (notably IE10).
var msPointer = !window.PointerEvent && window.MSPointerEvent;
// @property pointer: Boolean
// `true` for all browsers supporting [pointer events](https://msdn.microsoft.com/en-us/library/dn433244%28v=vs.85%29.aspx).
var pointer = !webkit && !!(window.PointerEvent || msPointer);
// @property touch: Boolean
// `true` for all browsers supporting [touch events](https://developer.mozilla.org/docs/Web/API/Touch_events).
// This does not necessarily mean that the browser is running in a computer with
// a touchscreen, it only means that the browser is capable of understanding
// touch events.
var touch = !window.L_NO_TOUCH && (pointer || 'ontouchstart' in window ||
(window.DocumentTouch && document instanceof window.DocumentTouch));
// @property mobileOpera: Boolean; `true` for the Opera browser in a mobile device.
var mobileOpera = mobile && opera;
// @property mobileGecko: Boolean
// `true` for gecko-based browsers running in a mobile device.
var mobileGecko = mobile && gecko;
// @property retina: Boolean
// `true` for browsers on a high-resolution "retina" screen or on any screen when browser's display zoom is more than 100%.
var retina = (window.devicePixelRatio || (window.screen.deviceXDPI / window.screen.logicalXDPI)) > 1;
// @property passiveEvents: Boolean
// `true` for browsers that support passive events.
var passiveEvents = (function () {
var supportsPassiveOption = false;
try {
var opts = Object.defineProperty({}, 'passive', {
get: function () {
supportsPassiveOption = true;
}
});
window.addEventListener('testPassiveEventSupport', falseFn, opts);
window.removeEventListener('testPassiveEventSupport', falseFn, opts);
} catch (e) {
// Errors can safely be ignored since this is only a browser support test.
}
return supportsPassiveOption;
});
// @property canvas: Boolean
// `true` when the browser supports [`<canvas>`](https://developer.mozilla.org/docs/Web/API/Canvas_API).
var canvas = (function () {
return !!document.createElement('canvas').getContext;
}());
// @property svg: Boolean
// `true` when the browser supports [SVG](https://developer.mozilla.org/docs/Web/SVG).
var svg = !!(document.createElementNS && svgCreate('svg').createSVGRect);
// @property vml: Boolean
// `true` if the browser supports [VML](https://en.wikipedia.org/wiki/Vector_Markup_Language).
var vml = !svg && (function () {
try {
var div = document.createElement('div');
div.innerHTML = '<v:shape adj="1"/>';
var shape = div.firstChild;
shape.style.behavior = 'url(#default#VML)';
return shape && (typeof shape.adj === 'object');
} catch (e) {
return false;
}
}());
function userAgentContains(str) {
return navigator.userAgent.toLowerCase().indexOf(str) >= 0;
}
var Browser = (Object.freeze || Object)({
ie: ie,
ielt9: ielt9,
edge: edge,
webkit: webkit,
android: android,
android23: android23,
androidStock: androidStock,
opera: opera,
chrome: chrome,
gecko: gecko,
safari: safari,
phantom: phantom,
opera12: opera12,
win: win,
ie3d: ie3d,
webkit3d: webkit3d,
gecko3d: gecko3d,
any3d: any3d,
mobile: mobile,
mobileWebkit: mobileWebkit,
mobileWebkit3d: mobileWebkit3d,
msPointer: msPointer,
pointer: pointer,
touch: touch,
mobileOpera: mobileOpera,
mobileGecko: mobileGecko,
retina: retina,
passiveEvents: passiveEvents,
canvas: canvas,
svg: svg,
vml: vml
});
/*
* Extends L.DomEvent to provide touch support for Internet Explorer and Windows-based devices.
*/
var POINTER_DOWN = msPointer ? 'MSPointerDown' : 'pointerdown';
var POINTER_MOVE = msPointer ? 'MSPointerMove' : 'pointermove';
var POINTER_UP = msPointer ? 'MSPointerUp' : 'pointerup';
var POINTER_CANCEL = msPointer ? 'MSPointerCancel' : 'pointercancel';
var TAG_WHITE_LIST = ['INPUT', 'SELECT', 'OPTION'];
var _pointers = {};
var _pointerDocListener = false;
// DomEvent.DoubleTap needs to know about this
var _pointersCount = 0;
// Provides a touch events wrapper for (ms)pointer events.
// ref http://www.w3.org/TR/pointerevents/ https://www.w3.org/Bugs/Public/show_bug.cgi?id=22890
function addPointerListener(obj, type, handler, id) {
if (type === 'touchstart') {
_addPointerStart(obj, handler, id);
} else if (type === 'touchmove') {
_addPointerMove(obj, handler, id);
} else if (type === 'touchend') {
_addPointerEnd(obj, handler, id);
}
return this;
}
function removePointerListener(obj, type, id) {
var handler = obj['_leaflet_' + type + id];
if (type === 'touchstart') {
obj.removeEventListener(POINTER_DOWN, handler, false);
} else if (type === 'touchmove') {
obj.removeEventListener(POINTER_MOVE, handler, false);
} else if (type === 'touchend') {
obj.removeEventListener(POINTER_UP, handler, false);
obj.removeEventListener(POINTER_CANCEL, handler, false);
}
return this;
}
function _addPointerStart(obj, handler, id) {
var onDown = bind(function (e) {
if (e.pointerType !== 'mouse' && e.MSPOINTER_TYPE_MOUSE && e.pointerType !== e.MSPOINTER_TYPE_MOUSE) {
// In IE11, some touch events needs to fire for form controls, or
// the controls will stop working. We keep a whitelist of tag names that
// need these events. For other target tags, we prevent default on the event.
if (TAG_WHITE_LIST.indexOf(e.target.tagName) < 0) {
preventDefault(e);
} else {
return;
}
}
_handlePointer(e, handler);
});
obj['_leaflet_touchstart' + id] = onDown;
obj.addEventListener(POINTER_DOWN, onDown, false);
// need to keep track of what pointers and how many are active to provide e.touches emulation
if (!_pointerDocListener) {
// we listen documentElement as any drags that end by moving the touch off the screen get fired there
document.documentElement.addEventListener(POINTER_DOWN, _globalPointerDown, true);
document.documentElement.addEventListener(POINTER_MOVE, _globalPointerMove, true);
document.documentElement.addEventListener(POINTER_UP, _globalPointerUp, true);
document.documentElement.addEventListener(POINTER_CANCEL, _globalPointerUp, true);
_pointerDocListener = true;
}
}
function _globalPointerDown(e) {
_pointers[e.pointerId] = e;
_pointersCount++;
}
function _globalPointerMove(e) {
if (_pointers[e.pointerId]) {
_pointers[e.pointerId] = e;
}
}
function _globalPointerUp(e) {
delete _pointers[e.pointerId];
_pointersCount--;
}
function _handlePointer(e, handler) {
e.touches = [];
for (var i in _pointers) {
e.touches.push(_pointers[i]);
}
e.changedTouches = [e];
handler(e);
}
function _addPointerMove(obj, handler, id) {
var onMove = function (e) {
// don't fire touch moves when mouse isn't down
if ((e.pointerType === e.MSPOINTER_TYPE_MOUSE || e.pointerType === 'mouse') && e.buttons === 0) { return; }
_handlePointer(e, handler);
};
obj['_leaflet_touchmove' + id] = onMove;
obj.addEventListener(POINTER_MOVE, onMove, false);
}
function _addPointerEnd(obj, handler, id) {
var onUp = function (e) {
_handlePointer(e, handler);
};
obj['_leaflet_touchend' + id] = onUp;
obj.addEventListener(POINTER_UP, onUp, false);
obj.addEventListener(POINTER_CANCEL, onUp, false);
}
/*
* Extends the event handling code with double tap support for mobile browsers.
*/
var _touchstart = msPointer ? 'MSPointerDown' : pointer ? 'pointerdown' : 'touchstart';
var _touchend = msPointer ? 'MSPointerUp' : pointer ? 'pointerup' : 'touchend';
var _pre = '_leaflet_';
// inspired by Zepto touch code by Thomas Fuchs
function addDoubleTapListener(obj, handler, id) {
var last, touch$$1,
doubleTap = false,
delay = 250;
function onTouchStart(e) {
var count;
if (pointer) {
if ((!edge) || e.pointerType === 'mouse') { return; }
count = _pointersCount;
} else {
count = e.touches.length;
}
if (count > 1) { return; }
var now = Date.now(),
delta = now - (last || now);
touch$$1 = e.touches ? e.touches[0] : e;
doubleTap = (delta > 0 && delta <= delay);
last = now;
}
function onTouchEnd(e) {
if (doubleTap && !touch$$1.cancelBubble) {
if (pointer) {
if ((!edge) || e.pointerType === 'mouse') { return; }
// work around .type being readonly with MSPointer* events
var newTouch = {},
prop, i;
for (i in touch$$1) {
prop = touch$$1[i];
newTouch[i] = prop && prop.bind ? prop.bind(touch$$1) : prop;
}
touch$$1 = newTouch;
}
touch$$1.type = 'dblclick';
touch$$1.button = 0;
handler(touch$$1);
last = null;
}
}
obj[_pre + _touchstart + id] = onTouchStart;
obj[_pre + _touchend + id] = onTouchEnd;
obj[_pre + 'dblclick' + id] = handler;
obj.addEventListener(_touchstart, onTouchStart, passiveEvents ? {passive: false} : false);
obj.addEventListener(_touchend, onTouchEnd, passiveEvents ? {passive: false} : false);
// On some platforms (notably, chrome<55 on win10 + touchscreen + mouse),
// the browser doesn't fire touchend/pointerup events but does fire
// native dblclicks. See #4127.
// Edge 14 also fires native dblclicks, but only for pointerType mouse, see #5180.
obj.addEventListener('dblclick', handler, false);
return this;
}
function removeDoubleTapListener(obj, id) {
var touchstart = obj[_pre + _touchstart + id],
touchend = obj[_pre + _touchend + id],
dblclick = obj[_pre + 'dblclick' + id];
obj.removeEventListener(_touchstart, touchstart, passiveEvents ? {passive: false} : false);
obj.removeEventListener(_touchend, touchend, passiveEvents ? {passive: false} : false);
if (!edge) {
obj.removeEventListener('dblclick', dblclick, false);
}
return this;
}
/*
* @namespace DomUtil
*
* Utility functions to work with the [DOM](https://developer.mozilla.org/docs/Web/API/Document_Object_Model)
* tree, used by Leaflet internally.
*
* Most functions expecting or returning a `HTMLElement` also work for
* SVG elements. The only difference is that classes refer to CSS classes
* in HTML and SVG classes in SVG.
*/
// @property TRANSFORM: String
// Vendor-prefixed transform style name (e.g. `'webkitTransform'` for WebKit).
var TRANSFORM = testProp(
['transform', 'webkitTransform', 'OTransform', 'MozTransform', 'msTransform']);
// webkitTransition comes first because some browser versions that drop vendor prefix don't do
// the same for the transitionend event, in particular the Android 4.1 stock browser
// @property TRANSITION: String
// Vendor-prefixed transition style name.
var TRANSITION = testProp(
['webkitTransition', 'transition', 'OTransition', 'MozTransition', 'msTransition']);
// @property TRANSITION_END: String
// Vendor-prefixed transitionend event name.
var TRANSITION_END =
TRANSITION === 'webkitTransition' || TRANSITION === 'OTransition' ? TRANSITION + 'End' : 'transitionend';
// @function get(id: String|HTMLElement): HTMLElement
// Returns an element given its DOM id, or returns the element itself
// if it was passed directly.
function get(id) {
return typeof id === 'string' ? document.getElementById(id) : id;
}
// @function getStyle(el: HTMLElement, styleAttrib: String): String
// Returns the value for a certain style attribute on an element,
// including computed values or values set through CSS.
function getStyle(el, style) {
var value = el.style[style] || (el.currentStyle && el.currentStyle[style]);
if ((!value || value === 'auto') && document.defaultView) {
var css = document.defaultView.getComputedStyle(el, null);
value = css ? css[style] : null;
}
return value === 'auto' ? null : value;
}
// @function create(tagName: String, className?: String, container?: HTMLElement): HTMLElement
// Creates an HTML element with `tagName`, sets its class to `className`, and optionally appends it to `container` element.
function create$1(tagName, className, container) {
var el = document.createElement(tagName);
el.className = className || '';
if (container) {
container.appendChild(el);
}
return el;
}
// @function remove(el: HTMLElement)
// Removes `el` from its parent element
function remove(el) {
var parent = el.parentNode;
if (parent) {
parent.removeChild(el);
}
}
// @function empty(el: HTMLElement)
// Removes all of `el`'s children elements from `el`
function empty(el) {
while (el.firstChild) {
el.removeChild(el.firstChild);
}
}
// @function toFront(el: HTMLElement)
// Makes `el` the last child of its parent, so it renders in front of the other children.
function toFront(el) {
var parent = el.parentNode;
if (parent && parent.lastChild !== el) {
parent.appendChild(el);
}
}
// @function toBack(el: HTMLElement)
// Makes `el` the first child of its parent, so it renders behind the other children.
function toBack(el) {
var parent = el.parentNode;
if (parent && parent.firstChild !== el) {
parent.insertBefore(el, parent.firstChild);
}
}
// @function hasClass(el: HTMLElement, name: String): Boolean
// Returns `true` if the element's class attribute contains `name`.
function hasClass(el, name) {
if (el.classList !== undefined) {
return el.classList.contains(name);
}
var className = getClass(el);
return className.length > 0 && new RegExp('(^|\\s)' + name + '(\\s|$)').test(className);
}
// @function addClass(el: HTMLElement, name: String)
// Adds `name` to the element's class attribute.
function addClass(el, name) {
if (el.classList !== undefined) {
var classes = splitWords(name);
for (var i = 0, len = classes.length; i < len; i++) {
el.classList.add(classes[i]);
}
} else if (!hasClass(el, name)) {
var className = getClass(el);
setClass(el, (className ? className + ' ' : '') + name);
}
}
// @function removeClass(el: HTMLElement, name: String)
// Removes `name` from the element's class attribute.
function removeClass(el, name) {
if (el.classList !== undefined) {
el.classList.remove(name);
} else {
setClass(el, trim((' ' + getClass(el) + ' ').replace(' ' + name + ' ', ' ')));
}
}
// @function setClass(el: HTMLElement, name: String)
// Sets the element's class.
function setClass(el, name) {
if (el.className.baseVal === undefined) {
el.className = name;
} else {
// in case of SVG element
el.className.baseVal = name;
}
}
// @function getClass(el: HTMLElement): String
// Returns the element's class.
function getClass(el) {
// Check if the element is an SVGElementInstance and use the correspondingElement instead
// (Required for linked SVG elements in IE11.)
if (el.correspondingElement) {
el = el.correspondingElement;
}
return el.className.baseVal === undefined ? el.className : el.className.baseVal;
}
// @function setOpacity(el: HTMLElement, opacity: Number)
// Set the opacity of an element (including old IE support).
// `opacity` must be a number from `0` to `1`.
function setOpacity(el, value) {
if ('opacity' in el.style) {
el.style.opacity = value;
} else if ('filter' in el.style) {
_setOpacityIE(el, value);
}
}
function _setOpacityIE(el, value) {
var filter = false,
filterName = 'DXImageTransform.Microsoft.Alpha';
// filters collection throws an error if we try to retrieve a filter that doesn't exist
try {
filter = el.filters.item(filterName);
} catch (e) {
// don't set opacity to 1 if we haven't already set an opacity,
// it isn't needed and breaks transparent pngs.
if (value === 1) { return; }
}
value = Math.round(value * 100);
if (filter) {
filter.Enabled = (value !== 100);
filter.Opacity = value;
} else {
el.style.filter += ' progid:' + filterName + '(opacity=' + value + ')';
}
}
// @function testProp(props: String[]): String|false
// Goes through the array of style names and returns the first name
// that is a valid style name for an element. If no such name is found,
// it returns false. Useful for vendor-prefixed styles like `transform`.
function testProp(props) {
var style = document.documentElement.style;
for (var i = 0; i < props.length; i++) {
if (props[i] in style) {
return props[i];
}
}
return false;
}
// @function setTransform(el: HTMLElement, offset: Point, scale?: Number)
// Resets the 3D CSS transform of `el` so it is translated by `offset` pixels
// and optionally scaled by `scale`. Does not have an effect if the
// browser doesn't support 3D CSS transforms.
function setTransform(el, offset, scale) {
var pos = offset || new Point(0, 0);
el.style[TRANSFORM] =
(ie3d ?
'translate(' + pos.x + 'px,' + pos.y + 'px)' :
'translate3d(' + pos.x + 'px,' + pos.y + 'px,0)') +
(scale ? ' scale(' + scale + ')' : '');
}
// @function setPosition(el: HTMLElement, position: Point)
// Sets the position of `el` to coordinates specified by `position`,
// using CSS translate or top/left positioning depending on the browser
// (used by Leaflet internally to position its layers).
function setPosition(el, point) {
/*eslint-disable */
el._leaflet_pos = point;
/* eslint-enable */
if (any3d) {
setTransform(el, point);
} else {
el.style.left = point.x + 'px';
el.style.top = point.y + 'px';
}
}
// @function getPosition(el: HTMLElement): Point
// Returns the coordinates of an element previously positioned with setPosition.
function getPosition(el) {
// this method is only used for elements previously positioned using setPosition,
// so it's safe to cache the position for performance
return el._leaflet_pos || new Point(0, 0);
}
// @function disableTextSelection()
// Prevents the user from generating `selectstart` DOM events, usually generated
// when the user drags the mouse through a page with text. Used internally
// by Leaflet to override the behaviour of any click-and-drag interaction on
// the map. Affects drag interactions on the whole document.
// @function enableTextSelection()
// Cancels the effects of a previous [`L.DomUtil.disableTextSelection`](#domutil-disabletextselection).
var disableTextSelection;
var enableTextSelection;
var _userSelect;
if ('onselectstart' in document) {
disableTextSelection = function () {
on(window, 'selectstart', preventDefault);
};
enableTextSelection = function () {
off(window, 'selectstart', preventDefault);
};
} else {
var userSelectProperty = testProp(
['userSelect', 'WebkitUserSelect', 'OUserSelect', 'MozUserSelect', 'msUserSelect']);
disableTextSelection = function () {
if (userSelectProperty) {
var style = document.documentElement.style;
_userSelect = style[userSelectProperty];
style[userSelectProperty] = 'none';
}
};
enableTextSelection = function () {
if (userSelectProperty) {
document.documentElement.style[userSelectProperty] = _userSelect;
_userSelect = undefined;
}
};
}
// @function disableImageDrag()
// As [`L.DomUtil.disableTextSelection`](#domutil-disabletextselection), but
// for `dragstart` DOM events, usually generated when the user drags an image.
function disableImageDrag() {
on(window, 'dragstart', preventDefault);
}
// @function enableImageDrag()
// Cancels the effects of a previous [`L.DomUtil.disableImageDrag`](#domutil-disabletextselection).
function enableImageDrag() {
off(window, 'dragstart', preventDefault);
}
var _outlineElement;
var _outlineStyle;
// @function preventOutline(el: HTMLElement)
// Makes the [outline](https://developer.mozilla.org/docs/Web/CSS/outline)
// of the element `el` invisible. Used internally by Leaflet to prevent
// focusable elements from displaying an outline when the user performs a
// drag interaction on them.
function preventOutline(element) {
while (element.tabIndex === -1) {
element = element.parentNode;
}
if (!element.style) { return; }
restoreOutline();
_outlineElement = element;
_outlineStyle = element.style.outline;
element.style.outline = 'none';
on(window, 'keydown', restoreOutline);
}
// @function restoreOutline()
// Cancels the effects of a previous [`L.DomUtil.preventOutline`]().
function restoreOutline() {
if (!_outlineElement) { return; }
_outlineElement.style.outline = _outlineStyle;
_outlineElement = undefined;
_outlineStyle = undefined;
off(window, 'keydown', restoreOutline);
}
// @function getSizedParentNode(el: HTMLElement): HTMLElement
// Finds the closest parent node which size (width and height) is not null.
function getSizedParentNode(element) {
do {
element = element.parentNode;
} while ((!element.offsetWidth || !element.offsetHeight) && element !== document.body);
return element;
}
// @function getScale(el: HTMLElement): Object
// Computes the CSS scale currently applied on the element.
// Returns an object with `x` and `y` members as horizontal and vertical scales respectively,
// and `boundingClientRect` as the result of [`getBoundingClientRect()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect).
function getScale(element) {
var rect = element.getBoundingClientRect(); // Read-only in old browsers.
return {
x: rect.width / element.offsetWidth || 1,
y: rect.height / element.offsetHeight || 1,
boundingClientRect: rect
};
}
var DomUtil = (Object.freeze || Object)({
TRANSFORM: TRANSFORM,
TRANSITION: TRANSITION,
TRANSITION_END: TRANSITION_END,
get: get,
getStyle: getStyle,
create: create$1,
remove: remove,
empty: empty,
toFront: toFront,
toBack: toBack,
hasClass: hasClass,
addClass: addClass,
removeClass: removeClass,
setClass: setClass,
getClass: getClass,
setOpacity: setOpacity,
testProp: testProp,
setTransform: setTransform,
setPosition: setPosition,
getPosition: getPosition,
disableTextSelection: disableTextSelection,
enableTextSelection: enableTextSelection,
disableImageDrag: disableImageDrag,
enableImageDrag: enableImageDrag,
preventOutline: preventOutline,
restoreOutline: restoreOutline,
getSizedParentNode: getSizedParentNode,
getScale: getScale
});
/*
* @namespace DomEvent
* Utility functions to work with the [DOM events](https://developer.mozilla.org/docs/Web/API/Event), used by Leaflet internally.
*/
// Inspired by John Resig, Dean Edwards and YUI addEvent implementations.
// @function on(el: HTMLElement, types: String, fn: Function, context?: Object): this
// Adds a listener function (`fn`) to a particular DOM event type of the
// element `el`. You can optionally specify the context of the listener
// (object the `this` keyword will point to). You can also pass several
// space-separated types (e.g. `'click dblclick'`).
// @alternative
// @function on(el: HTMLElement, eventMap: Object, context?: Object): this
// Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`
function on(obj, types, fn, context) {
if (typeof types === 'object') {
for (var type in types) {
addOne(obj, type, types[type], fn);
}
} else {
types = splitWords(types);
for (var i = 0, len = types.length; i < len; i++) {
addOne(obj, types[i], fn, context);
}
}
return this;
}
var eventsKey = '_leaflet_events';
// @function off(el: HTMLElement, types: String, fn: Function, context?: Object): this
// Removes a previously added listener function.
// Note that if you passed a custom context to on, you must pass the same
// context to `off` in order to remove the listener.
// @alternative
// @function off(el: HTMLElement, eventMap: Object, context?: Object): this
// Removes a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`
function off(obj, types, fn, context) {
if (typeof types === 'object') {
for (var type in types) {
removeOne(obj, type, types[type], fn);
}
} else if (types) {
types = splitWords(types);
for (var i = 0, len = types.length; i < len; i++) {
removeOne(obj, types[i], fn, context);
}
} else {
for (var j in obj[eventsKey]) {
removeOne(obj, j, obj[eventsKey][j]);
}
delete obj[eventsKey];
}
return this;
}
function addOne(obj, type, fn, context) {
var id = type + stamp(fn) + (context ? '_' + stamp(context) : '');
if (obj[eventsKey] && obj[eventsKey][id]) { return this; }
var handler = function (e) {
return fn.call(context || obj, e || window.event);
};
var originalHandler = handler;
if (pointer && type.indexOf('touch') === 0) {
// Needs DomEvent.Pointer.js
addPointerListener(obj, type, handler, id);
} else if (touch && (type === 'dblclick') && addDoubleTapListener &&
!(pointer && chrome)) {
// Chrome >55 does not need the synthetic dblclicks from addDoubleTapListener
// See #5180
addDoubleTapListener(obj, handler, id);
} else if ('addEventListener' in obj) {
if (type === 'mousewheel') {
obj.addEventListener('onwheel' in obj ? 'wheel' : 'mousewheel', handler, passiveEvents ? {passive: false} : false);
} else if ((type === 'mouseenter') || (type === 'mouseleave')) {
handler = function (e) {
e = e || window.event;
if (isExternalTarget(obj, e)) {
originalHandler(e);
}
};
obj.addEventListener(type === 'mouseenter' ? 'mouseover' : 'mouseout', handler, false);
} else {
if (type === 'click' && android) {
handler = function (e) {
filterClick(e, originalHandler);
};
}
obj.addEventListener(type, handler, false);
}
} else if ('attachEvent' in obj) {
obj.attachEvent('on' + type, handler);
}
obj[eventsKey] = obj[eventsKey] || {};
obj[eventsKey][id] = handler;
}
function removeOne(obj, type, fn, context) {
var id = type + stamp(fn) + (context ? '_' + stamp(context) : ''),
handler = obj[eventsKey] && obj[eventsKey][id];
if (!handler) { return this; }
if (pointer && type.indexOf('touch') === 0) {
removePointerListener(obj, type, id);
} else if (touch && (type === 'dblclick') && removeDoubleTapListener &&
!(pointer && chrome)) {
removeDoubleTapListener(obj, id);
} else if ('removeEventListener' in obj) {
if (type === 'mousewheel') {
obj.removeEventListener('onwheel' in obj ? 'wheel' : 'mousewheel', handler, passiveEvents ? {passive: false} : false);
} else {
obj.removeEventListener(
type === 'mouseenter' ? 'mouseover' :
type === 'mouseleave' ? 'mouseout' : type, handler, false);
}
} else if ('detachEvent' in obj) {
obj.detachEvent('on' + type, handler);
}
obj[eventsKey][id] = null;
}
// @function stopPropagation(ev: DOMEvent): this
// Stop the given event from propagation to parent elements. Used inside the listener functions:
// ```js
// L.DomEvent.on(div, 'click', function (ev) {
// L.DomEvent.stopPropagation(ev);
// });
// ```
function stopPropagation(e) {
if (e.stopPropagation) {
e.stopPropagation();
} else if (e.originalEvent) { // In case of Leaflet event.
e.originalEvent._stopped = true;
} else {
e.cancelBubble = true;
}
skipped(e);
return this;
}
// @function disableScrollPropagation(el: HTMLElement): this
// Adds `stopPropagation` to the element's `'mousewheel'` events (plus browser variants).
function disableScrollPropagation(el) {
addOne(el, 'mousewheel', stopPropagation);
return this;
}
// @function disableClickPropagation(el: HTMLElement): this
// Adds `stopPropagation` to the element's `'click'`, `'doubleclick'`,
// `'mousedown'` and `'touchstart'` events (plus browser variants).
function disableClickPropagation(el) {
on(el, 'mousedown touchstart dblclick', stopPropagation);
addOne(el, 'click', fakeStop);
return this;
}
// @function preventDefault(ev: DOMEvent): this
// Prevents the default action of the DOM Event `ev` from happening (such as
// following a link in the href of the a element, or doing a POST request
// with page reload when a `<form>` is submitted).
// Use it inside listener functions.
function preventDefault(e) {
if (e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;
}
return this;
}
// @function stop(ev: DOMEvent): this
// Does `stopPropagation` and `preventDefault` at the same time.
function stop(e) {
preventDefault(e);
stopPropagation(e);
return this;
}
// @function getMousePosition(ev: DOMEvent, container?: HTMLElement): Point
// Gets normalized mouse position from a DOM event relative to the
// `container` (border excluded) or to the whole page if not specified.
function getMousePosition(e, container) {
if (!container) {
return new Point(e.clientX, e.clientY);
}
var scale = getScale(container),
offset = scale.boundingClientRect; // left and top values are in page scale (like the event clientX/Y)
return new Point(
// offset.left/top values are in page scale (like clientX/Y),
// whereas clientLeft/Top (border width) values are the original values (before CSS scale applies).
(e.clientX - offset.left) / scale.x - container.clientLeft,
(e.clientY - offset.top) / scale.y - container.clientTop
);
}
// Chrome on Win scrolls double the pixels as in other platforms (see #4538),
// and Firefox scrolls device pixels, not CSS pixels
var wheelPxFactor =
(win && chrome) ? 2 * window.devicePixelRatio :
gecko ? window.devicePixelRatio : 1;
// @function getWheelDelta(ev: DOMEvent): Number
// Gets normalized wheel delta from a mousewheel DOM event, in vertical
// pixels scrolled (negative if scrolling down).
// Events from pointing devices without precise scrolling are mapped to
// a best guess of 60 pixels.
function getWheelDelta(e) {
return (edge) ? e.wheelDeltaY / 2 : // Don't trust window-geometry-based delta
(e.deltaY && e.deltaMode === 0) ? -e.deltaY / wheelPxFactor : // Pixels
(e.deltaY && e.deltaMode === 1) ? -e.deltaY * 20 : // Lines
(e.deltaY && e.deltaMode === 2) ? -e.deltaY * 60 : // Pages
(e.deltaX || e.deltaZ) ? 0 : // Skip horizontal/depth wheel events
e.wheelDelta ? (e.wheelDeltaY || e.wheelDelta) / 2 : // Legacy IE pixels
(e.detail && Math.abs(e.detail) < 32765) ? -e.detail * 20 : // Legacy Moz lines
e.detail ? e.detail / -32765 * 60 : // Legacy Moz pages
0;
}
var skipEvents = {};
function fakeStop(e) {
// fakes stopPropagation by setting a special event flag, checked/reset with skipped(e)
skipEvents[e.type] = true;
}
function skipped(e) {
var events = skipEvents[e.type];
// reset when checking, as it's only used in map container and propagates outside of the map
skipEvents[e.type] = false;
return events;
}
// check if element really left/entered the event target (for mouseenter/mouseleave)
function isExternalTarget(el, e) {
var related = e.relatedTarget;
if (!related) { return true; }
try {
while (related && (related !== el)) {
related = related.parentNode;
}
} catch (err) {
return false;
}
return (related !== el);
}
var lastClick;
// this is a horrible workaround for a bug in Android where a single touch triggers two click events
function filterClick(e, handler) {
var timeStamp = (e.timeStamp || (e.originalEvent && e.originalEvent.timeStamp)),
elapsed = lastClick && (timeStamp - lastClick);
// are they closer together than 500ms yet more than 100ms?
// Android typically triggers them ~300ms apart while multiple listeners
// on the same event should be triggered far faster;
// or check if click is simulated on the element, and if it is, reject any non-simulated events
if ((elapsed && elapsed > 100 && elapsed < 500) || (e.target._simulatedClick && !e._simulated)) {
stop(e);
return;
}
lastClick = timeStamp;
handler(e);
}
var DomEvent = (Object.freeze || Object)({
on: on,
off: off,
stopPropagation: stopPropagation,
disableScrollPropagation: disableScrollPropagation,
disableClickPropagation: disableClickPropagation,
preventDefault: preventDefault,
stop: stop,
getMousePosition: getMousePosition,
getWheelDelta: getWheelDelta,
fakeStop: fakeStop,
skipped: skipped,
isExternalTarget: isExternalTarget,
addListener: on,
removeListener: off
});
/*
* @class PosAnimation
* @aka L.PosAnimation
* @inherits Evented
* Used internally for panning animations, utilizing CSS3 Transitions for modern browsers and a timer fallback for IE6-9.
*
* @example
* ```js
* var fx = new L.PosAnimation();
* fx.run(el, [300, 500], 0.5);
* ```
*
* @constructor L.PosAnimation()
* Creates a `PosAnimation` object.
*
*/
var PosAnimation = Evented.extend({
// @method run(el: HTMLElement, newPos: Point, duration?: Number, easeLinearity?: Number)
// Run an animation of a given element to a new position, optionally setting
// duration in seconds (`0.25` by default) and easing linearity factor (3rd
// argument of the [cubic bezier curve](http://cubic-bezier.com/#0,0,.5,1),
// `0.5` by default).
run: function (el, newPos, duration, easeLinearity) {
this.stop();
this._el = el;
this._inProgress = true;
this._duration = duration || 0.25;
this._easeOutPower = 1 / Math.max(easeLinearity || 0.5, 0.2);
this._startPos = getPosition(el);
this._offset = newPos.subtract(this._startPos);
this._startTime = +new Date();
// @event start: Event
// Fired when the animation starts
this.fire('start');
this._animate();
},
// @method stop()
// Stops the animation (if currently running).
stop: function () {
if (!this._inProgress) { return; }
this._step(true);
this._complete();
},
_animate: function () {
// animation loop
this._animId = requestAnimFrame(this._animate, this);
this._step();
},
_step: function (round) {
var elapsed = (+new Date()) - this._startTime,
duration = this._duration * 1000;
if (elapsed < duration) {
this._runFrame(this._easeOut(elapsed / duration), round);
} else {
this._runFrame(1);
this._complete();
}
},
_runFrame: function (progress, round) {
var pos = this._startPos.add(this._offset.multiplyBy(progress));
if (round) {
pos._round();
}
setPosition(this._el, pos);
// @event step: Event
// Fired continuously during the animation.
this.fire('step');
},
_complete: function () {
cancelAnimFrame(this._animId);
this._inProgress = false;
// @event end: Event
// Fired when the animation ends.
this.fire('end');
},
_easeOut: function (t) {
return 1 - Math.pow(1 - t, this._easeOutPower);
}
});
/*
* @class Map
* @aka L.Map
* @inherits Evented
*
* The central class of the API — it is used to create a map on a page and manipulate it.
*
* @example
*
* ```js
* // initialize the map on the "map" div with a given center and zoom
* var map = L.map('map', {
* center: [51.505, -0.09],
* zoom: 13
* });
* ```
*
*/
var Map = Evented.extend({
options: {
// @section Map State Options
// @option crs: CRS = L.CRS.EPSG3857
// The [Coordinate Reference System](#crs) to use. Don't change this if you're not
// sure what it means.
crs: EPSG3857,
// @option center: LatLng = undefined
// Initial geographic center of the map
center: undefined,
// @option zoom: Number = undefined
// Initial map zoom level
zoom: undefined,
// @option minZoom: Number = *
// Minimum zoom level of the map.
// If not specified and at least one `GridLayer` or `TileLayer` is in the map,
// the lowest of their `minZoom` options will be used instead.
minZoom: undefined,
// @option maxZoom: Number = *
// Maximum zoom level of the map.
// If not specified and at least one `GridLayer` or `TileLayer` is in the map,
// the highest of their `maxZoom` options will be used instead.
maxZoom: undefined,
// @option layers: Layer[] = []
// Array of layers that will be added to the map initially
layers: [],
// @option maxBounds: LatLngBounds = null
// When this option is set, the map restricts the view to the given
// geographical bounds, bouncing the user back if the user tries to pan
// outside the view. To set the restriction dynamically, use
// [`setMaxBounds`](#map-setmaxbounds) method.
maxBounds: undefined,
// @option renderer: Renderer = *
// The default method for drawing vector layers on the map. `L.SVG`
// or `L.Canvas` by default depending on browser support.
renderer: undefined,
// @section Animation Options
// @option zoomAnimation: Boolean = true
// Whether the map zoom animation is enabled. By default it's enabled
// in all browsers that support CSS3 Transitions except Android.
zoomAnimation: true,
// @option zoomAnimationThreshold: Number = 4
// Won't animate zoom if the zoom difference exceeds this value.
zoomAnimationThreshold: 4,
// @option fadeAnimation: Boolean = true
// Whether the tile fade animation is enabled. By default it's enabled
// in all browsers that support CSS3 Transitions except Android.
fadeAnimation: true,
// @option markerZoomAnimation: Boolean = true
// Whether markers animate their zoom with the zoom animation, if disabled
// they will disappear for the length of the animation. By default it's
// enabled in all browsers that support CSS3 Transitions except Android.
markerZoomAnimation: true,
// @option transform3DLimit: Number = 2^23
// Defines the maximum size of a CSS translation transform. The default
// value should not be changed unless a web browser positions layers in
// the wrong place after doing a large `panBy`.
transform3DLimit: 8388608, // Precision limit of a 32-bit float
// @section Interaction Options
// @option zoomSnap: Number = 1
// Forces the map's zoom level to always be a multiple of this, particularly
// right after a [`fitBounds()`](#map-fitbounds) or a pinch-zoom.
// By default, the zoom level snaps to the nearest integer; lower values
// (e.g. `0.5` or `0.1`) allow for greater granularity. A value of `0`
// means the zoom level will not be snapped after `fitBounds` or a pinch-zoom.
zoomSnap: 1,
// @option zoomDelta: Number = 1
// Controls how much the map's zoom level will change after a
// [`zoomIn()`](#map-zoomin), [`zoomOut()`](#map-zoomout), pressing `+`
// or `-` on the keyboard, or using the [zoom controls](#control-zoom).
// Values smaller than `1` (e.g. `0.5`) allow for greater granularity.
zoomDelta: 1,
// @option trackResize: Boolean = true
// Whether the map automatically handles browser window resize to update itself.
trackResize: true
},
initialize: function (id, options) { // (HTMLElement or String, Object)
options = setOptions(this, options);
// Make sure to assign internal flags at the beginning,
// to avoid inconsistent state in some edge cases.
this._handlers = [];
this._layers = {};
this._zoomBoundLayers = {};
this._sizeChanged = true;
this._initContainer(id);
this._initLayout();
// hack for https://github.com/Leaflet/Leaflet/issues/1980
this._onResize = bind(this._onResize, this);
this._initEvents();
if (options.maxBounds) {
this.setMaxBounds(options.maxBounds);
}
if (options.zoom !== undefined) {
this._zoom = this._limitZoom(options.zoom);
}
if (options.center && options.zoom !== undefined) {
this.setView(toLatLng(options.center), options.zoom, {reset: true});
}
this.callInitHooks();
// don't animate on browsers without hardware-accelerated transitions or old Android/Opera
this._zoomAnimated = TRANSITION && any3d && !mobileOpera &&
this.options.zoomAnimation;
// zoom transitions run with the same duration for all layers, so if one of transitionend events
// happens after starting zoom animation (propagating to the map pane), we know that it ended globally
if (this._zoomAnimated) {
this._createAnimProxy();
on(this._proxy, TRANSITION_END, this._catchTransitionEnd, this);
}
this._addLayers(this.options.layers);
},
// @section Methods for modifying map state
// @method setView(center: LatLng, zoom: Number, options?: Zoom/pan options): this
// Sets the view of the map (geographical center and zoom) with the given
// animation options.
setView: function (center, zoom, options) {
zoom = zoom === undefined ? this._zoom : this._limitZoom(zoom);
center = this._limitCenter(toLatLng(center), zoom, this.options.maxBounds);
options = options || {};
this._stop();
if (this._loaded && !options.reset && options !== true) {
if (options.animate !== undefined) {
options.zoom = extend({animate: options.animate}, options.zoom);
options.pan = extend({animate: options.animate, duration: options.duration}, options.pan);
}
// try animating pan or zoom
var moved = (this._zoom !== zoom) ?
this._tryAnimatedZoom && this._tryAnimatedZoom(center, zoom, options.zoom) :
this._tryAnimatedPan(center, options.pan);
if (moved) {
// prevent resize handler call, the view will refresh after animation anyway
clearTimeout(this._sizeTimer);
return this;
}
}
// animation didn't start, just reset the map view
this._resetView(center, zoom);
return this;
},
// @method setZoom(zoom: Number, options?: Zoom/pan options): this
// Sets the zoom of the map.
setZoom: function (zoom, options) {
if (!this._loaded) {
this._zoom = zoom;
return this;
}
return this.setView(this.getCenter(), zoom, {zoom: options});
},
// @method zoomIn(delta?: Number, options?: Zoom options): this
// Increases the zoom of the map by `delta` ([`zoomDelta`](#map-zoomdelta) by default).
zoomIn: function (delta, options) {
delta = delta || (any3d ? this.options.zoomDelta : 1);
return this.setZoom(this._zoom + delta, options);
},
// @method zoomOut(delta?: Number, options?: Zoom options): this
// Decreases the zoom of the map by `delta` ([`zoomDelta`](#map-zoomdelta) by default).
zoomOut: function (delta, options) {
delta = delta || (any3d ? this.options.zoomDelta : 1);
return this.setZoom(this._zoom - delta, options);
},
// @method setZoomAround(latlng: LatLng, zoom: Number, options: Zoom options): this
// Zooms the map while keeping a specified geographical point on the map
// stationary (e.g. used internally for scroll zoom and double-click zoom).
// @alternative
// @method setZoomAround(offset: Point, zoom: Number, options: Zoom options): this
// Zooms the map while keeping a specified pixel on the map (relative to the top-left corner) stationary.
setZoomAround: function (latlng, zoom, options) {
var scale = this.getZoomScale(zoom),
viewHalf = this.getSize().divideBy(2),
containerPoint = latlng instanceof Point ? latlng : this.latLngToContainerPoint(latlng),
centerOffset = containerPoint.subtract(viewHalf).multiplyBy(1 - 1 / scale),
newCenter = this.containerPointToLatLng(viewHalf.add(centerOffset));
return this.setView(newCenter, zoom, {zoom: options});
},
_getBoundsCenterZoom: function (bounds, options) {
options = options || {};
bounds = bounds.getBounds ? bounds.getBounds() : toLatLngBounds(bounds);
var paddingTL = toPoint(options.paddingTopLeft || options.padding || [0, 0]),
paddingBR = toPoint(options.paddingBottomRight || options.padding || [0, 0]),
zoom = this.getBoundsZoom(bounds, false, paddingTL.add(paddingBR));
zoom = (typeof options.maxZoom === 'number') ? Math.min(options.maxZoom, zoom) : zoom;
if (zoom === Infinity) {
return {
center: bounds.getCenter(),
zoom: zoom
};
}
var paddingOffset = paddingBR.subtract(paddingTL).divideBy(2),
swPoint = this.project(bounds.getSouthWest(), zoom),
nePoint = this.project(bounds.getNorthEast(), zoom),
center = this.unproject(swPoint.add(nePoint).divideBy(2).add(paddingOffset), zoom);
return {
center: center,
zoom: zoom
};
},
// @method fitBounds(bounds: LatLngBounds, options?: fitBounds options): this
// Sets a map view that contains the given geographical bounds with the
// maximum zoom level possible.
fitBounds: function (bounds, options) {
bounds = toLatLngBounds(bounds);
if (!bounds.isValid()) {
throw new Error('Bounds are not valid.');
}
var target = this._getBoundsCenterZoom(bounds, options);
return this.setView(target.center, target.zoom, options);
},
// @method fitWorld(options?: fitBounds options): this
// Sets a map view that mostly contains the whole world with the maximum
// zoom level possible.
fitWorld: function (options) {
return this.fitBounds([[-90, -180], [90, 180]], options);
},
// @method panTo(latlng: LatLng, options?: Pan options): this
// Pans the map to a given center.
panTo: function (center, options) { // (LatLng)
return this.setView(center, this._zoom, {pan: options});
},
// @method panBy(offset: Point, options?: Pan options): this
// Pans the map by a given number of pixels (animated).
panBy: function (offset, options) {
offset = toPoint(offset).round();
options = options || {};
if (!offset.x && !offset.y) {
return this.fire('moveend');
}
// If we pan too far, Chrome gets issues with tiles
// and makes them disappear or appear in the wrong place (slightly offset) #2602
if (options.animate !== true && !this.getSize().contains(offset)) {
this._resetView(this.unproject(this.project(this.getCenter()).add(offset)), this.getZoom());
return this;
}
if (!this._panAnim) {
this._panAnim = new PosAnimation();
this._panAnim.on({
'step': this._onPanTransitionStep,
'end': this._onPanTransitionEnd
}, this);
}
// don't fire movestart if animating inertia
if (!options.noMoveStart) {
this.fire('movestart');
}
// animate pan unless animate: false specified
if (options.animate !== false) {
addClass(this._mapPane, 'leaflet-pan-anim');
var newPos = this._getMapPanePos().subtract(offset).round();
this._panAnim.run(this._mapPane, newPos, options.duration || 0.25, options.easeLinearity);
} else {
this._rawPanBy(offset);
this.fire('move').fire('moveend');
}
return this;
},
// @method flyTo(latlng: LatLng, zoom?: Number, options?: Zoom/pan options): this
// Sets the view of the map (geographical center and zoom) performing a smooth
// pan-zoom animation.
flyTo: function (targetCenter, targetZoom, options) {
options = options || {};
if (options.animate === false || !any3d) {
return this.setView(targetCenter, targetZoom, options);
}
this._stop();
var from = this.project(this.getCenter()),
to = this.project(targetCenter),
size = this.getSize(),
startZoom = this._zoom;
targetCenter = toLatLng(targetCenter);
targetZoom = targetZoom === undefined ? startZoom : targetZoom;
var w0 = Math.max(size.x, size.y),
w1 = w0 * this.getZoomScale(startZoom, targetZoom),
u1 = (to.distanceTo(from)) || 1,
rho = 1.42,
rho2 = rho * rho;
function r(i) {
var s1 = i ? -1 : 1,
s2 = i ? w1 : w0,
t1 = w1 * w1 - w0 * w0 + s1 * rho2 * rho2 * u1 * u1,
b1 = 2 * s2 * rho2 * u1,
b = t1 / b1,
sq = Math.sqrt(b * b + 1) - b;
// workaround for floating point precision bug when sq = 0, log = -Infinite,
// thus triggering an infinite loop in flyTo
var log = sq < 0.000000001 ? -18 : Math.log(sq);
return log;
}
function sinh(n) { return (Math.exp(n) - Math.exp(-n)) / 2; }
function cosh(n) { return (Math.exp(n) + Math.exp(-n)) / 2; }
function tanh(n) { return sinh(n) / cosh(n); }
var r0 = r(0);
function w(s) { return w0 * (cosh(r0) / cosh(r0 + rho * s)); }
function u(s) { return w0 * (cosh(r0) * tanh(r0 + rho * s) - sinh(r0)) / rho2; }
function easeOut(t) { return 1 - Math.pow(1 - t, 1.5); }
var start = Date.now(),
S = (r(1) - r0) / rho,
duration = options.duration ? 1000 * options.duration : 1000 * S * 0.8;
function frame() {
var t = (Date.now() - start) / duration,
s = easeOut(t) * S;
if (t <= 1) {
this._flyToFrame = requestAnimFrame(frame, this);
this._move(
this.unproject(from.add(to.subtract(from).multiplyBy(u(s) / u1)), startZoom),
this.getScaleZoom(w0 / w(s), startZoom),
{flyTo: true});
} else {
this
._move(targetCenter, targetZoom)
._moveEnd(true);
}
}
this._moveStart(true, options.noMoveStart);
frame.call(this);
return this;
},
// @method flyToBounds(bounds: LatLngBounds, options?: fitBounds options): this
// Sets the view of the map with a smooth animation like [`flyTo`](#map-flyto),
// but takes a bounds parameter like [`fitBounds`](#map-fitbounds).
flyToBounds: function (bounds, options) {
var target = this._getBoundsCenterZoom(bounds, options);
return this.flyTo(target.center, target.zoom, options);
},
// @method setMaxBounds(bounds: Bounds): this
// Restricts the map view to the given bounds (see the [maxBounds](#map-maxbounds) option).
setMaxBounds: function (bounds) {
bounds = toLatLngBounds(bounds);
if (!bounds.isValid()) {
this.options.maxBounds = null;
return this.off('moveend', this._panInsideMaxBounds);
} else if (this.options.maxBounds) {
this.off('moveend', this._panInsideMaxBounds);
}
this.options.maxBounds = bounds;
if (this._loaded) {
this._panInsideMaxBounds();
}
return this.on('moveend', this._panInsideMaxBounds);
},
// @method setMinZoom(zoom: Number): this
// Sets the lower limit for the available zoom levels (see the [minZoom](#map-minzoom) option).
setMinZoom: function (zoom) {
var oldZoom = this.options.minZoom;
this.options.minZoom = zoom;
if (this._loaded && oldZoom !== zoom) {
this.fire('zoomlevelschange');
if (this.getZoom() < this.options.minZoom) {
return this.setZoom(zoom);
}
}
return this;
},
// @method setMaxZoom(zoom: Number): this
// Sets the upper limit for the available zoom levels (see the [maxZoom](#map-maxzoom) option).
setMaxZoom: function (zoom) {
var oldZoom = this.options.maxZoom;
this.options.maxZoom = zoom;
if (this._loaded && oldZoom !== zoom) {
this.fire('zoomlevelschange');
if (this.getZoom() > this.options.maxZoom) {
return this.setZoom(zoom);
}
}
return this;
},
// @method panInsideBounds(bounds: LatLngBounds, options?: Pan options): this
// Pans the map to the closest view that would lie inside the given bounds (if it's not already), controlling the animation using the options specific, if any.
panInsideBounds: function (bounds, options) {
this._enforcingBounds = true;
var center = this.getCenter(),
newCenter = this._limitCenter(center, this._zoom, toLatLngBounds(bounds));
if (!center.equals(newCenter)) {
this.panTo(newCenter, options);
}
this._enforcingBounds = false;
return this;
},
// @method panInside(latlng: LatLng, options?: options): this
// Pans the map the minimum amount to make the `latlng` visible. Use
// `padding`, `paddingTopLeft` and `paddingTopRight` options to fit
// the display to more restricted bounds, like [`fitBounds`](#map-fitbounds).
// If `latlng` is already within the (optionally padded) display bounds,
// the map will not be panned.
panInside: function (latlng, options) {
options = options || {};
var paddingTL = toPoint(options.paddingTopLeft || options.padding || [0, 0]),
paddingBR = toPoint(options.paddingBottomRight || options.padding || [0, 0]),
center = this.getCenter(),
pixelCenter = this.project(center),
pixelPoint = this.project(latlng),
pixelBounds = this.getPixelBounds(),
halfPixelBounds = pixelBounds.getSize().divideBy(2),
paddedBounds = toBounds([pixelBounds.min.add(paddingTL), pixelBounds.max.subtract(paddingBR)]);
if (!paddedBounds.contains(pixelPoint)) {
this._enforcingBounds = true;
var diff = pixelCenter.subtract(pixelPoint),
newCenter = toPoint(pixelPoint.x + diff.x, pixelPoint.y + diff.y);
if (pixelPoint.x < paddedBounds.min.x || pixelPoint.x > paddedBounds.max.x) {
newCenter.x = pixelCenter.x - diff.x;
if (diff.x > 0) {
newCenter.x += halfPixelBounds.x - paddingTL.x;
} else {
newCenter.x -= halfPixelBounds.x - paddingBR.x;
}
}
if (pixelPoint.y < paddedBounds.min.y || pixelPoint.y > paddedBounds.max.y) {
newCenter.y = pixelCenter.y - diff.y;
if (diff.y > 0) {
newCenter.y += halfPixelBounds.y - paddingTL.y;
} else {
newCenter.y -= halfPixelBounds.y - paddingBR.y;
}
}
this.panTo(this.unproject(newCenter), options);
this._enforcingBounds = false;
}
return this;
},
// @method invalidateSize(options: Zoom/pan options): this
// Checks if the map container size changed and updates the map if so —
// call it after you've changed the map size dynamically, also animating
// pan by default. If `options.pan` is `false`, panning will not occur.
// If `options.debounceMoveend` is `true`, it will delay `moveend` event so
// that it doesn't happen often even if the method is called many
// times in a row.
// @alternative
// @method invalidateSize(animate: Boolean): this
// Checks if the map container size changed and updates the map if so —
// call it after you've changed the map size dynamically, also animating
// pan by default.
invalidateSize: function (options) {
if (!this._loaded) { return this; }
options = extend({
animate: false,
pan: true
}, options === true ? {animate: true} : options);
var oldSize = this.getSize();
this._sizeChanged = true;
this._lastCenter = null;
var newSize = this.getSize(),
oldCenter = oldSize.divideBy(2).round(),
newCenter = newSize.divideBy(2).round(),
offset = oldCenter.subtract(newCenter);
if (!offset.x && !offset.y) { return this; }
if (options.animate && options.pan) {
this.panBy(offset);
} else {
if (options.pan) {
this._rawPanBy(offset);
}
this.fire('move');
if (options.debounceMoveend) {
clearTimeout(this._sizeTimer);
this._sizeTimer = setTimeout(bind(this.fire, this, 'moveend'), 200);
} else {
this.fire('moveend');
}
}
// @section Map state change events
// @event resize: ResizeEvent
// Fired when the map is resized.
return this.fire('resize', {
oldSize: oldSize,
newSize: newSize
});
},
// @section Methods for modifying map state
// @method stop(): this
// Stops the currently running `panTo` or `flyTo` animation, if any.
stop: function () {
this.setZoom(this._limitZoom(this._zoom));
if (!this.options.zoomSnap) {
this.fire('viewreset');
}
return this._stop();
},
// @section Geolocation methods
// @method locate(options?: Locate options): this
// Tries to locate the user using the Geolocation API, firing a [`locationfound`](#map-locationfound)
// event with location data on success or a [`locationerror`](#map-locationerror) event on failure,
// and optionally sets the map view to the user's location with respect to
// detection accuracy (or to the world view if geolocation failed).
// Note that, if your page doesn't use HTTPS, this method will fail in
// modern browsers ([Chrome 50 and newer](https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-powerful-features-on-insecure-origins))
// See `Locate options` for more details.
locate: function (options) {
options = this._locateOptions = extend({
timeout: 10000,
watch: false
// setView: false
// maxZoom: <Number>
// maximumAge: 0
// enableHighAccuracy: false
}, options);
if (!('geolocation' in navigator)) {
this._handleGeolocationError({
code: 0,
message: 'Geolocation not supported.'
});
return this;
}
var onResponse = bind(this._handleGeolocationResponse, this),
onError = bind(this._handleGeolocationError, this);
if (options.watch) {
this._locationWatchId =
navigator.geolocation.watchPosition(onResponse, onError, options);
} else {
navigator.geolocation.getCurrentPosition(onResponse, onError, options);
}
return this;
},
// @method stopLocate(): this
// Stops watching location previously initiated by `map.locate({watch: true})`
// and aborts resetting the map view if map.locate was called with
// `{setView: true}`.
stopLocate: function () {
if (navigator.geolocation && navigator.geolocation.clearWatch) {
navigator.geolocation.clearWatch(this._locationWatchId);
}
if (this._locateOptions) {
this._locateOptions.setView = false;
}
return this;
},
_handleGeolocationError: function (error) {
var c = error.code,
message = error.message ||
(c === 1 ? 'permission denied' :
(c === 2 ? 'position unavailable' : 'timeout'));
if (this._locateOptions.setView && !this._loaded) {
this.fitWorld();
}
// @section Location events
// @event locationerror: ErrorEvent
// Fired when geolocation (using the [`locate`](#map-locate) method) failed.
this.fire('locationerror', {
code: c,
message: 'Geolocation error: ' + message + '.'
});
},
_handleGeolocationResponse: function (pos) {
var lat = pos.coords.latitude,
lng = pos.coords.longitude,
latlng = new LatLng(lat, lng),
bounds = latlng.toBounds(pos.coords.accuracy * 2),
options = this._locateOptions;
if (options.setView) {
var zoom = this.getBoundsZoom(bounds);
this.setView(latlng, options.maxZoom ? Math.min(zoom, options.maxZoom) : zoom);
}
var data = {
latlng: latlng,
bounds: bounds,
timestamp: pos.timestamp
};
for (var i in pos.coords) {
if (typeof pos.coords[i] === 'number') {
data[i] = pos.coords[i];
}
}
// @event locationfound: LocationEvent
// Fired when geolocation (using the [`locate`](#map-locate) method)
// went successfully.
this.fire('locationfound', data);
},
// TODO Appropriate docs section?
// @section Other Methods
// @method addHandler(name: String, HandlerClass: Function): this
// Adds a new `Handler` to the map, given its name and constructor function.
addHandler: function (name, HandlerClass) {
if (!HandlerClass) { return this; }
var handler = this[name] = new HandlerClass(this);
this._handlers.push(handler);
if (this.options[name]) {
handler.enable();
}
return this;
},
// @method remove(): this
// Destroys the map and clears all related event listeners.
remove: function () {
this._initEvents(true);
if (this._containerId !== this._container._leaflet_id) {
throw new Error('Map container is being reused by another instance');
}
try {
// throws error in IE6-8
delete this._container._leaflet_id;
delete this._containerId;
} catch (e) {
/*eslint-disable */
this._container._leaflet_id = undefined;
/* eslint-enable */
this._containerId = undefined;
}
if (this._locationWatchId !== undefined) {
this.stopLocate();
}
this._stop();
remove(this._mapPane);
if (this._clearControlPos) {
this._clearControlPos();
}
if (this._resizeRequest) {
cancelAnimFrame(this._resizeRequest);
this._resizeRequest = null;
}
this._clearHandlers();
if (this._loaded) {
// @section Map state change events
// @event unload: Event
// Fired when the map is destroyed with [remove](#map-remove) method.
this.fire('unload');
}
var i;
for (i in this._layers) {
this._layers[i].remove();
}
for (i in this._panes) {
remove(this._panes[i]);
}
this._layers = [];
this._panes = [];
delete this._mapPane;
delete this._renderer;
return this;
},
// @section Other Methods
// @method createPane(name: String, container?: HTMLElement): HTMLElement
// Creates a new [map pane](#map-pane) with the given name if it doesn't exist already,
// then returns it. The pane is created as a child of `container`, or
// as a child of the main map pane if not set.
createPane: function (name, container) {
var className = 'leaflet-pane' + (name ? ' leaflet-' + name.replace('Pane', '') + '-pane' : ''),
pane = create$1('div', className, container || this._mapPane);
if (name) {
this._panes[name] = pane;
}
return pane;
},
// @section Methods for Getting Map State
// @method getCenter(): LatLng
// Returns the geographical center of the map view
getCenter: function () {
this._checkIfLoaded();
if (this._lastCenter && !this._moved()) {
return this._lastCenter;
}
return this.layerPointToLatLng(this._getCenterLayerPoint());
},
// @method getZoom(): Number
// Returns the current zoom level of the map view
getZoom: function () {
return this._zoom;
},
// @method getBounds(): LatLngBounds
// Returns the geographical bounds visible in the current map view
getBounds: function () {
var bounds = this.getPixelBounds(),
sw = this.unproject(bounds.getBottomLeft()),
ne = this.unproject(bounds.getTopRight());
return new LatLngBounds(sw, ne);
},
// @method getMinZoom(): Number
// Returns the minimum zoom level of the map (if set in the `minZoom` option of the map or of any layers), or `0` by default.
getMinZoom: function () {
return this.options.minZoom === undefined ? this._layersMinZoom || 0 : this.options.minZoom;
},
// @method getMaxZoom(): Number
// Returns the maximum zoom level of the map (if set in the `maxZoom` option of the map or of any layers).
getMaxZoom: function () {
return this.options.maxZoom === undefined ?
(this._layersMaxZoom === undefined ? Infinity : this._layersMaxZoom) :
this.options.maxZoom;
},
// @method getBoundsZoom(bounds: LatLngBounds, inside?: Boolean, padding?: Point): Number
// Returns the maximum zoom level on which the given bounds fit to the map
// view in its entirety. If `inside` (optional) is set to `true`, the method
// instead returns the minimum zoom level on which the map view fits into
// the given bounds in its entirety.
getBoundsZoom: function (bounds, inside, padding) { // (LatLngBounds[, Boolean, Point]) -> Number
bounds = toLatLngBounds(bounds);
padding = toPoint(padding || [0, 0]);
var zoom = this.getZoom() || 0,
min = this.getMinZoom(),
max = this.getMaxZoom(),
nw = bounds.getNorthWest(),
se = bounds.getSouthEast(),
size = this.getSize().subtract(padding),
boundsSize = toBounds(this.project(se, zoom), this.project(nw, zoom)).getSize(),
snap = any3d ? this.options.zoomSnap : 1,
scalex = size.x / boundsSize.x,
scaley = size.y / boundsSize.y,
scale = inside ? Math.max(scalex, scaley) : Math.min(scalex, scaley);
zoom = this.getScaleZoom(scale, zoom);
if (snap) {
zoom = Math.round(zoom / (snap / 100)) * (snap / 100); // don't jump if within 1% of a snap level
zoom = inside ? Math.ceil(zoom / snap) * snap : Math.floor(zoom / snap) * snap;
}
return Math.max(min, Math.min(max, zoom));
},
// @method getSize(): Point
// Returns the current size of the map container (in pixels).
getSize: function () {
if (!this._size || this._sizeChanged) {
this._size = new Point(
this._container.clientWidth || 0,
this._container.clientHeight || 0);
this._sizeChanged = false;
}
return this._size.clone();
},
// @method getPixelBounds(): Bounds
// Returns the bounds of the current map view in projected pixel
// coordinates (sometimes useful in layer and overlay implementations).
getPixelBounds: function (center, zoom) {
var topLeftPoint = this._getTopLeftPoint(center, zoom);
return new Bounds(topLeftPoint, topLeftPoint.add(this.getSize()));
},
// TODO: Check semantics - isn't the pixel origin the 0,0 coord relative to
// the map pane? "left point of the map layer" can be confusing, specially
// since there can be negative offsets.
// @method getPixelOrigin(): Point
// Returns the projected pixel coordinates of the top left point of
// the map layer (useful in custom layer and overlay implementations).
getPixelOrigin: function () {
this._checkIfLoaded();
return this._pixelOrigin;
},
// @method getPixelWorldBounds(zoom?: Number): Bounds
// Returns the world's bounds in pixel coordinates for zoom level `zoom`.
// If `zoom` is omitted, the map's current zoom level is used.
getPixelWorldBounds: function (zoom) {
return this.options.crs.getProjectedBounds(zoom === undefined ? this.getZoom() : zoom);
},
// @section Other Methods
// @method getPane(pane: String|HTMLElement): HTMLElement
// Returns a [map pane](#map-pane), given its name or its HTML element (its identity).
getPane: function (pane) {
return typeof pane === 'string' ? this._panes[pane] : pane;
},
// @method getPanes(): Object
// Returns a plain object containing the names of all [panes](#map-pane) as keys and
// the panes as values.
getPanes: function () {
return this._panes;
},
// @method getContainer: HTMLElement
// Returns the HTML element that contains the map.
getContainer: function () {
return this._container;
},
// @section Conversion Methods
// @method getZoomScale(toZoom: Number, fromZoom: Number): Number
// Returns the scale factor to be applied to a map transition from zoom level
// `fromZoom` to `toZoom`. Used internally to help with zoom animations.
getZoomScale: function (toZoom, fromZoom) {
// TODO replace with universal implementation after refactoring projections
var crs = this.options.crs;
fromZoom = fromZoom === undefined ? this._zoom : fromZoom;
return crs.scale(toZoom) / crs.scale(fromZoom);
},
// @method getScaleZoom(scale: Number, fromZoom: Number): Number
// Returns the zoom level that the map would end up at, if it is at `fromZoom`
// level and everything is scaled by a factor of `scale`. Inverse of
// [`getZoomScale`](#map-getZoomScale).
getScaleZoom: function (scale, fromZoom) {
var crs = this.options.crs;
fromZoom = fromZoom === undefined ? this._zoom : fromZoom;
var zoom = crs.zoom(scale * crs.scale(fromZoom));
return isNaN(zoom) ? Infinity : zoom;
},
// @method project(latlng: LatLng, zoom: Number): Point
// Projects a geographical coordinate `LatLng` according to the projection
// of the map's CRS, then scales it according to `zoom` and the CRS's
// `Transformation`. The result is pixel coordinate relative to
// the CRS origin.
project: function (latlng, zoom) {
zoom = zoom === undefined ? this._zoom : zoom;
return this.options.crs.latLngToPoint(toLatLng(latlng), zoom);
},
// @method unproject(point: Point, zoom: Number): LatLng
// Inverse of [`project`](#map-project).
unproject: function (point, zoom) {
zoom = zoom === undefined ? this._zoom : zoom;
return this.options.crs.pointToLatLng(toPoint(point), zoom);
},
// @method layerPointToLatLng(point: Point): LatLng
// Given a pixel coordinate relative to the [origin pixel](#map-getpixelorigin),
// returns the corresponding geographical coordinate (for the current zoom level).
layerPointToLatLng: function (point) {
var projectedPoint = toPoint(point).add(this.getPixelOrigin());
return this.unproject(projectedPoint);
},
// @method latLngToLayerPoint(latlng: LatLng): Point
// Given a geographical coordinate, returns the corresponding pixel coordinate
// relative to the [origin pixel](#map-getpixelorigin).
latLngToLayerPoint: function (latlng) {
var projectedPoint = this.project(toLatLng(latlng))._round();
return projectedPoint._subtract(this.getPixelOrigin());
},
// @method wrapLatLng(latlng: LatLng): LatLng
// Returns a `LatLng` where `lat` and `lng` has been wrapped according to the
// map's CRS's `wrapLat` and `wrapLng` properties, if they are outside the
// CRS's bounds.
// By default this means longitude is wrapped around the dateline so its
// value is between -180 and +180 degrees.
wrapLatLng: function (latlng) {
return this.options.crs.wrapLatLng(toLatLng(latlng));
},
// @method wrapLatLngBounds(bounds: LatLngBounds): LatLngBounds
// Returns a `LatLngBounds` with the same size as the given one, ensuring that
// its center is within the CRS's bounds.
// By default this means the center longitude is wrapped around the dateline so its
// value is between -180 and +180 degrees, and the majority of the bounds
// overlaps the CRS's bounds.
wrapLatLngBounds: function (latlng) {
return this.options.crs.wrapLatLngBounds(toLatLngBounds(latlng));
},
// @method distance(latlng1: LatLng, latlng2: LatLng): Number
// Returns the distance between two geographical coordinates according to
// the map's CRS. By default this measures distance in meters.
distance: function (latlng1, latlng2) {
return this.options.crs.distance(toLatLng(latlng1), toLatLng(latlng2));
},
// @method containerPointToLayerPoint(point: Point): Point
// Given a pixel coordinate relative to the map container, returns the corresponding
// pixel coordinate relative to the [origin pixel](#map-getpixelorigin).
containerPointToLayerPoint: function (point) { // (Point)
return toPoint(point).subtract(this._getMapPanePos());
},
// @method layerPointToContainerPoint(point: Point): Point
// Given a pixel coordinate relative to the [origin pixel](#map-getpixelorigin),
// returns the corresponding pixel coordinate relative to the map container.
layerPointToContainerPoint: function (point) { // (Point)
return toPoint(point).add(this._getMapPanePos());
},
// @method containerPointToLatLng(point: Point): LatLng
// Given a pixel coordinate relative to the map container, returns
// the corresponding geographical coordinate (for the current zoom level).
containerPointToLatLng: function (point) {
var layerPoint = this.containerPointToLayerPoint(toPoint(point));
return this.layerPointToLatLng(layerPoint);
},
// @method latLngToContainerPoint(latlng: LatLng): Point
// Given a geographical coordinate, returns the corresponding pixel coordinate
// relative to the map container.
latLngToContainerPoint: function (latlng) {
return this.layerPointToContainerPoint(this.latLngToLayerPoint(toLatLng(latlng)));
},
// @method mouseEventToContainerPoint(ev: MouseEvent): Point
// Given a MouseEvent object, returns the pixel coordinate relative to the
// map container where the event took place.
mouseEventToContainerPoint: function (e) {
return getMousePosition(e, this._container);
},
// @method mouseEventToLayerPoint(ev: MouseEvent): Point
// Given a MouseEvent object, returns the pixel coordinate relative to
// the [origin pixel](#map-getpixelorigin) where the event took place.
mouseEventToLayerPoint: function (e) {
return this.containerPointToLayerPoint(this.mouseEventToContainerPoint(e));
},
// @method mouseEventToLatLng(ev: MouseEvent): LatLng
// Given a MouseEvent object, returns geographical coordinate where the
// event took place.
mouseEventToLatLng: function (e) { // (MouseEvent)
return this.layerPointToLatLng(this.mouseEventToLayerPoint(e));
},
// map initialization methods
_initContainer: function (id) {
var container = this._container = get(id);
if (!container) {
throw new Error('Map container not found.');
} else if (container._leaflet_id) {
throw new Error('Map container is already initialized.');
}
on(container, 'scroll', this._onScroll, this);
this._containerId = stamp(container);
},
_initLayout: function () {
var container = this._container;
this._fadeAnimated = this.options.fadeAnimation && any3d;
addClass(container, 'leaflet-container' +
(touch ? ' leaflet-touch' : '') +
(retina ? ' leaflet-retina' : '') +
(ielt9 ? ' leaflet-oldie' : '') +
(safari ? ' leaflet-safari' : '') +
(this._fadeAnimated ? ' leaflet-fade-anim' : ''));
var position = getStyle(container, 'position');
if (position !== 'absolute' && position !== 'relative' && position !== 'fixed') {
container.style.position = 'relative';
}
this._initPanes();
if (this._initControlPos) {
this._initControlPos();
}
},
_initPanes: function () {
var panes = this._panes = {};
this._paneRenderers = {};
// @section
//
// Panes are DOM elements used to control the ordering of layers on the map. You
// can access panes with [`map.getPane`](#map-getpane) or
// [`map.getPanes`](#map-getpanes) methods. New panes can be created with the
// [`map.createPane`](#map-createpane) method.
//
// Every map has the following default panes that differ only in zIndex.
//
// @pane mapPane: HTMLElement = 'auto'
// Pane that contains all other map panes
this._mapPane = this.createPane('mapPane', this._container);
setPosition(this._mapPane, new Point(0, 0));
// @pane tilePane: HTMLElement = 200
// Pane for `GridLayer`s and `TileLayer`s
this.createPane('tilePane');
// @pane overlayPane: HTMLElement = 400
// Pane for vectors (`Path`s, like `Polyline`s and `Polygon`s), `ImageOverlay`s and `VideoOverlay`s
this.createPane('shadowPane');
// @pane shadowPane: HTMLElement = 500
// Pane for overlay shadows (e.g. `Marker` shadows)
this.createPane('overlayPane');
// @pane markerPane: HTMLElement = 600
// Pane for `Icon`s of `Marker`s
this.createPane('markerPane');
// @pane tooltipPane: HTMLElement = 650
// Pane for `Tooltip`s.
this.createPane('tooltipPane');
// @pane popupPane: HTMLElement = 700
// Pane for `Popup`s.
this.createPane('popupPane');
if (!this.options.markerZoomAnimation) {
addClass(panes.markerPane, 'leaflet-zoom-hide');
addClass(panes.shadowPane, 'leaflet-zoom-hide');
}
},
// private methods that modify map state
// @section Map state change events
_resetView: function (center, zoom) {
setPosition(this._mapPane, new Point(0, 0));
var loading = !this._loaded;
this._loaded = true;
zoom = this._limitZoom(zoom);
this.fire('viewprereset');
var zoomChanged = this._zoom !== zoom;
this
._moveStart(zoomChanged, false)
._move(center, zoom)
._moveEnd(zoomChanged);
// @event viewreset: Event
// Fired when the map needs to redraw its content (this usually happens
// on map zoom or load). Very useful for creating custom overlays.
this.fire('viewreset');
// @event load: Event
// Fired when the map is initialized (when its center and zoom are set
// for the first time).
if (loading) {
this.fire('load');
}
},
_moveStart: function (zoomChanged, noMoveStart) {
// @event zoomstart: Event
// Fired when the map zoom is about to change (e.g. before zoom animation).
// @event movestart: Event
// Fired when the view of the map starts changing (e.g. user starts dragging the map).
if (zoomChanged) {
this.fire('zoomstart');
}
if (!noMoveStart) {
this.fire('movestart');
}
return this;
},
_move: function (center, zoom, data) {
if (zoom === undefined) {
zoom = this._zoom;
}
var zoomChanged = this._zoom !== zoom;
this._zoom = zoom;
this._lastCenter = center;
this._pixelOrigin = this._getNewPixelOrigin(center);
// @event zoom: Event
// Fired repeatedly during any change in zoom level, including zoom
// and fly animations.
if (zoomChanged || (data && data.pinch)) { // Always fire 'zoom' if pinching because #3530
this.fire('zoom', data);
}
// @event move: Event
// Fired repeatedly during any movement of the map, including pan and
// fly animations.
return this.fire('move', data);
},
_moveEnd: function (zoomChanged) {
// @event zoomend: Event
// Fired when the map has changed, after any animations.
if (zoomChanged) {
this.fire('zoomend');
}
// @event moveend: Event
// Fired when the center of the map stops changing (e.g. user stopped
// dragging the map).
return this.fire('moveend');
},
_stop: function () {
cancelAnimFrame(this._flyToFrame);
if (this._panAnim) {
this._panAnim.stop();
}
return this;
},
_rawPanBy: function (offset) {
setPosition(this._mapPane, this._getMapPanePos().subtract(offset));
},
_getZoomSpan: function () {
return this.getMaxZoom() - this.getMinZoom();
},
_panInsideMaxBounds: function () {
if (!this._enforcingBounds) {
this.panInsideBounds(this.options.maxBounds);
}
},
_checkIfLoaded: function () {
if (!this._loaded) {
throw new Error('Set map center and zoom first.');
}
},
// DOM event handling
// @section Interaction events
_initEvents: function (remove$$1) {
this._targets = {};
this._targets[stamp(this._container)] = this;
var onOff = remove$$1 ? off : on;
// @event click: MouseEvent
// Fired when the user clicks (or taps) the map.
// @event dblclick: MouseEvent
// Fired when the user double-clicks (or double-taps) the map.
// @event mousedown: MouseEvent
// Fired when the user pushes the mouse button on the map.
// @event mouseup: MouseEvent
// Fired when the user releases the mouse button on the map.
// @event mouseover: MouseEvent
// Fired when the mouse enters the map.
// @event mouseout: MouseEvent
// Fired when the mouse leaves the map.
// @event mousemove: MouseEvent
// Fired while the mouse moves over the map.
// @event contextmenu: MouseEvent
// Fired when the user pushes the right mouse button on the map, prevents
// default browser context menu from showing if there are listeners on
// this event. Also fired on mobile when the user holds a single touch
// for a second (also called long press).
// @event keypress: KeyboardEvent
// Fired when the user presses a key from the keyboard that produces a character value while the map is focused.
// @event keydown: KeyboardEvent
// Fired when the user presses a key from the keyboard while the map is focused. Unlike the `keypress` event,
// the `keydown` event is fired for keys that produce a character value and for keys
// that do not produce a character value.
// @event keyup: KeyboardEvent
// Fired when the user releases a key from the keyboard while the map is focused.
onOff(this._container, 'click dblclick mousedown mouseup ' +
'mouseover mouseout mousemove contextmenu keypress keydown keyup', this._handleDOMEvent, this);
if (this.options.trackResize) {
onOff(window, 'resize', this._onResize, this);
}
if (any3d && this.options.transform3DLimit) {
(remove$$1 ? this.off : this.on).call(this, 'moveend', this._onMoveEnd);
}
},
_onResize: function () {
cancelAnimFrame(this._resizeRequest);
this._resizeRequest = requestAnimFrame(
function () { this.invalidateSize({debounceMoveend: true}); }, this);
},
_onScroll: function () {
this._container.scrollTop = 0;
this._container.scrollLeft = 0;
},
_onMoveEnd: function () {
var pos = this._getMapPanePos();
if (Math.max(Math.abs(pos.x), Math.abs(pos.y)) >= this.options.transform3DLimit) {
// https://bugzilla.mozilla.org/show_bug.cgi?id=1203873 but Webkit also have
// a pixel offset on very high values, see: http://jsfiddle.net/dg6r5hhb/
this._resetView(this.getCenter(), this.getZoom());
}
},
_findEventTargets: function (e, type) {
var targets = [],
target,
isHover = type === 'mouseout' || type === 'mouseover',
src = e.target || e.srcElement,
dragging = false;
while (src) {
target = this._targets[stamp(src)];
if (target && (type === 'click' || type === 'preclick') && !e._simulated && this._draggableMoved(target)) {
// Prevent firing click after you just dragged an object.
dragging = true;
break;
}
if (target && target.listens(type, true)) {
if (isHover && !isExternalTarget(src, e)) { break; }
targets.push(target);
if (isHover) { break; }
}
if (src === this._container) { break; }
src = src.parentNode;
}
if (!targets.length && !dragging && !isHover && isExternalTarget(src, e)) {
targets = [this];
}
return targets;
},
_handleDOMEvent: function (e) {
if (!this._loaded || skipped(e)) { return; }
var type = e.type;
if (type === 'mousedown' || type === 'keypress' || type === 'keyup' || type === 'keydown') {
// prevents outline when clicking on keyboard-focusable element
preventOutline(e.target || e.srcElement);
}
this._fireDOMEvent(e, type);
},
_mouseEvents: ['click', 'dblclick', 'mouseover', 'mouseout', 'contextmenu'],
_fireDOMEvent: function (e, type, targets) {
if (e.type === 'click') {
// Fire a synthetic 'preclick' event which propagates up (mainly for closing popups).
// @event preclick: MouseEvent
// Fired before mouse click on the map (sometimes useful when you
// want something to happen on click before any existing click
// handlers start running).
var synth = extend({}, e);
synth.type = 'preclick';
this._fireDOMEvent(synth, synth.type, targets);
}
if (e._stopped) { return; }
// Find the layer the event is propagating from and its parents.
targets = (targets || []).concat(this._findEventTargets(e, type));
if (!targets.length) { return; }
var target = targets[0];
if (type === 'contextmenu' && target.listens(type, true)) {
preventDefault(e);
}
var data = {
originalEvent: e
};
if (e.type !== 'keypress' && e.type !== 'keydown' && e.type !== 'keyup') {
var isMarker = target.getLatLng && (!target._radius || target._radius <= 10);
data.containerPoint = isMarker ?
this.latLngToContainerPoint(target.getLatLng()) : this.mouseEventToContainerPoint(e);
data.layerPoint = this.containerPointToLayerPoint(data.containerPoint);
data.latlng = isMarker ? target.getLatLng() : this.layerPointToLatLng(data.layerPoint);
}
for (var i = 0; i < targets.length; i++) {
targets[i].fire(type, data, true);
if (data.originalEvent._stopped ||
(targets[i].options.bubblingMouseEvents === false && indexOf(this._mouseEvents, type) !== -1)) { return; }
}
},
_draggableMoved: function (obj) {
obj = obj.dragging && obj.dragging.enabled() ? obj : this;
return (obj.dragging && obj.dragging.moved()) || (this.boxZoom && this.boxZoom.moved());
},
_clearHandlers: function () {
for (var i = 0, len = this._handlers.length; i < len; i++) {
this._handlers[i].disable();
}
},
// @section Other Methods
// @method whenReady(fn: Function, context?: Object): this
// Runs the given function `fn` when the map gets initialized with
// a view (center and zoom) and at least one layer, or immediately
// if it's already initialized, optionally passing a function context.
whenReady: function (callback, context) {
if (this._loaded) {
callback.call(context || this, {target: this});
} else {
this.on('load', callback, context);
}
return this;
},
// private methods for getting map state
_getMapPanePos: function () {
return getPosition(this._mapPane) || new Point(0, 0);
},
_moved: function () {
var pos = this._getMapPanePos();
return pos && !pos.equals([0, 0]);
},
_getTopLeftPoint: function (center, zoom) {
var pixelOrigin = center && zoom !== undefined ?
this._getNewPixelOrigin(center, zoom) :
this.getPixelOrigin();
return pixelOrigin.subtract(this._getMapPanePos());
},
_getNewPixelOrigin: function (center, zoom) {
var viewHalf = this.getSize()._divideBy(2);
return this.project(center, zoom)._subtract(viewHalf)._add(this._getMapPanePos())._round();
},
_latLngToNewLayerPoint: function (latlng, zoom, center) {
var topLeft = this._getNewPixelOrigin(center, zoom);
return this.project(latlng, zoom)._subtract(topLeft);
},
_latLngBoundsToNewLayerBounds: function (latLngBounds, zoom, center) {
var topLeft = this._getNewPixelOrigin(center, zoom);
return toBounds([
this.project(latLngBounds.getSouthWest(), zoom)._subtract(topLeft),
this.project(latLngBounds.getNorthWest(), zoom)._subtract(topLeft),
this.project(latLngBounds.getSouthEast(), zoom)._subtract(topLeft),
this.project(latLngBounds.getNorthEast(), zoom)._subtract(topLeft)
]);
},
// layer point of the current center
_getCenterLayerPoint: function () {
return this.containerPointToLayerPoint(this.getSize()._divideBy(2));
},
// offset of the specified place to the current center in pixels
_getCenterOffset: function (latlng) {
return this.latLngToLayerPoint(latlng).subtract(this._getCenterLayerPoint());
},
// adjust center for view to get inside bounds
_limitCenter: function (center, zoom, bounds) {
if (!bounds) { return center; }
var centerPoint = this.project(center, zoom),
viewHalf = this.getSize().divideBy(2),
viewBounds = new Bounds(centerPoint.subtract(viewHalf), centerPoint.add(viewHalf)),
offset = this._getBoundsOffset(viewBounds, bounds, zoom);
// If offset is less than a pixel, ignore.
// This prevents unstable projections from getting into
// an infinite loop of tiny offsets.
if (offset.round().equals([0, 0])) {
return center;
}
return this.unproject(centerPoint.add(offset), zoom);
},
// adjust offset for view to get inside bounds
_limitOffset: function (offset, bounds) {
if (!bounds) { return offset; }
var viewBounds = this.getPixelBounds(),
newBounds = new Bounds(viewBounds.min.add(offset), viewBounds.max.add(offset));
return offset.add(this._getBoundsOffset(newBounds, bounds));
},
// returns offset needed for pxBounds to get inside maxBounds at a specified zoom
_getBoundsOffset: function (pxBounds, maxBounds, zoom) {
var projectedMaxBounds = toBounds(
this.project(maxBounds.getNorthEast(), zoom),
this.project(maxBounds.getSouthWest(), zoom)
),
minOffset = projectedMaxBounds.min.subtract(pxBounds.min),
maxOffset = projectedMaxBounds.max.subtract(pxBounds.max),
dx = this._rebound(minOffset.x, -maxOffset.x),
dy = this._rebound(minOffset.y, -maxOffset.y);
return new Point(dx, dy);
},
_rebound: function (left, right) {
return left + right > 0 ?
Math.round(left - right) / 2 :
Math.max(0, Math.ceil(left)) - Math.max(0, Math.floor(right));
},
_limitZoom: function (zoom) {
var min = this.getMinZoom(),
max = this.getMaxZoom(),
snap = any3d ? this.options.zoomSnap : 1;
if (snap) {
zoom = Math.round(zoom / snap) * snap;
}
return Math.max(min, Math.min(max, zoom));
},
_onPanTransitionStep: function () {
this.fire('move');
},
_onPanTransitionEnd: function () {
removeClass(this._mapPane, 'leaflet-pan-anim');
this.fire('moveend');
},
_tryAnimatedPan: function (center, options) {
// difference between the new and current centers in pixels
var offset = this._getCenterOffset(center)._trunc();
// don't animate too far unless animate: true specified in options
if ((options && options.animate) !== true && !this.getSize().contains(offset)) { return false; }
this.panBy(offset, options);
return true;
},
_createAnimProxy: function () {
var proxy = this._proxy = create$1('div', 'leaflet-proxy leaflet-zoom-animated');
this._panes.mapPane.appendChild(proxy);
this.on('zoomanim', function (e) {
var prop = TRANSFORM,
transform = this._proxy.style[prop];
setTransform(this._proxy, this.project(e.center, e.zoom), this.getZoomScale(e.zoom, 1));
// workaround for case when transform is the same and so transitionend event is not fired
if (transform === this._proxy.style[prop] && this._animatingZoom) {
this._onZoomTransitionEnd();
}
}, this);
this.on('load moveend', this._animMoveEnd, this);
this._on('unload', this._destroyAnimProxy, this);
},
_destroyAnimProxy: function () {
remove(this._proxy);
this.off('load moveend', this._animMoveEnd, this);
delete this._proxy;
},
_animMoveEnd: function () {
var c = this.getCenter(),
z = this.getZoom();
setTransform(this._proxy, this.project(c, z), this.getZoomScale(z, 1));
},
_catchTransitionEnd: function (e) {
if (this._animatingZoom && e.propertyName.indexOf('transform') >= 0) {
this._onZoomTransitionEnd();
}
},
_nothingToAnimate: function () {
return !this._container.getElementsByClassName('leaflet-zoom-animated').length;
},
_tryAnimatedZoom: function (center, zoom, options) {
if (this._animatingZoom) { return true; }
options = options || {};
// don't animate if disabled, not supported or zoom difference is too large
if (!this._zoomAnimated || options.animate === false || this._nothingToAnimate() ||
Math.abs(zoom - this._zoom) > this.options.zoomAnimationThreshold) { return false; }
// offset is the pixel coords of the zoom origin relative to the current center
var scale = this.getZoomScale(zoom),
offset = this._getCenterOffset(center)._divideBy(1 - 1 / scale);
// don't animate if the zoom origin isn't within one screen from the current center, unless forced
if (options.animate !== true && !this.getSize().contains(offset)) { return false; }
requestAnimFrame(function () {
this
._moveStart(true, false)
._animateZoom(center, zoom, true);
}, this);
return true;
},
_animateZoom: function (center, zoom, startAnim, noUpdate) {
if (!this._mapPane) { return; }
if (startAnim) {
this._animatingZoom = true;
// remember what center/zoom to set after animation
this._animateToCenter = center;
this._animateToZoom = zoom;
addClass(this._mapPane, 'leaflet-zoom-anim');
}
// @section Other Events
// @event zoomanim: ZoomAnimEvent
// Fired at least once per zoom animation. For continuous zoom, like pinch zooming, fired once per frame during zoom.
this.fire('zoomanim', {
center: center,
zoom: zoom,
noUpdate: noUpdate
});
// Work around webkit not firing 'transitionend', see https://github.com/Leaflet/Leaflet/issues/3689, 2693
setTimeout(bind(this._onZoomTransitionEnd, this), 250);
},
_onZoomTransitionEnd: function () {
if (!this._animatingZoom) { return; }
if (this._mapPane) {
removeClass(this._mapPane, 'leaflet-zoom-anim');
}
this._animatingZoom = false;
this._move(this._animateToCenter, this._animateToZoom);
// This anim frame should prevent an obscure iOS webkit tile loading race condition.
requestAnimFrame(function () {
this._moveEnd(true);
}, this);
}
});
// @section
// @factory L.map(id: String, options?: Map options)
// Instantiates a map object given the DOM ID of a `<div>` element
// and optionally an object literal with `Map options`.
//
// @alternative
// @factory L.map(el: HTMLElement, options?: Map options)
// Instantiates a map object given an instance of a `<div>` HTML element
// and optionally an object literal with `Map options`.
function createMap(id, options) {
return new Map(id, options);
}
/*
* @class Control
* @aka L.Control
* @inherits Class
*
* L.Control is a base class for implementing map controls. Handles positioning.
* All other controls extend from this class.
*/
var Control = Class.extend({
// @section
// @aka Control options
options: {
// @option position: String = 'topright'
// The position of the control (one of the map corners). Possible values are `'topleft'`,
// `'topright'`, `'bottomleft'` or `'bottomright'`
position: 'topright'
},
initialize: function (options) {
setOptions(this, options);
},
/* @section
* Classes extending L.Control will inherit the following methods:
*
* @method getPosition: string
* Returns the position of the control.
*/
getPosition: function () {
return this.options.position;
},
// @method setPosition(position: string): this
// Sets the position of the control.
setPosition: function (position) {
var map = this._map;
if (map) {
map.removeControl(this);
}
this.options.position = position;
if (map) {
map.addControl(this);
}
return this;
},
// @method getContainer: HTMLElement
// Returns the HTMLElement that contains the control.
getContainer: function () {
return this._container;
},
// @method addTo(map: Map): this
// Adds the control to the given map.
addTo: function (map) {
this.remove();
this._map = map;
var container = this._container = this.onAdd(map),
pos = this.getPosition(),
corner = map._controlCorners[pos];
addClass(container, 'leaflet-control');
if (pos.indexOf('bottom') !== -1) {
corner.insertBefore(container, corner.firstChild);
} else {
corner.appendChild(container);
}
this._map.on('unload', this.remove, this);
return this;
},
// @method remove: this
// Removes the control from the map it is currently active on.
remove: function () {
if (!this._map) {
return this;
}
remove(this._container);
if (this.onRemove) {
this.onRemove(this._map);
}
this._map.off('unload', this.remove, this);
this._map = null;
return this;
},
_refocusOnMap: function (e) {
// if map exists and event is not a keyboard event
if (this._map && e && e.screenX > 0 && e.screenY > 0) {
this._map.getContainer().focus();
}
}
});
var control = function (options) {
return new Control(options);
};
/* @section Extension methods
* @uninheritable
*
* Every control should extend from `L.Control` and (re-)implement the following methods.
*
* @method onAdd(map: Map): HTMLElement
* Should return the container DOM element for the control and add listeners on relevant map events. Called on [`control.addTo(map)`](#control-addTo).
*
* @method onRemove(map: Map)
* Optional method. Should contain all clean up code that removes the listeners previously added in [`onAdd`](#control-onadd). Called on [`control.remove()`](#control-remove).
*/
/* @namespace Map
* @section Methods for Layers and Controls
*/
Map.include({
// @method addControl(control: Control): this
// Adds the given control to the map
addControl: function (control) {
control.addTo(this);
return this;
},
// @method removeControl(control: Control): this
// Removes the given control from the map
removeControl: function (control) {
control.remove();
return this;
},
_initControlPos: function () {
var corners = this._controlCorners = {},
l = 'leaflet-',
container = this._controlContainer =
create$1('div', l + 'control-container', this._container);
function createCorner(vSide, hSide) {
var className = l + vSide + ' ' + l + hSide;
corners[vSide + hSide] = create$1('div', className, container);
}
createCorner('top', 'left');
createCorner('top', 'right');
createCorner('bottom', 'left');
createCorner('bottom', 'right');
},
_clearControlPos: function () {
for (var i in this._controlCorners) {
remove(this._controlCorners[i]);
}
remove(this._controlContainer);
delete this._controlCorners;
delete this._controlContainer;
}
});
/*
* @class Control.Layers
* @aka L.Control.Layers
* @inherits Control
*
* The layers control gives users the ability to switch between different base layers and switch overlays on/off (check out the [detailed example](http://leafletjs.com/examples/layers-control/)). Extends `Control`.
*
* @example
*
* ```js
* var baseLayers = {
* "Mapbox": mapbox,
* "OpenStreetMap": osm
* };
*
* var overlays = {
* "Marker": marker,
* "Roads": roadsLayer
* };
*
* L.control.layers(baseLayers, overlays).addTo(map);
* ```
*
* The `baseLayers` and `overlays` parameters are object literals with layer names as keys and `Layer` objects as values:
*
* ```js
* {
* "<someName1>": layer1,
* "<someName2>": layer2
* }
* ```
*
* The layer names can contain HTML, which allows you to add additional styling to the items:
*
* ```js
* {"<img src='my-layer-icon' /> <span class='my-layer-item'>My Layer</span>": myLayer}
* ```
*/
var Layers = Control.extend({
// @section
// @aka Control.Layers options
options: {
// @option collapsed: Boolean = true
// If `true`, the control will be collapsed into an icon and expanded on mouse hover or touch.
collapsed: true,
position: 'topright',
// @option autoZIndex: Boolean = true
// If `true`, the control will assign zIndexes in increasing order to all of its layers so that the order is preserved when switching them on/off.
autoZIndex: true,
// @option hideSingleBase: Boolean = false
// If `true`, the base layers in the control will be hidden when there is only one.
hideSingleBase: false,
// @option sortLayers: Boolean = false
// Whether to sort the layers. When `false`, layers will keep the order
// in which they were added to the control.
sortLayers: false,
// @option sortFunction: Function = *
// A [compare function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)
// that will be used for sorting the layers, when `sortLayers` is `true`.
// The function receives both the `L.Layer` instances and their names, as in
// `sortFunction(layerA, layerB, nameA, nameB)`.
// By default, it sorts layers alphabetically by their name.
sortFunction: function (layerA, layerB, nameA, nameB) {
return nameA < nameB ? -1 : (nameB < nameA ? 1 : 0);
}
},
initialize: function (baseLayers, overlays, options) {
setOptions(this, options);
this._layerControlInputs = [];
this._layers = [];
this._lastZIndex = 0;
this._handlingClick = false;
for (var i in baseLayers) {
this._addLayer(baseLayers[i], i);
}
for (i in overlays) {
this._addLayer(overlays[i], i, true);
}
},
onAdd: function (map) {
this._initLayout();
this._update();
this._map = map;
map.on('zoomend', this._checkDisabledLayers, this);
for (var i = 0; i < this._layers.length; i++) {
this._layers[i].layer.on('add remove', this._onLayerChange, this);
}
return this._container;
},
addTo: function (map) {
Control.prototype.addTo.call(this, map);
// Trigger expand after Layers Control has been inserted into DOM so that is now has an actual height.
return this._expandIfNotCollapsed();
},
onRemove: function () {
this._map.off('zoomend', this._checkDisabledLayers, this);
for (var i = 0; i < this._layers.length; i++) {
this._layers[i].layer.off('add remove', this._onLayerChange, this);
}
},
// @method addBaseLayer(layer: Layer, name: String): this
// Adds a base layer (radio button entry) with the given name to the control.
addBaseLayer: function (layer, name) {
this._addLayer(layer, name);
return (this._map) ? this._update() : this;
},
// @method addOverlay(layer: Layer, name: String): this
// Adds an overlay (checkbox entry) with the given name to the control.
addOverlay: function (layer, name) {
this._addLayer(layer, name, true);
return (this._map) ? this._update() : this;
},
// @method removeLayer(layer: Layer): this
// Remove the given layer from the control.
removeLayer: function (layer) {
layer.off('add remove', this._onLayerChange, this);
var obj = this._getLayer(stamp(layer));
if (obj) {
this._layers.splice(this._layers.indexOf(obj), 1);
}
return (this._map) ? this._update() : this;
},
// @method expand(): this
// Expand the control container if collapsed.
expand: function () {
addClass(this._container, 'leaflet-control-layers-expanded');
this._section.style.height = null;
var acceptableHeight = this._map.getSize().y - (this._container.offsetTop + 50);
if (acceptableHeight < this._section.clientHeight) {
addClass(this._section, 'leaflet-control-layers-scrollbar');
this._section.style.height = acceptableHeight + 'px';
} else {
removeClass(this._section, 'leaflet-control-layers-scrollbar');
}
this._checkDisabledLayers();
return this;
},
// @method collapse(): this
// Collapse the control container if expanded.
collapse: function () {
removeClass(this._container, 'leaflet-control-layers-expanded');
return this;
},
_initLayout: function () {
var className = 'leaflet-control-layers',
container = this._container = create$1('div', className),
collapsed = this.options.collapsed;
// makes this work on IE touch devices by stopping it from firing a mouseout event when the touch is released
container.setAttribute('aria-haspopup', true);
disableClickPropagation(container);
disableScrollPropagation(container);
var section = this._section = create$1('section', className + '-list');
if (collapsed) {
this._map.on('click', this.collapse, this);
if (!android) {
on(container, {
mouseenter: this.expand,
mouseleave: this.collapse
}, this);
}
}
var link = this._layersLink = create$1('a', className + '-toggle', container);
link.href = '#';
link.title = 'Layers';
if (touch) {
on(link, 'click', stop);
on(link, 'click', this.expand, this);
} else {
on(link, 'focus', this.expand, this);
}
if (!collapsed) {
this.expand();
}
this._baseLayersList = create$1('div', className + '-base', section);
this._separator = create$1('div', className + '-separator', section);
this._overlaysList = create$1('div', className + '-overlays', section);
container.appendChild(section);
},
_getLayer: function (id) {
for (var i = 0; i < this._layers.length; i++) {
if (this._layers[i] && stamp(this._layers[i].layer) === id) {
return this._layers[i];
}
}
},
_addLayer: function (layer, name, overlay) {
if (this._map) {
layer.on('add remove', this._onLayerChange, this);
}
this._layers.push({
layer: layer,
name: name,
overlay: overlay
});
if (this.options.sortLayers) {
this._layers.sort(bind(function (a, b) {
return this.options.sortFunction(a.layer, b.layer, a.name, b.name);
}, this));
}
if (this.options.autoZIndex && layer.setZIndex) {
this._lastZIndex++;
layer.setZIndex(this._lastZIndex);
}
this._expandIfNotCollapsed();
},
_update: function () {
if (!this._container) { return this; }
empty(this._baseLayersList);
empty(this._overlaysList);
this._layerControlInputs = [];
var baseLayersPresent, overlaysPresent, i, obj, baseLayersCount = 0;
for (i = 0; i < this._layers.length; i++) {
obj = this._layers[i];
this._addItem(obj);
overlaysPresent = overlaysPresent || obj.overlay;
baseLayersPresent = baseLayersPresent || !obj.overlay;
baseLayersCount += !obj.overlay ? 1 : 0;
}
// Hide base layers section if there's only one layer.
if (this.options.hideSingleBase) {
baseLayersPresent = baseLayersPresent && baseLayersCount > 1;
this._baseLayersList.style.display = baseLayersPresent ? '' : 'none';
}
this._separator.style.display = overlaysPresent && baseLayersPresent ? '' : 'none';
return this;
},
_onLayerChange: function (e) {
if (!this._handlingClick) {
this._update();
}
var obj = this._getLayer(stamp(e.target));
// @namespace Map
// @section Layer events
// @event baselayerchange: LayersControlEvent
// Fired when the base layer is changed through the [layer control](#control-layers).
// @event overlayadd: LayersControlEvent
// Fired when an overlay is selected through the [layer control](#control-layers).
// @event overlayremove: LayersControlEvent
// Fired when an overlay is deselected through the [layer control](#control-layers).
// @namespace Control.Layers
var type = obj.overlay ?
(e.type === 'add' ? 'overlayadd' : 'overlayremove') :
(e.type === 'add' ? 'baselayerchange' : null);
if (type) {
this._map.fire(type, obj);
}
},
// IE7 bugs out if you create a radio dynamically, so you have to do it this hacky way (see http://bit.ly/PqYLBe)
_createRadioElement: function (name, checked) {
var radioHtml = '<input type="radio" class="leaflet-control-layers-selector" name="' +
name + '"' + (checked ? ' checked="checked"' : '') + '/>';
var radioFragment = document.createElement('div');
radioFragment.innerHTML = radioHtml;
return radioFragment.firstChild;
},
_addItem: function (obj) {
var label = document.createElement('label'),
checked = this._map.hasLayer(obj.layer),
input;
if (obj.overlay) {
input = document.createElement('input');
input.type = 'checkbox';
input.className = 'leaflet-control-layers-selector';
input.defaultChecked = checked;
} else {
input = this._createRadioElement('leaflet-base-layers_' + stamp(this), checked);
}
this._layerControlInputs.push(input);
input.layerId = stamp(obj.layer);
on(input, 'click', this._onInputClick, this);
var name = document.createElement('span');
name.innerHTML = ' ' + obj.name;
// Helps from preventing layer control flicker when checkboxes are disabled
// https://github.com/Leaflet/Leaflet/issues/2771
var holder = document.createElement('div');
label.appendChild(holder);
holder.appendChild(input);
holder.appendChild(name);
var container = obj.overlay ? this._overlaysList : this._baseLayersList;
container.appendChild(label);
this._checkDisabledLayers();
return label;
},
_onInputClick: function () {
var inputs = this._layerControlInputs,
input, layer;
var addedLayers = [],
removedLayers = [];
this._handlingClick = true;
for (var i = inputs.length - 1; i >= 0; i--) {
input = inputs[i];
layer = this._getLayer(input.layerId).layer;
if (input.checked) {
addedLayers.push(layer);
} else if (!input.checked) {
removedLayers.push(layer);
}
}
// Bugfix issue 2318: Should remove all old layers before readding new ones
for (i = 0; i < removedLayers.length; i++) {
if (this._map.hasLayer(removedLayers[i])) {
this._map.removeLayer(removedLayers[i]);
}
}
for (i = 0; i < addedLayers.length; i++) {
if (!this._map.hasLayer(addedLayers[i])) {
this._map.addLayer(addedLayers[i]);
}
}
this._handlingClick = false;
this._refocusOnMap();
},
_checkDisabledLayers: function () {
var inputs = this._layerControlInputs,
input,
layer,
zoom = this._map.getZoom();
for (var i = inputs.length - 1; i >= 0; i--) {
input = inputs[i];
layer = this._getLayer(input.layerId).layer;
input.disabled = (layer.options.minZoom !== undefined && zoom < layer.options.minZoom) ||
(layer.options.maxZoom !== undefined && zoom > layer.options.maxZoom);
}
},
_expandIfNotCollapsed: function () {
if (this._map && !this.options.collapsed) {
this.expand();
}
return this;
},
_expand: function () {
// Backward compatibility, remove me in 1.1.
return this.expand();
},
_collapse: function () {
// Backward compatibility, remove me in 1.1.
return this.collapse();
}
});
// @factory L.control.layers(baselayers?: Object, overlays?: Object, options?: Control.Layers options)
// Creates a layers control with the given layers. Base layers will be switched with radio buttons, while overlays will be switched with checkboxes. Note that all base layers should be passed in the base layers object, but only one should be added to the map during map instantiation.
var layers = function (baseLayers, overlays, options) {
return new Layers(baseLayers, overlays, options);
};
/*
* @class Control.Zoom
* @aka L.Control.Zoom
* @inherits Control
*
* A basic zoom control with two buttons (zoom in and zoom out). It is put on the map by default unless you set its [`zoomControl` option](#map-zoomcontrol) to `false`. Extends `Control`.
*/
var Zoom = Control.extend({
// @section
// @aka Control.Zoom options
options: {
position: 'topleft',
// @option zoomInText: String = '+'
// The text set on the 'zoom in' button.
zoomInText: '+',
// @option zoomInTitle: String = 'Zoom in'
// The title set on the 'zoom in' button.
zoomInTitle: 'Zoom in',
// @option zoomOutText: String = '−'
// The text set on the 'zoom out' button.
zoomOutText: '−',
// @option zoomOutTitle: String = 'Zoom out'
// The title set on the 'zoom out' button.
zoomOutTitle: 'Zoom out'
},
onAdd: function (map) {
var zoomName = 'leaflet-control-zoom',
container = create$1('div', zoomName + ' leaflet-bar'),
options = this.options;
this._zoomInButton = this._createButton(options.zoomInText, options.zoomInTitle,
zoomName + '-in', container, this._zoomIn);
this._zoomOutButton = this._createButton(options.zoomOutText, options.zoomOutTitle,
zoomName + '-out', container, this._zoomOut);
this._updateDisabled();
map.on('zoomend zoomlevelschange', this._updateDisabled, this);
return container;
},
onRemove: function (map) {
map.off('zoomend zoomlevelschange', this._updateDisabled, this);
},
disable: function () {
this._disabled = true;
this._updateDisabled();
return this;
},
enable: function () {
this._disabled = false;
this._updateDisabled();
return this;
},
_zoomIn: function (e) {
if (!this._disabled && this._map._zoom < this._map.getMaxZoom()) {
this._map.zoomIn(this._map.options.zoomDelta * (e.shiftKey ? 3 : 1));
}
},
_zoomOut: function (e) {
if (!this._disabled && this._map._zoom > this._map.getMinZoom()) {
this._map.zoomOut(this._map.options.zoomDelta * (e.shiftKey ? 3 : 1));
}
},
_createButton: function (html, title, className, container, fn) {
var link = create$1('a', className, container);
link.innerHTML = html;
link.href = '#';
link.title = title;
/*
* Will force screen readers like VoiceOver to read this as "Zoom in - button"
*/
link.setAttribute('role', 'button');
link.setAttribute('aria-label', title);
disableClickPropagation(link);
on(link, 'click', stop);
on(link, 'click', fn, this);
on(link, 'click', this._refocusOnMap, this);
return link;
},
_updateDisabled: function () {
var map = this._map,
className = 'leaflet-disabled';
removeClass(this._zoomInButton, className);
removeClass(this._zoomOutButton, className);
if (this._disabled || map._zoom === map.getMinZoom()) {
addClass(this._zoomOutButton, className);
}
if (this._disabled || map._zoom === map.getMaxZoom()) {
addClass(this._zoomInButton, className);
}
}
});
// @namespace Map
// @section Control options
// @option zoomControl: Boolean = true
// Whether a [zoom control](#control-zoom) is added to the map by default.
Map.mergeOptions({
zoomControl: true
});
Map.addInitHook(function () {
if (this.options.zoomControl) {
// @section Controls
// @property zoomControl: Control.Zoom
// The default zoom control (only available if the
// [`zoomControl` option](#map-zoomcontrol) was `true` when creating the map).
this.zoomControl = new Zoom();
this.addControl(this.zoomControl);
}
});
// @namespace Control.Zoom
// @factory L.control.zoom(options: Control.Zoom options)
// Creates a zoom control
var zoom = function (options) {
return new Zoom(options);
};
/*
* @class Control.Scale
* @aka L.Control.Scale
* @inherits Control
*
* A simple scale control that shows the scale of the current center of screen in metric (m/km) and imperial (mi/ft) systems. Extends `Control`.
*
* @example
*
* ```js
* L.control.scale().addTo(map);
* ```
*/
var Scale = Control.extend({
// @section
// @aka Control.Scale options
options: {
position: 'bottomleft',
// @option maxWidth: Number = 100
// Maximum width of the control in pixels. The width is set dynamically to show round values (e.g. 100, 200, 500).
maxWidth: 100,
// @option metric: Boolean = True
// Whether to show the metric scale line (m/km).
metric: true,
// @option imperial: Boolean = True
// Whether to show the imperial scale line (mi/ft).
imperial: true
// @option updateWhenIdle: Boolean = false
// If `true`, the control is updated on [`moveend`](#map-moveend), otherwise it's always up-to-date (updated on [`move`](#map-move)).
},
onAdd: function (map) {
var className = 'leaflet-control-scale',
container = create$1('div', className),
options = this.options;
this._addScales(options, className + '-line', container);
map.on(options.updateWhenIdle ? 'moveend' : 'move', this._update, this);
map.whenReady(this._update, this);
return container;
},
onRemove: function (map) {
map.off(this.options.updateWhenIdle ? 'moveend' : 'move', this._update, this);
},
_addScales: function (options, className, container) {
if (options.metric) {
this._mScale = create$1('div', className, container);
}
if (options.imperial) {
this._iScale = create$1('div', className, container);
}
},
_update: function () {
var map = this._map,
y = map.getSize().y / 2;
var maxMeters = map.distance(
map.containerPointToLatLng([0, y]),
map.containerPointToLatLng([this.options.maxWidth, y]));
this._updateScales(maxMeters);
},
_updateScales: function (maxMeters) {
if (this.options.metric && maxMeters) {
this._updateMetric(maxMeters);
}
if (this.options.imperial && maxMeters) {
this._updateImperial(maxMeters);
}
},
_updateMetric: function (maxMeters) {
var meters = this._getRoundNum(maxMeters),
label = meters < 1000 ? meters + ' m' : (meters / 1000) + ' km';
this._updateScale(this._mScale, label, meters / maxMeters);
},
_updateImperial: function (maxMeters) {
var maxFeet = maxMeters * 3.2808399,
maxMiles, miles, feet;
if (maxFeet > 5280) {
maxMiles = maxFeet / 5280;
miles = this._getRoundNum(maxMiles);
this._updateScale(this._iScale, miles + ' mi', miles / maxMiles);
} else {
feet = this._getRoundNum(maxFeet);
this._updateScale(this._iScale, feet + ' ft', feet / maxFeet);
}
},
_updateScale: function (scale, text, ratio) {
scale.style.width = Math.round(this.options.maxWidth * ratio) + 'px';
scale.innerHTML = text;
},
_getRoundNum: function (num) {
var pow10 = Math.pow(10, (Math.floor(num) + '').length - 1),
d = num / pow10;
d = d >= 10 ? 10 :
d >= 5 ? 5 :
d >= 3 ? 3 :
d >= 2 ? 2 : 1;
return pow10 * d;
}
});
// @factory L.control.scale(options?: Control.Scale options)
// Creates an scale control with the given options.
var scale = function (options) {
return new Scale(options);
};
/*
* @class Control.Attribution
* @aka L.Control.Attribution
* @inherits Control
*
* The attribution control allows you to display attribution data in a small text box on a map. It is put on the map by default unless you set its [`attributionControl` option](#map-attributioncontrol) to `false`, and it fetches attribution texts from layers with the [`getAttribution` method](#layer-getattribution) automatically. Extends Control.
*/
var Attribution = Control.extend({
// @section
// @aka Control.Attribution options
options: {
position: 'bottomright',
// @option prefix: String = 'Leaflet'
// The HTML text shown before the attributions. Pass `false` to disable.
prefix: '<a href="https://leafletjs.com" title="A JS library for interactive maps">Leaflet</a>'
},
initialize: function (options) {
setOptions(this, options);
this._attributions = {};
},
onAdd: function (map) {
map.attributionControl = this;
this._container = create$1('div', 'leaflet-control-attribution');
disableClickPropagation(this._container);
// TODO ugly, refactor
for (var i in map._layers) {
if (map._layers[i].getAttribution) {
this.addAttribution(map._layers[i].getAttribution());
}
}
this._update();
return this._container;
},
// @method setPrefix(prefix: String): this
// Sets the text before the attributions.
setPrefix: function (prefix) {
this.options.prefix = prefix;
this._update();
return this;
},
// @method addAttribution(text: String): this
// Adds an attribution text (e.g. `'Vector data © Mapbox'`).
addAttribution: function (text) {
if (!text) { return this; }
if (!this._attributions[text]) {
this._attributions[text] = 0;
}
this._attributions[text]++;
this._update();
return this;
},
// @method removeAttribution(text: String): this
// Removes an attribution text.
removeAttribution: function (text) {
if (!text) { return this; }
if (this._attributions[text]) {
this._attributions[text]--;
this._update();
}
return this;
},
_update: function () {
if (!this._map) { return; }
var attribs = [];
for (var i in this._attributions) {
if (this._attributions[i]) {
attribs.push(i);
}
}
var prefixAndAttribs = [];
if (this.options.prefix) {
prefixAndAttribs.push(this.options.prefix);
}
if (attribs.length) {
prefixAndAttribs.push(attribs.join(', '));
}
this._container.innerHTML = prefixAndAttribs.join(' | ');
}
});
// @namespace Map
// @section Control options
// @option attributionControl: Boolean = true
// Whether a [attribution control](#control-attribution) is added to the map by default.
Map.mergeOptions({
attributionControl: true
});
Map.addInitHook(function () {
if (this.options.attributionControl) {
new Attribution().addTo(this);
}
});
// @namespace Control.Attribution
// @factory L.control.attribution(options: Control.Attribution options)
// Creates an attribution control.
var attribution = function (options) {
return new Attribution(options);
};
Control.Layers = Layers;
Control.Zoom = Zoom;
Control.Scale = Scale;
Control.Attribution = Attribution;
control.layers = layers;
control.zoom = zoom;
control.scale = scale;
control.attribution = attribution;
/*
L.Handler is a base class for handler classes that are used internally to inject
interaction features like dragging to classes like Map and Marker.
*/
// @class Handler
// @aka L.Handler
// Abstract class for map interaction handlers
var Handler = Class.extend({
initialize: function (map) {
this._map = map;
},
// @method enable(): this
// Enables the handler
enable: function () {
if (this._enabled) { return this; }
this._enabled = true;
this.addHooks();
return this;
},
// @method disable(): this
// Disables the handler
disable: function () {
if (!this._enabled) { return this; }
this._enabled = false;
this.removeHooks();
return this;
},
// @method enabled(): Boolean
// Returns `true` if the handler is enabled
enabled: function () {
return !!this._enabled;
}
// @section Extension methods
// Classes inheriting from `Handler` must implement the two following methods:
// @method addHooks()
// Called when the handler is enabled, should add event hooks.
// @method removeHooks()
// Called when the handler is disabled, should remove the event hooks added previously.
});
// @section There is static function which can be called without instantiating L.Handler:
// @function addTo(map: Map, name: String): this
// Adds a new Handler to the given map with the given name.
Handler.addTo = function (map, name) {
map.addHandler(name, this);
return this;
};
var Mixin = {Events: Events};
/*
* @class Draggable
* @aka L.Draggable
* @inherits Evented
*
* A class for making DOM elements draggable (including touch support).
* Used internally for map and marker dragging. Only works for elements
* that were positioned with [`L.DomUtil.setPosition`](#domutil-setposition).
*
* @example
* ```js
* var draggable = new L.Draggable(elementToDrag);
* draggable.enable();
* ```
*/
var START = touch ? 'touchstart mousedown' : 'mousedown';
var END = {
mousedown: 'mouseup',
touchstart: 'touchend',
pointerdown: 'touchend',
MSPointerDown: 'touchend'
};
var MOVE = {
mousedown: 'mousemove',
touchstart: 'touchmove',
pointerdown: 'touchmove',
MSPointerDown: 'touchmove'
};
var Draggable = Evented.extend({
options: {
// @section
// @aka Draggable options
// @option clickTolerance: Number = 3
// The max number of pixels a user can shift the mouse pointer during a click
// for it to be considered a valid click (as opposed to a mouse drag).
clickTolerance: 3
},
// @constructor L.Draggable(el: HTMLElement, dragHandle?: HTMLElement, preventOutline?: Boolean, options?: Draggable options)
// Creates a `Draggable` object for moving `el` when you start dragging the `dragHandle` element (equals `el` itself by default).
initialize: function (element, dragStartTarget, preventOutline$$1, options) {
setOptions(this, options);
this._element = element;
this._dragStartTarget = dragStartTarget || element;
this._preventOutline = preventOutline$$1;
},
// @method enable()
// Enables the dragging ability
enable: function () {
if (this._enabled) { return; }
on(this._dragStartTarget, START, this._onDown, this);
this._enabled = true;
},
// @method disable()
// Disables the dragging ability
disable: function () {
if (!this._enabled) { return; }
// If we're currently dragging this draggable,
// disabling it counts as first ending the drag.
if (Draggable._dragging === this) {
this.finishDrag();
}
off(this._dragStartTarget, START, this._onDown, this);
this._enabled = false;
this._moved = false;
},
_onDown: function (e) {
// Ignore simulated events, since we handle both touch and
// mouse explicitly; otherwise we risk getting duplicates of
// touch events, see #4315.
// Also ignore the event if disabled; this happens in IE11
// under some circumstances, see #3666.
if (e._simulated || !this._enabled) { return; }
this._moved = false;
if (hasClass(this._element, 'leaflet-zoom-anim')) { return; }
if (Draggable._dragging || e.shiftKey || ((e.which !== 1) && (e.button !== 1) && !e.touches)) { return; }
Draggable._dragging = this; // Prevent dragging multiple objects at once.
if (this._preventOutline) {
preventOutline(this._element);
}
disableImageDrag();
disableTextSelection();
if (this._moving) { return; }
// @event down: Event
// Fired when a drag is about to start.
this.fire('down');
var first = e.touches ? e.touches[0] : e,
sizedParent = getSizedParentNode(this._element);
this._startPoint = new Point(first.clientX, first.clientY);
// Cache the scale, so that we can continuously compensate for it during drag (_onMove).
this._parentScale = getScale(sizedParent);
on(document, MOVE[e.type], this._onMove, this);
on(document, END[e.type], this._onUp, this);
},
_onMove: function (e) {
// Ignore simulated events, since we handle both touch and
// mouse explicitly; otherwise we risk getting duplicates of
// touch events, see #4315.
// Also ignore the event if disabled; this happens in IE11
// under some circumstances, see #3666.
if (e._simulated || !this._enabled) { return; }
if (e.touches && e.touches.length > 1) {
this._moved = true;
return;
}
var first = (e.touches && e.touches.length === 1 ? e.touches[0] : e),
offset = new Point(first.clientX, first.clientY)._subtract(this._startPoint);
if (!offset.x && !offset.y) { return; }
if (Math.abs(offset.x) + Math.abs(offset.y) < this.options.clickTolerance) { return; }
// We assume that the parent container's position, border and scale do not change for the duration of the drag.
// Therefore there is no need to account for the position and border (they are eliminated by the subtraction)
// and we can use the cached value for the scale.
offset.x /= this._parentScale.x;
offset.y /= this._parentScale.y;
preventDefault(e);
if (!this._moved) {
// @event dragstart: Event
// Fired when a drag starts
this.fire('dragstart');
this._moved = true;
this._startPos = getPosition(this._element).subtract(offset);
addClass(document.body, 'leaflet-dragging');
this._lastTarget = e.target || e.srcElement;
// IE and Edge do not give the <use> element, so fetch it
// if necessary
if ((window.SVGElementInstance) && (this._lastTarget instanceof SVGElementInstance)) {
this._lastTarget = this._lastTarget.correspondingUseElement;
}
addClass(this._lastTarget, 'leaflet-drag-target');
}
this._newPos = this._startPos.add(offset);
this._moving = true;
cancelAnimFrame(this._animRequest);
this._lastEvent = e;
this._animRequest = requestAnimFrame(this._updatePosition, this, true);
},
_updatePosition: function () {
var e = {originalEvent: this._lastEvent};
// @event predrag: Event
// Fired continuously during dragging *before* each corresponding
// update of the element's position.
this.fire('predrag', e);
setPosition(this._element, this._newPos);
// @event drag: Event
// Fired continuously during dragging.
this.fire('drag', e);
},
_onUp: function (e) {
// Ignore simulated events, since we handle both touch and
// mouse explicitly; otherwise we risk getting duplicates of
// touch events, see #4315.
// Also ignore the event if disabled; this happens in IE11
// under some circumstances, see #3666.
if (e._simulated || !this._enabled) { return; }
this.finishDrag();
},
finishDrag: function () {
removeClass(document.body, 'leaflet-dragging');
if (this._lastTarget) {
removeClass(this._lastTarget, 'leaflet-drag-target');
this._lastTarget = null;
}
for (var i in MOVE) {
off(document, MOVE[i], this._onMove, this);
off(document, END[i], this._onUp, this);
}
enableImageDrag();
enableTextSelection();
if (this._moved && this._moving) {
// ensure drag is not fired after dragend
cancelAnimFrame(this._animRequest);
// @event dragend: DragEndEvent
// Fired when the drag ends.
this.fire('dragend', {
distance: this._newPos.distanceTo(this._startPos)
});
}
this._moving = false;
Draggable._dragging = false;
}
});
/*
* @namespace LineUtil
*
* Various utility functions for polyline points processing, used by Leaflet internally to make polylines lightning-fast.
*/
// Simplify polyline with vertex reduction and Douglas-Peucker simplification.
// Improves rendering performance dramatically by lessening the number of points to draw.
// @function simplify(points: Point[], tolerance: Number): Point[]
// Dramatically reduces the number of points in a polyline while retaining
// its shape and returns a new array of simplified points, using the
// [Douglas-Peucker algorithm](http://en.wikipedia.org/wiki/Douglas-Peucker_algorithm).
// Used for a huge performance boost when processing/displaying Leaflet polylines for
// each zoom level and also reducing visual noise. tolerance affects the amount of
// simplification (lesser value means higher quality but slower and with more points).
// Also released as a separated micro-library [Simplify.js](http://mourner.github.com/simplify-js/).
function simplify(points, tolerance) {
if (!tolerance || !points.length) {
return points.slice();
}
var sqTolerance = tolerance * tolerance;
// stage 1: vertex reduction
points = _reducePoints(points, sqTolerance);
// stage 2: Douglas-Peucker simplification
points = _simplifyDP(points, sqTolerance);
return points;
}
// @function pointToSegmentDistance(p: Point, p1: Point, p2: Point): Number
// Returns the distance between point `p` and segment `p1` to `p2`.
function pointToSegmentDistance(p, p1, p2) {
return Math.sqrt(_sqClosestPointOnSegment(p, p1, p2, true));
}
// @function closestPointOnSegment(p: Point, p1: Point, p2: Point): Number
// Returns the closest point from a point `p` on a segment `p1` to `p2`.
function closestPointOnSegment(p, p1, p2) {
return _sqClosestPointOnSegment(p, p1, p2);
}
// Douglas-Peucker simplification, see http://en.wikipedia.org/wiki/Douglas-Peucker_algorithm
function _simplifyDP(points, sqTolerance) {
var len = points.length,
ArrayConstructor = typeof Uint8Array !== undefined + '' ? Uint8Array : Array,
markers = new ArrayConstructor(len);
markers[0] = markers[len - 1] = 1;
_simplifyDPStep(points, markers, sqTolerance, 0, len - 1);
var i,
newPoints = [];
for (i = 0; i < len; i++) {
if (markers[i]) {
newPoints.push(points[i]);
}
}
return newPoints;
}
function _simplifyDPStep(points, markers, sqTolerance, first, last) {
var maxSqDist = 0,
index, i, sqDist;
for (i = first + 1; i <= last - 1; i++) {
sqDist = _sqClosestPointOnSegment(points[i], points[first], points[last], true);
if (sqDist > maxSqDist) {
index = i;
maxSqDist = sqDist;
}
}
if (maxSqDist > sqTolerance) {
markers[index] = 1;
_simplifyDPStep(points, markers, sqTolerance, first, index);
_simplifyDPStep(points, markers, sqTolerance, index, last);
}
}
// reduce points that are too close to each other to a single point
function _reducePoints(points, sqTolerance) {
var reducedPoints = [points[0]];
for (var i = 1, prev = 0, len = points.length; i < len; i++) {
if (_sqDist(points[i], points[prev]) > sqTolerance) {
reducedPoints.push(points[i]);
prev = i;
}
}
if (prev < len - 1) {
reducedPoints.push(points[len - 1]);
}
return reducedPoints;
}
var _lastCode;
// @function clipSegment(a: Point, b: Point, bounds: Bounds, useLastCode?: Boolean, round?: Boolean): Point[]|Boolean
// Clips the segment a to b by rectangular bounds with the
// [Cohen-Sutherland algorithm](https://en.wikipedia.org/wiki/Cohen%E2%80%93Sutherland_algorithm)
// (modifying the segment points directly!). Used by Leaflet to only show polyline
// points that are on the screen or near, increasing performance.
function clipSegment(a, b, bounds, useLastCode, round) {
var codeA = useLastCode ? _lastCode : _getBitCode(a, bounds),
codeB = _getBitCode(b, bounds),
codeOut, p, newCode;
// save 2nd code to avoid calculating it on the next segment
_lastCode = codeB;
while (true) {
// if a,b is inside the clip window (trivial accept)
if (!(codeA | codeB)) {
return [a, b];
}
// if a,b is outside the clip window (trivial reject)
if (codeA & codeB) {
return false;
}
// other cases
codeOut = codeA || codeB;
p = _getEdgeIntersection(a, b, codeOut, bounds, round);
newCode = _getBitCode(p, bounds);
if (codeOut === codeA) {
a = p;
codeA = newCode;
} else {
b = p;
codeB = newCode;
}
}
}
function _getEdgeIntersection(a, b, code, bounds, round) {
var dx = b.x - a.x,
dy = b.y - a.y,
min = bounds.min,
max = bounds.max,
x, y;
if (code & 8) { // top
x = a.x + dx * (max.y - a.y) / dy;
y = max.y;
} else if (code & 4) { // bottom
x = a.x + dx * (min.y - a.y) / dy;
y = min.y;
} else if (code & 2) { // right
x = max.x;
y = a.y + dy * (max.x - a.x) / dx;
} else if (code & 1) { // left
x = min.x;
y = a.y + dy * (min.x - a.x) / dx;
}
return new Point(x, y, round);
}
function _getBitCode(p, bounds) {
var code = 0;
if (p.x < bounds.min.x) { // left
code |= 1;
} else if (p.x > bounds.max.x) { // right
code |= 2;
}
if (p.y < bounds.min.y) { // bottom
code |= 4;
} else if (p.y > bounds.max.y) { // top
code |= 8;
}
return code;
}
// square distance (to avoid unnecessary Math.sqrt calls)
function _sqDist(p1, p2) {
var dx = p2.x - p1.x,
dy = p2.y - p1.y;
return dx * dx + dy * dy;
}
// return closest point on segment or distance to that point
function _sqClosestPointOnSegment(p, p1, p2, sqDist) {
var x = p1.x,
y = p1.y,
dx = p2.x - x,
dy = p2.y - y,
dot = dx * dx + dy * dy,
t;
if (dot > 0) {
t = ((p.x - x) * dx + (p.y - y) * dy) / dot;
if (t > 1) {
x = p2.x;
y = p2.y;
} else if (t > 0) {
x += dx * t;
y += dy * t;
}
}
dx = p.x - x;
dy = p.y - y;
return sqDist ? dx * dx + dy * dy : new Point(x, y);
}
// @function isFlat(latlngs: LatLng[]): Boolean
// Returns true if `latlngs` is a flat array, false is nested.
function isFlat(latlngs) {
return !isArray(latlngs[0]) || (typeof latlngs[0][0] !== 'object' && typeof latlngs[0][0] !== 'undefined');
}
function _flat(latlngs) {
console.warn('Deprecated use of _flat, please use L.LineUtil.isFlat instead.');
return isFlat(latlngs);
}
var LineUtil = (Object.freeze || Object)({
simplify: simplify,
pointToSegmentDistance: pointToSegmentDistance,
closestPointOnSegment: closestPointOnSegment,
clipSegment: clipSegment,
_getEdgeIntersection: _getEdgeIntersection,
_getBitCode: _getBitCode,
_sqClosestPointOnSegment: _sqClosestPointOnSegment,
isFlat: isFlat,
_flat: _flat
});
/*
* @namespace PolyUtil
* Various utility functions for polygon geometries.
*/
/* @function clipPolygon(points: Point[], bounds: Bounds, round?: Boolean): Point[]
* Clips the polygon geometry defined by the given `points` by the given bounds (using the [Sutherland-Hodgman algorithm](https://en.wikipedia.org/wiki/Sutherland%E2%80%93Hodgman_algorithm)).
* Used by Leaflet to only show polygon points that are on the screen or near, increasing
* performance. Note that polygon points needs different algorithm for clipping
* than polyline, so there's a separate method for it.
*/
function clipPolygon(points, bounds, round) {
var clippedPoints,
edges = [1, 4, 2, 8],
i, j, k,
a, b,
len, edge, p;
for (i = 0, len = points.length; i < len; i++) {
points[i]._code = _getBitCode(points[i], bounds);
}
// for each edge (left, bottom, right, top)
for (k = 0; k < 4; k++) {
edge = edges[k];
clippedPoints = [];
for (i = 0, len = points.length, j = len - 1; i < len; j = i++) {
a = points[i];
b = points[j];
// if a is inside the clip window
if (!(a._code & edge)) {
// if b is outside the clip window (a->b goes out of screen)
if (b._code & edge) {
p = _getEdgeIntersection(b, a, edge, bounds, round);
p._code = _getBitCode(p, bounds);
clippedPoints.push(p);
}
clippedPoints.push(a);
// else if b is inside the clip window (a->b enters the screen)
} else if (!(b._code & edge)) {
p = _getEdgeIntersection(b, a, edge, bounds, round);
p._code = _getBitCode(p, bounds);
clippedPoints.push(p);
}
}
points = clippedPoints;
}
return points;
}
var PolyUtil = (Object.freeze || Object)({
clipPolygon: clipPolygon
});
/*
* @namespace Projection
* @section
* Leaflet comes with a set of already defined Projections out of the box:
*
* @projection L.Projection.LonLat
*
* Equirectangular, or Plate Carree projection — the most simple projection,
* mostly used by GIS enthusiasts. Directly maps `x` as longitude, and `y` as
* latitude. Also suitable for flat worlds, e.g. game maps. Used by the
* `EPSG:4326` and `Simple` CRS.
*/
var LonLat = {
project: function (latlng) {
return new Point(latlng.lng, latlng.lat);
},
unproject: function (point) {
return new LatLng(point.y, point.x);
},
bounds: new Bounds([-180, -90], [180, 90])
};
/*
* @namespace Projection
* @projection L.Projection.Mercator
*
* Elliptical Mercator projection — more complex than Spherical Mercator. Assumes that Earth is an ellipsoid. Used by the EPSG:3395 CRS.
*/
var Mercator = {
R: 6378137,
R_MINOR: 6356752.314245179,
bounds: new Bounds([-20037508.34279, -15496570.73972], [20037508.34279, 18764656.23138]),
project: function (latlng) {
var d = Math.PI / 180,
r = this.R,
y = latlng.lat * d,
tmp = this.R_MINOR / r,
e = Math.sqrt(1 - tmp * tmp),
con = e * Math.sin(y);
var ts = Math.tan(Math.PI / 4 - y / 2) / Math.pow((1 - con) / (1 + con), e / 2);
y = -r * Math.log(Math.max(ts, 1E-10));
return new Point(latlng.lng * d * r, y);
},
unproject: function (point) {
var d = 180 / Math.PI,
r = this.R,
tmp = this.R_MINOR / r,
e = Math.sqrt(1 - tmp * tmp),
ts = Math.exp(-point.y / r),
phi = Math.PI / 2 - 2 * Math.atan(ts);
for (var i = 0, dphi = 0.1, con; i < 15 && Math.abs(dphi) > 1e-7; i++) {
con = e * Math.sin(phi);
con = Math.pow((1 - con) / (1 + con), e / 2);
dphi = Math.PI / 2 - 2 * Math.atan(ts * con) - phi;
phi += dphi;
}
return new LatLng(phi * d, point.x * d / r);
}
};
/*
* @class Projection
* An object with methods for projecting geographical coordinates of the world onto
* a flat surface (and back). See [Map projection](http://en.wikipedia.org/wiki/Map_projection).
* @property bounds: Bounds
* The bounds (specified in CRS units) where the projection is valid
* @method project(latlng: LatLng): Point
* Projects geographical coordinates into a 2D point.
* Only accepts actual `L.LatLng` instances, not arrays.
* @method unproject(point: Point): LatLng
* The inverse of `project`. Projects a 2D point into a geographical location.
* Only accepts actual `L.Point` instances, not arrays.
* Note that the projection instances do not inherit from Leafet's `Class` object,
* and can't be instantiated. Also, new classes can't inherit from them,
* and methods can't be added to them with the `include` function.
*/
var index = (Object.freeze || Object)({
LonLat: LonLat,
Mercator: Mercator,
SphericalMercator: SphericalMercator
});
/*
* @namespace CRS
* @crs L.CRS.EPSG3395
*
* Rarely used by some commercial tile providers. Uses Elliptical Mercator projection.
*/
var EPSG3395 = extend({}, Earth, {
code: 'EPSG:3395',
projection: Mercator,
transformation: (function () {
var scale = 0.5 / (Math.PI * Mercator.R);
return toTransformation(scale, 0.5, -scale, 0.5);
}())
});
/*
* @namespace CRS
* @crs L.CRS.EPSG4326
*
* A common CRS among GIS enthusiasts. Uses simple Equirectangular projection.
*
* Leaflet 1.0.x complies with the [TMS coordinate scheme for EPSG:4326](https://wiki.osgeo.org/wiki/Tile_Map_Service_Specification#global-geodetic),
* which is a breaking change from 0.7.x behaviour. If you are using a `TileLayer`
* with this CRS, ensure that there are two 256x256 pixel tiles covering the
* whole earth at zoom level zero, and that the tile coordinate origin is (-180,+90),
* or (-180,-90) for `TileLayer`s with [the `tms` option](#tilelayer-tms) set.
*/
var EPSG4326 = extend({}, Earth, {
code: 'EPSG:4326',
projection: LonLat,
transformation: toTransformation(1 / 180, 1, -1 / 180, 0.5)
});
/*
* @namespace CRS
* @crs L.CRS.Simple
*
* A simple CRS that maps longitude and latitude into `x` and `y` directly.
* May be used for maps of flat surfaces (e.g. game maps). Note that the `y`
* axis should still be inverted (going from bottom to top). `distance()` returns
* simple euclidean distance.
*/
var Simple = extend({}, CRS, {
projection: LonLat,
transformation: toTransformation(1, 0, -1, 0),
scale: function (zoom) {
return Math.pow(2, zoom);
},
zoom: function (scale) {
return Math.log(scale) / Math.LN2;
},
distance: function (latlng1, latlng2) {
var dx = latlng2.lng - latlng1.lng,
dy = latlng2.lat - latlng1.lat;
return Math.sqrt(dx * dx + dy * dy);
},
infinite: true
});
CRS.Earth = Earth;
CRS.EPSG3395 = EPSG3395;
CRS.EPSG3857 = EPSG3857;
CRS.EPSG900913 = EPSG900913;
CRS.EPSG4326 = EPSG4326;
CRS.Simple = Simple;
/*
* @class Layer
* @inherits Evented
* @aka L.Layer
* @aka ILayer
*
* A set of methods from the Layer base class that all Leaflet layers use.
* Inherits all methods, options and events from `L.Evented`.
*
* @example
*
* ```js
* var layer = L.marker(latlng).addTo(map);
* layer.addTo(map);
* layer.remove();
* ```
*
* @event add: Event
* Fired after the layer is added to a map
*
* @event remove: Event
* Fired after the layer is removed from a map
*/
var Layer = Evented.extend({
// Classes extending `L.Layer` will inherit the following options:
options: {
// @option pane: String = 'overlayPane'
// By default the layer will be added to the map's [overlay pane](#map-overlaypane). Overriding this option will cause the layer to be placed on another pane by default.
pane: 'overlayPane',
// @option attribution: String = null
// String to be shown in the attribution control, e.g. "© OpenStreetMap contributors". It describes the layer data and is often a legal obligation towards copyright holders and tile providers.
attribution: null,
bubblingMouseEvents: true
},
/* @section
* Classes extending `L.Layer` will inherit the following methods:
*
* @method addTo(map: Map|LayerGroup): this
* Adds the layer to the given map or layer group.
*/
addTo: function (map) {
map.addLayer(this);
return this;
},
// @method remove: this
// Removes the layer from the map it is currently active on.
remove: function () {
return this.removeFrom(this._map || this._mapToAdd);
},
// @method removeFrom(map: Map): this
// Removes the layer from the given map
removeFrom: function (obj) {
if (obj) {
obj.removeLayer(this);
}
return this;
},
// @method getPane(name? : String): HTMLElement
// Returns the `HTMLElement` representing the named pane on the map. If `name` is omitted, returns the pane for this layer.
getPane: function (name) {
return this._map.getPane(name ? (this.options[name] || name) : this.options.pane);
},
addInteractiveTarget: function (targetEl) {
this._map._targets[stamp(targetEl)] = this;
return this;
},
removeInteractiveTarget: function (targetEl) {
delete this._map._targets[stamp(targetEl)];
return this;
},
// @method getAttribution: String
// Used by the `attribution control`, returns the [attribution option](#gridlayer-attribution).
getAttribution: function () {
return this.options.attribution;
},
_layerAdd: function (e) {
var map = e.target;
// check in case layer gets added and then removed before the map is ready
if (!map.hasLayer(this)) { return; }
this._map = map;
this._zoomAnimated = map._zoomAnimated;
if (this.getEvents) {
var events = this.getEvents();
map.on(events, this);
this.once('remove', function () {
map.off(events, this);
}, this);
}
this.onAdd(map);
if (this.getAttribution && map.attributionControl) {
map.attributionControl.addAttribution(this.getAttribution());
}
this.fire('add');
map.fire('layeradd', {layer: this});
}
});
/* @section Extension methods
* @uninheritable
*
* Every layer should extend from `L.Layer` and (re-)implement the following methods.
*
* @method onAdd(map: Map): this
* Should contain code that creates DOM elements for the layer, adds them to `map panes` where they should belong and puts listeners on relevant map events. Called on [`map.addLayer(layer)`](#map-addlayer).
*
* @method onRemove(map: Map): this
* Should contain all clean up code that removes the layer's elements from the DOM and removes listeners previously added in [`onAdd`](#layer-onadd). Called on [`map.removeLayer(layer)`](#map-removelayer).
*
* @method getEvents(): Object
* This optional method should return an object like `{ viewreset: this._reset }` for [`addEventListener`](#evented-addeventlistener). The event handlers in this object will be automatically added and removed from the map with your layer.
*
* @method getAttribution(): String
* This optional method should return a string containing HTML to be shown on the `Attribution control` whenever the layer is visible.
*
* @method beforeAdd(map: Map): this
* Optional method. Called on [`map.addLayer(layer)`](#map-addlayer), before the layer is added to the map, before events are initialized, without waiting until the map is in a usable state. Use for early initialization only.
*/
/* @namespace Map
* @section Layer events
*
* @event layeradd: LayerEvent
* Fired when a new layer is added to the map.
*
* @event layerremove: LayerEvent
* Fired when some layer is removed from the map
*
* @section Methods for Layers and Controls
*/
Map.include({
// @method addLayer(layer: Layer): this
// Adds the given layer to the map
addLayer: function (layer) {
if (!layer._layerAdd) {
throw new Error('The provided object is not a Layer.');
}
var id = stamp(layer);
if (this._layers[id]) { return this; }
this._layers[id] = layer;
layer._mapToAdd = this;
if (layer.beforeAdd) {
layer.beforeAdd(this);
}
this.whenReady(layer._layerAdd, layer);
return this;
},
// @method removeLayer(layer: Layer): this
// Removes the given layer from the map.
removeLayer: function (layer) {
var id = stamp(layer);
if (!this._layers[id]) { return this; }
if (this._loaded) {
layer.onRemove(this);
}
if (layer.getAttribution && this.attributionControl) {
this.attributionControl.removeAttribution(layer.getAttribution());
}
delete this._layers[id];
if (this._loaded) {
this.fire('layerremove', {layer: layer});
layer.fire('remove');
}
layer._map = layer._mapToAdd = null;
return this;
},
// @method hasLayer(layer: Layer): Boolean
// Returns `true` if the given layer is currently added to the map
hasLayer: function (layer) {
return !!layer && (stamp(layer) in this._layers);
},
/* @method eachLayer(fn: Function, context?: Object): this
* Iterates over the layers of the map, optionally specifying context of the iterator function.
* ```
* map.eachLayer(function(layer){
* layer.bindPopup('Hello');
* });
* ```
*/
eachLayer: function (method, context) {
for (var i in this._layers) {
method.call(context, this._layers[i]);
}
return this;
},
_addLayers: function (layers) {
layers = layers ? (isArray(layers) ? layers : [layers]) : [];
for (var i = 0, len = layers.length; i < len; i++) {
this.addLayer(layers[i]);
}
},
_addZoomLimit: function (layer) {
if (isNaN(layer.options.maxZoom) || !isNaN(layer.options.minZoom)) {
this._zoomBoundLayers[stamp(layer)] = layer;
this._updateZoomLevels();
}
},
_removeZoomLimit: function (layer) {
var id = stamp(layer);
if (this._zoomBoundLayers[id]) {
delete this._zoomBoundLayers[id];
this._updateZoomLevels();
}
},
_updateZoomLevels: function () {
var minZoom = Infinity,
maxZoom = -Infinity,
oldZoomSpan = this._getZoomSpan();
for (var i in this._zoomBoundLayers) {
var options = this._zoomBoundLayers[i].options;
minZoom = options.minZoom === undefined ? minZoom : Math.min(minZoom, options.minZoom);
maxZoom = options.maxZoom === undefined ? maxZoom : Math.max(maxZoom, options.maxZoom);
}
this._layersMaxZoom = maxZoom === -Infinity ? undefined : maxZoom;
this._layersMinZoom = minZoom === Infinity ? undefined : minZoom;
// @section Map state change events
// @event zoomlevelschange: Event
// Fired when the number of zoomlevels on the map is changed due
// to adding or removing a layer.
if (oldZoomSpan !== this._getZoomSpan()) {
this.fire('zoomlevelschange');
}
if (this.options.maxZoom === undefined && this._layersMaxZoom && this.getZoom() > this._layersMaxZoom) {
this.setZoom(this._layersMaxZoom);
}
if (this.options.minZoom === undefined && this._layersMinZoom && this.getZoom() < this._layersMinZoom) {
this.setZoom(this._layersMinZoom);
}
}
});
/*
* @class LayerGroup
* @aka L.LayerGroup
* @inherits Layer
*
* Used to group several layers and handle them as one. If you add it to the map,
* any layers added or removed from the group will be added/removed on the map as
* well. Extends `Layer`.
*
* @example
*
* ```js
* L.layerGroup([marker1, marker2])
* .addLayer(polyline)
* .addTo(map);
* ```
*/
var LayerGroup = Layer.extend({
initialize: function (layers, options) {
setOptions(this, options);
this._layers = {};
var i, len;
if (layers) {
for (i = 0, len = layers.length; i < len; i++) {
this.addLayer(layers[i]);
}
}
},
// @method addLayer(layer: Layer): this
// Adds the given layer to the group.
addLayer: function (layer) {
var id = this.getLayerId(layer);
this._layers[id] = layer;
if (this._map) {
this._map.addLayer(layer);
}
return this;
},
// @method removeLayer(layer: Layer): this
// Removes the given layer from the group.
// @alternative
// @method removeLayer(id: Number): this
// Removes the layer with the given internal ID from the group.
removeLayer: function (layer) {
var id = layer in this._layers ? layer : this.getLayerId(layer);
if (this._map && this._layers[id]) {
this._map.removeLayer(this._layers[id]);
}
delete this._layers[id];
return this;
},
// @method hasLayer(layer: Layer): Boolean
// Returns `true` if the given layer is currently added to the group.
// @alternative
// @method hasLayer(id: Number): Boolean
// Returns `true` if the given internal ID is currently added to the group.
hasLayer: function (layer) {
return !!layer && (layer in this._layers || this.getLayerId(layer) in this._layers);
},
// @method clearLayers(): this
// Removes all the layers from the group.
clearLayers: function () {
return this.eachLayer(this.removeLayer, this);
},
// @method invoke(methodName: String, …): this
// Calls `methodName` on every layer contained in this group, passing any
// additional parameters. Has no effect if the layers contained do not
// implement `methodName`.
invoke: function (methodName) {
var args = Array.prototype.slice.call(arguments, 1),
i, layer;
for (i in this._layers) {
layer = this._layers[i];
if (layer[methodName]) {
layer[methodName].apply(layer, args);
}
}
return this;
},
onAdd: function (map) {
this.eachLayer(map.addLayer, map);
},
onRemove: function (map) {
this.eachLayer(map.removeLayer, map);
},
// @method eachLayer(fn: Function, context?: Object): this
// Iterates over the layers of the group, optionally specifying context of the iterator function.
// ```js
// group.eachLayer(function (layer) {
// layer.bindPopup('Hello');
// });
// ```
eachLayer: function (method, context) {
for (var i in this._layers) {
method.call(context, this._layers[i]);
}
return this;
},
// @method getLayer(id: Number): Layer
// Returns the layer with the given internal ID.
getLayer: function (id) {
return this._layers[id];
},
// @method getLayers(): Layer[]
// Returns an array of all the layers added to the group.
getLayers: function () {
var layers = [];
this.eachLayer(layers.push, layers);
return layers;
},
// @method setZIndex(zIndex: Number): this
// Calls `setZIndex` on every layer contained in this group, passing the z-index.
setZIndex: function (zIndex) {
return this.invoke('setZIndex', zIndex);
},
// @method getLayerId(layer: Layer): Number
// Returns the internal ID for a layer
getLayerId: function (layer) {
return stamp(layer);
}
});
// @factory L.layerGroup(layers?: Layer[], options?: Object)
// Create a layer group, optionally given an initial set of layers and an `options` object.
var layerGroup = function (layers, options) {
return new LayerGroup(layers, options);
};
/*
* @class FeatureGroup
* @aka L.FeatureGroup
* @inherits LayerGroup
*
* Extended `LayerGroup` that makes it easier to do the same thing to all its member layers:
* * [`bindPopup`](#layer-bindpopup) binds a popup to all of the layers at once (likewise with [`bindTooltip`](#layer-bindtooltip))
* * Events are propagated to the `FeatureGroup`, so if the group has an event
* handler, it will handle events from any of the layers. This includes mouse events
* and custom events.
* * Has `layeradd` and `layerremove` events
*
* @example
*
* ```js
* L.featureGroup([marker1, marker2, polyline])
* .bindPopup('Hello world!')
* .on('click', function() { alert('Clicked on a member of the group!'); })
* .addTo(map);
* ```
*/
var FeatureGroup = LayerGroup.extend({
addLayer: function (layer) {
if (this.hasLayer(layer)) {
return this;
}
layer.addEventParent(this);
LayerGroup.prototype.addLayer.call(this, layer);
// @event layeradd: LayerEvent
// Fired when a layer is added to this `FeatureGroup`
return this.fire('layeradd', {layer: layer});
},
removeLayer: function (layer) {
if (!this.hasLayer(layer)) {
return this;
}
if (layer in this._layers) {
layer = this._layers[layer];
}
layer.removeEventParent(this);
LayerGroup.prototype.removeLayer.call(this, layer);
// @event layerremove: LayerEvent
// Fired when a layer is removed from this `FeatureGroup`
return this.fire('layerremove', {layer: layer});
},
// @method setStyle(style: Path options): this
// Sets the given path options to each layer of the group that has a `setStyle` method.
setStyle: function (style) {
return this.invoke('setStyle', style);
},
// @method bringToFront(): this
// Brings the layer group to the top of all other layers
bringToFront: function () {
return this.invoke('bringToFront');
},
// @method bringToBack(): this
// Brings the layer group to the back of all other layers
bringToBack: function () {
return this.invoke('bringToBack');
},
// @method getBounds(): LatLngBounds
// Returns the LatLngBounds of the Feature Group (created from bounds and coordinates of its children).
getBounds: function () {
var bounds = new LatLngBounds();
for (var id in this._layers) {
var layer = this._layers[id];
bounds.extend(layer.getBounds ? layer.getBounds() : layer.getLatLng());
}
return bounds;
}
});
// @factory L.featureGroup(layers: Layer[])
// Create a feature group, optionally given an initial set of layers.
var featureGroup = function (layers) {
return new FeatureGroup(layers);
};
/*
* @class Icon
* @aka L.Icon
*
* Represents an icon to provide when creating a marker.
*
* @example
*
* ```js
* var myIcon = L.icon({
* iconUrl: 'my-icon.png',
* iconRetinaUrl: 'my-icon@2x.png',
* iconSize: [38, 95],
* iconAnchor: [22, 94],
* popupAnchor: [-3, -76],
* shadowUrl: 'my-icon-shadow.png',
* shadowRetinaUrl: 'my-icon-shadow@2x.png',
* shadowSize: [68, 95],
* shadowAnchor: [22, 94]
* });
*
* L.marker([50.505, 30.57], {icon: myIcon}).addTo(map);
* ```
*
* `L.Icon.Default` extends `L.Icon` and is the blue icon Leaflet uses for markers by default.
*
*/
var Icon = Class.extend({
/* @section
* @aka Icon options
*
* @option iconUrl: String = null
* **(required)** The URL to the icon image (absolute or relative to your script path).
*
* @option iconRetinaUrl: String = null
* The URL to a retina sized version of the icon image (absolute or relative to your
* script path). Used for Retina screen devices.
*
* @option iconSize: Point = null
* Size of the icon image in pixels.
*
* @option iconAnchor: Point = null
* The coordinates of the "tip" of the icon (relative to its top left corner). The icon
* will be aligned so that this point is at the marker's geographical location. Centered
* by default if size is specified, also can be set in CSS with negative margins.
*
* @option popupAnchor: Point = [0, 0]
* The coordinates of the point from which popups will "open", relative to the icon anchor.
*
* @option tooltipAnchor: Point = [0, 0]
* The coordinates of the point from which tooltips will "open", relative to the icon anchor.
*
* @option shadowUrl: String = null
* The URL to the icon shadow image. If not specified, no shadow image will be created.
*
* @option shadowRetinaUrl: String = null
*
* @option shadowSize: Point = null
* Size of the shadow image in pixels.
*
* @option shadowAnchor: Point = null
* The coordinates of the "tip" of the shadow (relative to its top left corner) (the same
* as iconAnchor if not specified).
*
* @option className: String = ''
* A custom class name to assign to both icon and shadow images. Empty by default.
*/
options: {
popupAnchor: [0, 0],
tooltipAnchor: [0, 0]
},
initialize: function (options) {
setOptions(this, options);
},
// @method createIcon(oldIcon?: HTMLElement): HTMLElement
// Called internally when the icon has to be shown, returns a `<img>` HTML element
// styled according to the options.
createIcon: function (oldIcon) {
return this._createIcon('icon', oldIcon);
},
// @method createShadow(oldIcon?: HTMLElement): HTMLElement
// As `createIcon`, but for the shadow beneath it.
createShadow: function (oldIcon) {
return this._createIcon('shadow', oldIcon);
},
_createIcon: function (name, oldIcon) {
var src = this._getIconUrl(name);
if (!src) {
if (name === 'icon') {
throw new Error('iconUrl not set in Icon options (see the docs).');
}
return null;
}
var img = this._createImg(src, oldIcon && oldIcon.tagName === 'IMG' ? oldIcon : null);
this._setIconStyles(img, name);
return img;
},
_setIconStyles: function (img, name) {
var options = this.options;
var sizeOption = options[name + 'Size'];
if (typeof sizeOption === 'number') {
sizeOption = [sizeOption, sizeOption];
}
var size = toPoint(sizeOption),
anchor = toPoint(name === 'shadow' && options.shadowAnchor || options.iconAnchor ||
size && size.divideBy(2, true));
img.className = 'leaflet-marker-' + name + ' ' + (options.className || '');
if (anchor) {
img.style.marginLeft = (-anchor.x) + 'px';
img.style.marginTop = (-anchor.y) + 'px';
}
if (size) {
img.style.width = size.x + 'px';
img.style.height = size.y + 'px';
}
},
_createImg: function (src, el) {
el = el || document.createElement('img');
el.src = src;
return el;
},
_getIconUrl: function (name) {
return retina && this.options[name + 'RetinaUrl'] || this.options[name + 'Url'];
}
});
// @factory L.icon(options: Icon options)
// Creates an icon instance with the given options.
function icon(options) {
return new Icon(options);
}
/*
* @miniclass Icon.Default (Icon)
* @aka L.Icon.Default
* @section
*
* A trivial subclass of `Icon`, represents the icon to use in `Marker`s when
* no icon is specified. Points to the blue marker image distributed with Leaflet
* releases.
*
* In order to customize the default icon, just change the properties of `L.Icon.Default.prototype.options`
* (which is a set of `Icon options`).
*
* If you want to _completely_ replace the default icon, override the
* `L.Marker.prototype.options.icon` with your own icon instead.
*/
var IconDefault = Icon.extend({
options: {
iconUrl: 'marker-icon.png',
iconRetinaUrl: 'marker-icon-2x.png',
shadowUrl: 'marker-shadow.png',
iconSize: [25, 41],
iconAnchor: [12, 41],
popupAnchor: [1, -34],
tooltipAnchor: [16, -28],
shadowSize: [41, 41]
},
_getIconUrl: function (name) {
if (!IconDefault.imagePath) { // Deprecated, backwards-compatibility only
IconDefault.imagePath = this._detectIconPath();
}
// @option imagePath: String
// `Icon.Default` will try to auto-detect the location of the
// blue icon images. If you are placing these images in a non-standard
// way, set this option to point to the right path.
return (this.options.imagePath || IconDefault.imagePath) + Icon.prototype._getIconUrl.call(this, name);
},
_detectIconPath: function () {
var el = create$1('div', 'leaflet-default-icon-path', document.body);
var path = getStyle(el, 'background-image') ||
getStyle(el, 'backgroundImage'); // IE8
document.body.removeChild(el);
if (path === null || path.indexOf('url') !== 0) {
path = '';
} else {
path = path.replace(/^url\(["']?/, '').replace(/marker-icon\.png["']?\)$/, '');
}
return path;
}
});
/*
* L.Handler.MarkerDrag is used internally by L.Marker to make the markers draggable.
*/
/* @namespace Marker
* @section Interaction handlers
*
* Interaction handlers are properties of a marker instance that allow you to control interaction behavior in runtime, enabling or disabling certain features such as dragging (see `Handler` methods). Example:
*
* ```js
* marker.dragging.disable();
* ```
*
* @property dragging: Handler
* Marker dragging handler (by both mouse and touch). Only valid when the marker is on the map (Otherwise set [`marker.options.draggable`](#marker-draggable)).
*/
var MarkerDrag = Handler.extend({
initialize: function (marker) {
this._marker = marker;
},
addHooks: function () {
var icon = this._marker._icon;
if (!this._draggable) {
this._draggable = new Draggable(icon, icon, true);
}
this._draggable.on({
dragstart: this._onDragStart,
predrag: this._onPreDrag,
drag: this._onDrag,
dragend: this._onDragEnd
}, this).enable();
addClass(icon, 'leaflet-marker-draggable');
},
removeHooks: function () {
this._draggable.off({
dragstart: this._onDragStart,
predrag: this._onPreDrag,
drag: this._onDrag,
dragend: this._onDragEnd
}, this).disable();
if (this._marker._icon) {
removeClass(this._marker._icon, 'leaflet-marker-draggable');
}
},
moved: function () {
return this._draggable && this._draggable._moved;
},
_adjustPan: function (e) {
var marker = this._marker,
map = marker._map,
speed = this._marker.options.autoPanSpeed,
padding = this._marker.options.autoPanPadding,
iconPos = getPosition(marker._icon),
bounds = map.getPixelBounds(),
origin = map.getPixelOrigin();
var panBounds = toBounds(
bounds.min._subtract(origin).add(padding),
bounds.max._subtract(origin).subtract(padding)
);
if (!panBounds.contains(iconPos)) {
// Compute incremental movement
var movement = toPoint(
(Math.max(panBounds.max.x, iconPos.x) - panBounds.max.x) / (bounds.max.x - panBounds.max.x) -
(Math.min(panBounds.min.x, iconPos.x) - panBounds.min.x) / (bounds.min.x - panBounds.min.x),
(Math.max(panBounds.max.y, iconPos.y) - panBounds.max.y) / (bounds.max.y - panBounds.max.y) -
(Math.min(panBounds.min.y, iconPos.y) - panBounds.min.y) / (bounds.min.y - panBounds.min.y)
).multiplyBy(speed);
map.panBy(movement, {animate: false});
this._draggable._newPos._add(movement);
this._draggable._startPos._add(movement);
setPosition(marker._icon, this._draggable._newPos);
this._onDrag(e);
this._panRequest = requestAnimFrame(this._adjustPan.bind(this, e));
}
},
_onDragStart: function () {
// @section Dragging events
// @event dragstart: Event
// Fired when the user starts dragging the marker.
// @event movestart: Event
// Fired when the marker starts moving (because of dragging).
this._oldLatLng = this._marker.getLatLng();
this._marker
.closePopup()
.fire('movestart')
.fire('dragstart');
},
_onPreDrag: function (e) {
if (this._marker.options.autoPan) {
cancelAnimFrame(this._panRequest);
this._panRequest = requestAnimFrame(this._adjustPan.bind(this, e));
}
},
_onDrag: function (e) {
var marker = this._marker,
shadow = marker._shadow,
iconPos = getPosition(marker._icon),
latlng = marker._map.layerPointToLatLng(iconPos);
// update shadow position
if (shadow) {
setPosition(shadow, iconPos);
}
marker._latlng = latlng;
e.latlng = latlng;
e.oldLatLng = this._oldLatLng;
// @event drag: Event
// Fired repeatedly while the user drags the marker.
marker
.fire('move', e)
.fire('drag', e);
},
_onDragEnd: function (e) {
// @event dragend: DragEndEvent
// Fired when the user stops dragging the marker.
cancelAnimFrame(this._panRequest);
// @event moveend: Event
// Fired when the marker stops moving (because of dragging).
delete this._oldLatLng;
this._marker
.fire('moveend')
.fire('dragend', e);
}
});
/*
* @class Marker
* @inherits Interactive layer
* @aka L.Marker
* L.Marker is used to display clickable/draggable icons on the map. Extends `Layer`.
*
* @example
*
* ```js
* L.marker([50.5, 30.5]).addTo(map);
* ```
*/
var Marker = Layer.extend({
// @section
// @aka Marker options
options: {
// @option icon: Icon = *
// Icon instance to use for rendering the marker.
// See [Icon documentation](#L.Icon) for details on how to customize the marker icon.
// If not specified, a common instance of `L.Icon.Default` is used.
icon: new IconDefault(),
// Option inherited from "Interactive layer" abstract class
interactive: true,
// @option keyboard: Boolean = true
// Whether the marker can be tabbed to with a keyboard and clicked by pressing enter.
keyboard: true,
// @option title: String = ''
// Text for the browser tooltip that appear on marker hover (no tooltip by default).
title: '',
// @option alt: String = ''
// Text for the `alt` attribute of the icon image (useful for accessibility).
alt: '',
// @option zIndexOffset: Number = 0
// By default, marker images zIndex is set automatically based on its latitude. Use this option if you want to put the marker on top of all others (or below), specifying a high value like `1000` (or high negative value, respectively).
zIndexOffset: 0,
// @option opacity: Number = 1.0
// The opacity of the marker.
opacity: 1,
// @option riseOnHover: Boolean = false
// If `true`, the marker will get on top of others when you hover the mouse over it.
riseOnHover: false,
// @option riseOffset: Number = 250
// The z-index offset used for the `riseOnHover` feature.
riseOffset: 250,
// @option pane: String = 'markerPane'
// `Map pane` where the markers icon will be added.
pane: 'markerPane',
// @option pane: String = 'shadowPane'
// `Map pane` where the markers shadow will be added.
shadowPane: 'shadowPane',
// @option bubblingMouseEvents: Boolean = false
// When `true`, a mouse event on this marker will trigger the same event on the map
// (unless [`L.DomEvent.stopPropagation`](#domevent-stoppropagation) is used).
bubblingMouseEvents: false,
// @section Draggable marker options
// @option draggable: Boolean = false
// Whether the marker is draggable with mouse/touch or not.
draggable: false,
// @option autoPan: Boolean = false
// Whether to pan the map when dragging this marker near its edge or not.
autoPan: false,
// @option autoPanPadding: Point = Point(50, 50)
// Distance (in pixels to the left/right and to the top/bottom) of the
// map edge to start panning the map.
autoPanPadding: [50, 50],
// @option autoPanSpeed: Number = 10
// Number of pixels the map should pan by.
autoPanSpeed: 10
},
/* @section
*
* In addition to [shared layer methods](#Layer) like `addTo()` and `remove()` and [popup methods](#Popup) like bindPopup() you can also use the following methods:
*/
initialize: function (latlng, options) {
setOptions(this, options);
this._latlng = toLatLng(latlng);
},
onAdd: function (map) {
this._zoomAnimated = this._zoomAnimated && map.options.markerZoomAnimation;
if (this._zoomAnimated) {
map.on('zoomanim', this._animateZoom, this);
}
this._initIcon();
this.update();
},
onRemove: function (map) {
if (this.dragging && this.dragging.enabled()) {
this.options.draggable = true;
this.dragging.removeHooks();
}
delete this.dragging;
if (this._zoomAnimated) {
map.off('zoomanim', this._animateZoom, this);
}
this._removeIcon();
this._removeShadow();
},
getEvents: function () {
return {
zoom: this.update,
viewreset: this.update
};
},
// @method getLatLng: LatLng
// Returns the current geographical position of the marker.
getLatLng: function () {
return this._latlng;
},
// @method setLatLng(latlng: LatLng): this
// Changes the marker position to the given point.
setLatLng: function (latlng) {
var oldLatLng = this._latlng;
this._latlng = toLatLng(latlng);
this.update();
// @event move: Event
// Fired when the marker is moved via [`setLatLng`](#marker-setlatlng) or by [dragging](#marker-dragging). Old and new coordinates are included in event arguments as `oldLatLng`, `latlng`.
return this.fire('move', {oldLatLng: oldLatLng, latlng: this._latlng});
},
// @method setZIndexOffset(offset: Number): this
// Changes the [zIndex offset](#marker-zindexoffset) of the marker.
setZIndexOffset: function (offset) {
this.options.zIndexOffset = offset;
return this.update();
},
// @method getIcon: Icon
// Returns the current icon used by the marker
getIcon: function () {
return this.options.icon;
},
// @method setIcon(icon: Icon): this
// Changes the marker icon.
setIcon: function (icon) {
this.options.icon = icon;
if (this._map) {
this._initIcon();
this.update();
}
if (this._popup) {
this.bindPopup(this._popup, this._popup.options);
}
return this;
},
getElement: function () {
return this._icon;
},
update: function () {
if (this._icon && this._map) {
var pos = this._map.latLngToLayerPoint(this._latlng).round();
this._setPos(pos);
}
return this;
},
_initIcon: function () {
var options = this.options,
classToAdd = 'leaflet-zoom-' + (this._zoomAnimated ? 'animated' : 'hide');
var icon = options.icon.createIcon(this._icon),
addIcon = false;
// if we're not reusing the icon, remove the old one and init new one
if (icon !== this._icon) {
if (this._icon) {
this._removeIcon();
}
addIcon = true;
if (options.title) {
icon.title = options.title;
}
if (icon.tagName === 'IMG') {
icon.alt = options.alt || '';
}
}
addClass(icon, classToAdd);
if (options.keyboard) {
icon.tabIndex = '0';
}
this._icon = icon;
if (options.riseOnHover) {
this.on({
mouseover: this._bringToFront,
mouseout: this._resetZIndex
});
}
var newShadow = options.icon.createShadow(this._shadow),
addShadow = false;
if (newShadow !== this._shadow) {
this._removeShadow();
addShadow = true;
}
if (newShadow) {
addClass(newShadow, classToAdd);
newShadow.alt = '';
}
this._shadow = newShadow;
if (options.opacity < 1) {
this._updateOpacity();
}
if (addIcon) {
this.getPane().appendChild(this._icon);
}
this._initInteraction();
if (newShadow && addShadow) {
this.getPane(options.shadowPane).appendChild(this._shadow);
}
},
_removeIcon: function () {
if (this.options.riseOnHover) {
this.off({
mouseover: this._bringToFront,
mouseout: this._resetZIndex
});
}
remove(this._icon);
this.removeInteractiveTarget(this._icon);
this._icon = null;
},
_removeShadow: function () {
if (this._shadow) {
remove(this._shadow);
}
this._shadow = null;
},
_setPos: function (pos) {
if (this._icon) {
setPosition(this._icon, pos);
}
if (this._shadow) {
setPosition(this._shadow, pos);
}
this._zIndex = pos.y + this.options.zIndexOffset;
this._resetZIndex();
},
_updateZIndex: function (offset) {
if (this._icon) {
this._icon.style.zIndex = this._zIndex + offset;
}
},
_animateZoom: function (opt) {
var pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center).round();
this._setPos(pos);
},
_initInteraction: function () {
if (!this.options.interactive) { return; }
addClass(this._icon, 'leaflet-interactive');
this.addInteractiveTarget(this._icon);
if (MarkerDrag) {
var draggable = this.options.draggable;
if (this.dragging) {
draggable = this.dragging.enabled();
this.dragging.disable();
}
this.dragging = new MarkerDrag(this);
if (draggable) {
this.dragging.enable();
}
}
},
// @method setOpacity(opacity: Number): this
// Changes the opacity of the marker.
setOpacity: function (opacity) {
this.options.opacity = opacity;
if (this._map) {
this._updateOpacity();
}
return this;
},
_updateOpacity: function () {
var opacity = this.options.opacity;
if (this._icon) {
setOpacity(this._icon, opacity);
}
if (this._shadow) {
setOpacity(this._shadow, opacity);
}
},
_bringToFront: function () {
this._updateZIndex(this.options.riseOffset);
},
_resetZIndex: function () {
this._updateZIndex(0);
},
_getPopupAnchor: function () {
return this.options.icon.options.popupAnchor;
},
_getTooltipAnchor: function () {
return this.options.icon.options.tooltipAnchor;
}
});
// factory L.marker(latlng: LatLng, options? : Marker options)
// @factory L.marker(latlng: LatLng, options? : Marker options)
// Instantiates a Marker object given a geographical point and optionally an options object.
function marker(latlng, options) {
return new Marker(latlng, options);
}
/*
* @class Path
* @aka L.Path
* @inherits Interactive layer
*
* An abstract class that contains options and constants shared between vector
* overlays (Polygon, Polyline, Circle). Do not use it directly. Extends `Layer`.
*/
var Path = Layer.extend({
// @section
// @aka Path options
options: {
// @option stroke: Boolean = true
// Whether to draw stroke along the path. Set it to `false` to disable borders on polygons or circles.
stroke: true,
// @option color: String = '#3388ff'
// Stroke color
color: '#3388ff',
// @option weight: Number = 3
// Stroke width in pixels
weight: 3,
// @option opacity: Number = 1.0
// Stroke opacity
opacity: 1,
// @option lineCap: String= 'round'
// A string that defines [shape to be used at the end](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linecap) of the stroke.
lineCap: 'round',
// @option lineJoin: String = 'round'
// A string that defines [shape to be used at the corners](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linejoin) of the stroke.
lineJoin: 'round',
// @option dashArray: String = null
// A string that defines the stroke [dash pattern](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-dasharray). Doesn't work on `Canvas`-powered layers in [some old browsers](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/setLineDash#Browser_compatibility).
dashArray: null,
// @option dashOffset: String = null
// A string that defines the [distance into the dash pattern to start the dash](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-dashoffset). Doesn't work on `Canvas`-powered layers in [some old browsers](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/setLineDash#Browser_compatibility).
dashOffset: null,
// @option fill: Boolean = depends
// Whether to fill the path with color. Set it to `false` to disable filling on polygons or circles.
fill: false,
// @option fillColor: String = *
// Fill color. Defaults to the value of the [`color`](#path-color) option
fillColor: null,
// @option fillOpacity: Number = 0.2
// Fill opacity.
fillOpacity: 0.2,
// @option fillRule: String = 'evenodd'
// A string that defines [how the inside of a shape](https://developer.mozilla.org/docs/Web/SVG/Attribute/fill-rule) is determined.
fillRule: 'evenodd',
// className: '',
// Option inherited from "Interactive layer" abstract class
interactive: true,
// @option bubblingMouseEvents: Boolean = true
// When `true`, a mouse event on this path will trigger the same event on the map
// (unless [`L.DomEvent.stopPropagation`](#domevent-stoppropagation) is used).
bubblingMouseEvents: true
},
beforeAdd: function (map) {
// Renderer is set here because we need to call renderer.getEvents
// before this.getEvents.
this._renderer = map.getRenderer(this);
},
onAdd: function () {
this._renderer._initPath(this);
this._reset();
this._renderer._addPath(this);
},
onRemove: function () {
this._renderer._removePath(this);
},
// @method redraw(): this
// Redraws the layer. Sometimes useful after you changed the coordinates that the path uses.
redraw: function () {
if (this._map) {
this._renderer._updatePath(this);
}
return this;
},
// @method setStyle(style: Path options): this
// Changes the appearance of a Path based on the options in the `Path options` object.
setStyle: function (style) {
setOptions(this, style);
if (this._renderer) {
this._renderer._updateStyle(this);
if (this.options.stroke && style && style.hasOwnProperty('weight')) {
this._updateBounds();
}
}
return this;
},
// @method bringToFront(): this
// Brings the layer to the top of all path layers.
bringToFront: function () {
if (this._renderer) {
this._renderer._bringToFront(this);
}
return this;
},
// @method bringToBack(): this
// Brings the layer to the bottom of all path layers.
bringToBack: function () {
if (this._renderer) {
this._renderer._bringToBack(this);
}
return this;
},
getElement: function () {
return this._path;
},
_reset: function () {
// defined in child classes
this._project();
this._update();
},
_clickTolerance: function () {
// used when doing hit detection for Canvas layers
return (this.options.stroke ? this.options.weight / 2 : 0) + this._renderer.options.tolerance;
}
});
/*
* @class CircleMarker
* @aka L.CircleMarker
* @inherits Path
*
* A circle of a fixed size with radius specified in pixels. Extends `Path`.
*/
var CircleMarker = Path.extend({
// @section
// @aka CircleMarker options
options: {
fill: true,
// @option radius: Number = 10
// Radius of the circle marker, in pixels
radius: 10
},
initialize: function (latlng, options) {
setOptions(this, options);
this._latlng = toLatLng(latlng);
this._radius = this.options.radius;
},
// @method setLatLng(latLng: LatLng): this
// Sets the position of a circle marker to a new location.
setLatLng: function (latlng) {
var oldLatLng = this._latlng;
this._latlng = toLatLng(latlng);
this.redraw();
// @event move: Event
// Fired when the marker is moved via [`setLatLng`](#circlemarker-setlatlng). Old and new coordinates are included in event arguments as `oldLatLng`, `latlng`.
return this.fire('move', {oldLatLng: oldLatLng, latlng: this._latlng});
},
// @method getLatLng(): LatLng
// Returns the current geographical position of the circle marker
getLatLng: function () {
return this._latlng;
},
// @method setRadius(radius: Number): this
// Sets the radius of a circle marker. Units are in pixels.
setRadius: function (radius) {
this.options.radius = this._radius = radius;
return this.redraw();
},
// @method getRadius(): Number
// Returns the current radius of the circle
getRadius: function () {
return this._radius;
},
setStyle : function (options) {
var radius = options && options.radius || this._radius;
Path.prototype.setStyle.call(this, options);
this.setRadius(radius);
return this;
},
_project: function () {
this._point = this._map.latLngToLayerPoint(this._latlng);
this._updateBounds();
},
_updateBounds: function () {
var r = this._radius,
r2 = this._radiusY || r,
w = this._clickTolerance(),
p = [r + w, r2 + w];
this._pxBounds = new Bounds(this._point.subtract(p), this._point.add(p));
},
_update: function () {
if (this._map) {
this._updatePath();
}
},
_updatePath: function () {
this._renderer._updateCircle(this);
},
_empty: function () {
return this._radius && !this._renderer._bounds.intersects(this._pxBounds);
},
// Needed by the `Canvas` renderer for interactivity
_containsPoint: function (p) {
return p.distanceTo(this._point) <= this._radius + this._clickTolerance();
}
});
// @factory L.circleMarker(latlng: LatLng, options?: CircleMarker options)
// Instantiates a circle marker object given a geographical point, and an optional options object.
function circleMarker(latlng, options) {
return new CircleMarker(latlng, options);
}
/*
* @class Circle
* @aka L.Circle
* @inherits CircleMarker
*
* A class for drawing circle overlays on a map. Extends `CircleMarker`.
*
* It's an approximation and starts to diverge from a real circle closer to poles (due to projection distortion).
*
* @example
*
* ```js
* L.circle([50.5, 30.5], {radius: 200}).addTo(map);
* ```
*/
var Circle = CircleMarker.extend({
initialize: function (latlng, options, legacyOptions) {
if (typeof options === 'number') {
// Backwards compatibility with 0.7.x factory (latlng, radius, options?)
options = extend({}, legacyOptions, {radius: options});
}
setOptions(this, options);
this._latlng = toLatLng(latlng);
if (isNaN(this.options.radius)) { throw new Error('Circle radius cannot be NaN'); }
// @section
// @aka Circle options
// @option radius: Number; Radius of the circle, in meters.
this._mRadius = this.options.radius;
},
// @method setRadius(radius: Number): this
// Sets the radius of a circle. Units are in meters.
setRadius: function (radius) {
this._mRadius = radius;
return this.redraw();
},
// @method getRadius(): Number
// Returns the current radius of a circle. Units are in meters.
getRadius: function () {
return this._mRadius;
},
// @method getBounds(): LatLngBounds
// Returns the `LatLngBounds` of the path.
getBounds: function () {
var half = [this._radius, this._radiusY || this._radius];
return new LatLngBounds(
this._map.layerPointToLatLng(this._point.subtract(half)),
this._map.layerPointToLatLng(this._point.add(half)));
},
setStyle: Path.prototype.setStyle,
_project: function () {
var lng = this._latlng.lng,
lat = this._latlng.lat,
map = this._map,
crs = map.options.crs;
if (crs.distance === Earth.distance) {
var d = Math.PI / 180,
latR = (this._mRadius / Earth.R) / d,
top = map.project([lat + latR, lng]),
bottom = map.project([lat - latR, lng]),
p = top.add(bottom).divideBy(2),
lat2 = map.unproject(p).lat,
lngR = Math.acos((Math.cos(latR * d) - Math.sin(lat * d) * Math.sin(lat2 * d)) /
(Math.cos(lat * d) * Math.cos(lat2 * d))) / d;
if (isNaN(lngR) || lngR === 0) {
lngR = latR / Math.cos(Math.PI / 180 * lat); // Fallback for edge case, #2425
}
this._point = p.subtract(map.getPixelOrigin());
this._radius = isNaN(lngR) ? 0 : p.x - map.project([lat2, lng - lngR]).x;
this._radiusY = p.y - top.y;
} else {
var latlng2 = crs.unproject(crs.project(this._latlng).subtract([this._mRadius, 0]));
this._point = map.latLngToLayerPoint(this._latlng);
this._radius = this._point.x - map.latLngToLayerPoint(latlng2).x;
}
this._updateBounds();
}
});
// @factory L.circle(latlng: LatLng, options?: Circle options)
// Instantiates a circle object given a geographical point, and an options object
// which contains the circle radius.
// @alternative
// @factory L.circle(latlng: LatLng, radius: Number, options?: Circle options)
// Obsolete way of instantiating a circle, for compatibility with 0.7.x code.
// Do not use in new applications or plugins.
function circle(latlng, options, legacyOptions) {
return new Circle(latlng, options, legacyOptions);
}
/*
* @class Polyline
* @aka L.Polyline
* @inherits Path
*
* A class for drawing polyline overlays on a map. Extends `Path`.
*
* @example
*
* ```js
* // create a red polyline from an array of LatLng points
* var latlngs = [
* [45.51, -122.68],
* [37.77, -122.43],
* [34.04, -118.2]
* ];
*
* var polyline = L.polyline(latlngs, {color: 'red'}).addTo(map);
*
* // zoom the map to the polyline
* map.fitBounds(polyline.getBounds());
* ```
*
* You can also pass a multi-dimensional array to represent a `MultiPolyline` shape:
*
* ```js
* // create a red polyline from an array of arrays of LatLng points
* var latlngs = [
* [[45.51, -122.68],
* [37.77, -122.43],
* [34.04, -118.2]],
* [[40.78, -73.91],
* [41.83, -87.62],
* [32.76, -96.72]]
* ];
* ```
*/
var Polyline = Path.extend({
// @section
// @aka Polyline options
options: {
// @option smoothFactor: Number = 1.0
// How much to simplify the polyline on each zoom level. More means
// better performance and smoother look, and less means more accurate representation.
smoothFactor: 1.0,
// @option noClip: Boolean = false
// Disable polyline clipping.
noClip: false
},
initialize: function (latlngs, options) {
setOptions(this, options);
this._setLatLngs(latlngs);
},
// @method getLatLngs(): LatLng[]
// Returns an array of the points in the path, or nested arrays of points in case of multi-polyline.
getLatLngs: function () {
return this._latlngs;
},
// @method setLatLngs(latlngs: LatLng[]): this
// Replaces all the points in the polyline with the given array of geographical points.
setLatLngs: function (latlngs) {
this._setLatLngs(latlngs);
return this.redraw();
},
// @method isEmpty(): Boolean
// Returns `true` if the Polyline has no LatLngs.
isEmpty: function () {
return !this._latlngs.length;
},
// @method closestLayerPoint(p: Point): Point
// Returns the point closest to `p` on the Polyline.
closestLayerPoint: function (p) {
var minDistance = Infinity,
minPoint = null,
closest = _sqClosestPointOnSegment,
p1, p2;
for (var j = 0, jLen = this._parts.length; j < jLen; j++) {
var points = this._parts[j];
for (var i = 1, len = points.length; i < len; i++) {
p1 = points[i - 1];
p2 = points[i];
var sqDist = closest(p, p1, p2, true);
if (sqDist < minDistance) {
minDistance = sqDist;
minPoint = closest(p, p1, p2);
}
}
}
if (minPoint) {
minPoint.distance = Math.sqrt(minDistance);
}
return minPoint;
},
// @method getCenter(): LatLng
// Returns the center ([centroid](http://en.wikipedia.org/wiki/Centroid)) of the polyline.
getCenter: function () {
// throws error when not yet added to map as this center calculation requires projected coordinates
if (!this._map) {
throw new Error('Must add layer to map before using getCenter()');
}
var i, halfDist, segDist, dist, p1, p2, ratio,
points = this._rings[0],
len = points.length;
if (!len) { return null; }
// polyline centroid algorithm; only uses the first ring if there are multiple
for (i = 0, halfDist = 0; i < len - 1; i++) {
halfDist += points[i].distanceTo(points[i + 1]) / 2;
}
// The line is so small in the current view that all points are on the same pixel.
if (halfDist === 0) {
return this._map.layerPointToLatLng(points[0]);
}
for (i = 0, dist = 0; i < len - 1; i++) {
p1 = points[i];
p2 = points[i + 1];
segDist = p1.distanceTo(p2);
dist += segDist;
if (dist > halfDist) {
ratio = (dist - halfDist) / segDist;
return this._map.layerPointToLatLng([
p2.x - ratio * (p2.x - p1.x),
p2.y - ratio * (p2.y - p1.y)
]);
}
}
},
// @method getBounds(): LatLngBounds
// Returns the `LatLngBounds` of the path.
getBounds: function () {
return this._bounds;
},
// @method addLatLng(latlng: LatLng, latlngs? LatLng[]): this
// Adds a given point to the polyline. By default, adds to the first ring of
// the polyline in case of a multi-polyline, but can be overridden by passing
// a specific ring as a LatLng array (that you can earlier access with [`getLatLngs`](#polyline-getlatlngs)).
addLatLng: function (latlng, latlngs) {
latlngs = latlngs || this._defaultShape();
latlng = toLatLng(latlng);
latlngs.push(latlng);
this._bounds.extend(latlng);
return this.redraw();
},
_setLatLngs: function (latlngs) {
this._bounds = new LatLngBounds();
this._latlngs = this._convertLatLngs(latlngs);
},
_defaultShape: function () {
return isFlat(this._latlngs) ? this._latlngs : this._latlngs[0];
},
// recursively convert latlngs input into actual LatLng instances; calculate bounds along the way
_convertLatLngs: function (latlngs) {
var result = [],
flat = isFlat(latlngs);
for (var i = 0, len = latlngs.length; i < len; i++) {
if (flat) {
result[i] = toLatLng(latlngs[i]);
this._bounds.extend(result[i]);
} else {
result[i] = this._convertLatLngs(latlngs[i]);
}
}
return result;
},
_project: function () {
var pxBounds = new Bounds();
this._rings = [];
this._projectLatlngs(this._latlngs, this._rings, pxBounds);
if (this._bounds.isValid() && pxBounds.isValid()) {
this._rawPxBounds = pxBounds;
this._updateBounds();
}
},
_updateBounds: function () {
var w = this._clickTolerance(),
p = new Point(w, w);
this._pxBounds = new Bounds([
this._rawPxBounds.min.subtract(p),
this._rawPxBounds.max.add(p)
]);
},
// recursively turns latlngs into a set of rings with projected coordinates
_projectLatlngs: function (latlngs, result, projectedBounds) {
var flat = latlngs[0] instanceof LatLng,
len = latlngs.length,
i, ring;
if (flat) {
ring = [];
for (i = 0; i < len; i++) {
ring[i] = this._map.latLngToLayerPoint(latlngs[i]);
projectedBounds.extend(ring[i]);
}
result.push(ring);
} else {
for (i = 0; i < len; i++) {
this._projectLatlngs(latlngs[i], result, projectedBounds);
}
}
},
// clip polyline by renderer bounds so that we have less to render for performance
_clipPoints: function () {
var bounds = this._renderer._bounds;
this._parts = [];
if (!this._pxBounds || !this._pxBounds.intersects(bounds)) {
return;
}
if (this.options.noClip) {
this._parts = this._rings;
return;
}
var parts = this._parts,
i, j, k, len, len2, segment, points;
for (i = 0, k = 0, len = this._rings.length; i < len; i++) {
points = this._rings[i];
for (j = 0, len2 = points.length; j < len2 - 1; j++) {
segment = clipSegment(points[j], points[j + 1], bounds, j, true);
if (!segment) { continue; }
parts[k] = parts[k] || [];
parts[k].push(segment[0]);
// if segment goes out of screen, or it's the last one, it's the end of the line part
if ((segment[1] !== points[j + 1]) || (j === len2 - 2)) {
parts[k].push(segment[1]);
k++;
}
}
}
},
// simplify each clipped part of the polyline for performance
_simplifyPoints: function () {
var parts = this._parts,
tolerance = this.options.smoothFactor;
for (var i = 0, len = parts.length; i < len; i++) {
parts[i] = simplify(parts[i], tolerance);
}
},
_update: function () {
if (!this._map) { return; }
this._clipPoints();
this._simplifyPoints();
this._updatePath();
},
_updatePath: function () {
this._renderer._updatePoly(this);
},
// Needed by the `Canvas` renderer for interactivity
_containsPoint: function (p, closed) {
var i, j, k, len, len2, part,
w = this._clickTolerance();
if (!this._pxBounds || !this._pxBounds.contains(p)) { return false; }
// hit detection for polylines
for (i = 0, len = this._parts.length; i < len; i++) {
part = this._parts[i];
for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {
if (!closed && (j === 0)) { continue; }
if (pointToSegmentDistance(p, part[k], part[j]) <= w) {
return true;
}
}
}
return false;
}
});
// @factory L.polyline(latlngs: LatLng[], options?: Polyline options)
// Instantiates a polyline object given an array of geographical points and
// optionally an options object. You can create a `Polyline` object with
// multiple separate lines (`MultiPolyline`) by passing an array of arrays
// of geographic points.
function polyline(latlngs, options) {
return new Polyline(latlngs, options);
}
// Retrocompat. Allow plugins to support Leaflet versions before and after 1.1.
Polyline._flat = _flat;
/*
* @class Polygon
* @aka L.Polygon
* @inherits Polyline
*
* A class for drawing polygon overlays on a map. Extends `Polyline`.
*
* Note that points you pass when creating a polygon shouldn't have an additional last point equal to the first one — it's better to filter out such points.
*
*
* @example
*
* ```js
* // create a red polygon from an array of LatLng points
* var latlngs = [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]];
*
* var polygon = L.polygon(latlngs, {color: 'red'}).addTo(map);
*
* // zoom the map to the polygon
* map.fitBounds(polygon.getBounds());
* ```
*
* You can also pass an array of arrays of latlngs, with the first array representing the outer shape and the other arrays representing holes in the outer shape:
*
* ```js
* var latlngs = [
* [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]], // outer ring
* [[37.29, -108.58],[40.71, -108.58],[40.71, -102.50],[37.29, -102.50]] // hole
* ];
* ```
*
* Additionally, you can pass a multi-dimensional array to represent a MultiPolygon shape.
*
* ```js
* var latlngs = [
* [ // first polygon
* [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]], // outer ring
* [[37.29, -108.58],[40.71, -108.58],[40.71, -102.50],[37.29, -102.50]] // hole
* ],
* [ // second polygon
* [[41, -111.03],[45, -111.04],[45, -104.05],[41, -104.05]]
* ]
* ];
* ```
*/
var Polygon = Polyline.extend({
options: {
fill: true
},
isEmpty: function () {
return !this._latlngs.length || !this._latlngs[0].length;
},
getCenter: function () {
// throws error when not yet added to map as this center calculation requires projected coordinates
if (!this._map) {
throw new Error('Must add layer to map before using getCenter()');
}
var i, j, p1, p2, f, area, x, y, center,
points = this._rings[0],
len = points.length;
if (!len) { return null; }
// polygon centroid algorithm; only uses the first ring if there are multiple
area = x = y = 0;
for (i = 0, j = len - 1; i < len; j = i++) {
p1 = points[i];
p2 = points[j];
f = p1.y * p2.x - p2.y * p1.x;
x += (p1.x + p2.x) * f;
y += (p1.y + p2.y) * f;
area += f * 3;
}
if (area === 0) {
// Polygon is so small that all points are on same pixel.
center = points[0];
} else {
center = [x / area, y / area];
}
return this._map.layerPointToLatLng(center);
},
_convertLatLngs: function (latlngs) {
var result = Polyline.prototype._convertLatLngs.call(this, latlngs),
len = result.length;
// remove last point if it equals first one
if (len >= 2 && result[0] instanceof LatLng && result[0].equals(result[len - 1])) {
result.pop();
}
return result;
},
_setLatLngs: function (latlngs) {
Polyline.prototype._setLatLngs.call(this, latlngs);
if (isFlat(this._latlngs)) {
this._latlngs = [this._latlngs];
}
},
_defaultShape: function () {
return isFlat(this._latlngs[0]) ? this._latlngs[0] : this._latlngs[0][0];
},
_clipPoints: function () {
// polygons need a different clipping algorithm so we redefine that
var bounds = this._renderer._bounds,
w = this.options.weight,
p = new Point(w, w);
// increase clip padding by stroke width to avoid stroke on clip edges
bounds = new Bounds(bounds.min.subtract(p), bounds.max.add(p));
this._parts = [];
if (!this._pxBounds || !this._pxBounds.intersects(bounds)) {
return;
}
if (this.options.noClip) {
this._parts = this._rings;
return;
}
for (var i = 0, len = this._rings.length, clipped; i < len; i++) {
clipped = clipPolygon(this._rings[i], bounds, true);
if (clipped.length) {
this._parts.push(clipped);
}
}
},
_updatePath: function () {
this._renderer._updatePoly(this, true);
},
// Needed by the `Canvas` renderer for interactivity
_containsPoint: function (p) {
var inside = false,
part, p1, p2, i, j, k, len, len2;
if (!this._pxBounds || !this._pxBounds.contains(p)) { return false; }
// ray casting algorithm for detecting if point is in polygon
for (i = 0, len = this._parts.length; i < len; i++) {
part = this._parts[i];
for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {
p1 = part[j];
p2 = part[k];
if (((p1.y > p.y) !== (p2.y > p.y)) && (p.x < (p2.x - p1.x) * (p.y - p1.y) / (p2.y - p1.y) + p1.x)) {
inside = !inside;
}
}
}
// also check if it's on polygon stroke
return inside || Polyline.prototype._containsPoint.call(this, p, true);
}
});
// @factory L.polygon(latlngs: LatLng[], options?: Polyline options)
function polygon(latlngs, options) {
return new Polygon(latlngs, options);
}
/*
* @class GeoJSON
* @aka L.GeoJSON
* @inherits FeatureGroup
*
* Represents a GeoJSON object or an array of GeoJSON objects. Allows you to parse
* GeoJSON data and display it on the map. Extends `FeatureGroup`.
*
* @example
*
* ```js
* L.geoJSON(data, {
* style: function (feature) {
* return {color: feature.properties.color};
* }
* }).bindPopup(function (layer) {
* return layer.feature.properties.description;
* }).addTo(map);
* ```
*/
var GeoJSON = FeatureGroup.extend({
/* @section
* @aka GeoJSON options
*
* @option pointToLayer: Function = *
* A `Function` defining how GeoJSON points spawn Leaflet layers. It is internally
* called when data is added, passing the GeoJSON point feature and its `LatLng`.
* The default is to spawn a default `Marker`:
* ```js
* function(geoJsonPoint, latlng) {
* return L.marker(latlng);
* }
* ```
*
* @option style: Function = *
* A `Function` defining the `Path options` for styling GeoJSON lines and polygons,
* called internally when data is added.
* The default value is to not override any defaults:
* ```js
* function (geoJsonFeature) {
* return {}
* }
* ```
*
* @option onEachFeature: Function = *
* A `Function` that will be called once for each created `Feature`, after it has
* been created and styled. Useful for attaching events and popups to features.
* The default is to do nothing with the newly created layers:
* ```js
* function (feature, layer) {}
* ```
*
* @option filter: Function = *
* A `Function` that will be used to decide whether to include a feature or not.
* The default is to include all features:
* ```js
* function (geoJsonFeature) {
* return true;
* }
* ```
* Note: dynamically changing the `filter` option will have effect only on newly
* added data. It will _not_ re-evaluate already included features.
*
* @option coordsToLatLng: Function = *
* A `Function` that will be used for converting GeoJSON coordinates to `LatLng`s.
* The default is the `coordsToLatLng` static method.
*
* @option markersInheritOptions: Boolean = false
* Whether default Markers for "Point" type Features inherit from group options.
*/
initialize: function (geojson, options) {
setOptions(this, options);
this._layers = {};
if (geojson) {
this.addData(geojson);
}
},
// @method addData( <GeoJSON> data ): this
// Adds a GeoJSON object to the layer.
addData: function (geojson) {
var features = isArray(geojson) ? geojson : geojson.features,
i, len, feature;
if (features) {
for (i = 0, len = features.length; i < len; i++) {
// only add this if geometry or geometries are set and not null
feature = features[i];
if (feature.geometries || feature.geometry || feature.features || feature.coordinates) {
this.addData(feature);
}
}
return this;
}
var options = this.options;
if (options.filter && !options.filter(geojson)) { return this; }
var layer = geometryToLayer(geojson, options);
if (!layer) {
return this;
}
layer.feature = asFeature(geojson);
layer.defaultOptions = layer.options;
this.resetStyle(layer);
if (options.onEachFeature) {
options.onEachFeature(geojson, layer);
}
return this.addLayer(layer);
},
// @method resetStyle( <Path> layer? ): this
// Resets the given vector layer's style to the original GeoJSON style, useful for resetting style after hover events.
// If `layer` is omitted, the style of all features in the current layer is reset.
resetStyle: function (layer) {
if (layer === undefined) {
return this.eachLayer(this.resetStyle, this);
}
// reset any custom styles
layer.options = extend({}, layer.defaultOptions);
this._setLayerStyle(layer, this.options.style);
return this;
},
// @method setStyle( <Function> style ): this
// Changes styles of GeoJSON vector layers with the given style function.
setStyle: function (style) {
return this.eachLayer(function (layer) {
this._setLayerStyle(layer, style);
}, this);
},
_setLayerStyle: function (layer, style) {
if (layer.setStyle) {
if (typeof style === 'function') {
style = style(layer.feature);
}
layer.setStyle(style);
}
}
});
// @section
// There are several static functions which can be called without instantiating L.GeoJSON:
// @function geometryToLayer(featureData: Object, options?: GeoJSON options): Layer
// Creates a `Layer` from a given GeoJSON feature. Can use a custom
// [`pointToLayer`](#geojson-pointtolayer) and/or [`coordsToLatLng`](#geojson-coordstolatlng)
// functions if provided as options.
function geometryToLayer(geojson, options) {
var geometry = geojson.type === 'Feature' ? geojson.geometry : geojson,
coords = geometry ? geometry.coordinates : null,
layers = [],
pointToLayer = options && options.pointToLayer,
_coordsToLatLng = options && options.coordsToLatLng || coordsToLatLng,
latlng, latlngs, i, len;
if (!coords && !geometry) {
return null;
}
switch (geometry.type) {
case 'Point':
latlng = _coordsToLatLng(coords);
return _pointToLayer(pointToLayer, geojson, latlng, options);
case 'MultiPoint':
for (i = 0, len = coords.length; i < len; i++) {
latlng = _coordsToLatLng(coords[i]);
layers.push(_pointToLayer(pointToLayer, geojson, latlng, options));
}
return new FeatureGroup(layers);
case 'LineString':
case 'MultiLineString':
latlngs = coordsToLatLngs(coords, geometry.type === 'LineString' ? 0 : 1, _coordsToLatLng);
return new Polyline(latlngs, options);
case 'Polygon':
case 'MultiPolygon':
latlngs = coordsToLatLngs(coords, geometry.type === 'Polygon' ? 1 : 2, _coordsToLatLng);
return new Polygon(latlngs, options);
case 'GeometryCollection':
for (i = 0, len = geometry.geometries.length; i < len; i++) {
var layer = geometryToLayer({
geometry: geometry.geometries[i],
type: 'Feature',
properties: geojson.properties
}, options);
if (layer) {
layers.push(layer);
}
}
return new FeatureGroup(layers);
default:
throw new Error('Invalid GeoJSON object.');
}
}
function _pointToLayer(pointToLayerFn, geojson, latlng, options) {
return pointToLayerFn ?
pointToLayerFn(geojson, latlng) :
new Marker(latlng, options && options.markersInheritOptions && options);
}
// @function coordsToLatLng(coords: Array): LatLng
// Creates a `LatLng` object from an array of 2 numbers (longitude, latitude)
// or 3 numbers (longitude, latitude, altitude) used in GeoJSON for points.
function coordsToLatLng(coords) {
return new LatLng(coords[1], coords[0], coords[2]);
}
// @function coordsToLatLngs(coords: Array, levelsDeep?: Number, coordsToLatLng?: Function): Array
// Creates a multidimensional array of `LatLng`s from a GeoJSON coordinates array.
// `levelsDeep` specifies the nesting level (0 is for an array of points, 1 for an array of arrays of points, etc., 0 by default).
// Can use a custom [`coordsToLatLng`](#geojson-coordstolatlng) function.
function coordsToLatLngs(coords, levelsDeep, _coordsToLatLng) {
var latlngs = [];
for (var i = 0, len = coords.length, latlng; i < len; i++) {
latlng = levelsDeep ?
coordsToLatLngs(coords[i], levelsDeep - 1, _coordsToLatLng) :
(_coordsToLatLng || coordsToLatLng)(coords[i]);
latlngs.push(latlng);
}
return latlngs;
}
// @function latLngToCoords(latlng: LatLng, precision?: Number): Array
// Reverse of [`coordsToLatLng`](#geojson-coordstolatlng)
function latLngToCoords(latlng, precision) {
precision = typeof precision === 'number' ? precision : 6;
return latlng.alt !== undefined ?
[formatNum(latlng.lng, precision), formatNum(latlng.lat, precision), formatNum(latlng.alt, precision)] :
[formatNum(latlng.lng, precision), formatNum(latlng.lat, precision)];
}
// @function latLngsToCoords(latlngs: Array, levelsDeep?: Number, closed?: Boolean): Array
// Reverse of [`coordsToLatLngs`](#geojson-coordstolatlngs)
// `closed` determines whether the first point should be appended to the end of the array to close the feature, only used when `levelsDeep` is 0. False by default.
function latLngsToCoords(latlngs, levelsDeep, closed, precision) {
var coords = [];
for (var i = 0, len = latlngs.length; i < len; i++) {
coords.push(levelsDeep ?
latLngsToCoords(latlngs[i], levelsDeep - 1, closed, precision) :
latLngToCoords(latlngs[i], precision));
}
if (!levelsDeep && closed) {
coords.push(coords[0]);
}
return coords;
}
function getFeature(layer, newGeometry) {
return layer.feature ?
extend({}, layer.feature, {geometry: newGeometry}) :
asFeature(newGeometry);
}
// @function asFeature(geojson: Object): Object
// Normalize GeoJSON geometries/features into GeoJSON features.
function asFeature(geojson) {
if (geojson.type === 'Feature' || geojson.type === 'FeatureCollection') {
return geojson;
}
return {
type: 'Feature',
properties: {},
geometry: geojson
};
}
var PointToGeoJSON = {
toGeoJSON: function (precision) {
return getFeature(this, {
type: 'Point',
coordinates: latLngToCoords(this.getLatLng(), precision)
});
}
};
// @namespace Marker
// @section Other methods
// @method toGeoJSON(precision?: Number): Object
// `precision` is the number of decimal places for coordinates.
// The default value is 6 places.
// Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the marker (as a GeoJSON `Point` Feature).
Marker.include(PointToGeoJSON);
// @namespace CircleMarker
// @method toGeoJSON(precision?: Number): Object
// `precision` is the number of decimal places for coordinates.
// The default value is 6 places.
// Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the circle marker (as a GeoJSON `Point` Feature).
Circle.include(PointToGeoJSON);
CircleMarker.include(PointToGeoJSON);
// @namespace Polyline
// @method toGeoJSON(precision?: Number): Object
// `precision` is the number of decimal places for coordinates.
// The default value is 6 places.
// Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the polyline (as a GeoJSON `LineString` or `MultiLineString` Feature).
Polyline.include({
toGeoJSON: function (precision) {
var multi = !isFlat(this._latlngs);
var coords = latLngsToCoords(this._latlngs, multi ? 1 : 0, false, precision);
return getFeature(this, {
type: (multi ? 'Multi' : '') + 'LineString',
coordinates: coords
});
}
});
// @namespace Polygon
// @method toGeoJSON(precision?: Number): Object
// `precision` is the number of decimal places for coordinates.
// The default value is 6 places.
// Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the polygon (as a GeoJSON `Polygon` or `MultiPolygon` Feature).
Polygon.include({
toGeoJSON: function (precision) {
var holes = !isFlat(this._latlngs),
multi = holes && !isFlat(this._latlngs[0]);
var coords = latLngsToCoords(this._latlngs, multi ? 2 : holes ? 1 : 0, true, precision);
if (!holes) {
coords = [coords];
}
return getFeature(this, {
type: (multi ? 'Multi' : '') + 'Polygon',
coordinates: coords
});
}
});
// @namespace LayerGroup
LayerGroup.include({
toMultiPoint: function (precision) {
var coords = [];
this.eachLayer(function (layer) {
coords.push(layer.toGeoJSON(precision).geometry.coordinates);
});
return getFeature(this, {
type: 'MultiPoint',
coordinates: coords
});
},
// @method toGeoJSON(precision?: Number): Object
// `precision` is the number of decimal places for coordinates.
// The default value is 6 places.
// Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the layer group (as a GeoJSON `FeatureCollection`, `GeometryCollection`, or `MultiPoint`).
toGeoJSON: function (precision) {
var type = this.feature && this.feature.geometry && this.feature.geometry.type;
if (type === 'MultiPoint') {
return this.toMultiPoint(precision);
}
var isGeometryCollection = type === 'GeometryCollection',
jsons = [];
this.eachLayer(function (layer) {
if (layer.toGeoJSON) {
var json = layer.toGeoJSON(precision);
if (isGeometryCollection) {
jsons.push(json.geometry);
} else {
var feature = asFeature(json);
// Squash nested feature collections
if (feature.type === 'FeatureCollection') {
jsons.push.apply(jsons, feature.features);
} else {
jsons.push(feature);
}
}
}
});
if (isGeometryCollection) {
return getFeature(this, {
geometries: jsons,
type: 'GeometryCollection'
});
}
return {
type: 'FeatureCollection',
features: jsons
};
}
});
// @namespace GeoJSON
// @factory L.geoJSON(geojson?: Object, options?: GeoJSON options)
// Creates a GeoJSON layer. Optionally accepts an object in
// [GeoJSON format](https://tools.ietf.org/html/rfc7946) to display on the map
// (you can alternatively add it later with `addData` method) and an `options` object.
function geoJSON(geojson, options) {
return new GeoJSON(geojson, options);
}
// Backward compatibility.
var geoJson = geoJSON;
/*
* @class ImageOverlay
* @aka L.ImageOverlay
* @inherits Interactive layer
*
* Used to load and display a single image over specific bounds of the map. Extends `Layer`.
*
* @example
*
* ```js
* var imageUrl = 'http://www.lib.utexas.edu/maps/historical/newark_nj_1922.jpg',
* imageBounds = [[40.712216, -74.22655], [40.773941, -74.12544]];
* L.imageOverlay(imageUrl, imageBounds).addTo(map);
* ```
*/
var ImageOverlay = Layer.extend({
// @section
// @aka ImageOverlay options
options: {
// @option opacity: Number = 1.0
// The opacity of the image overlay.
opacity: 1,
// @option alt: String = ''
// Text for the `alt` attribute of the image (useful for accessibility).
alt: '',
// @option interactive: Boolean = false
// If `true`, the image overlay will emit [mouse events](#interactive-layer) when clicked or hovered.
interactive: false,
// @option crossOrigin: Boolean|String = false
// Whether the crossOrigin attribute will be added to the image.
// If a String is provided, the image will have its crossOrigin attribute set to the String provided. This is needed if you want to access image pixel data.
// Refer to [CORS Settings](https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes) for valid String values.
crossOrigin: false,
// @option errorOverlayUrl: String = ''
// URL to the overlay image to show in place of the overlay that failed to load.
errorOverlayUrl: '',
// @option zIndex: Number = 1
// The explicit [zIndex](https://developer.mozilla.org/docs/Web/CSS/CSS_Positioning/Understanding_z_index) of the overlay layer.
zIndex: 1,
// @option className: String = ''
// A custom class name to assign to the image. Empty by default.
className: ''
},
initialize: function (url, bounds, options) { // (String, LatLngBounds, Object)
this._url = url;
this._bounds = toLatLngBounds(bounds);
setOptions(this, options);
},
onAdd: function () {
if (!this._image) {
this._initImage();
if (this.options.opacity < 1) {
this._updateOpacity();
}
}
if (this.options.interactive) {
addClass(this._image, 'leaflet-interactive');
this.addInteractiveTarget(this._image);
}
this.getPane().appendChild(this._image);
this._reset();
},
onRemove: function () {
remove(this._image);
if (this.options.interactive) {
this.removeInteractiveTarget(this._image);
}
},
// @method setOpacity(opacity: Number): this
// Sets the opacity of the overlay.
setOpacity: function (opacity) {
this.options.opacity = opacity;
if (this._image) {
this._updateOpacity();
}
return this;
},
setStyle: function (styleOpts) {
if (styleOpts.opacity) {
this.setOpacity(styleOpts.opacity);
}
return this;
},
// @method bringToFront(): this
// Brings the layer to the top of all overlays.
bringToFront: function () {
if (this._map) {
toFront(this._image);
}
return this;
},
// @method bringToBack(): this
// Brings the layer to the bottom of all overlays.
bringToBack: function () {
if (this._map) {
toBack(this._image);
}
return this;
},
// @method setUrl(url: String): this
// Changes the URL of the image.
setUrl: function (url) {
this._url = url;
if (this._image) {
this._image.src = url;
}
return this;
},
// @method setBounds(bounds: LatLngBounds): this
// Update the bounds that this ImageOverlay covers
setBounds: function (bounds) {
this._bounds = toLatLngBounds(bounds);
if (this._map) {
this._reset();
}
return this;
},
getEvents: function () {
var events = {
zoom: this._reset,
viewreset: this._reset
};
if (this._zoomAnimated) {
events.zoomanim = this._animateZoom;
}
return events;
},
// @method setZIndex(value: Number): this
// Changes the [zIndex](#imageoverlay-zindex) of the image overlay.
setZIndex: function (value) {
this.options.zIndex = value;
this._updateZIndex();
return this;
},
// @method getBounds(): LatLngBounds
// Get the bounds that this ImageOverlay covers
getBounds: function () {
return this._bounds;
},
// @method getElement(): HTMLElement
// Returns the instance of [`HTMLImageElement`](https://developer.mozilla.org/docs/Web/API/HTMLImageElement)
// used by this overlay.
getElement: function () {
return this._image;
},
_initImage: function () {
var wasElementSupplied = this._url.tagName === 'IMG';
var img = this._image = wasElementSupplied ? this._url : create$1('img');
addClass(img, 'leaflet-image-layer');
if (this._zoomAnimated) { addClass(img, 'leaflet-zoom-animated'); }
if (this.options.className) { addClass(img, this.options.className); }
img.onselectstart = falseFn;
img.onmousemove = falseFn;
// @event load: Event
// Fired when the ImageOverlay layer has loaded its image
img.onload = bind(this.fire, this, 'load');
img.onerror = bind(this._overlayOnError, this, 'error');
if (this.options.crossOrigin || this.options.crossOrigin === '') {
img.crossOrigin = this.options.crossOrigin === true ? '' : this.options.crossOrigin;
}
if (this.options.zIndex) {
this._updateZIndex();
}
if (wasElementSupplied) {
this._url = img.src;
return;
}
img.src = this._url;
img.alt = this.options.alt;
},
_animateZoom: function (e) {
var scale = this._map.getZoomScale(e.zoom),
offset = this._map._latLngBoundsToNewLayerBounds(this._bounds, e.zoom, e.center).min;
setTransform(this._image, offset, scale);
},
_reset: function () {
var image = this._image,
bounds = new Bounds(
this._map.latLngToLayerPoint(this._bounds.getNorthWest()),
this._map.latLngToLayerPoint(this._bounds.getSouthEast())),
size = bounds.getSize();
setPosition(image, bounds.min);
image.style.width = size.x + 'px';
image.style.height = size.y + 'px';
},
_updateOpacity: function () {
setOpacity(this._image, this.options.opacity);
},
_updateZIndex: function () {
if (this._image && this.options.zIndex !== undefined && this.options.zIndex !== null) {
this._image.style.zIndex = this.options.zIndex;
}
},
_overlayOnError: function () {
// @event error: Event
// Fired when the ImageOverlay layer fails to load its image
this.fire('error');
var errorUrl = this.options.errorOverlayUrl;
if (errorUrl && this._url !== errorUrl) {
this._url = errorUrl;
this._image.src = errorUrl;
}
}
});
// @factory L.imageOverlay(imageUrl: String, bounds: LatLngBounds, options?: ImageOverlay options)
// Instantiates an image overlay object given the URL of the image and the
// geographical bounds it is tied to.
var imageOverlay = function (url, bounds, options) {
return new ImageOverlay(url, bounds, options);
};
/*
* @class VideoOverlay
* @aka L.VideoOverlay
* @inherits ImageOverlay
*
* Used to load and display a video player over specific bounds of the map. Extends `ImageOverlay`.
*
* A video overlay uses the [`<video>`](https://developer.mozilla.org/docs/Web/HTML/Element/video)
* HTML5 element.
*
* @example
*
* ```js
* var videoUrl = 'https://www.mapbox.com/bites/00188/patricia_nasa.webm',
* videoBounds = [[ 32, -130], [ 13, -100]];
* L.videoOverlay(videoUrl, videoBounds ).addTo(map);
* ```
*/
var VideoOverlay = ImageOverlay.extend({
// @section
// @aka VideoOverlay options
options: {
// @option autoplay: Boolean = true
// Whether the video starts playing automatically when loaded.
autoplay: true,
// @option loop: Boolean = true
// Whether the video will loop back to the beginning when played.
loop: true,
// @option keepAspectRatio: Boolean = true
// Whether the video will save aspect ratio after the projection.
// Relevant for supported browsers. Browser compatibility- https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit
keepAspectRatio: true
},
_initImage: function () {
var wasElementSupplied = this._url.tagName === 'VIDEO';
var vid = this._image = wasElementSupplied ? this._url : create$1('video');
addClass(vid, 'leaflet-image-layer');
if (this._zoomAnimated) { addClass(vid, 'leaflet-zoom-animated'); }
if (this.options.className) { addClass(vid, this.options.className); }
vid.onselectstart = falseFn;
vid.onmousemove = falseFn;
// @event load: Event
// Fired when the video has finished loading the first frame
vid.onloadeddata = bind(this.fire, this, 'load');
if (wasElementSupplied) {
var sourceElements = vid.getElementsByTagName('source');
var sources = [];
for (var j = 0; j < sourceElements.length; j++) {
sources.push(sourceElements[j].src);
}
this._url = (sourceElements.length > 0) ? sources : [vid.src];
return;
}
if (!isArray(this._url)) { this._url = [this._url]; }
if (!this.options.keepAspectRatio && vid.style.hasOwnProperty('objectFit')) { vid.style['objectFit'] = 'fill'; }
vid.autoplay = !!this.options.autoplay;
vid.loop = !!this.options.loop;
for (var i = 0; i < this._url.length; i++) {
var source = create$1('source');
source.src = this._url[i];
vid.appendChild(source);
}
}
// @method getElement(): HTMLVideoElement
// Returns the instance of [`HTMLVideoElement`](https://developer.mozilla.org/docs/Web/API/HTMLVideoElement)
// used by this overlay.
});
// @factory L.videoOverlay(video: String|Array|HTMLVideoElement, bounds: LatLngBounds, options?: VideoOverlay options)
// Instantiates an image overlay object given the URL of the video (or array of URLs, or even a video element) and the
// geographical bounds it is tied to.
function videoOverlay(video, bounds, options) {
return new VideoOverlay(video, bounds, options);
}
/*
* @class SVGOverlay
* @aka L.SVGOverlay
* @inherits ImageOverlay
*
* Used to load, display and provide DOM access to an SVG file over specific bounds of the map. Extends `ImageOverlay`.
*
* An SVG overlay uses the [`<svg>`](https://developer.mozilla.org/docs/Web/SVG/Element/svg) element.
*
* @example
*
* ```js
* var svgElement = document.createElementNS("http://www.w3.org/2000/svg", "svg");
* svgElement.setAttribute('xmlns', "http://www.w3.org/2000/svg");
* svgElement.setAttribute('viewBox', "0 0 200 200");
* svgElement.innerHTML = '<rect width="200" height="200"/><rect x="75" y="23" width="50" height="50" style="fill:red"/><rect x="75" y="123" width="50" height="50" style="fill:#0013ff"/>';
* var svgElementBounds = [ [ 32, -130 ], [ 13, -100 ] ];
* L.svgOverlay(svgElement, svgElementBounds).addTo(map);
* ```
*/
var SVGOverlay = ImageOverlay.extend({
_initImage: function () {
var el = this._image = this._url;
addClass(el, 'leaflet-image-layer');
if (this._zoomAnimated) { addClass(el, 'leaflet-zoom-animated'); }
if (this.options.className) { addClass(el, this.options.className); }
el.onselectstart = falseFn;
el.onmousemove = falseFn;
}
// @method getElement(): SVGElement
// Returns the instance of [`SVGElement`](https://developer.mozilla.org/docs/Web/API/SVGElement)
// used by this overlay.
});
// @factory L.svgOverlay(svg: String|SVGElement, bounds: LatLngBounds, options?: SVGOverlay options)
// Instantiates an image overlay object given an SVG element and the geographical bounds it is tied to.
// A viewBox attribute is required on the SVG element to zoom in and out properly.
function svgOverlay(el, bounds, options) {
return new SVGOverlay(el, bounds, options);
}
/*
* @class DivOverlay
* @inherits Layer
* @aka L.DivOverlay
* Base model for L.Popup and L.Tooltip. Inherit from it for custom popup like plugins.
*/
// @namespace DivOverlay
var DivOverlay = Layer.extend({
// @section
// @aka DivOverlay options
options: {
// @option offset: Point = Point(0, 7)
// The offset of the popup position. Useful to control the anchor
// of the popup when opening it on some overlays.
offset: [0, 7],
// @option className: String = ''
// A custom CSS class name to assign to the popup.
className: '',
// @option pane: String = 'popupPane'
// `Map pane` where the popup will be added.
pane: 'popupPane'
},
initialize: function (options, source) {
setOptions(this, options);
this._source = source;
},
onAdd: function (map) {
this._zoomAnimated = map._zoomAnimated;
if (!this._container) {
this._initLayout();
}
if (map._fadeAnimated) {
setOpacity(this._container, 0);
}
clearTimeout(this._removeTimeout);
this.getPane().appendChild(this._container);
this.update();
if (map._fadeAnimated) {
setOpacity(this._container, 1);
}
this.bringToFront();
},
onRemove: function (map) {
if (map._fadeAnimated) {
setOpacity(this._container, 0);
this._removeTimeout = setTimeout(bind(remove, undefined, this._container), 200);
} else {
remove(this._container);
}
},
// @namespace Popup
// @method getLatLng: LatLng
// Returns the geographical point of popup.
getLatLng: function () {
return this._latlng;
},
// @method setLatLng(latlng: LatLng): this
// Sets the geographical point where the popup will open.
setLatLng: function (latlng) {
this._latlng = toLatLng(latlng);
if (this._map) {
this._updatePosition();
this._adjustPan();
}
return this;
},
// @method getContent: String|HTMLElement
// Returns the content of the popup.
getContent: function () {
return this._content;
},
// @method setContent(htmlContent: String|HTMLElement|Function): this
// Sets the HTML content of the popup. If a function is passed the source layer will be passed to the function. The function should return a `String` or `HTMLElement` to be used in the popup.
setContent: function (content) {
this._content = content;
this.update();
return this;
},
// @method getElement: String|HTMLElement
// Alias for [getContent()](#popup-getcontent)
getElement: function () {
return this._container;
},
// @method update: null
// Updates the popup content, layout and position. Useful for updating the popup after something inside changed, e.g. image loaded.
update: function () {
if (!this._map) { return; }
this._container.style.visibility = 'hidden';
this._updateContent();
this._updateLayout();
this._updatePosition();
this._container.style.visibility = '';
this._adjustPan();
},
getEvents: function () {
var events = {
zoom: this._updatePosition,
viewreset: this._updatePosition
};
if (this._zoomAnimated) {
events.zoomanim = this._animateZoom;
}
return events;
},
// @method isOpen: Boolean
// Returns `true` when the popup is visible on the map.
isOpen: function () {
return !!this._map && this._map.hasLayer(this);
},
// @method bringToFront: this
// Brings this popup in front of other popups (in the same map pane).
bringToFront: function () {
if (this._map) {
toFront(this._container);
}
return this;
},
// @method bringToBack: this
// Brings this popup to the back of other popups (in the same map pane).
bringToBack: function () {
if (this._map) {
toBack(this._container);
}
return this;
},
_prepareOpen: function (parent, layer, latlng) {
if (!(layer instanceof Layer)) {
latlng = layer;
layer = parent;
}
if (layer instanceof FeatureGroup) {
for (var id in parent._layers) {
layer = parent._layers[id];
break;
}
}
if (!latlng) {
if (layer.getCenter) {
latlng = layer.getCenter();
} else if (layer.getLatLng) {
latlng = layer.getLatLng();
} else {
throw new Error('Unable to get source layer LatLng.');
}
}
// set overlay source to this layer
this._source = layer;
// update the overlay (content, layout, ect...)
this.update();
return latlng;
},
_updateContent: function () {
if (!this._content) { return; }
var node = this._contentNode;
var content = (typeof this._content === 'function') ? this._content(this._source || this) : this._content;
if (typeof content === 'string') {
node.innerHTML = content;
} else {
while (node.hasChildNodes()) {
node.removeChild(node.firstChild);
}
node.appendChild(content);
}
this.fire('contentupdate');
},
_updatePosition: function () {
if (!this._map) { return; }
var pos = this._map.latLngToLayerPoint(this._latlng),
offset = toPoint(this.options.offset),
anchor = this._getAnchor();
if (this._zoomAnimated) {
setPosition(this._container, pos.add(anchor));
} else {
offset = offset.add(pos).add(anchor);
}
var bottom = this._containerBottom = -offset.y,
left = this._containerLeft = -Math.round(this._containerWidth / 2) + offset.x;
// bottom position the popup in case the height of the popup changes (images loading etc)
this._container.style.bottom = bottom + 'px';
this._container.style.left = left + 'px';
},
_getAnchor: function () {
return [0, 0];
}
});
/*
* @class Popup
* @inherits DivOverlay
* @aka L.Popup
* Used to open popups in certain places of the map. Use [Map.openPopup](#map-openpopup) to
* open popups while making sure that only one popup is open at one time
* (recommended for usability), or use [Map.addLayer](#map-addlayer) to open as many as you want.
*
* @example
*
* If you want to just bind a popup to marker click and then open it, it's really easy:
*
* ```js
* marker.bindPopup(popupContent).openPopup();
* ```
* Path overlays like polylines also have a `bindPopup` method.
* Here's a more complicated way to open a popup on a map:
*
* ```js
* var popup = L.popup()
* .setLatLng(latlng)
* .setContent('<p>Hello world!<br />This is a nice popup.</p>')
* .openOn(map);
* ```
*/
// @namespace Popup
var Popup = DivOverlay.extend({
// @section
// @aka Popup options
options: {
// @option maxWidth: Number = 300
// Max width of the popup, in pixels.
maxWidth: 300,
// @option minWidth: Number = 50
// Min width of the popup, in pixels.
minWidth: 50,
// @option maxHeight: Number = null
// If set, creates a scrollable container of the given height
// inside a popup if its content exceeds it.
maxHeight: null,
// @option autoPan: Boolean = true
// Set it to `false` if you don't want the map to do panning animation
// to fit the opened popup.
autoPan: true,
// @option autoPanPaddingTopLeft: Point = null
// The margin between the popup and the top left corner of the map
// view after autopanning was performed.
autoPanPaddingTopLeft: null,
// @option autoPanPaddingBottomRight: Point = null
// The margin between the popup and the bottom right corner of the map
// view after autopanning was performed.
autoPanPaddingBottomRight: null,
// @option autoPanPadding: Point = Point(5, 5)
// Equivalent of setting both top left and bottom right autopan padding to the same value.
autoPanPadding: [5, 5],
// @option keepInView: Boolean = false
// Set it to `true` if you want to prevent users from panning the popup
// off of the screen while it is open.
keepInView: false,
// @option closeButton: Boolean = true
// Controls the presence of a close button in the popup.
closeButton: true,
// @option autoClose: Boolean = true
// Set it to `false` if you want to override the default behavior of
// the popup closing when another popup is opened.
autoClose: true,
// @option closeOnEscapeKey: Boolean = true
// Set it to `false` if you want to override the default behavior of
// the ESC key for closing of the popup.
closeOnEscapeKey: true,
// @option closeOnClick: Boolean = *
// Set it if you want to override the default behavior of the popup closing when user clicks
// on the map. Defaults to the map's [`closePopupOnClick`](#map-closepopuponclick) option.
// @option className: String = ''
// A custom CSS class name to assign to the popup.
className: ''
},
// @namespace Popup
// @method openOn(map: Map): this
// Adds the popup to the map and closes the previous one. The same as `map.openPopup(popup)`.
openOn: function (map) {
map.openPopup(this);
return this;
},
onAdd: function (map) {
DivOverlay.prototype.onAdd.call(this, map);
// @namespace Map
// @section Popup events
// @event popupopen: PopupEvent
// Fired when a popup is opened in the map
map.fire('popupopen', {popup: this});
if (this._source) {
// @namespace Layer
// @section Popup events
// @event popupopen: PopupEvent
// Fired when a popup bound to this layer is opened
this._source.fire('popupopen', {popup: this}, true);
// For non-path layers, we toggle the popup when clicking
// again the layer, so prevent the map to reopen it.
if (!(this._source instanceof Path)) {
this._source.on('preclick', stopPropagation);
}
}
},
onRemove: function (map) {
DivOverlay.prototype.onRemove.call(this, map);
// @namespace Map
// @section Popup events
// @event popupclose: PopupEvent
// Fired when a popup in the map is closed
map.fire('popupclose', {popup: this});
if (this._source) {
// @namespace Layer
// @section Popup events
// @event popupclose: PopupEvent
// Fired when a popup bound to this layer is closed
this._source.fire('popupclose', {popup: this}, true);
if (!(this._source instanceof Path)) {
this._source.off('preclick', stopPropagation);
}
}
},
getEvents: function () {
var events = DivOverlay.prototype.getEvents.call(this);
if (this.options.closeOnClick !== undefined ? this.options.closeOnClick : this._map.options.closePopupOnClick) {
events.preclick = this._close;
}
if (this.options.keepInView) {
events.moveend = this._adjustPan;
}
return events;
},
_close: function () {
if (this._map) {
this._map.closePopup(this);
}
},
_initLayout: function () {
var prefix = 'leaflet-popup',
container = this._container = create$1('div',
prefix + ' ' + (this.options.className || '') +
' leaflet-zoom-animated');
var wrapper = this._wrapper = create$1('div', prefix + '-content-wrapper', container);
this._contentNode = create$1('div', prefix + '-content', wrapper);
disableClickPropagation(wrapper);
disableScrollPropagation(this._contentNode);
on(wrapper, 'contextmenu', stopPropagation);
this._tipContainer = create$1('div', prefix + '-tip-container', container);
this._tip = create$1('div', prefix + '-tip', this._tipContainer);
if (this.options.closeButton) {
var closeButton = this._closeButton = create$1('a', prefix + '-close-button', container);
closeButton.href = '#close';
closeButton.innerHTML = '×';
on(closeButton, 'click', this._onCloseButtonClick, this);
}
},
_updateLayout: function () {
var container = this._contentNode,
style = container.style;
style.width = '';
style.whiteSpace = 'nowrap';
var width = container.offsetWidth;
width = Math.min(width, this.options.maxWidth);
width = Math.max(width, this.options.minWidth);
style.width = (width + 1) + 'px';
style.whiteSpace = '';
style.height = '';
var height = container.offsetHeight,
maxHeight = this.options.maxHeight,
scrolledClass = 'leaflet-popup-scrolled';
if (maxHeight && height > maxHeight) {
style.height = maxHeight + 'px';
addClass(container, scrolledClass);
} else {
removeClass(container, scrolledClass);
}
this._containerWidth = this._container.offsetWidth;
},
_animateZoom: function (e) {
var pos = this._map._latLngToNewLayerPoint(this._latlng, e.zoom, e.center),
anchor = this._getAnchor();
setPosition(this._container, pos.add(anchor));
},
_adjustPan: function () {
if (!this.options.autoPan) { return; }
if (this._map._panAnim) { this._map._panAnim.stop(); }
var map = this._map,
marginBottom = parseInt(getStyle(this._container, 'marginBottom'), 10) || 0,
containerHeight = this._container.offsetHeight + marginBottom,
containerWidth = this._containerWidth,
layerPos = new Point(this._containerLeft, -containerHeight - this._containerBottom);
layerPos._add(getPosition(this._container));
var containerPos = map.layerPointToContainerPoint(layerPos),
padding = toPoint(this.options.autoPanPadding),
paddingTL = toPoint(this.options.autoPanPaddingTopLeft || padding),
paddingBR = toPoint(this.options.autoPanPaddingBottomRight || padding),
size = map.getSize(),
dx = 0,
dy = 0;
if (containerPos.x + containerWidth + paddingBR.x > size.x) { // right
dx = containerPos.x + containerWidth - size.x + paddingBR.x;
}
if (containerPos.x - dx - paddingTL.x < 0) { // left
dx = containerPos.x - paddingTL.x;
}
if (containerPos.y + containerHeight + paddingBR.y > size.y) { // bottom
dy = containerPos.y + containerHeight - size.y + paddingBR.y;
}
if (containerPos.y - dy - paddingTL.y < 0) { // top
dy = containerPos.y - paddingTL.y;
}
// @namespace Map
// @section Popup events
// @event autopanstart: Event
// Fired when the map starts autopanning when opening a popup.
if (dx || dy) {
map
.fire('autopanstart')
.panBy([dx, dy]);
}
},
_onCloseButtonClick: function (e) {
this._close();
stop(e);
},
_getAnchor: function () {
// Where should we anchor the popup on the source layer?
return toPoint(this._source && this._source._getPopupAnchor ? this._source._getPopupAnchor() : [0, 0]);
}
});
// @namespace Popup
// @factory L.popup(options?: Popup options, source?: Layer)
// Instantiates a `Popup` object given an optional `options` object that describes its appearance and location and an optional `source` object that is used to tag the popup with a reference to the Layer to which it refers.
var popup = function (options, source) {
return new Popup(options, source);
};
/* @namespace Map
* @section Interaction Options
* @option closePopupOnClick: Boolean = true
* Set it to `false` if you don't want popups to close when user clicks the map.
*/
Map.mergeOptions({
closePopupOnClick: true
});
// @namespace Map
// @section Methods for Layers and Controls
Map.include({
// @method openPopup(popup: Popup): this
// Opens the specified popup while closing the previously opened (to make sure only one is opened at one time for usability).
// @alternative
// @method openPopup(content: String|HTMLElement, latlng: LatLng, options?: Popup options): this
// Creates a popup with the specified content and options and opens it in the given point on a map.
openPopup: function (popup, latlng, options) {
if (!(popup instanceof Popup)) {
popup = new Popup(options).setContent(popup);
}
if (latlng) {
popup.setLatLng(latlng);
}
if (this.hasLayer(popup)) {
return this;
}
if (this._popup && this._popup.options.autoClose) {
this.closePopup();
}
this._popup = popup;
return this.addLayer(popup);
},
// @method closePopup(popup?: Popup): this
// Closes the popup previously opened with [openPopup](#map-openpopup) (or the given one).
closePopup: function (popup) {
if (!popup || popup === this._popup) {
popup = this._popup;
this._popup = null;
}
if (popup) {
this.removeLayer(popup);
}
return this;
}
});
/*
* @namespace Layer
* @section Popup methods example
*
* All layers share a set of methods convenient for binding popups to it.
*
* ```js
* var layer = L.Polygon(latlngs).bindPopup('Hi There!').addTo(map);
* layer.openPopup();
* layer.closePopup();
* ```
*
* Popups will also be automatically opened when the layer is clicked on and closed when the layer is removed from the map or another popup is opened.
*/
// @section Popup methods
Layer.include({
// @method bindPopup(content: String|HTMLElement|Function|Popup, options?: Popup options): this
// Binds a popup to the layer with the passed `content` and sets up the
// necessary event listeners. If a `Function` is passed it will receive
// the layer as the first argument and should return a `String` or `HTMLElement`.
bindPopup: function (content, options) {
if (content instanceof Popup) {
setOptions(content, options);
this._popup = content;
content._source = this;
} else {
if (!this._popup || options) {
this._popup = new Popup(options, this);
}
this._popup.setContent(content);
}
if (!this._popupHandlersAdded) {
this.on({
click: this._openPopup,
keypress: this._onKeyPress,
remove: this.closePopup,
move: this._movePopup
});
this._popupHandlersAdded = true;
}
return this;
},
// @method unbindPopup(): this
// Removes the popup previously bound with `bindPopup`.
unbindPopup: function () {
if (this._popup) {
this.off({
click: this._openPopup,
keypress: this._onKeyPress,
remove: this.closePopup,
move: this._movePopup
});
this._popupHandlersAdded = false;
this._popup = null;
}
return this;
},
// @method openPopup(latlng?: LatLng): this
// Opens the bound popup at the specified `latlng` or at the default popup anchor if no `latlng` is passed.
openPopup: function (layer, latlng) {
if (this._popup && this._map) {
latlng = this._popup._prepareOpen(this, layer, latlng);
// open the popup on the map
this._map.openPopup(this._popup, latlng);
}
return this;
},
// @method closePopup(): this
// Closes the popup bound to this layer if it is open.
closePopup: function () {
if (this._popup) {
this._popup._close();
}
return this;
},
// @method togglePopup(): this
// Opens or closes the popup bound to this layer depending on its current state.
togglePopup: function (target) {
if (this._popup) {
if (this._popup._map) {
this.closePopup();
} else {
this.openPopup(target);
}
}
return this;
},
// @method isPopupOpen(): boolean
// Returns `true` if the popup bound to this layer is currently open.
isPopupOpen: function () {
return (this._popup ? this._popup.isOpen() : false);
},
// @method setPopupContent(content: String|HTMLElement|Popup): this
// Sets the content of the popup bound to this layer.
setPopupContent: function (content) {
if (this._popup) {
this._popup.setContent(content);
}
return this;
},
// @method getPopup(): Popup
// Returns the popup bound to this layer.
getPopup: function () {
return this._popup;
},
_openPopup: function (e) {
var layer = e.layer || e.target;
if (!this._popup) {
return;
}
if (!this._map) {
return;
}
// prevent map click
stop(e);
// if this inherits from Path its a vector and we can just
// open the popup at the new location
if (layer instanceof Path) {
this.openPopup(e.layer || e.target, e.latlng);
return;
}
// otherwise treat it like a marker and figure out
// if we should toggle it open/closed
if (this._map.hasLayer(this._popup) && this._popup._source === layer) {
this.closePopup();
} else {
this.openPopup(layer, e.latlng);
}
},
_movePopup: function (e) {
this._popup.setLatLng(e.latlng);
},
_onKeyPress: function (e) {
if (e.originalEvent.keyCode === 13) {
this._openPopup(e);
}
}
});
/*
* @class Tooltip
* @inherits DivOverlay
* @aka L.Tooltip
* Used to display small texts on top of map layers.
*
* @example
*
* ```js
* marker.bindTooltip("my tooltip text").openTooltip();
* ```
* Note about tooltip offset. Leaflet takes two options in consideration
* for computing tooltip offsetting:
* - the `offset` Tooltip option: it defaults to [0, 0], and it's specific to one tooltip.
* Add a positive x offset to move the tooltip to the right, and a positive y offset to
* move it to the bottom. Negatives will move to the left and top.
* - the `tooltipAnchor` Icon option: this will only be considered for Marker. You
* should adapt this value if you use a custom icon.
*/
// @namespace Tooltip
var Tooltip = DivOverlay.extend({
// @section
// @aka Tooltip options
options: {
// @option pane: String = 'tooltipPane'
// `Map pane` where the tooltip will be added.
pane: 'tooltipPane',
// @option offset: Point = Point(0, 0)
// Optional offset of the tooltip position.
offset: [0, 0],
// @option direction: String = 'auto'
// Direction where to open the tooltip. Possible values are: `right`, `left`,
// `top`, `bottom`, `center`, `auto`.
// `auto` will dynamically switch between `right` and `left` according to the tooltip
// position on the map.
direction: 'auto',
// @option permanent: Boolean = false
// Whether to open the tooltip permanently or only on mouseover.
permanent: false,
// @option sticky: Boolean = false
// If true, the tooltip will follow the mouse instead of being fixed at the feature center.
sticky: false,
// @option interactive: Boolean = false
// If true, the tooltip will listen to the feature events.
interactive: false,
// @option opacity: Number = 0.9
// Tooltip container opacity.
opacity: 0.9
},
onAdd: function (map) {
DivOverlay.prototype.onAdd.call(this, map);
this.setOpacity(this.options.opacity);
// @namespace Map
// @section Tooltip events
// @event tooltipopen: TooltipEvent
// Fired when a tooltip is opened in the map.
map.fire('tooltipopen', {tooltip: this});
if (this._source) {
// @namespace Layer
// @section Tooltip events
// @event tooltipopen: TooltipEvent
// Fired when a tooltip bound to this layer is opened.
this._source.fire('tooltipopen', {tooltip: this}, true);
}
},
onRemove: function (map) {
DivOverlay.prototype.onRemove.call(this, map);
// @namespace Map
// @section Tooltip events
// @event tooltipclose: TooltipEvent
// Fired when a tooltip in the map is closed.
map.fire('tooltipclose', {tooltip: this});
if (this._source) {
// @namespace Layer
// @section Tooltip events
// @event tooltipclose: TooltipEvent
// Fired when a tooltip bound to this layer is closed.
this._source.fire('tooltipclose', {tooltip: this}, true);
}
},
getEvents: function () {
var events = DivOverlay.prototype.getEvents.call(this);
if (touch && !this.options.permanent) {
events.preclick = this._close;
}
return events;
},
_close: function () {
if (this._map) {
this._map.closeTooltip(this);
}
},
_initLayout: function () {
var prefix = 'leaflet-tooltip',
className = prefix + ' ' + (this.options.className || '') + ' leaflet-zoom-' + (this._zoomAnimated ? 'animated' : 'hide');
this._contentNode = this._container = create$1('div', className);
},
_updateLayout: function () {},
_adjustPan: function () {},
_setPosition: function (pos) {
var map = this._map,
container = this._container,
centerPoint = map.latLngToContainerPoint(map.getCenter()),
tooltipPoint = map.layerPointToContainerPoint(pos),
direction = this.options.direction,
tooltipWidth = container.offsetWidth,
tooltipHeight = container.offsetHeight,
offset = toPoint(this.options.offset),
anchor = this._getAnchor();
if (direction === 'top') {
pos = pos.add(toPoint(-tooltipWidth / 2 + offset.x, -tooltipHeight + offset.y + anchor.y, true));
} else if (direction === 'bottom') {
pos = pos.subtract(toPoint(tooltipWidth / 2 - offset.x, -offset.y, true));
} else if (direction === 'center') {
pos = pos.subtract(toPoint(tooltipWidth / 2 + offset.x, tooltipHeight / 2 - anchor.y + offset.y, true));
} else if (direction === 'right' || direction === 'auto' && tooltipPoint.x < centerPoint.x) {
direction = 'right';
pos = pos.add(toPoint(offset.x + anchor.x, anchor.y - tooltipHeight / 2 + offset.y, true));
} else {
direction = 'left';
pos = pos.subtract(toPoint(tooltipWidth + anchor.x - offset.x, tooltipHeight / 2 - anchor.y - offset.y, true));
}
removeClass(container, 'leaflet-tooltip-right');
removeClass(container, 'leaflet-tooltip-left');
removeClass(container, 'leaflet-tooltip-top');
removeClass(container, 'leaflet-tooltip-bottom');
addClass(container, 'leaflet-tooltip-' + direction);
setPosition(container, pos);
},
_updatePosition: function () {
var pos = this._map.latLngToLayerPoint(this._latlng);
this._setPosition(pos);
},
setOpacity: function (opacity) {
this.options.opacity = opacity;
if (this._container) {
setOpacity(this._container, opacity);
}
},
_animateZoom: function (e) {
var pos = this._map._latLngToNewLayerPoint(this._latlng, e.zoom, e.center);
this._setPosition(pos);
},
_getAnchor: function () {
// Where should we anchor the tooltip on the source layer?
return toPoint(this._source && this._source._getTooltipAnchor && !this.options.sticky ? this._source._getTooltipAnchor() : [0, 0]);
}
});
// @namespace Tooltip
// @factory L.tooltip(options?: Tooltip options, source?: Layer)
// Instantiates a Tooltip object given an optional `options` object that describes its appearance and location and an optional `source` object that is used to tag the tooltip with a reference to the Layer to which it refers.
var tooltip = function (options, source) {
return new Tooltip(options, source);
};
// @namespace Map
// @section Methods for Layers and Controls
Map.include({
// @method openTooltip(tooltip: Tooltip): this
// Opens the specified tooltip.
// @alternative
// @method openTooltip(content: String|HTMLElement, latlng: LatLng, options?: Tooltip options): this
// Creates a tooltip with the specified content and options and open it.
openTooltip: function (tooltip, latlng, options) {
if (!(tooltip instanceof Tooltip)) {
tooltip = new Tooltip(options).setContent(tooltip);
}
if (latlng) {
tooltip.setLatLng(latlng);
}
if (this.hasLayer(tooltip)) {
return this;
}
return this.addLayer(tooltip);
},
// @method closeTooltip(tooltip?: Tooltip): this
// Closes the tooltip given as parameter.
closeTooltip: function (tooltip) {
if (tooltip) {
this.removeLayer(tooltip);
}
return this;
}
});
/*
* @namespace Layer
* @section Tooltip methods example
*
* All layers share a set of methods convenient for binding tooltips to it.
*
* ```js
* var layer = L.Polygon(latlngs).bindTooltip('Hi There!').addTo(map);
* layer.openTooltip();
* layer.closeTooltip();
* ```
*/
// @section Tooltip methods
Layer.include({
// @method bindTooltip(content: String|HTMLElement|Function|Tooltip, options?: Tooltip options): this
// Binds a tooltip to the layer with the passed `content` and sets up the
// necessary event listeners. If a `Function` is passed it will receive
// the layer as the first argument and should return a `String` or `HTMLElement`.
bindTooltip: function (content, options) {
if (content instanceof Tooltip) {
setOptions(content, options);
this._tooltip = content;
content._source = this;
} else {
if (!this._tooltip || options) {
this._tooltip = new Tooltip(options, this);
}
this._tooltip.setContent(content);
}
this._initTooltipInteractions();
if (this._tooltip.options.permanent && this._map && this._map.hasLayer(this)) {
this.openTooltip();
}
return this;
},
// @method unbindTooltip(): this
// Removes the tooltip previously bound with `bindTooltip`.
unbindTooltip: function () {
if (this._tooltip) {
this._initTooltipInteractions(true);
this.closeTooltip();
this._tooltip = null;
}
return this;
},
_initTooltipInteractions: function (remove$$1) {
if (!remove$$1 && this._tooltipHandlersAdded) { return; }
var onOff = remove$$1 ? 'off' : 'on',
events = {
remove: this.closeTooltip,
move: this._moveTooltip
};
if (!this._tooltip.options.permanent) {
events.mouseover = this._openTooltip;
events.mouseout = this.closeTooltip;
if (this._tooltip.options.sticky) {
events.mousemove = this._moveTooltip;
}
if (touch) {
events.click = this._openTooltip;
}
} else {
events.add = this._openTooltip;
}
this[onOff](events);
this._tooltipHandlersAdded = !remove$$1;
},
// @method openTooltip(latlng?: LatLng): this
// Opens the bound tooltip at the specified `latlng` or at the default tooltip anchor if no `latlng` is passed.
openTooltip: function (layer, latlng) {
if (this._tooltip && this._map) {
latlng = this._tooltip._prepareOpen(this, layer, latlng);
// open the tooltip on the map
this._map.openTooltip(this._tooltip, latlng);
// Tooltip container may not be defined if not permanent and never
// opened.
if (this._tooltip.options.interactive && this._tooltip._container) {
addClass(this._tooltip._container, 'leaflet-clickable');
this.addInteractiveTarget(this._tooltip._container);
}
}
return this;
},
// @method closeTooltip(): this
// Closes the tooltip bound to this layer if it is open.
closeTooltip: function () {
if (this._tooltip) {
this._tooltip._close();
if (this._tooltip.options.interactive && this._tooltip._container) {
removeClass(this._tooltip._container, 'leaflet-clickable');
this.removeInteractiveTarget(this._tooltip._container);
}
}
return this;
},
// @method toggleTooltip(): this
// Opens or closes the tooltip bound to this layer depending on its current state.
toggleTooltip: function (target) {
if (this._tooltip) {
if (this._tooltip._map) {
this.closeTooltip();
} else {
this.openTooltip(target);
}
}
return this;
},
// @method isTooltipOpen(): boolean
// Returns `true` if the tooltip bound to this layer is currently open.
isTooltipOpen: function () {
return this._tooltip.isOpen();
},
// @method setTooltipContent(content: String|HTMLElement|Tooltip): this
// Sets the content of the tooltip bound to this layer.
setTooltipContent: function (content) {
if (this._tooltip) {
this._tooltip.setContent(content);
}
return this;
},
// @method getTooltip(): Tooltip
// Returns the tooltip bound to this layer.
getTooltip: function () {
return this._tooltip;
},
_openTooltip: function (e) {
var layer = e.layer || e.target;
if (!this._tooltip || !this._map) {
return;
}
this.openTooltip(layer, this._tooltip.options.sticky ? e.latlng : undefined);
},
_moveTooltip: function (e) {
var latlng = e.latlng, containerPoint, layerPoint;
if (this._tooltip.options.sticky && e.originalEvent) {
containerPoint = this._map.mouseEventToContainerPoint(e.originalEvent);
layerPoint = this._map.containerPointToLayerPoint(containerPoint);
latlng = this._map.layerPointToLatLng(layerPoint);
}
this._tooltip.setLatLng(latlng);
}
});
/*
* @class DivIcon
* @aka L.DivIcon
* @inherits Icon
*
* Represents a lightweight icon for markers that uses a simple `<div>`
* element instead of an image. Inherits from `Icon` but ignores the `iconUrl` and shadow options.
*
* @example
* ```js
* var myIcon = L.divIcon({className: 'my-div-icon'});
* // you can set .my-div-icon styles in CSS
*
* L.marker([50.505, 30.57], {icon: myIcon}).addTo(map);
* ```
*
* By default, it has a 'leaflet-div-icon' CSS class and is styled as a little white square with a shadow.
*/
var DivIcon = Icon.extend({
options: {
// @section
// @aka DivIcon options
iconSize: [12, 12], // also can be set through CSS
// iconAnchor: (Point),
// popupAnchor: (Point),
// @option html: String|HTMLElement = ''
// Custom HTML code to put inside the div element, empty by default. Alternatively,
// an instance of `HTMLElement`.
html: false,
// @option bgPos: Point = [0, 0]
// Optional relative position of the background, in pixels
bgPos: null,
className: 'leaflet-div-icon'
},
createIcon: function (oldIcon) {
var div = (oldIcon && oldIcon.tagName === 'DIV') ? oldIcon : document.createElement('div'),
options = this.options;
if (options.html instanceof Element) {
empty(div);
div.appendChild(options.html);
} else {
div.innerHTML = options.html !== false ? options.html : '';
}
if (options.bgPos) {
var bgPos = toPoint(options.bgPos);
div.style.backgroundPosition = (-bgPos.x) + 'px ' + (-bgPos.y) + 'px';
}
this._setIconStyles(div, 'icon');
return div;
},
createShadow: function () {
return null;
}
});
// @factory L.divIcon(options: DivIcon options)
// Creates a `DivIcon` instance with the given options.
function divIcon(options) {
return new DivIcon(options);
}
Icon.Default = IconDefault;
/*
* @class GridLayer
* @inherits Layer
* @aka L.GridLayer
*
* Generic class for handling a tiled grid of HTML elements. This is the base class for all tile layers and replaces `TileLayer.Canvas`.
* GridLayer can be extended to create a tiled grid of HTML elements like `<canvas>`, `<img>` or `<div>`. GridLayer will handle creating and animating these DOM elements for you.
*
*
* @section Synchronous usage
* @example
*
* To create a custom layer, extend GridLayer and implement the `createTile()` method, which will be passed a `Point` object with the `x`, `y`, and `z` (zoom level) coordinates to draw your tile.
*
* ```js
* var CanvasLayer = L.GridLayer.extend({
* createTile: function(coords){
* // create a <canvas> element for drawing
* var tile = L.DomUtil.create('canvas', 'leaflet-tile');
*
* // setup tile width and height according to the options
* var size = this.getTileSize();
* tile.width = size.x;
* tile.height = size.y;
*
* // get a canvas context and draw something on it using coords.x, coords.y and coords.z
* var ctx = tile.getContext('2d');
*
* // return the tile so it can be rendered on screen
* return tile;
* }
* });
* ```
*
* @section Asynchronous usage
* @example
*
* Tile creation can also be asynchronous, this is useful when using a third-party drawing library. Once the tile is finished drawing it can be passed to the `done()` callback.
*
* ```js
* var CanvasLayer = L.GridLayer.extend({
* createTile: function(coords, done){
* var error;
*
* // create a <canvas> element for drawing
* var tile = L.DomUtil.create('canvas', 'leaflet-tile');
*
* // setup tile width and height according to the options
* var size = this.getTileSize();
* tile.width = size.x;
* tile.height = size.y;
*
* // draw something asynchronously and pass the tile to the done() callback
* setTimeout(function() {
* done(error, tile);
* }, 1000);
*
* return tile;
* }
* });
* ```
*
* @section
*/
var GridLayer = Layer.extend({
// @section
// @aka GridLayer options
options: {
// @option tileSize: Number|Point = 256
// Width and height of tiles in the grid. Use a number if width and height are equal, or `L.point(width, height)` otherwise.
tileSize: 256,
// @option opacity: Number = 1.0
// Opacity of the tiles. Can be used in the `createTile()` function.
opacity: 1,
// @option updateWhenIdle: Boolean = (depends)
// Load new tiles only when panning ends.
// `true` by default on mobile browsers, in order to avoid too many requests and keep smooth navigation.
// `false` otherwise in order to display new tiles _during_ panning, since it is easy to pan outside the
// [`keepBuffer`](#gridlayer-keepbuffer) option in desktop browsers.
updateWhenIdle: mobile,
// @option updateWhenZooming: Boolean = true
// By default, a smooth zoom animation (during a [touch zoom](#map-touchzoom) or a [`flyTo()`](#map-flyto)) will update grid layers every integer zoom level. Setting this option to `false` will update the grid layer only when the smooth animation ends.
updateWhenZooming: true,
// @option updateInterval: Number = 200
// Tiles will not update more than once every `updateInterval` milliseconds when panning.
updateInterval: 200,
// @option zIndex: Number = 1
// The explicit zIndex of the tile layer.
zIndex: 1,
// @option bounds: LatLngBounds = undefined
// If set, tiles will only be loaded inside the set `LatLngBounds`.
bounds: null,
// @option minZoom: Number = 0
// The minimum zoom level down to which this layer will be displayed (inclusive).
minZoom: 0,
// @option maxZoom: Number = undefined
// The maximum zoom level up to which this layer will be displayed (inclusive).
maxZoom: undefined,
// @option maxNativeZoom: Number = undefined
// Maximum zoom number the tile source has available. If it is specified,
// the tiles on all zoom levels higher than `maxNativeZoom` will be loaded
// from `maxNativeZoom` level and auto-scaled.
maxNativeZoom: undefined,
// @option minNativeZoom: Number = undefined
// Minimum zoom number the tile source has available. If it is specified,
// the tiles on all zoom levels lower than `minNativeZoom` will be loaded
// from `minNativeZoom` level and auto-scaled.
minNativeZoom: undefined,
// @option noWrap: Boolean = false
// Whether the layer is wrapped around the antimeridian. If `true`, the
// GridLayer will only be displayed once at low zoom levels. Has no
// effect when the [map CRS](#map-crs) doesn't wrap around. Can be used
// in combination with [`bounds`](#gridlayer-bounds) to prevent requesting
// tiles outside the CRS limits.
noWrap: false,
// @option pane: String = 'tilePane'
// `Map pane` where the grid layer will be added.
pane: 'tilePane',
// @option className: String = ''
// A custom class name to assign to the tile layer. Empty by default.
className: '',
// @option keepBuffer: Number = 2
// When panning the map, keep this many rows and columns of tiles before unloading them.
keepBuffer: 2
},
initialize: function (options) {
setOptions(this, options);
},
onAdd: function () {
this._initContainer();
this._levels = {};
this._tiles = {};
this._resetView();
this._update();
},
beforeAdd: function (map) {
map._addZoomLimit(this);
},
onRemove: function (map) {
this._removeAllTiles();
remove(this._container);
map._removeZoomLimit(this);
this._container = null;
this._tileZoom = undefined;
},
// @method bringToFront: this
// Brings the tile layer to the top of all tile layers.
bringToFront: function () {
if (this._map) {
toFront(this._container);
this._setAutoZIndex(Math.max);
}
return this;
},
// @method bringToBack: this
// Brings the tile layer to the bottom of all tile layers.
bringToBack: function () {
if (this._map) {
toBack(this._container);
this._setAutoZIndex(Math.min);
}
return this;
},
// @method getContainer: HTMLElement
// Returns the HTML element that contains the tiles for this layer.
getContainer: function () {
return this._container;
},
// @method setOpacity(opacity: Number): this
// Changes the [opacity](#gridlayer-opacity) of the grid layer.
setOpacity: function (opacity) {
this.options.opacity = opacity;
this._updateOpacity();
return this;
},
// @method setZIndex(zIndex: Number): this
// Changes the [zIndex](#gridlayer-zindex) of the grid layer.
setZIndex: function (zIndex) {
this.options.zIndex = zIndex;
this._updateZIndex();
return this;
},
// @method isLoading: Boolean
// Returns `true` if any tile in the grid layer has not finished loading.
isLoading: function () {
return this._loading;
},
// @method redraw: this
// Causes the layer to clear all the tiles and request them again.
redraw: function () {
if (this._map) {
this._removeAllTiles();
this._update();
}
return this;
},
getEvents: function () {
var events = {
viewprereset: this._invalidateAll,
viewreset: this._resetView,
zoom: this._resetView,
moveend: this._onMoveEnd
};
if (!this.options.updateWhenIdle) {
// update tiles on move, but not more often than once per given interval
if (!this._onMove) {
this._onMove = throttle(this._onMoveEnd, this.options.updateInterval, this);
}
events.move = this._onMove;
}
if (this._zoomAnimated) {
events.zoomanim = this._animateZoom;
}
return events;
},
// @section Extension methods
// Layers extending `GridLayer` shall reimplement the following method.
// @method createTile(coords: Object, done?: Function): HTMLElement
// Called only internally, must be overridden by classes extending `GridLayer`.
// Returns the `HTMLElement` corresponding to the given `coords`. If the `done` callback
// is specified, it must be called when the tile has finished loading and drawing.
createTile: function () {
return document.createElement('div');
},
// @section
// @method getTileSize: Point
// Normalizes the [tileSize option](#gridlayer-tilesize) into a point. Used by the `createTile()` method.
getTileSize: function () {
var s = this.options.tileSize;
return s instanceof Point ? s : new Point(s, s);
},
_updateZIndex: function () {
if (this._container && this.options.zIndex !== undefined && this.options.zIndex !== null) {
this._container.style.zIndex = this.options.zIndex;
}
},
_setAutoZIndex: function (compare) {
// go through all other layers of the same pane, set zIndex to max + 1 (front) or min - 1 (back)
var layers = this.getPane().children,
edgeZIndex = -compare(-Infinity, Infinity); // -Infinity for max, Infinity for min
for (var i = 0, len = layers.length, zIndex; i < len; i++) {
zIndex = layers[i].style.zIndex;
if (layers[i] !== this._container && zIndex) {
edgeZIndex = compare(edgeZIndex, +zIndex);
}
}
if (isFinite(edgeZIndex)) {
this.options.zIndex = edgeZIndex + compare(-1, 1);
this._updateZIndex();
}
},
_updateOpacity: function () {
if (!this._map) { return; }
// IE doesn't inherit filter opacity properly, so we're forced to set it on tiles
if (ielt9) { return; }
setOpacity(this._container, this.options.opacity);
var now = +new Date(),
nextFrame = false,
willPrune = false;
for (var key in this._tiles) {
var tile = this._tiles[key];
if (!tile.current || !tile.loaded) { continue; }
var fade = Math.min(1, (now - tile.loaded) / 200);
setOpacity(tile.el, fade);
if (fade < 1) {
nextFrame = true;
} else {
if (tile.active) {
willPrune = true;
} else {
this._onOpaqueTile(tile);
}
tile.active = true;
}
}
if (willPrune && !this._noPrune) { this._pruneTiles(); }
if (nextFrame) {
cancelAnimFrame(this._fadeFrame);
this._fadeFrame = requestAnimFrame(this._updateOpacity, this);
}
},
_onOpaqueTile: falseFn,
_initContainer: function () {
if (this._container) { return; }
this._container = create$1('div', 'leaflet-layer ' + (this.options.className || ''));
this._updateZIndex();
if (this.options.opacity < 1) {
this._updateOpacity();
}
this.getPane().appendChild(this._container);
},
_updateLevels: function () {
var zoom = this._tileZoom,
maxZoom = this.options.maxZoom;
if (zoom === undefined) { return undefined; }
for (var z in this._levels) {
if (this._levels[z].el.children.length || z === zoom) {
this._levels[z].el.style.zIndex = maxZoom - Math.abs(zoom - z);
this._onUpdateLevel(z);
} else {
remove(this._levels[z].el);
this._removeTilesAtZoom(z);
this._onRemoveLevel(z);
delete this._levels[z];
}
}
var level = this._levels[zoom],
map = this._map;
if (!level) {
level = this._levels[zoom] = {};
level.el = create$1('div', 'leaflet-tile-container leaflet-zoom-animated', this._container);
level.el.style.zIndex = maxZoom;
level.origin = map.project(map.unproject(map.getPixelOrigin()), zoom).round();
level.zoom = zoom;
this._setZoomTransform(level, map.getCenter(), map.getZoom());
// force the browser to consider the newly added element for transition
falseFn(level.el.offsetWidth);
this._onCreateLevel(level);
}
this._level = level;
return level;
},
_onUpdateLevel: falseFn,
_onRemoveLevel: falseFn,
_onCreateLevel: falseFn,
_pruneTiles: function () {
if (!this._map) {
return;
}
var key, tile;
var zoom = this._map.getZoom();
if (zoom > this.options.maxZoom ||
zoom < this.options.minZoom) {
this._removeAllTiles();
return;
}
for (key in this._tiles) {
tile = this._tiles[key];
tile.retain = tile.current;
}
for (key in this._tiles) {
tile = this._tiles[key];
if (tile.current && !tile.active) {
var coords = tile.coords;
if (!this._retainParent(coords.x, coords.y, coords.z, coords.z - 5)) {
this._retainChildren(coords.x, coords.y, coords.z, coords.z + 2);
}
}
}
for (key in this._tiles) {
if (!this._tiles[key].retain) {
this._removeTile(key);
}
}
},
_removeTilesAtZoom: function (zoom) {
for (var key in this._tiles) {
if (this._tiles[key].coords.z !== zoom) {
continue;
}
this._removeTile(key);
}
},
_removeAllTiles: function () {
for (var key in this._tiles) {
this._removeTile(key);
}
},
_invalidateAll: function () {
for (var z in this._levels) {
remove(this._levels[z].el);
this._onRemoveLevel(z);
delete this._levels[z];
}
this._removeAllTiles();
this._tileZoom = undefined;
},
_retainParent: function (x, y, z, minZoom) {
var x2 = Math.floor(x / 2),
y2 = Math.floor(y / 2),
z2 = z - 1,
coords2 = new Point(+x2, +y2);
coords2.z = +z2;
var key = this._tileCoordsToKey(coords2),
tile = this._tiles[key];
if (tile && tile.active) {
tile.retain = true;
return true;
} else if (tile && tile.loaded) {
tile.retain = true;
}
if (z2 > minZoom) {
return this._retainParent(x2, y2, z2, minZoom);
}
return false;
},
_retainChildren: function (x, y, z, maxZoom) {
for (var i = 2 * x; i < 2 * x + 2; i++) {
for (var j = 2 * y; j < 2 * y + 2; j++) {
var coords = new Point(i, j);
coords.z = z + 1;
var key = this._tileCoordsToKey(coords),
tile = this._tiles[key];
if (tile && tile.active) {
tile.retain = true;
continue;
} else if (tile && tile.loaded) {
tile.retain = true;
}
if (z + 1 < maxZoom) {
this._retainChildren(i, j, z + 1, maxZoom);
}
}
}
},
_resetView: function (e) {
var animating = e && (e.pinch || e.flyTo);
this._setView(this._map.getCenter(), this._map.getZoom(), animating, animating);
},
_animateZoom: function (e) {
this._setView(e.center, e.zoom, true, e.noUpdate);
},
_clampZoom: function (zoom) {
var options = this.options;
if (undefined !== options.minNativeZoom && zoom < options.minNativeZoom) {
return options.minNativeZoom;
}
if (undefined !== options.maxNativeZoom && options.maxNativeZoom < zoom) {
return options.maxNativeZoom;
}
return zoom;
},
_setView: function (center, zoom, noPrune, noUpdate) {
var tileZoom = this._clampZoom(Math.round(zoom));
if ((this.options.maxZoom !== undefined && tileZoom > this.options.maxZoom) ||
(this.options.minZoom !== undefined && tileZoom < this.options.minZoom)) {
tileZoom = undefined;
}
var tileZoomChanged = this.options.updateWhenZooming && (tileZoom !== this._tileZoom);
if (!noUpdate || tileZoomChanged) {
this._tileZoom = tileZoom;
if (this._abortLoading) {
this._abortLoading();
}
this._updateLevels();
this._resetGrid();
if (tileZoom !== undefined) {
this._update(center);
}
if (!noPrune) {
this._pruneTiles();
}
// Flag to prevent _updateOpacity from pruning tiles during
// a zoom anim or a pinch gesture
this._noPrune = !!noPrune;
}
this._setZoomTransforms(center, zoom);
},
_setZoomTransforms: function (center, zoom) {
for (var i in this._levels) {
this._setZoomTransform(this._levels[i], center, zoom);
}
},
_setZoomTransform: function (level, center, zoom) {
var scale = this._map.getZoomScale(zoom, level.zoom),
translate = level.origin.multiplyBy(scale)
.subtract(this._map._getNewPixelOrigin(center, zoom)).round();
if (any3d) {
setTransform(level.el, translate, scale);
} else {
setPosition(level.el, translate);
}
},
_resetGrid: function () {
var map = this._map,
crs = map.options.crs,
tileSize = this._tileSize = this.getTileSize(),
tileZoom = this._tileZoom;
var bounds = this._map.getPixelWorldBounds(this._tileZoom);
if (bounds) {
this._globalTileRange = this._pxBoundsToTileRange(bounds);
}
this._wrapX = crs.wrapLng && !this.options.noWrap && [
Math.floor(map.project([0, crs.wrapLng[0]], tileZoom).x / tileSize.x),
Math.ceil(map.project([0, crs.wrapLng[1]], tileZoom).x / tileSize.y)
];
this._wrapY = crs.wrapLat && !this.options.noWrap && [
Math.floor(map.project([crs.wrapLat[0], 0], tileZoom).y / tileSize.x),
Math.ceil(map.project([crs.wrapLat[1], 0], tileZoom).y / tileSize.y)
];
},
_onMoveEnd: function () {
if (!this._map || this._map._animatingZoom) { return; }
this._update();
},
_getTiledPixelBounds: function (center) {
var map = this._map,
mapZoom = map._animatingZoom ? Math.max(map._animateToZoom, map.getZoom()) : map.getZoom(),
scale = map.getZoomScale(mapZoom, this._tileZoom),
pixelCenter = map.project(center, this._tileZoom).floor(),
halfSize = map.getSize().divideBy(scale * 2);
return new Bounds(pixelCenter.subtract(halfSize), pixelCenter.add(halfSize));
},
// Private method to load tiles in the grid's active zoom level according to map bounds
_update: function (center) {
var map = this._map;
if (!map) { return; }
var zoom = this._clampZoom(map.getZoom());
if (center === undefined) { center = map.getCenter(); }
if (this._tileZoom === undefined) { return; } // if out of minzoom/maxzoom
var pixelBounds = this._getTiledPixelBounds(center),
tileRange = this._pxBoundsToTileRange(pixelBounds),
tileCenter = tileRange.getCenter(),
queue = [],
margin = this.options.keepBuffer,
noPruneRange = new Bounds(tileRange.getBottomLeft().subtract([margin, -margin]),
tileRange.getTopRight().add([margin, -margin]));
// Sanity check: panic if the tile range contains Infinity somewhere.
if (!(isFinite(tileRange.min.x) &&
isFinite(tileRange.min.y) &&
isFinite(tileRange.max.x) &&
isFinite(tileRange.max.y))) { throw new Error('Attempted to load an infinite number of tiles'); }
for (var key in this._tiles) {
var c = this._tiles[key].coords;
if (c.z !== this._tileZoom || !noPruneRange.contains(new Point(c.x, c.y))) {
this._tiles[key].current = false;
}
}
// _update just loads more tiles. If the tile zoom level differs too much
// from the map's, let _setView reset levels and prune old tiles.
if (Math.abs(zoom - this._tileZoom) > 1) { this._setView(center, zoom); return; }
// create a queue of coordinates to load tiles from
for (var j = tileRange.min.y; j <= tileRange.max.y; j++) {
for (var i = tileRange.min.x; i <= tileRange.max.x; i++) {
var coords = new Point(i, j);
coords.z = this._tileZoom;
if (!this._isValidTile(coords)) { continue; }
var tile = this._tiles[this._tileCoordsToKey(coords)];
if (tile) {
tile.current = true;
} else {
queue.push(coords);
}
}
}
// sort tile queue to load tiles in order of their distance to center
queue.sort(function (a, b) {
return a.distanceTo(tileCenter) - b.distanceTo(tileCenter);
});
if (queue.length !== 0) {
// if it's the first batch of tiles to load
if (!this._loading) {
this._loading = true;
// @event loading: Event
// Fired when the grid layer starts loading tiles.
this.fire('loading');
}
// create DOM fragment to append tiles in one batch
var fragment = document.createDocumentFragment();
for (i = 0; i < queue.length; i++) {
this._addTile(queue[i], fragment);
}
this._level.el.appendChild(fragment);
}
},
_isValidTile: function (coords) {
var crs = this._map.options.crs;
if (!crs.infinite) {
// don't load tile if it's out of bounds and not wrapped
var bounds = this._globalTileRange;
if ((!crs.wrapLng && (coords.x < bounds.min.x || coords.x > bounds.max.x)) ||
(!crs.wrapLat && (coords.y < bounds.min.y || coords.y > bounds.max.y))) { return false; }
}
if (!this.options.bounds) { return true; }
// don't load tile if it doesn't intersect the bounds in options
var tileBounds = this._tileCoordsToBounds(coords);
return toLatLngBounds(this.options.bounds).overlaps(tileBounds);
},
_keyToBounds: function (key) {
return this._tileCoordsToBounds(this._keyToTileCoords(key));
},
_tileCoordsToNwSe: function (coords) {
var map = this._map,
tileSize = this.getTileSize(),
nwPoint = coords.scaleBy(tileSize),
sePoint = nwPoint.add(tileSize),
nw = map.unproject(nwPoint, coords.z),
se = map.unproject(sePoint, coords.z);
return [nw, se];
},
// converts tile coordinates to its geographical bounds
_tileCoordsToBounds: function (coords) {
var bp = this._tileCoordsToNwSe(coords),
bounds = new LatLngBounds(bp[0], bp[1]);
if (!this.options.noWrap) {
bounds = this._map.wrapLatLngBounds(bounds);
}
return bounds;
},
// converts tile coordinates to key for the tile cache
_tileCoordsToKey: function (coords) {
return coords.x + ':' + coords.y + ':' + coords.z;
},
// converts tile cache key to coordinates
_keyToTileCoords: function (key) {
var k = key.split(':'),
coords = new Point(+k[0], +k[1]);
coords.z = +k[2];
return coords;
},
_removeTile: function (key) {
var tile = this._tiles[key];
if (!tile) { return; }
remove(tile.el);
delete this._tiles[key];
// @event tileunload: TileEvent
// Fired when a tile is removed (e.g. when a tile goes off the screen).
this.fire('tileunload', {
tile: tile.el,
coords: this._keyToTileCoords(key)
});
},
_initTile: function (tile) {
addClass(tile, 'leaflet-tile');
var tileSize = this.getTileSize();
tile.style.width = tileSize.x + 'px';
tile.style.height = tileSize.y + 'px';
tile.onselectstart = falseFn;
tile.onmousemove = falseFn;
// update opacity on tiles in IE7-8 because of filter inheritance problems
if (ielt9 && this.options.opacity < 1) {
setOpacity(tile, this.options.opacity);
}
// without this hack, tiles disappear after zoom on Chrome for Android
// https://github.com/Leaflet/Leaflet/issues/2078
if (android && !android23) {
tile.style.WebkitBackfaceVisibility = 'hidden';
}
},
_addTile: function (coords, container) {
var tilePos = this._getTilePos(coords),
key = this._tileCoordsToKey(coords);
var tile = this.createTile(this._wrapCoords(coords), bind(this._tileReady, this, coords));
this._initTile(tile);
// if createTile is defined with a second argument ("done" callback),
// we know that tile is async and will be ready later; otherwise
if (this.createTile.length < 2) {
// mark tile as ready, but delay one frame for opacity animation to happen
requestAnimFrame(bind(this._tileReady, this, coords, null, tile));
}
setPosition(tile, tilePos);
// save tile in cache
this._tiles[key] = {
el: tile,
coords: coords,
current: true
};
container.appendChild(tile);
// @event tileloadstart: TileEvent
// Fired when a tile is requested and starts loading.
this.fire('tileloadstart', {
tile: tile,
coords: coords
});
},
_tileReady: function (coords, err, tile) {
if (err) {
// @event tileerror: TileErrorEvent
// Fired when there is an error loading a tile.
this.fire('tileerror', {
error: err,
tile: tile,
coords: coords
});
}
var key = this._tileCoordsToKey(coords);
tile = this._tiles[key];
if (!tile) { return; }
tile.loaded = +new Date();
if (this._map._fadeAnimated) {
setOpacity(tile.el, 0);
cancelAnimFrame(this._fadeFrame);
this._fadeFrame = requestAnimFrame(this._updateOpacity, this);
} else {
tile.active = true;
this._pruneTiles();
}
if (!err) {
addClass(tile.el, 'leaflet-tile-loaded');
// @event tileload: TileEvent
// Fired when a tile loads.
this.fire('tileload', {
tile: tile.el,
coords: coords
});
}
if (this._noTilesToLoad()) {
this._loading = false;
// @event load: Event
// Fired when the grid layer loaded all visible tiles.
this.fire('load');
if (ielt9 || !this._map._fadeAnimated) {
requestAnimFrame(this._pruneTiles, this);
} else {
// Wait a bit more than 0.2 secs (the duration of the tile fade-in)
// to trigger a pruning.
setTimeout(bind(this._pruneTiles, this), 250);
}
}
},
_getTilePos: function (coords) {
return coords.scaleBy(this.getTileSize()).subtract(this._level.origin);
},
_wrapCoords: function (coords) {
var newCoords = new Point(
this._wrapX ? wrapNum(coords.x, this._wrapX) : coords.x,
this._wrapY ? wrapNum(coords.y, this._wrapY) : coords.y);
newCoords.z = coords.z;
return newCoords;
},
_pxBoundsToTileRange: function (bounds) {
var tileSize = this.getTileSize();
return new Bounds(
bounds.min.unscaleBy(tileSize).floor(),
bounds.max.unscaleBy(tileSize).ceil().subtract([1, 1]));
},
_noTilesToLoad: function () {
for (var key in this._tiles) {
if (!this._tiles[key].loaded) { return false; }
}
return true;
}
});
// @factory L.gridLayer(options?: GridLayer options)
// Creates a new instance of GridLayer with the supplied options.
function gridLayer(options) {
return new GridLayer(options);
}
/*
* @class TileLayer
* @inherits GridLayer
* @aka L.TileLayer
* Used to load and display tile layers on the map. Note that most tile servers require attribution, which you can set under `Layer`. Extends `GridLayer`.
*
* @example
*
* ```js
* L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png?{foo}', {foo: 'bar', attribution: 'Map data © <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>'}).addTo(map);
* ```
*
* @section URL template
* @example
*
* A string of the following form:
*
* ```
* 'http://{s}.somedomain.com/blabla/{z}/{x}/{y}{r}.png'
* ```
*
* `{s}` means one of the available subdomains (used sequentially to help with browser parallel requests per domain limitation; subdomain values are specified in options; `a`, `b` or `c` by default, can be omitted), `{z}` — zoom level, `{x}` and `{y}` — tile coordinates. `{r}` can be used to add "@2x" to the URL to load retina tiles.
*
* You can use custom keys in the template, which will be [evaluated](#util-template) from TileLayer options, like this:
*
* ```
* L.tileLayer('http://{s}.somedomain.com/{foo}/{z}/{x}/{y}.png', {foo: 'bar'});
* ```
*/
var TileLayer = GridLayer.extend({
// @section
// @aka TileLayer options
options: {
// @option minZoom: Number = 0
// The minimum zoom level down to which this layer will be displayed (inclusive).
minZoom: 0,
// @option maxZoom: Number = 18
// The maximum zoom level up to which this layer will be displayed (inclusive).
maxZoom: 18,
// @option subdomains: String|String[] = 'abc'
// Subdomains of the tile service. Can be passed in the form of one string (where each letter is a subdomain name) or an array of strings.
subdomains: 'abc',
// @option errorTileUrl: String = ''
// URL to the tile image to show in place of the tile that failed to load.
errorTileUrl: '',
// @option zoomOffset: Number = 0
// The zoom number used in tile URLs will be offset with this value.
zoomOffset: 0,
// @option tms: Boolean = false
// If `true`, inverses Y axis numbering for tiles (turn this on for [TMS](https://en.wikipedia.org/wiki/Tile_Map_Service) services).
tms: false,
// @option zoomReverse: Boolean = false
// If set to true, the zoom number used in tile URLs will be reversed (`maxZoom - zoom` instead of `zoom`)
zoomReverse: false,
// @option detectRetina: Boolean = false
// If `true` and user is on a retina display, it will request four tiles of half the specified size and a bigger zoom level in place of one to utilize the high resolution.
detectRetina: false,
// @option crossOrigin: Boolean|String = false
// Whether the crossOrigin attribute will be added to the tiles.
// If a String is provided, all tiles will have their crossOrigin attribute set to the String provided. This is needed if you want to access tile pixel data.
// Refer to [CORS Settings](https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes) for valid String values.
crossOrigin: false
},
initialize: function (url, options) {
this._url = url;
options = setOptions(this, options);
// detecting retina displays, adjusting tileSize and zoom levels
if (options.detectRetina && retina && options.maxZoom > 0) {
options.tileSize = Math.floor(options.tileSize / 2);
if (!options.zoomReverse) {
options.zoomOffset++;
options.maxZoom--;
} else {
options.zoomOffset--;
options.minZoom++;
}
options.minZoom = Math.max(0, options.minZoom);
}
if (typeof options.subdomains === 'string') {
options.subdomains = options.subdomains.split('');
}
// for https://github.com/Leaflet/Leaflet/issues/137
if (!android) {
this.on('tileunload', this._onTileRemove);
}
},
// @method setUrl(url: String, noRedraw?: Boolean): this
// Updates the layer's URL template and redraws it (unless `noRedraw` is set to `true`).
// If the URL does not change, the layer will not be redrawn unless
// the noRedraw parameter is set to false.
setUrl: function (url, noRedraw) {
if (this._url === url && noRedraw === undefined) {
noRedraw = true;
}
this._url = url;
if (!noRedraw) {
this.redraw();
}
return this;
},
// @method createTile(coords: Object, done?: Function): HTMLElement
// Called only internally, overrides GridLayer's [`createTile()`](#gridlayer-createtile)
// to return an `<img>` HTML element with the appropriate image URL given `coords`. The `done`
// callback is called when the tile has been loaded.
createTile: function (coords, done) {
var tile = document.createElement('img');
on(tile, 'load', bind(this._tileOnLoad, this, done, tile));
on(tile, 'error', bind(this._tileOnError, this, done, tile));
if (this.options.crossOrigin || this.options.crossOrigin === '') {
tile.crossOrigin = this.options.crossOrigin === true ? '' : this.options.crossOrigin;
}
/*
Alt tag is set to empty string to keep screen readers from reading URL and for compliance reasons
http://www.w3.org/TR/WCAG20-TECHS/H67
*/
tile.alt = '';
/*
Set role="presentation" to force screen readers to ignore this
https://www.w3.org/TR/wai-aria/roles#textalternativecomputation
*/
tile.setAttribute('role', 'presentation');
tile.src = this.getTileUrl(coords);
return tile;
},
// @section Extension methods
// @uninheritable
// Layers extending `TileLayer` might reimplement the following method.
// @method getTileUrl(coords: Object): String
// Called only internally, returns the URL for a tile given its coordinates.
// Classes extending `TileLayer` can override this function to provide custom tile URL naming schemes.
getTileUrl: function (coords) {
var data = {
r: retina ? '@2x' : '',
s: this._getSubdomain(coords),
x: coords.x,
y: coords.y,
z: this._getZoomForUrl()
};
if (this._map && !this._map.options.crs.infinite) {
var invertedY = this._globalTileRange.max.y - coords.y;
if (this.options.tms) {
data['y'] = invertedY;
}
data['-y'] = invertedY;
}
return template(this._url, extend(data, this.options));
},
_tileOnLoad: function (done, tile) {
// For https://github.com/Leaflet/Leaflet/issues/3332
if (ielt9) {
setTimeout(bind(done, this, null, tile), 0);
} else {
done(null, tile);
}
},
_tileOnError: function (done, tile, e) {
var errorUrl = this.options.errorTileUrl;
if (errorUrl && tile.getAttribute('src') !== errorUrl) {
tile.src = errorUrl;
}
done(e, tile);
},
_onTileRemove: function (e) {
e.tile.onload = null;
},
_getZoomForUrl: function () {
var zoom = this._tileZoom,
maxZoom = this.options.maxZoom,
zoomReverse = this.options.zoomReverse,
zoomOffset = this.options.zoomOffset;
if (zoomReverse) {
zoom = maxZoom - zoom;
}
return zoom + zoomOffset;
},
_getSubdomain: function (tilePoint) {
var index = Math.abs(tilePoint.x + tilePoint.y) % this.options.subdomains.length;
return this.options.subdomains[index];
},
// stops loading all tiles in the background layer
_abortLoading: function () {
var i, tile;
for (i in this._tiles) {
if (this._tiles[i].coords.z !== this._tileZoom) {
tile = this._tiles[i].el;
tile.onload = falseFn;
tile.onerror = falseFn;
if (!tile.complete) {
tile.src = emptyImageUrl;
remove(tile);
delete this._tiles[i];
}
}
}
},
_removeTile: function (key) {
var tile = this._tiles[key];
if (!tile) { return; }
// Cancels any pending http requests associated with the tile
// unless we're on Android's stock browser,
// see https://github.com/Leaflet/Leaflet/issues/137
if (!androidStock) {
tile.el.setAttribute('src', emptyImageUrl);
}
return GridLayer.prototype._removeTile.call(this, key);
},
_tileReady: function (coords, err, tile) {
if (!this._map || (tile && tile.getAttribute('src') === emptyImageUrl)) {
return;
}
return GridLayer.prototype._tileReady.call(this, coords, err, tile);
}
});
// @factory L.tilelayer(urlTemplate: String, options?: TileLayer options)
// Instantiates a tile layer object given a `URL template` and optionally an options object.
function tileLayer(url, options) {
return new TileLayer(url, options);
}
/*
* @class TileLayer.WMS
* @inherits TileLayer
* @aka L.TileLayer.WMS
* Used to display [WMS](https://en.wikipedia.org/wiki/Web_Map_Service) services as tile layers on the map. Extends `TileLayer`.
*
* @example
*
* ```js
* var nexrad = L.tileLayer.wms("http://mesonet.agron.iastate.edu/cgi-bin/wms/nexrad/n0r.cgi", {
* layers: 'nexrad-n0r-900913',
* format: 'image/png',
* transparent: true,
* attribution: "Weather data © 2012 IEM Nexrad"
* });
* ```
*/
var TileLayerWMS = TileLayer.extend({
// @section
// @aka TileLayer.WMS options
// If any custom options not documented here are used, they will be sent to the
// WMS server as extra parameters in each request URL. This can be useful for
// [non-standard vendor WMS parameters](http://docs.geoserver.org/stable/en/user/services/wms/vendor.html).
defaultWmsParams: {
service: 'WMS',
request: 'GetMap',
// @option layers: String = ''
// **(required)** Comma-separated list of WMS layers to show.
layers: '',
// @option styles: String = ''
// Comma-separated list of WMS styles.
styles: '',
// @option format: String = 'image/jpeg'
// WMS image format (use `'image/png'` for layers with transparency).
format: 'image/jpeg',
// @option transparent: Boolean = false
// If `true`, the WMS service will return images with transparency.
transparent: false,
// @option version: String = '1.1.1'
// Version of the WMS service to use
version: '1.1.1'
},
options: {
// @option crs: CRS = null
// Coordinate Reference System to use for the WMS requests, defaults to
// map CRS. Don't change this if you're not sure what it means.
crs: null,
// @option uppercase: Boolean = false
// If `true`, WMS request parameter keys will be uppercase.
uppercase: false
},
initialize: function (url, options) {
this._url = url;
var wmsParams = extend({}, this.defaultWmsParams);
// all keys that are not TileLayer options go to WMS params
for (var i in options) {
if (!(i in this.options)) {
wmsParams[i] = options[i];
}
}
options = setOptions(this, options);
var realRetina = options.detectRetina && retina ? 2 : 1;
var tileSize = this.getTileSize();
wmsParams.width = tileSize.x * realRetina;
wmsParams.height = tileSize.y * realRetina;
this.wmsParams = wmsParams;
},
onAdd: function (map) {
this._crs = this.options.crs || map.options.crs;
this._wmsVersion = parseFloat(this.wmsParams.version);
var projectionKey = this._wmsVersion >= 1.3 ? 'crs' : 'srs';
this.wmsParams[projectionKey] = this._crs.code;
TileLayer.prototype.onAdd.call(this, map);
},
getTileUrl: function (coords) {
var tileBounds = this._tileCoordsToNwSe(coords),
crs = this._crs,
bounds = toBounds(crs.project(tileBounds[0]), crs.project(tileBounds[1])),
min = bounds.min,
max = bounds.max,
bbox = (this._wmsVersion >= 1.3 && this._crs === EPSG4326 ?
[min.y, min.x, max.y, max.x] :
[min.x, min.y, max.x, max.y]).join(','),
url = TileLayer.prototype.getTileUrl.call(this, coords);
return url +
getParamString(this.wmsParams, url, this.options.uppercase) +
(this.options.uppercase ? '&BBOX=' : '&bbox=') + bbox;
},
// @method setParams(params: Object, noRedraw?: Boolean): this
// Merges an object with the new parameters and re-requests tiles on the current screen (unless `noRedraw` was set to true).
setParams: function (params, noRedraw) {
extend(this.wmsParams, params);
if (!noRedraw) {
this.redraw();
}
return this;
}
});
// @factory L.tileLayer.wms(baseUrl: String, options: TileLayer.WMS options)
// Instantiates a WMS tile layer object given a base URL of the WMS service and a WMS parameters/options object.
function tileLayerWMS(url, options) {
return new TileLayerWMS(url, options);
}
TileLayer.WMS = TileLayerWMS;
tileLayer.wms = tileLayerWMS;
/*
* @class Renderer
* @inherits Layer
* @aka L.Renderer
*
* Base class for vector renderer implementations (`SVG`, `Canvas`). Handles the
* DOM container of the renderer, its bounds, and its zoom animation.
*
* A `Renderer` works as an implicit layer group for all `Path`s - the renderer
* itself can be added or removed to the map. All paths use a renderer, which can
* be implicit (the map will decide the type of renderer and use it automatically)
* or explicit (using the [`renderer`](#path-renderer) option of the path).
*
* Do not use this class directly, use `SVG` and `Canvas` instead.
*
* @event update: Event
* Fired when the renderer updates its bounds, center and zoom, for example when
* its map has moved
*/
var Renderer = Layer.extend({
// @section
// @aka Renderer options
options: {
// @option padding: Number = 0.1
// How much to extend the clip area around the map view (relative to its size)
// e.g. 0.1 would be 10% of map view in each direction
padding: 0.1,
// @option tolerance: Number = 0
// How much to extend click tolerance round a path/object on the map
tolerance : 0
},
initialize: function (options) {
setOptions(this, options);
stamp(this);
this._layers = this._layers || {};
},
onAdd: function () {
if (!this._container) {
this._initContainer(); // defined by renderer implementations
if (this._zoomAnimated) {
addClass(this._container, 'leaflet-zoom-animated');
}
}
this.getPane().appendChild(this._container);
this._update();
this.on('update', this._updatePaths, this);
},
onRemove: function () {
this.off('update', this._updatePaths, this);
this._destroyContainer();
},
getEvents: function () {
var events = {
viewreset: this._reset,
zoom: this._onZoom,
moveend: this._update,
zoomend: this._onZoomEnd
};
if (this._zoomAnimated) {
events.zoomanim = this._onAnimZoom;
}
return events;
},
_onAnimZoom: function (ev) {
this._updateTransform(ev.center, ev.zoom);
},
_onZoom: function () {
this._updateTransform(this._map.getCenter(), this._map.getZoom());
},
_updateTransform: function (center, zoom) {
var scale = this._map.getZoomScale(zoom, this._zoom),
position = getPosition(this._container),
viewHalf = this._map.getSize().multiplyBy(0.5 + this.options.padding),
currentCenterPoint = this._map.project(this._center, zoom),
destCenterPoint = this._map.project(center, zoom),
centerOffset = destCenterPoint.subtract(currentCenterPoint),
topLeftOffset = viewHalf.multiplyBy(-scale).add(position).add(viewHalf).subtract(centerOffset);
if (any3d) {
setTransform(this._container, topLeftOffset, scale);
} else {
setPosition(this._container, topLeftOffset);
}
},
_reset: function () {
this._update();
this._updateTransform(this._center, this._zoom);
for (var id in this._layers) {
this._layers[id]._reset();
}
},
_onZoomEnd: function () {
for (var id in this._layers) {
this._layers[id]._project();
}
},
_updatePaths: function () {
for (var id in this._layers) {
this._layers[id]._update();
}
},
_update: function () {
// Update pixel bounds of renderer container (for positioning/sizing/clipping later)
// Subclasses are responsible of firing the 'update' event.
var p = this.options.padding,
size = this._map.getSize(),
min = this._map.containerPointToLayerPoint(size.multiplyBy(-p)).round();
this._bounds = new Bounds(min, min.add(size.multiplyBy(1 + p * 2)).round());
this._center = this._map.getCenter();
this._zoom = this._map.getZoom();
}
});
/*
* @class Canvas
* @inherits Renderer
* @aka L.Canvas
*
* Allows vector layers to be displayed with [`<canvas>`](https://developer.mozilla.org/docs/Web/API/Canvas_API).
* Inherits `Renderer`.
*
* Due to [technical limitations](http://caniuse.com/#search=canvas), Canvas is not
* available in all web browsers, notably IE8, and overlapping geometries might
* not display properly in some edge cases.
*
* @example
*
* Use Canvas by default for all paths in the map:
*
* ```js
* var map = L.map('map', {
* renderer: L.canvas()
* });
* ```
*
* Use a Canvas renderer with extra padding for specific vector geometries:
*
* ```js
* var map = L.map('map');
* var myRenderer = L.canvas({ padding: 0.5 });
* var line = L.polyline( coordinates, { renderer: myRenderer } );
* var circle = L.circle( center, { renderer: myRenderer } );
* ```
*/
var Canvas = Renderer.extend({
getEvents: function () {
var events = Renderer.prototype.getEvents.call(this);
events.viewprereset = this._onViewPreReset;
return events;
},
_onViewPreReset: function () {
// Set a flag so that a viewprereset+moveend+viewreset only updates&redraws once
this._postponeUpdatePaths = true;
},
onAdd: function () {
Renderer.prototype.onAdd.call(this);
// Redraw vectors since canvas is cleared upon removal,
// in case of removing the renderer itself from the map.
this._draw();
},
_initContainer: function () {
var container = this._container = document.createElement('canvas');
on(container, 'mousemove', this._onMouseMove, this);
on(container, 'click dblclick mousedown mouseup contextmenu', this._onClick, this);
on(container, 'mouseout', this._handleMouseOut, this);
this._ctx = container.getContext('2d');
},
_destroyContainer: function () {
cancelAnimFrame(this._redrawRequest);
delete this._ctx;
remove(this._container);
off(this._container);
delete this._container;
},
_updatePaths: function () {
if (this._postponeUpdatePaths) { return; }
var layer;
this._redrawBounds = null;
for (var id in this._layers) {
layer = this._layers[id];
layer._update();
}
this._redraw();
},
_update: function () {
if (this._map._animatingZoom && this._bounds) { return; }
Renderer.prototype._update.call(this);
var b = this._bounds,
container = this._container,
size = b.getSize(),
m = retina ? 2 : 1;
setPosition(container, b.min);
// set canvas size (also clearing it); use double size on retina
container.width = m * size.x;
container.height = m * size.y;
container.style.width = size.x + 'px';
container.style.height = size.y + 'px';
if (retina) {
this._ctx.scale(2, 2);
}
// translate so we use the same path coordinates after canvas element moves
this._ctx.translate(-b.min.x, -b.min.y);
// Tell paths to redraw themselves
this.fire('update');
},
_reset: function () {
Renderer.prototype._reset.call(this);
if (this._postponeUpdatePaths) {
this._postponeUpdatePaths = false;
this._updatePaths();
}
},
_initPath: function (layer) {
this._updateDashArray(layer);
this._layers[stamp(layer)] = layer;
var order = layer._order = {
layer: layer,
prev: this._drawLast,
next: null
};
if (this._drawLast) { this._drawLast.next = order; }
this._drawLast = order;
this._drawFirst = this._drawFirst || this._drawLast;
},
_addPath: function (layer) {
this._requestRedraw(layer);
},
_removePath: function (layer) {
var order = layer._order;
var next = order.next;
var prev = order.prev;
if (next) {
next.prev = prev;
} else {
this._drawLast = prev;
}
if (prev) {
prev.next = next;
} else {
this._drawFirst = next;
}
delete layer._order;
delete this._layers[stamp(layer)];
this._requestRedraw(layer);
},
_updatePath: function (layer) {
// Redraw the union of the layer's old pixel
// bounds and the new pixel bounds.
this._extendRedrawBounds(layer);
layer._project();
layer._update();
// The redraw will extend the redraw bounds
// with the new pixel bounds.
this._requestRedraw(layer);
},
_updateStyle: function (layer) {
this._updateDashArray(layer);
this._requestRedraw(layer);
},
_updateDashArray: function (layer) {
if (typeof layer.options.dashArray === 'string') {
var parts = layer.options.dashArray.split(/[, ]+/),
dashArray = [],
dashValue,
i;
for (i = 0; i < parts.length; i++) {
dashValue = Number(parts[i]);
// Ignore dash array containing invalid lengths
if (isNaN(dashValue)) { return; }
dashArray.push(dashValue);
}
layer.options._dashArray = dashArray;
} else {
layer.options._dashArray = layer.options.dashArray;
}
},
_requestRedraw: function (layer) {
if (!this._map) { return; }
this._extendRedrawBounds(layer);
this._redrawRequest = this._redrawRequest || requestAnimFrame(this._redraw, this);
},
_extendRedrawBounds: function (layer) {
if (layer._pxBounds) {
var padding = (layer.options.weight || 0) + 1;
this._redrawBounds = this._redrawBounds || new Bounds();
this._redrawBounds.extend(layer._pxBounds.min.subtract([padding, padding]));
this._redrawBounds.extend(layer._pxBounds.max.add([padding, padding]));
}
},
_redraw: function () {
this._redrawRequest = null;
if (this._redrawBounds) {
this._redrawBounds.min._floor();
this._redrawBounds.max._ceil();
}
this._clear(); // clear layers in redraw bounds
this._draw(); // draw layers
this._redrawBounds = null;
},
_clear: function () {
var bounds = this._redrawBounds;
if (bounds) {
var size = bounds.getSize();
this._ctx.clearRect(bounds.min.x, bounds.min.y, size.x, size.y);
} else {
this._ctx.clearRect(0, 0, this._container.width, this._container.height);
}
},
_draw: function () {
var layer, bounds = this._redrawBounds;
this._ctx.save();
if (bounds) {
var size = bounds.getSize();
this._ctx.beginPath();
this._ctx.rect(bounds.min.x, bounds.min.y, size.x, size.y);
this._ctx.clip();
}
this._drawing = true;
for (var order = this._drawFirst; order; order = order.next) {
layer = order.layer;
if (!bounds || (layer._pxBounds && layer._pxBounds.intersects(bounds))) {
layer._updatePath();
}
}
this._drawing = false;
this._ctx.restore(); // Restore state before clipping.
},
_updatePoly: function (layer, closed) {
if (!this._drawing) { return; }
var i, j, len2, p,
parts = layer._parts,
len = parts.length,
ctx = this._ctx;
if (!len) { return; }
ctx.beginPath();
for (i = 0; i < len; i++) {
for (j = 0, len2 = parts[i].length; j < len2; j++) {
p = parts[i][j];
ctx[j ? 'lineTo' : 'moveTo'](p.x, p.y);
}
if (closed) {
ctx.closePath();
}
}
this._fillStroke(ctx, layer);
// TODO optimization: 1 fill/stroke for all features with equal style instead of 1 for each feature
},
_updateCircle: function (layer) {
if (!this._drawing || layer._empty()) { return; }
var p = layer._point,
ctx = this._ctx,
r = Math.max(Math.round(layer._radius), 1),
s = (Math.max(Math.round(layer._radiusY), 1) || r) / r;
if (s !== 1) {
ctx.save();
ctx.scale(1, s);
}
ctx.beginPath();
ctx.arc(p.x, p.y / s, r, 0, Math.PI * 2, false);
if (s !== 1) {
ctx.restore();
}
this._fillStroke(ctx, layer);
},
_fillStroke: function (ctx, layer) {
var options = layer.options;
if (options.fill) {
ctx.globalAlpha = options.fillOpacity;
ctx.fillStyle = options.fillColor || options.color;
ctx.fill(options.fillRule || 'evenodd');
}
if (options.stroke && options.weight !== 0) {
if (ctx.setLineDash) {
ctx.setLineDash(layer.options && layer.options._dashArray || []);
}
ctx.globalAlpha = options.opacity;
ctx.lineWidth = options.weight;
ctx.strokeStyle = options.color;
ctx.lineCap = options.lineCap;
ctx.lineJoin = options.lineJoin;
ctx.stroke();
}
},
// Canvas obviously doesn't have mouse events for individual drawn objects,
// so we emulate that by calculating what's under the mouse on mousemove/click manually
_onClick: function (e) {
var point = this._map.mouseEventToLayerPoint(e), layer, clickedLayer;
for (var order = this._drawFirst; order; order = order.next) {
layer = order.layer;
if (layer.options.interactive && layer._containsPoint(point) && !this._map._draggableMoved(layer)) {
clickedLayer = layer;
}
}
if (clickedLayer) {
fakeStop(e);
this._fireEvent([clickedLayer], e);
}
},
_onMouseMove: function (e) {
if (!this._map || this._map.dragging.moving() || this._map._animatingZoom) { return; }
var point = this._map.mouseEventToLayerPoint(e);
this._handleMouseHover(e, point);
},
_handleMouseOut: function (e) {
var layer = this._hoveredLayer;
if (layer) {
// if we're leaving the layer, fire mouseout
removeClass(this._container, 'leaflet-interactive');
this._fireEvent([layer], e, 'mouseout');
this._hoveredLayer = null;
this._mouseHoverThrottled = false;
}
},
_handleMouseHover: function (e, point) {
if (this._mouseHoverThrottled) {
return;
}
var layer, candidateHoveredLayer;
for (var order = this._drawFirst; order; order = order.next) {
layer = order.layer;
if (layer.options.interactive && layer._containsPoint(point)) {
candidateHoveredLayer = layer;
}
}
if (candidateHoveredLayer !== this._hoveredLayer) {
this._handleMouseOut(e);
if (candidateHoveredLayer) {
addClass(this._container, 'leaflet-interactive'); // change cursor
this._fireEvent([candidateHoveredLayer], e, 'mouseover');
this._hoveredLayer = candidateHoveredLayer;
}
}
if (this._hoveredLayer) {
this._fireEvent([this._hoveredLayer], e);
}
this._mouseHoverThrottled = true;
setTimeout(L.bind(function () {
this._mouseHoverThrottled = false;
}, this), 32);
},
_fireEvent: function (layers, e, type) {
this._map._fireDOMEvent(e, type || e.type, layers);
},
_bringToFront: function (layer) {
var order = layer._order;
if (!order) { return; }
var next = order.next;
var prev = order.prev;
if (next) {
next.prev = prev;
} else {
// Already last
return;
}
if (prev) {
prev.next = next;
} else if (next) {
// Update first entry unless this is the
// single entry
this._drawFirst = next;
}
order.prev = this._drawLast;
this._drawLast.next = order;
order.next = null;
this._drawLast = order;
this._requestRedraw(layer);
},
_bringToBack: function (layer) {
var order = layer._order;
if (!order) { return; }
var next = order.next;
var prev = order.prev;
if (prev) {
prev.next = next;
} else {
// Already first
return;
}
if (next) {
next.prev = prev;
} else if (prev) {
// Update last entry unless this is the
// single entry
this._drawLast = prev;
}
order.prev = null;
order.next = this._drawFirst;
this._drawFirst.prev = order;
this._drawFirst = order;
this._requestRedraw(layer);
}
});
// @factory L.canvas(options?: Renderer options)
// Creates a Canvas renderer with the given options.
function canvas$1(options) {
return canvas ? new Canvas(options) : null;
}
/*
* Thanks to Dmitry Baranovsky and his Raphael library for inspiration!
*/
var vmlCreate = (function () {
try {
document.namespaces.add('lvml', 'urn:schemas-microsoft-com:vml');
return function (name) {
return document.createElement('<lvml:' + name + ' class="lvml">');
};
} catch (e) {
return function (name) {
return document.createElement('<' + name + ' xmlns="urn:schemas-microsoft.com:vml" class="lvml">');
};
}
})();
/*
* @class SVG
*
*
* VML was deprecated in 2012, which means VML functionality exists only for backwards compatibility
* with old versions of Internet Explorer.
*/
// mixin to redefine some SVG methods to handle VML syntax which is similar but with some differences
var vmlMixin = {
_initContainer: function () {
this._container = create$1('div', 'leaflet-vml-container');
},
_update: function () {
if (this._map._animatingZoom) { return; }
Renderer.prototype._update.call(this);
this.fire('update');
},
_initPath: function (layer) {
var container = layer._container = vmlCreate('shape');
addClass(container, 'leaflet-vml-shape ' + (this.options.className || ''));
container.coordsize = '1 1';
layer._path = vmlCreate('path');
container.appendChild(layer._path);
this._updateStyle(layer);
this._layers[stamp(layer)] = layer;
},
_addPath: function (layer) {
var container = layer._container;
this._container.appendChild(container);
if (layer.options.interactive) {
layer.addInteractiveTarget(container);
}
},
_removePath: function (layer) {
var container = layer._container;
remove(container);
layer.removeInteractiveTarget(container);
delete this._layers[stamp(layer)];
},
_updateStyle: function (layer) {
var stroke = layer._stroke,
fill = layer._fill,
options = layer.options,
container = layer._container;
container.stroked = !!options.stroke;
container.filled = !!options.fill;
if (options.stroke) {
if (!stroke) {
stroke = layer._stroke = vmlCreate('stroke');
}
container.appendChild(stroke);
stroke.weight = options.weight + 'px';
stroke.color = options.color;
stroke.opacity = options.opacity;
if (options.dashArray) {
stroke.dashStyle = isArray(options.dashArray) ?
options.dashArray.join(' ') :
options.dashArray.replace(/( *, *)/g, ' ');
} else {
stroke.dashStyle = '';
}
stroke.endcap = options.lineCap.replace('butt', 'flat');
stroke.joinstyle = options.lineJoin;
} else if (stroke) {
container.removeChild(stroke);
layer._stroke = null;
}
if (options.fill) {
if (!fill) {
fill = layer._fill = vmlCreate('fill');
}
container.appendChild(fill);
fill.color = options.fillColor || options.color;
fill.opacity = options.fillOpacity;
} else if (fill) {
container.removeChild(fill);
layer._fill = null;
}
},
_updateCircle: function (layer) {
var p = layer._point.round(),
r = Math.round(layer._radius),
r2 = Math.round(layer._radiusY || r);
this._setPath(layer, layer._empty() ? 'M0 0' :
'AL ' + p.x + ',' + p.y + ' ' + r + ',' + r2 + ' 0,' + (65535 * 360));
},
_setPath: function (layer, path) {
layer._path.v = path;
},
_bringToFront: function (layer) {
toFront(layer._container);
},
_bringToBack: function (layer) {
toBack(layer._container);
}
};
var create$2 = vml ? vmlCreate : svgCreate;
/*
* @class SVG
* @inherits Renderer
* @aka L.SVG
*
* Allows vector layers to be displayed with [SVG](https://developer.mozilla.org/docs/Web/SVG).
* Inherits `Renderer`.
*
* Due to [technical limitations](http://caniuse.com/#search=svg), SVG is not
* available in all web browsers, notably Android 2.x and 3.x.
*
* Although SVG is not available on IE7 and IE8, these browsers support
* [VML](https://en.wikipedia.org/wiki/Vector_Markup_Language)
* (a now deprecated technology), and the SVG renderer will fall back to VML in
* this case.
*
* @example
*
* Use SVG by default for all paths in the map:
*
* ```js
* var map = L.map('map', {
* renderer: L.svg()
* });
* ```
*
* Use a SVG renderer with extra padding for specific vector geometries:
*
* ```js
* var map = L.map('map');
* var myRenderer = L.svg({ padding: 0.5 });
* var line = L.polyline( coordinates, { renderer: myRenderer } );
* var circle = L.circle( center, { renderer: myRenderer } );
* ```
*/
var SVG = Renderer.extend({
getEvents: function () {
var events = Renderer.prototype.getEvents.call(this);
events.zoomstart = this._onZoomStart;
return events;
},
_initContainer: function () {
this._container = create$2('svg');
// makes it possible to click through svg root; we'll reset it back in individual paths
this._container.setAttribute('pointer-events', 'none');
this._rootGroup = create$2('g');
this._container.appendChild(this._rootGroup);
},
_destroyContainer: function () {
remove(this._container);
off(this._container);
delete this._container;
delete this._rootGroup;
delete this._svgSize;
},
_onZoomStart: function () {
// Drag-then-pinch interactions might mess up the center and zoom.
// In this case, the easiest way to prevent this is re-do the renderer
// bounds and padding when the zooming starts.
this._update();
},
_update: function () {
if (this._map._animatingZoom && this._bounds) { return; }
Renderer.prototype._update.call(this);
var b = this._bounds,
size = b.getSize(),
container = this._container;
// set size of svg-container if changed
if (!this._svgSize || !this._svgSize.equals(size)) {
this._svgSize = size;
container.setAttribute('width', size.x);
container.setAttribute('height', size.y);
}
// movement: update container viewBox so that we don't have to change coordinates of individual layers
setPosition(container, b.min);
container.setAttribute('viewBox', [b.min.x, b.min.y, size.x, size.y].join(' '));
this.fire('update');
},
// methods below are called by vector layers implementations
_initPath: function (layer) {
var path = layer._path = create$2('path');
// @namespace Path
// @option className: String = null
// Custom class name set on an element. Only for SVG renderer.
if (layer.options.className) {
addClass(path, layer.options.className);
}
if (layer.options.interactive) {
addClass(path, 'leaflet-interactive');
}
this._updateStyle(layer);
this._layers[stamp(layer)] = layer;
},
_addPath: function (layer) {
if (!this._rootGroup) { this._initContainer(); }
this._rootGroup.appendChild(layer._path);
layer.addInteractiveTarget(layer._path);
},
_removePath: function (layer) {
remove(layer._path);
layer.removeInteractiveTarget(layer._path);
delete this._layers[stamp(layer)];
},
_updatePath: function (layer) {
layer._project();
layer._update();
},
_updateStyle: function (layer) {
var path = layer._path,
options = layer.options;
if (!path) { return; }
if (options.stroke) {
path.setAttribute('stroke', options.color);
path.setAttribute('stroke-opacity', options.opacity);
path.setAttribute('stroke-width', options.weight);
path.setAttribute('stroke-linecap', options.lineCap);
path.setAttribute('stroke-linejoin', options.lineJoin);
if (options.dashArray) {
path.setAttribute('stroke-dasharray', options.dashArray);
} else {
path.removeAttribute('stroke-dasharray');
}
if (options.dashOffset) {
path.setAttribute('stroke-dashoffset', options.dashOffset);
} else {
path.removeAttribute('stroke-dashoffset');
}
} else {
path.setAttribute('stroke', 'none');
}
if (options.fill) {
path.setAttribute('fill', options.fillColor || options.color);
path.setAttribute('fill-opacity', options.fillOpacity);
path.setAttribute('fill-rule', options.fillRule || 'evenodd');
} else {
path.setAttribute('fill', 'none');
}
},
_updatePoly: function (layer, closed) {
this._setPath(layer, pointsToPath(layer._parts, closed));
},
_updateCircle: function (layer) {
var p = layer._point,
r = Math.max(Math.round(layer._radius), 1),
r2 = Math.max(Math.round(layer._radiusY), 1) || r,
arc = 'a' + r + ',' + r2 + ' 0 1,0 ';
// drawing a circle with two half-arcs
var d = layer._empty() ? 'M0 0' :
'M' + (p.x - r) + ',' + p.y +
arc + (r * 2) + ',0 ' +
arc + (-r * 2) + ',0 ';
this._setPath(layer, d);
},
_setPath: function (layer, path) {
layer._path.setAttribute('d', path);
},
// SVG does not have the concept of zIndex so we resort to changing the DOM order of elements
_bringToFront: function (layer) {
toFront(layer._path);
},
_bringToBack: function (layer) {
toBack(layer._path);
}
});
if (vml) {
SVG.include(vmlMixin);
}
// @namespace SVG
// @factory L.svg(options?: Renderer options)
// Creates a SVG renderer with the given options.
function svg$1(options) {
return svg || vml ? new SVG(options) : null;
}
Map.include({
// @namespace Map; @method getRenderer(layer: Path): Renderer
// Returns the instance of `Renderer` that should be used to render the given
// `Path`. It will ensure that the `renderer` options of the map and paths
// are respected, and that the renderers do exist on the map.
getRenderer: function (layer) {
// @namespace Path; @option renderer: Renderer
// Use this specific instance of `Renderer` for this path. Takes
// precedence over the map's [default renderer](#map-renderer).
var renderer = layer.options.renderer || this._getPaneRenderer(layer.options.pane) || this.options.renderer || this._renderer;
if (!renderer) {
renderer = this._renderer = this._createRenderer();
}
if (!this.hasLayer(renderer)) {
this.addLayer(renderer);
}
return renderer;
},
_getPaneRenderer: function (name) {
if (name === 'overlayPane' || name === undefined) {
return false;
}
var renderer = this._paneRenderers[name];
if (renderer === undefined) {
renderer = this._createRenderer({pane: name});
this._paneRenderers[name] = renderer;
}
return renderer;
},
_createRenderer: function (options) {
// @namespace Map; @option preferCanvas: Boolean = false
// Whether `Path`s should be rendered on a `Canvas` renderer.
// By default, all `Path`s are rendered in a `SVG` renderer.
return (this.options.preferCanvas && canvas$1(options)) || svg$1(options);
}
});
/*
* L.Rectangle extends Polygon and creates a rectangle when passed a LatLngBounds object.
*/
/*
* @class Rectangle
* @aka L.Rectangle
* @inherits Polygon
*
* A class for drawing rectangle overlays on a map. Extends `Polygon`.
*
* @example
*
* ```js
* // define rectangle geographical bounds
* var bounds = [[54.559322, -5.767822], [56.1210604, -3.021240]];
*
* // create an orange rectangle
* L.rectangle(bounds, {color: "#ff7800", weight: 1}).addTo(map);
*
* // zoom the map to the rectangle bounds
* map.fitBounds(bounds);
* ```
*
*/
var Rectangle = Polygon.extend({
initialize: function (latLngBounds, options) {
Polygon.prototype.initialize.call(this, this._boundsToLatLngs(latLngBounds), options);
},
// @method setBounds(latLngBounds: LatLngBounds): this
// Redraws the rectangle with the passed bounds.
setBounds: function (latLngBounds) {
return this.setLatLngs(this._boundsToLatLngs(latLngBounds));
},
_boundsToLatLngs: function (latLngBounds) {
latLngBounds = toLatLngBounds(latLngBounds);
return [
latLngBounds.getSouthWest(),
latLngBounds.getNorthWest(),
latLngBounds.getNorthEast(),
latLngBounds.getSouthEast()
];
}
});
// @factory L.rectangle(latLngBounds: LatLngBounds, options?: Polyline options)
function rectangle(latLngBounds, options) {
return new Rectangle(latLngBounds, options);
}
SVG.create = create$2;
SVG.pointsToPath = pointsToPath;
GeoJSON.geometryToLayer = geometryToLayer;
GeoJSON.coordsToLatLng = coordsToLatLng;
GeoJSON.coordsToLatLngs = coordsToLatLngs;
GeoJSON.latLngToCoords = latLngToCoords;
GeoJSON.latLngsToCoords = latLngsToCoords;
GeoJSON.getFeature = getFeature;
GeoJSON.asFeature = asFeature;
/*
* L.Handler.BoxZoom is used to add shift-drag zoom interaction to the map
* (zoom to a selected bounding box), enabled by default.
*/
// @namespace Map
// @section Interaction Options
Map.mergeOptions({
// @option boxZoom: Boolean = true
// Whether the map can be zoomed to a rectangular area specified by
// dragging the mouse while pressing the shift key.
boxZoom: true
});
var BoxZoom = Handler.extend({
initialize: function (map) {
this._map = map;
this._container = map._container;
this._pane = map._panes.overlayPane;
this._resetStateTimeout = 0;
map.on('unload', this._destroy, this);
},
addHooks: function () {
on(this._container, 'mousedown', this._onMouseDown, this);
},
removeHooks: function () {
off(this._container, 'mousedown', this._onMouseDown, this);
},
moved: function () {
return this._moved;
},
_destroy: function () {
remove(this._pane);
delete this._pane;
},
_resetState: function () {
this._resetStateTimeout = 0;
this._moved = false;
},
_clearDeferredResetState: function () {
if (this._resetStateTimeout !== 0) {
clearTimeout(this._resetStateTimeout);
this._resetStateTimeout = 0;
}
},
_onMouseDown: function (e) {
if (!e.shiftKey || ((e.which !== 1) && (e.button !== 1))) { return false; }
// Clear the deferred resetState if it hasn't executed yet, otherwise it
// will interrupt the interaction and orphan a box element in the container.
this._clearDeferredResetState();
this._resetState();
disableTextSelection();
disableImageDrag();
this._startPoint = this._map.mouseEventToContainerPoint(e);
on(document, {
contextmenu: stop,
mousemove: this._onMouseMove,
mouseup: this._onMouseUp,
keydown: this._onKeyDown
}, this);
},
_onMouseMove: function (e) {
if (!this._moved) {
this._moved = true;
this._box = create$1('div', 'leaflet-zoom-box', this._container);
addClass(this._container, 'leaflet-crosshair');
this._map.fire('boxzoomstart');
}
this._point = this._map.mouseEventToContainerPoint(e);
var bounds = new Bounds(this._point, this._startPoint),
size = bounds.getSize();
setPosition(this._box, bounds.min);
this._box.style.width = size.x + 'px';
this._box.style.height = size.y + 'px';
},
_finish: function () {
if (this._moved) {
remove(this._box);
removeClass(this._container, 'leaflet-crosshair');
}
enableTextSelection();
enableImageDrag();
off(document, {
contextmenu: stop,
mousemove: this._onMouseMove,
mouseup: this._onMouseUp,
keydown: this._onKeyDown
}, this);
},
_onMouseUp: function (e) {
if ((e.which !== 1) && (e.button !== 1)) { return; }
this._finish();
if (!this._moved) { return; }
// Postpone to next JS tick so internal click event handling
// still see it as "moved".
this._clearDeferredResetState();
this._resetStateTimeout = setTimeout(bind(this._resetState, this), 0);
var bounds = new LatLngBounds(
this._map.containerPointToLatLng(this._startPoint),
this._map.containerPointToLatLng(this._point));
this._map
.fitBounds(bounds)
.fire('boxzoomend', {boxZoomBounds: bounds});
},
_onKeyDown: function (e) {
if (e.keyCode === 27) {
this._finish();
}
}
});
// @section Handlers
// @property boxZoom: Handler
// Box (shift-drag with mouse) zoom handler.
Map.addInitHook('addHandler', 'boxZoom', BoxZoom);
/*
* L.Handler.DoubleClickZoom is used to handle double-click zoom on the map, enabled by default.
*/
// @namespace Map
// @section Interaction Options
Map.mergeOptions({
// @option doubleClickZoom: Boolean|String = true
// Whether the map can be zoomed in by double clicking on it and
// zoomed out by double clicking while holding shift. If passed
// `'center'`, double-click zoom will zoom to the center of the
// view regardless of where the mouse was.
doubleClickZoom: true
});
var DoubleClickZoom = Handler.extend({
addHooks: function () {
this._map.on('dblclick', this._onDoubleClick, this);
},
removeHooks: function () {
this._map.off('dblclick', this._onDoubleClick, this);
},
_onDoubleClick: function (e) {
var map = this._map,
oldZoom = map.getZoom(),
delta = map.options.zoomDelta,
zoom = e.originalEvent.shiftKey ? oldZoom - delta : oldZoom + delta;
if (map.options.doubleClickZoom === 'center') {
map.setZoom(zoom);
} else {
map.setZoomAround(e.containerPoint, zoom);
}
}
});
// @section Handlers
//
// Map properties include interaction handlers that allow you to control
// interaction behavior in runtime, enabling or disabling certain features such
// as dragging or touch zoom (see `Handler` methods). For example:
//
// ```js
// map.doubleClickZoom.disable();
// ```
//
// @property doubleClickZoom: Handler
// Double click zoom handler.
Map.addInitHook('addHandler', 'doubleClickZoom', DoubleClickZoom);
/*
* L.Handler.MapDrag is used to make the map draggable (with panning inertia), enabled by default.
*/
// @namespace Map
// @section Interaction Options
Map.mergeOptions({
// @option dragging: Boolean = true
// Whether the map be draggable with mouse/touch or not.
dragging: true,
// @section Panning Inertia Options
// @option inertia: Boolean = *
// If enabled, panning of the map will have an inertia effect where
// the map builds momentum while dragging and continues moving in
// the same direction for some time. Feels especially nice on touch
// devices. Enabled by default unless running on old Android devices.
inertia: !android23,
// @option inertiaDeceleration: Number = 3000
// The rate with which the inertial movement slows down, in pixels/second².
inertiaDeceleration: 3400, // px/s^2
// @option inertiaMaxSpeed: Number = Infinity
// Max speed of the inertial movement, in pixels/second.
inertiaMaxSpeed: Infinity, // px/s
// @option easeLinearity: Number = 0.2
easeLinearity: 0.2,
// TODO refactor, move to CRS
// @option worldCopyJump: Boolean = false
// With this option enabled, the map tracks when you pan to another "copy"
// of the world and seamlessly jumps to the original one so that all overlays
// like markers and vector layers are still visible.
worldCopyJump: false,
// @option maxBoundsViscosity: Number = 0.0
// If `maxBounds` is set, this option will control how solid the bounds
// are when dragging the map around. The default value of `0.0` allows the
// user to drag outside the bounds at normal speed, higher values will
// slow down map dragging outside bounds, and `1.0` makes the bounds fully
// solid, preventing the user from dragging outside the bounds.
maxBoundsViscosity: 0.0
});
var Drag = Handler.extend({
addHooks: function () {
if (!this._draggable) {
var map = this._map;
this._draggable = new Draggable(map._mapPane, map._container);
this._draggable.on({
dragstart: this._onDragStart,
drag: this._onDrag,
dragend: this._onDragEnd
}, this);
this._draggable.on('predrag', this._onPreDragLimit, this);
if (map.options.worldCopyJump) {
this._draggable.on('predrag', this._onPreDragWrap, this);
map.on('zoomend', this._onZoomEnd, this);
map.whenReady(this._onZoomEnd, this);
}
}
addClass(this._map._container, 'leaflet-grab leaflet-touch-drag');
this._draggable.enable();
this._positions = [];
this._times = [];
},
removeHooks: function () {
removeClass(this._map._container, 'leaflet-grab');
removeClass(this._map._container, 'leaflet-touch-drag');
this._draggable.disable();
},
moved: function () {
return this._draggable && this._draggable._moved;
},
moving: function () {
return this._draggable && this._draggable._moving;
},
_onDragStart: function () {
var map = this._map;
map._stop();
if (this._map.options.maxBounds && this._map.options.maxBoundsViscosity) {
var bounds = toLatLngBounds(this._map.options.maxBounds);
this._offsetLimit = toBounds(
this._map.latLngToContainerPoint(bounds.getNorthWest()).multiplyBy(-1),
this._map.latLngToContainerPoint(bounds.getSouthEast()).multiplyBy(-1)
.add(this._map.getSize()));
this._viscosity = Math.min(1.0, Math.max(0.0, this._map.options.maxBoundsViscosity));
} else {
this._offsetLimit = null;
}
map
.fire('movestart')
.fire('dragstart');
if (map.options.inertia) {
this._positions = [];
this._times = [];
}
},
_onDrag: function (e) {
if (this._map.options.inertia) {
var time = this._lastTime = +new Date(),
pos = this._lastPos = this._draggable._absPos || this._draggable._newPos;
this._positions.push(pos);
this._times.push(time);
this._prunePositions(time);
}
this._map
.fire('move', e)
.fire('drag', e);
},
_prunePositions: function (time) {
while (this._positions.length > 1 && time - this._times[0] > 50) {
this._positions.shift();
this._times.shift();
}
},
_onZoomEnd: function () {
var pxCenter = this._map.getSize().divideBy(2),
pxWorldCenter = this._map.latLngToLayerPoint([0, 0]);
this._initialWorldOffset = pxWorldCenter.subtract(pxCenter).x;
this._worldWidth = this._map.getPixelWorldBounds().getSize().x;
},
_viscousLimit: function (value, threshold) {
return value - (value - threshold) * this._viscosity;
},
_onPreDragLimit: function () {
if (!this._viscosity || !this._offsetLimit) { return; }
var offset = this._draggable._newPos.subtract(this._draggable._startPos);
var limit = this._offsetLimit;
if (offset.x < limit.min.x) { offset.x = this._viscousLimit(offset.x, limit.min.x); }
if (offset.y < limit.min.y) { offset.y = this._viscousLimit(offset.y, limit.min.y); }
if (offset.x > limit.max.x) { offset.x = this._viscousLimit(offset.x, limit.max.x); }
if (offset.y > limit.max.y) { offset.y = this._viscousLimit(offset.y, limit.max.y); }
this._draggable._newPos = this._draggable._startPos.add(offset);
},
_onPreDragWrap: function () {
// TODO refactor to be able to adjust map pane position after zoom
var worldWidth = this._worldWidth,
halfWidth = Math.round(worldWidth / 2),
dx = this._initialWorldOffset,
x = this._draggable._newPos.x,
newX1 = (x - halfWidth + dx) % worldWidth + halfWidth - dx,
newX2 = (x + halfWidth + dx) % worldWidth - halfWidth - dx,
newX = Math.abs(newX1 + dx) < Math.abs(newX2 + dx) ? newX1 : newX2;
this._draggable._absPos = this._draggable._newPos.clone();
this._draggable._newPos.x = newX;
},
_onDragEnd: function (e) {
var map = this._map,
options = map.options,
noInertia = !options.inertia || this._times.length < 2;
map.fire('dragend', e);
if (noInertia) {
map.fire('moveend');
} else {
this._prunePositions(+new Date());
var direction = this._lastPos.subtract(this._positions[0]),
duration = (this._lastTime - this._times[0]) / 1000,
ease = options.easeLinearity,
speedVector = direction.multiplyBy(ease / duration),
speed = speedVector.distanceTo([0, 0]),
limitedSpeed = Math.min(options.inertiaMaxSpeed, speed),
limitedSpeedVector = speedVector.multiplyBy(limitedSpeed / speed),
decelerationDuration = limitedSpeed / (options.inertiaDeceleration * ease),
offset = limitedSpeedVector.multiplyBy(-decelerationDuration / 2).round();
if (!offset.x && !offset.y) {
map.fire('moveend');
} else {
offset = map._limitOffset(offset, map.options.maxBounds);
requestAnimFrame(function () {
map.panBy(offset, {
duration: decelerationDuration,
easeLinearity: ease,
noMoveStart: true,
animate: true
});
});
}
}
}
});
// @section Handlers
// @property dragging: Handler
// Map dragging handler (by both mouse and touch).
Map.addInitHook('addHandler', 'dragging', Drag);
/*
* L.Map.Keyboard is handling keyboard interaction with the map, enabled by default.
*/
// @namespace Map
// @section Keyboard Navigation Options
Map.mergeOptions({
// @option keyboard: Boolean = true
// Makes the map focusable and allows users to navigate the map with keyboard
// arrows and `+`/`-` keys.
keyboard: true,
// @option keyboardPanDelta: Number = 80
// Amount of pixels to pan when pressing an arrow key.
keyboardPanDelta: 80
});
var Keyboard = Handler.extend({
keyCodes: {
left: [37],
right: [39],
down: [40],
up: [38],
zoomIn: [187, 107, 61, 171],
zoomOut: [189, 109, 54, 173]
},
initialize: function (map) {
this._map = map;
this._setPanDelta(map.options.keyboardPanDelta);
this._setZoomDelta(map.options.zoomDelta);
},
addHooks: function () {
var container = this._map._container;
// make the container focusable by tabbing
if (container.tabIndex <= 0) {
container.tabIndex = '0';
}
on(container, {
focus: this._onFocus,
blur: this._onBlur,
mousedown: this._onMouseDown
}, this);
this._map.on({
focus: this._addHooks,
blur: this._removeHooks
}, this);
},
removeHooks: function () {
this._removeHooks();
off(this._map._container, {
focus: this._onFocus,
blur: this._onBlur,
mousedown: this._onMouseDown
}, this);
this._map.off({
focus: this._addHooks,
blur: this._removeHooks
}, this);
},
_onMouseDown: function () {
if (this._focused) { return; }
var body = document.body,
docEl = document.documentElement,
top = body.scrollTop || docEl.scrollTop,
left = body.scrollLeft || docEl.scrollLeft;
this._map._container.focus();
window.scrollTo(left, top);
},
_onFocus: function () {
this._focused = true;
this._map.fire('focus');
},
_onBlur: function () {
this._focused = false;
this._map.fire('blur');
},
_setPanDelta: function (panDelta) {
var keys = this._panKeys = {},
codes = this.keyCodes,
i, len;
for (i = 0, len = codes.left.length; i < len; i++) {
keys[codes.left[i]] = [-1 * panDelta, 0];
}
for (i = 0, len = codes.right.length; i < len; i++) {
keys[codes.right[i]] = [panDelta, 0];
}
for (i = 0, len = codes.down.length; i < len; i++) {
keys[codes.down[i]] = [0, panDelta];
}
for (i = 0, len = codes.up.length; i < len; i++) {
keys[codes.up[i]] = [0, -1 * panDelta];
}
},
_setZoomDelta: function (zoomDelta) {
var keys = this._zoomKeys = {},
codes = this.keyCodes,
i, len;
for (i = 0, len = codes.zoomIn.length; i < len; i++) {
keys[codes.zoomIn[i]] = zoomDelta;
}
for (i = 0, len = codes.zoomOut.length; i < len; i++) {
keys[codes.zoomOut[i]] = -zoomDelta;
}
},
_addHooks: function () {
on(document, 'keydown', this._onKeyDown, this);
},
_removeHooks: function () {
off(document, 'keydown', this._onKeyDown, this);
},
_onKeyDown: function (e) {
if (e.altKey || e.ctrlKey || e.metaKey) { return; }
var key = e.keyCode,
map = this._map,
offset;
if (key in this._panKeys) {
if (!map._panAnim || !map._panAnim._inProgress) {
offset = this._panKeys[key];
if (e.shiftKey) {
offset = toPoint(offset).multiplyBy(3);
}
map.panBy(offset);
if (map.options.maxBounds) {
map.panInsideBounds(map.options.maxBounds);
}
}
} else if (key in this._zoomKeys) {
map.setZoom(map.getZoom() + (e.shiftKey ? 3 : 1) * this._zoomKeys[key]);
} else if (key === 27 && map._popup && map._popup.options.closeOnEscapeKey) {
map.closePopup();
} else {
return;
}
stop(e);
}
});
// @section Handlers
// @section Handlers
// @property keyboard: Handler
// Keyboard navigation handler.
Map.addInitHook('addHandler', 'keyboard', Keyboard);
/*
* L.Handler.ScrollWheelZoom is used by L.Map to enable mouse scroll wheel zoom on the map.
*/
// @namespace Map
// @section Interaction Options
Map.mergeOptions({
// @section Mousewheel options
// @option scrollWheelZoom: Boolean|String = true
// Whether the map can be zoomed by using the mouse wheel. If passed `'center'`,
// it will zoom to the center of the view regardless of where the mouse was.
scrollWheelZoom: true,
// @option wheelDebounceTime: Number = 40
// Limits the rate at which a wheel can fire (in milliseconds). By default
// user can't zoom via wheel more often than once per 40 ms.
wheelDebounceTime: 40,
// @option wheelPxPerZoomLevel: Number = 60
// How many scroll pixels (as reported by [L.DomEvent.getWheelDelta](#domevent-getwheeldelta))
// mean a change of one full zoom level. Smaller values will make wheel-zooming
// faster (and vice versa).
wheelPxPerZoomLevel: 60
});
var ScrollWheelZoom = Handler.extend({
addHooks: function () {
on(this._map._container, 'mousewheel', this._onWheelScroll, this);
this._delta = 0;
},
removeHooks: function () {
off(this._map._container, 'mousewheel', this._onWheelScroll, this);
},
_onWheelScroll: function (e) {
var delta = getWheelDelta(e);
var debounce = this._map.options.wheelDebounceTime;
this._delta += delta;
this._lastMousePos = this._map.mouseEventToContainerPoint(e);
if (!this._startTime) {
this._startTime = +new Date();
}
var left = Math.max(debounce - (+new Date() - this._startTime), 0);
clearTimeout(this._timer);
this._timer = setTimeout(bind(this._performZoom, this), left);
stop(e);
},
_performZoom: function () {
var map = this._map,
zoom = map.getZoom(),
snap = this._map.options.zoomSnap || 0;
map._stop(); // stop panning and fly animations if any
// map the delta with a sigmoid function to -4..4 range leaning on -1..1
var d2 = this._delta / (this._map.options.wheelPxPerZoomLevel * 4),
d3 = 4 * Math.log(2 / (1 + Math.exp(-Math.abs(d2)))) / Math.LN2,
d4 = snap ? Math.ceil(d3 / snap) * snap : d3,
delta = map._limitZoom(zoom + (this._delta > 0 ? d4 : -d4)) - zoom;
this._delta = 0;
this._startTime = null;
if (!delta) { return; }
if (map.options.scrollWheelZoom === 'center') {
map.setZoom(zoom + delta);
} else {
map.setZoomAround(this._lastMousePos, zoom + delta);
}
}
});
// @section Handlers
// @property scrollWheelZoom: Handler
// Scroll wheel zoom handler.
Map.addInitHook('addHandler', 'scrollWheelZoom', ScrollWheelZoom);
/*
* L.Map.Tap is used to enable mobile hacks like quick taps and long hold.
*/
// @namespace Map
// @section Interaction Options
Map.mergeOptions({
// @section Touch interaction options
// @option tap: Boolean = true
// Enables mobile hacks for supporting instant taps (fixing 200ms click
// delay on iOS/Android) and touch holds (fired as `contextmenu` events).
tap: true,
// @option tapTolerance: Number = 15
// The max number of pixels a user can shift his finger during touch
// for it to be considered a valid tap.
tapTolerance: 15
});
var Tap = Handler.extend({
addHooks: function () {
on(this._map._container, 'touchstart', this._onDown, this);
},
removeHooks: function () {
off(this._map._container, 'touchstart', this._onDown, this);
},
_onDown: function (e) {
if (!e.touches) { return; }
preventDefault(e);
this._fireClick = true;
// don't simulate click or track longpress if more than 1 touch
if (e.touches.length > 1) {
this._fireClick = false;
clearTimeout(this._holdTimeout);
return;
}
var first = e.touches[0],
el = first.target;
this._startPos = this._newPos = new Point(first.clientX, first.clientY);
// if touching a link, highlight it
if (el.tagName && el.tagName.toLowerCase() === 'a') {
addClass(el, 'leaflet-active');
}
// simulate long hold but setting a timeout
this._holdTimeout = setTimeout(bind(function () {
if (this._isTapValid()) {
this._fireClick = false;
this._onUp();
this._simulateEvent('contextmenu', first);
}
}, this), 1000);
this._simulateEvent('mousedown', first);
on(document, {
touchmove: this._onMove,
touchend: this._onUp
}, this);
},
_onUp: function (e) {
clearTimeout(this._holdTimeout);
off(document, {
touchmove: this._onMove,
touchend: this._onUp
}, this);
if (this._fireClick && e && e.changedTouches) {
var first = e.changedTouches[0],
el = first.target;
if (el && el.tagName && el.tagName.toLowerCase() === 'a') {
removeClass(el, 'leaflet-active');
}
this._simulateEvent('mouseup', first);
// simulate click if the touch didn't move too much
if (this._isTapValid()) {
this._simulateEvent('click', first);
}
}
},
_isTapValid: function () {
return this._newPos.distanceTo(this._startPos) <= this._map.options.tapTolerance;
},
_onMove: function (e) {
var first = e.touches[0];
this._newPos = new Point(first.clientX, first.clientY);
this._simulateEvent('mousemove', first);
},
_simulateEvent: function (type, e) {
var simulatedEvent = document.createEvent('MouseEvents');
simulatedEvent._simulated = true;
e.target._simulatedClick = true;
simulatedEvent.initMouseEvent(
type, true, true, window, 1,
e.screenX, e.screenY,
e.clientX, e.clientY,
false, false, false, false, 0, null);
e.target.dispatchEvent(simulatedEvent);
}
});
// @section Handlers
// @property tap: Handler
// Mobile touch hacks (quick tap and touch hold) handler.
if (touch && !pointer) {
Map.addInitHook('addHandler', 'tap', Tap);
}
/*
* L.Handler.TouchZoom is used by L.Map to add pinch zoom on supported mobile browsers.
*/
// @namespace Map
// @section Interaction Options
Map.mergeOptions({
// @section Touch interaction options
// @option touchZoom: Boolean|String = *
// Whether the map can be zoomed by touch-dragging with two fingers. If
// passed `'center'`, it will zoom to the center of the view regardless of
// where the touch events (fingers) were. Enabled for touch-capable web
// browsers except for old Androids.
touchZoom: touch && !android23,
// @option bounceAtZoomLimits: Boolean = true
// Set it to false if you don't want the map to zoom beyond min/max zoom
// and then bounce back when pinch-zooming.
bounceAtZoomLimits: true
});
var TouchZoom = Handler.extend({
addHooks: function () {
addClass(this._map._container, 'leaflet-touch-zoom');
on(this._map._container, 'touchstart', this._onTouchStart, this);
},
removeHooks: function () {
removeClass(this._map._container, 'leaflet-touch-zoom');
off(this._map._container, 'touchstart', this._onTouchStart, this);
},
_onTouchStart: function (e) {
var map = this._map;
if (!e.touches || e.touches.length !== 2 || map._animatingZoom || this._zooming) { return; }
var p1 = map.mouseEventToContainerPoint(e.touches[0]),
p2 = map.mouseEventToContainerPoint(e.touches[1]);
this._centerPoint = map.getSize()._divideBy(2);
this._startLatLng = map.containerPointToLatLng(this._centerPoint);
if (map.options.touchZoom !== 'center') {
this._pinchStartLatLng = map.containerPointToLatLng(p1.add(p2)._divideBy(2));
}
this._startDist = p1.distanceTo(p2);
this._startZoom = map.getZoom();
this._moved = false;
this._zooming = true;
map._stop();
on(document, 'touchmove', this._onTouchMove, this);
on(document, 'touchend', this._onTouchEnd, this);
preventDefault(e);
},
_onTouchMove: function (e) {
if (!e.touches || e.touches.length !== 2 || !this._zooming) { return; }
var map = this._map,
p1 = map.mouseEventToContainerPoint(e.touches[0]),
p2 = map.mouseEventToContainerPoint(e.touches[1]),
scale = p1.distanceTo(p2) / this._startDist;
this._zoom = map.getScaleZoom(scale, this._startZoom);
if (!map.options.bounceAtZoomLimits && (
(this._zoom < map.getMinZoom() && scale < 1) ||
(this._zoom > map.getMaxZoom() && scale > 1))) {
this._zoom = map._limitZoom(this._zoom);
}
if (map.options.touchZoom === 'center') {
this._center = this._startLatLng;
if (scale === 1) { return; }
} else {
// Get delta from pinch to center, so centerLatLng is delta applied to initial pinchLatLng
var delta = p1._add(p2)._divideBy(2)._subtract(this._centerPoint);
if (scale === 1 && delta.x === 0 && delta.y === 0) { return; }
this._center = map.unproject(map.project(this._pinchStartLatLng, this._zoom).subtract(delta), this._zoom);
}
if (!this._moved) {
map._moveStart(true, false);
this._moved = true;
}
cancelAnimFrame(this._animRequest);
var moveFn = bind(map._move, map, this._center, this._zoom, {pinch: true, round: false});
this._animRequest = requestAnimFrame(moveFn, this, true);
preventDefault(e);
},
_onTouchEnd: function () {
if (!this._moved || !this._zooming) {
this._zooming = false;
return;
}
this._zooming = false;
cancelAnimFrame(this._animRequest);
off(document, 'touchmove', this._onTouchMove);
off(document, 'touchend', this._onTouchEnd);
// Pinch updates GridLayers' levels only when zoomSnap is off, so zoomSnap becomes noUpdate.
if (this._map.options.zoomAnimation) {
this._map._animateZoom(this._center, this._map._limitZoom(this._zoom), true, this._map.options.zoomSnap);
} else {
this._map._resetView(this._center, this._map._limitZoom(this._zoom));
}
}
});
// @section Handlers
// @property touchZoom: Handler
// Touch zoom handler.
Map.addInitHook('addHandler', 'touchZoom', TouchZoom);
Map.BoxZoom = BoxZoom;
Map.DoubleClickZoom = DoubleClickZoom;
Map.Drag = Drag;
Map.Keyboard = Keyboard;
Map.ScrollWheelZoom = ScrollWheelZoom;
Map.Tap = Tap;
Map.TouchZoom = TouchZoom;
Object.freeze = freeze;
exports.version = version;
exports.Control = Control;
exports.control = control;
exports.Browser = Browser;
exports.Evented = Evented;
exports.Mixin = Mixin;
exports.Util = Util;
exports.Class = Class;
exports.Handler = Handler;
exports.extend = extend;
exports.bind = bind;
exports.stamp = stamp;
exports.setOptions = setOptions;
exports.DomEvent = DomEvent;
exports.DomUtil = DomUtil;
exports.PosAnimation = PosAnimation;
exports.Draggable = Draggable;
exports.LineUtil = LineUtil;
exports.PolyUtil = PolyUtil;
exports.Point = Point;
exports.point = toPoint;
exports.Bounds = Bounds;
exports.bounds = toBounds;
exports.Transformation = Transformation;
exports.transformation = toTransformation;
exports.Projection = index;
exports.LatLng = LatLng;
exports.latLng = toLatLng;
exports.LatLngBounds = LatLngBounds;
exports.latLngBounds = toLatLngBounds;
exports.CRS = CRS;
exports.GeoJSON = GeoJSON;
exports.geoJSON = geoJSON;
exports.geoJson = geoJson;
exports.Layer = Layer;
exports.LayerGroup = LayerGroup;
exports.layerGroup = layerGroup;
exports.FeatureGroup = FeatureGroup;
exports.featureGroup = featureGroup;
exports.ImageOverlay = ImageOverlay;
exports.imageOverlay = imageOverlay;
exports.VideoOverlay = VideoOverlay;
exports.videoOverlay = videoOverlay;
exports.SVGOverlay = SVGOverlay;
exports.svgOverlay = svgOverlay;
exports.DivOverlay = DivOverlay;
exports.Popup = Popup;
exports.popup = popup;
exports.Tooltip = Tooltip;
exports.tooltip = tooltip;
exports.Icon = Icon;
exports.icon = icon;
exports.DivIcon = DivIcon;
exports.divIcon = divIcon;
exports.Marker = Marker;
exports.marker = marker;
exports.TileLayer = TileLayer;
exports.tileLayer = tileLayer;
exports.GridLayer = GridLayer;
exports.gridLayer = gridLayer;
exports.SVG = SVG;
exports.svg = svg$1;
exports.Renderer = Renderer;
exports.Canvas = Canvas;
exports.canvas = canvas$1;
exports.Path = Path;
exports.CircleMarker = CircleMarker;
exports.circleMarker = circleMarker;
exports.Circle = Circle;
exports.circle = circle;
exports.Polyline = Polyline;
exports.polyline = polyline;
exports.Polygon = Polygon;
exports.polygon = polygon;
exports.Rectangle = Rectangle;
exports.rectangle = rectangle;
exports.Map = Map;
exports.map = createMap;
var oldL = window.L;
exports.noConflict = function() {
window.L = oldL;
return this;
}
// Always export us to window global (see #2364)
window.L = exports;
})));
//# sourceMappingURL=leaflet-src.js.map
| c3nav/c3nav | src/c3nav/static/leaflet/leaflet.js | JavaScript | apache-2.0 | 409,097 |
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
'use strict';
var aStackPool = [];
var bStackPool = [];
/**
* Checks if two values are equal. Values may be primitives, arrays, or objects.
* Returns true if both arguments have the same keys and values.
*
* @see http://underscorejs.org
* @copyright 2009-2013 Jeremy Ashkenas, DocumentCloud Inc.
* @license MIT
*/
function areEqual(a, b) {
var aStack = aStackPool.length ? aStackPool.pop() : [];
var bStack = bStackPool.length ? bStackPool.pop() : [];
var result = eq(a, b, aStack, bStack);
aStack.length = 0;
bStack.length = 0;
aStackPool.push(aStack);
bStackPool.push(bStack);
return result;
}
function eq(a, b, aStack, bStack) {
if (a === b) {
// Identical objects are equal. `0 === -0`, but they aren't identical.
return a !== 0 || 1 / a == 1 / b;
}
if (a == null || b == null) {
// a or b can be `null` or `undefined`
return false;
}
if (typeof a != 'object' || typeof b != 'object') {
return false;
}
var objToStr = Object.prototype.toString;
var className = objToStr.call(a);
if (className != objToStr.call(b)) {
return false;
}
switch (className) {
case '[object String]':
return a == String(b);
case '[object Number]':
return isNaN(a) || isNaN(b) ? false : a == Number(b);
case '[object Date]':
case '[object Boolean]':
return +a == +b;
case '[object RegExp]':
return a.source == b.source && a.global == b.global && a.multiline == b.multiline && a.ignoreCase == b.ignoreCase;
}
// Assume equality for cyclic structures.
var length = aStack.length;
while (length--) {
if (aStack[length] == a) {
return bStack[length] == b;
}
}
aStack.push(a);
bStack.push(b);
var size = 0;
// Recursively compare objects and arrays.
if (className === '[object Array]') {
size = a.length;
if (size !== b.length) {
return false;
}
// Deep compare the contents, ignoring non-numeric properties.
while (size--) {
if (!eq(a[size], b[size], aStack, bStack)) {
return false;
}
}
} else {
if (a.constructor !== b.constructor) {
return false;
}
if (a.hasOwnProperty('valueOf') && b.hasOwnProperty('valueOf')) {
return a.valueOf() == b.valueOf();
}
var keys = Object.keys(a);
if (keys.length != Object.keys(b).length) {
return false;
}
for (var i = 0; i < keys.length; i++) {
if (!eq(a[keys[i]], b[keys[i]], aStack, bStack)) {
return false;
}
}
}
aStack.pop();
bStack.pop();
return true;
}
module.exports = areEqual; | demns/todomvc-perf-comparison | todomvc/react/node_modules/flux/node_modules/fbemitter/node_modules/fbjs/lib/areEqual.js | JavaScript | mit | 2,892 |
/**
* ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v14.0.0
* @link http://www.ag-grid.com/
* @license MIT
*/
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
var context_1 = require("./context/context");
var constants_1 = require("./constants");
var columnController_1 = require("./columnController/columnController");
var utils_1 = require("./utils");
var gridRow_1 = require("./entities/gridRow");
var gridCell_1 = require("./entities/gridCell");
var gridOptionsWrapper_1 = require("./gridOptionsWrapper");
var pinnedRowModel_1 = require("./rowModels/pinnedRowModel");
var CellNavigationService = (function () {
function CellNavigationService() {
}
// returns null if no cell to focus on, ie at the end of the grid
CellNavigationService.prototype.getNextCellToFocus = function (key, lastCellToFocus) {
// starting with the provided cell, we keep moving until we find a cell we can
// focus on.
var pointer = lastCellToFocus;
var finished = false;
// finished will be true when either:
// a) cell found that we can focus on
// b) run out of cells (ie the method returns null)
while (!finished) {
switch (key) {
case constants_1.Constants.KEY_UP:
pointer = this.getCellAbove(pointer);
break;
case constants_1.Constants.KEY_DOWN:
pointer = this.getCellBelow(pointer);
break;
case constants_1.Constants.KEY_RIGHT:
if (this.gridOptionsWrapper.isEnableRtl()) {
pointer = this.getCellToLeft(pointer);
}
else {
pointer = this.getCellToRight(pointer);
}
break;
case constants_1.Constants.KEY_LEFT:
if (this.gridOptionsWrapper.isEnableRtl()) {
pointer = this.getCellToRight(pointer);
}
else {
pointer = this.getCellToLeft(pointer);
}
break;
default:
console.log('ag-Grid: unknown key for navigation ' + key);
pointer = null;
break;
}
if (pointer) {
finished = this.isCellGoodToFocusOn(pointer);
}
else {
finished = true;
}
}
return pointer;
};
CellNavigationService.prototype.isCellGoodToFocusOn = function (gridCell) {
var column = gridCell.column;
var rowNode;
switch (gridCell.floating) {
case constants_1.Constants.PINNED_TOP:
rowNode = this.pinnedRowModel.getPinnedTopRow(gridCell.rowIndex);
break;
case constants_1.Constants.PINNED_BOTTOM:
rowNode = this.pinnedRowModel.getPinnedBottomRow(gridCell.rowIndex);
break;
default:
rowNode = this.rowModel.getRow(gridCell.rowIndex);
break;
}
var suppressNavigable = column.isSuppressNavigable(rowNode);
return !suppressNavigable;
};
CellNavigationService.prototype.getCellToLeft = function (lastCell) {
var colToLeft = this.columnController.getDisplayedColBefore(lastCell.column);
if (!colToLeft) {
return null;
}
else {
var gridCellDef = { rowIndex: lastCell.rowIndex, column: colToLeft, floating: lastCell.floating };
return new gridCell_1.GridCell(gridCellDef);
}
};
CellNavigationService.prototype.getCellToRight = function (lastCell) {
var colToRight = this.columnController.getDisplayedColAfter(lastCell.column);
// if already on right, do nothing
if (!colToRight) {
return null;
}
else {
var gridCellDef = { rowIndex: lastCell.rowIndex, column: colToRight, floating: lastCell.floating };
return new gridCell_1.GridCell(gridCellDef);
}
};
CellNavigationService.prototype.getRowBelow = function (lastRow) {
// if already on top row, do nothing
if (this.isLastRowInContainer(lastRow)) {
if (lastRow.isFloatingBottom()) {
return null;
}
else if (lastRow.isNotFloating()) {
if (this.pinnedRowModel.isRowsToRender(constants_1.Constants.PINNED_BOTTOM)) {
return new gridRow_1.GridRow(0, constants_1.Constants.PINNED_BOTTOM);
}
else {
return null;
}
}
else {
if (this.rowModel.isRowsToRender()) {
return new gridRow_1.GridRow(0, null);
}
else if (this.pinnedRowModel.isRowsToRender(constants_1.Constants.PINNED_BOTTOM)) {
return new gridRow_1.GridRow(0, constants_1.Constants.PINNED_BOTTOM);
}
else {
return null;
}
}
}
else {
return new gridRow_1.GridRow(lastRow.rowIndex + 1, lastRow.floating);
}
};
CellNavigationService.prototype.getCellBelow = function (lastCell) {
var rowBelow = this.getRowBelow(lastCell.getGridRow());
if (rowBelow) {
var gridCellDef = { rowIndex: rowBelow.rowIndex, column: lastCell.column, floating: rowBelow.floating };
return new gridCell_1.GridCell(gridCellDef);
}
else {
return null;
}
};
CellNavigationService.prototype.isLastRowInContainer = function (gridRow) {
if (gridRow.isFloatingTop()) {
var lastTopIndex = this.pinnedRowModel.getPinnedTopRowData().length - 1;
return lastTopIndex <= gridRow.rowIndex;
}
else if (gridRow.isFloatingBottom()) {
var lastBottomIndex = this.pinnedRowModel.getPinnedBottomRowData().length - 1;
return lastBottomIndex <= gridRow.rowIndex;
}
else {
var lastBodyIndex = this.rowModel.getPageLastRow();
return lastBodyIndex <= gridRow.rowIndex;
}
};
CellNavigationService.prototype.getRowAbove = function (lastRow) {
// if already on top row, do nothing
if (lastRow.rowIndex === 0) {
if (lastRow.isFloatingTop()) {
return null;
}
else if (lastRow.isNotFloating()) {
if (this.pinnedRowModel.isRowsToRender(constants_1.Constants.PINNED_TOP)) {
return this.getLastFloatingTopRow();
}
else {
return null;
}
}
else {
// last floating bottom
if (this.rowModel.isRowsToRender()) {
return this.getLastBodyCell();
}
else if (this.pinnedRowModel.isRowsToRender(constants_1.Constants.PINNED_TOP)) {
return this.getLastFloatingTopRow();
}
else {
return null;
}
}
}
else {
return new gridRow_1.GridRow(lastRow.rowIndex - 1, lastRow.floating);
}
};
CellNavigationService.prototype.getCellAbove = function (lastCell) {
var rowAbove = this.getRowAbove(lastCell.getGridRow());
if (rowAbove) {
var gridCellDef = { rowIndex: rowAbove.rowIndex, column: lastCell.column, floating: rowAbove.floating };
return new gridCell_1.GridCell(gridCellDef);
}
else {
return null;
}
};
CellNavigationService.prototype.getLastBodyCell = function () {
var lastBodyRow = this.rowModel.getPageLastRow();
return new gridRow_1.GridRow(lastBodyRow, null);
};
CellNavigationService.prototype.getLastFloatingTopRow = function () {
var lastFloatingRow = this.pinnedRowModel.getPinnedTopRowData().length - 1;
return new gridRow_1.GridRow(lastFloatingRow, constants_1.Constants.PINNED_TOP);
};
CellNavigationService.prototype.getNextTabbedCell = function (gridCell, backwards) {
if (backwards) {
return this.getNextTabbedCellBackwards(gridCell);
}
else {
return this.getNextTabbedCellForwards(gridCell);
}
};
CellNavigationService.prototype.getNextTabbedCellForwards = function (gridCell) {
var displayedColumns = this.columnController.getAllDisplayedColumns();
var newRowIndex = gridCell.rowIndex;
var newFloating = gridCell.floating;
// move along to the next cell
var newColumn = this.columnController.getDisplayedColAfter(gridCell.column);
// check if end of the row, and if so, go forward a row
if (!newColumn) {
newColumn = displayedColumns[0];
var rowBelow = this.getRowBelow(gridCell.getGridRow());
if (utils_1.Utils.missing(rowBelow)) {
return;
}
newRowIndex = rowBelow.rowIndex;
newFloating = rowBelow.floating;
}
var gridCellDef = { rowIndex: newRowIndex, column: newColumn, floating: newFloating };
return new gridCell_1.GridCell(gridCellDef);
};
CellNavigationService.prototype.getNextTabbedCellBackwards = function (gridCell) {
var displayedColumns = this.columnController.getAllDisplayedColumns();
var newRowIndex = gridCell.rowIndex;
var newFloating = gridCell.floating;
// move along to the next cell
var newColumn = this.columnController.getDisplayedColBefore(gridCell.column);
// check if end of the row, and if so, go forward a row
if (!newColumn) {
newColumn = displayedColumns[displayedColumns.length - 1];
var rowAbove = this.getRowAbove(gridCell.getGridRow());
if (utils_1.Utils.missing(rowAbove)) {
return;
}
newRowIndex = rowAbove.rowIndex;
newFloating = rowAbove.floating;
}
var gridCellDef = { rowIndex: newRowIndex, column: newColumn, floating: newFloating };
return new gridCell_1.GridCell(gridCellDef);
};
__decorate([
context_1.Autowired('columnController'),
__metadata("design:type", columnController_1.ColumnController)
], CellNavigationService.prototype, "columnController", void 0);
__decorate([
context_1.Autowired('rowModel'),
__metadata("design:type", Object)
], CellNavigationService.prototype, "rowModel", void 0);
__decorate([
context_1.Autowired('pinnedRowModel'),
__metadata("design:type", pinnedRowModel_1.PinnedRowModel)
], CellNavigationService.prototype, "pinnedRowModel", void 0);
__decorate([
context_1.Autowired('gridOptionsWrapper'),
__metadata("design:type", gridOptionsWrapper_1.GridOptionsWrapper)
], CellNavigationService.prototype, "gridOptionsWrapper", void 0);
CellNavigationService = __decorate([
context_1.Bean('cellNavigationService')
], CellNavigationService);
return CellNavigationService;
}());
exports.CellNavigationService = CellNavigationService;
| ahocevar/cdnjs | ajax/libs/ag-grid/14.0.0/lib/cellNavigationService.js | JavaScript | mit | 12,314 |
(function() {
var DE = window.DiscourseEmbed || {};
var comments = document.getElementById('discourse-comments');
var iframe = document.createElement('iframe');
['discourseUrl', 'discourseEmbedUrl', 'discourseUserName'].forEach(function(i) {
if (window[i]) { DE[i] = DE[i] || window[i]; }
});
var queryParams = {};
if (DE.discourseEmbedUrl) {
queryParams.embed_url = encodeURIComponent(DE.discourseEmbedUrl);
}
if (DE.discourseUserName) {
queryParams.discourse_username = DE.discourseUserName;
}
if (DE.topicId) {
queryParams.topic_id = DE.topicId;
}
var src = DE.discourseUrl + 'embed/comments';
var keys = Object.keys(queryParams);
if (keys.length > 0) {
src += "?";
for (var i=0; i<keys.length; i++) {
if (i > 0) { src += "&"; }
var k = keys[i];
src += k + "=" + queryParams[k];
}
}
iframe.src = src;
iframe.id = 'discourse-embed-frame';
iframe.width = "100%";
iframe.frameBorder = "0";
iframe.scrolling = "no";
comments.appendChild(iframe);
// Thanks http://amendsoft-javascript.blogspot.ca/2010/04/find-x-and-y-coordinate-of-html-control.html
function findPosY(obj)
{
var top = 0;
if(obj.offsetParent)
{
while(1)
{
top += obj.offsetTop;
if(!obj.offsetParent)
break;
obj = obj.offsetParent;
}
}
else if(obj.y)
{
top += obj.y;
}
return top;
}
function normalizeUrl(url) {
return url.replace(/^https?(\:\/\/)?/, '');
}
function postMessageReceived(e) {
if (!e) { return; }
if (normalizeUrl(DE.discourseUrl).indexOf(normalizeUrl(e.origin)) === -1) { return; }
if (e.data) {
if (e.data.type === 'discourse-resize' && e.data.height) {
iframe.height = e.data.height + "px";
}
if (e.data.type === 'discourse-scroll' && e.data.top) {
// find iframe offset
var destY = findPosY(iframe) + e.data.top;
window.scrollTo(0, destY);
}
}
}
window.addEventListener('message', postMessageReceived, false);
})();
| charan47/discourse | public/javascripts/embed.js | JavaScript | gpl-2.0 | 2,104 |
/*
Copyright (c) 2008, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.net/yui/license.txt
version: 2.5.2
*/
/**
* The dom module provides helper methods for manipulating Dom elements.
* @module dom
*
*/
(function() {
var Y = YAHOO.util, // internal shorthand
getStyle, // for load time browser branching
setStyle, // ditto
propertyCache = {}, // for faster hyphen converts
reClassNameCache = {}, // cache regexes for className
document = window.document; // cache for faster lookups
YAHOO.env._id_counter = YAHOO.env._id_counter || 0; // for use with generateId (global to save state if Dom is overwritten)
// brower detection
var isOpera = YAHOO.env.ua.opera,
isSafari = YAHOO.env.ua.webkit,
isGecko = YAHOO.env.ua.gecko,
isIE = YAHOO.env.ua.ie;
// regex cache
var patterns = {
HYPHEN: /(-[a-z])/i, // to normalize get/setStyle
ROOT_TAG: /^body|html$/i, // body for quirks mode, html for standards,
OP_SCROLL:/^(?:inline|table-row)$/i
};
var toCamel = function(property) {
if ( !patterns.HYPHEN.test(property) ) {
return property; // no hyphens
}
if (propertyCache[property]) { // already converted
return propertyCache[property];
}
var converted = property;
while( patterns.HYPHEN.exec(converted) ) {
converted = converted.replace(RegExp.$1,
RegExp.$1.substr(1).toUpperCase());
}
propertyCache[property] = converted;
return converted;
//return property.replace(/-([a-z])/gi, function(m0, m1) {return m1.toUpperCase()}) // cant use function as 2nd arg yet due to safari bug
};
var getClassRegEx = function(className) {
var re = reClassNameCache[className];
if (!re) {
re = new RegExp('(?:^|\\s+)' + className + '(?:\\s+|$)');
reClassNameCache[className] = re;
}
return re;
};
// branching at load instead of runtime
if (document.defaultView && document.defaultView.getComputedStyle) { // W3C DOM method
getStyle = function(el, property) {
var value = null;
if (property == 'float') { // fix reserved word
property = 'cssFloat';
}
var computed = el.ownerDocument.defaultView.getComputedStyle(el, '');
if (computed) { // test computed before touching for safari
value = computed[toCamel(property)];
}
return el.style[property] || value;
};
} else if (document.documentElement.currentStyle && isIE) { // IE method
getStyle = function(el, property) {
switch( toCamel(property) ) {
case 'opacity' :// IE opacity uses filter
var val = 100;
try { // will error if no DXImageTransform
val = el.filters['DXImageTransform.Microsoft.Alpha'].opacity;
} catch(e) {
try { // make sure its in the document
val = el.filters('alpha').opacity;
} catch(e) {
YAHOO.log('getStyle: IE filter failed',
'error', 'Dom');
}
}
return val / 100;
case 'float': // fix reserved word
property = 'styleFloat'; // fall through
default:
// test currentStyle before touching
var value = el.currentStyle ? el.currentStyle[property] : null;
return ( el.style[property] || value );
}
};
} else { // default to inline only
getStyle = function(el, property) { return el.style[property]; };
}
if (isIE) {
setStyle = function(el, property, val) {
switch (property) {
case 'opacity':
if ( YAHOO.lang.isString(el.style.filter) ) { // in case not appended
el.style.filter = 'alpha(opacity=' + val * 100 + ')';
if (!el.currentStyle || !el.currentStyle.hasLayout) {
el.style.zoom = 1; // when no layout or cant tell
}
}
break;
case 'float':
property = 'styleFloat';
default:
el.style[property] = val;
}
};
} else {
setStyle = function(el, property, val) {
if (property == 'float') {
property = 'cssFloat';
}
el.style[property] = val;
};
}
var testElement = function(node, method) {
return node && node.nodeType == 1 && ( !method || method(node) );
};
/**
* Provides helper methods for DOM elements.
* @namespace YAHOO.util
* @class Dom
*/
YAHOO.util.Dom = {
/**
* Returns an HTMLElement reference.
* @method get
* @param {String | HTMLElement |Array} el Accepts a string to use as an ID for getting a DOM reference, an actual DOM reference, or an Array of IDs and/or HTMLElements.
* @return {HTMLElement | Array} A DOM reference to an HTML element or an array of HTMLElements.
*/
get: function(el) {
if (el && (el.nodeType || el.item)) { // Node, or NodeList
return el;
}
if (YAHOO.lang.isString(el) || !el) { // id or null
return document.getElementById(el);
}
if (el.length !== undefined) { // array-like
var c = [];
for (var i = 0, len = el.length; i < len; ++i) {
c[c.length] = Y.Dom.get(el[i]);
}
return c;
}
return el; // some other object, just pass it back
},
/**
* Normalizes currentStyle and ComputedStyle.
* @method getStyle
* @param {String | HTMLElement |Array} el Accepts a string to use as an ID, an actual DOM reference, or an Array of IDs and/or HTMLElements.
* @param {String} property The style property whose value is returned.
* @return {String | Array} The current value of the style property for the element(s).
*/
getStyle: function(el, property) {
property = toCamel(property);
var f = function(element) {
return getStyle(element, property);
};
return Y.Dom.batch(el, f, Y.Dom, true);
},
/**
* Wrapper for setting style properties of HTMLElements. Normalizes "opacity" across modern browsers.
* @method setStyle
* @param {String | HTMLElement | Array} el Accepts a string to use as an ID, an actual DOM reference, or an Array of IDs and/or HTMLElements.
* @param {String} property The style property to be set.
* @param {String} val The value to apply to the given property.
*/
setStyle: function(el, property, val) {
property = toCamel(property);
var f = function(element) {
setStyle(element, property, val);
YAHOO.log('setStyle setting ' + property + ' to ' + val, 'info', 'Dom');
};
Y.Dom.batch(el, f, Y.Dom, true);
},
/**
* Gets the current position of an element based on page coordinates. Element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
* @method getXY
* @param {String | HTMLElement | Array} el Accepts a string to use as an ID, an actual DOM reference, or an Array of IDs and/or HTMLElements
* @return {Array} The XY position of the element(s)
*/
getXY: function(el) {
var f = function(el) {
// has to be part of document to have pageXY
if ( (el.parentNode === null || el.offsetParent === null ||
this.getStyle(el, 'display') == 'none') && el != el.ownerDocument.body) {
YAHOO.log('getXY failed: element not available', 'error', 'Dom');
return false;
}
YAHOO.log('getXY returning ' + getXY(el), 'info', 'Dom');
return getXY(el);
};
return Y.Dom.batch(el, f, Y.Dom, true);
},
/**
* Gets the current X position of an element based on page coordinates. The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
* @method getX
* @param {String | HTMLElement | Array} el Accepts a string to use as an ID, an actual DOM reference, or an Array of IDs and/or HTMLElements
* @return {Number | Array} The X position of the element(s)
*/
getX: function(el) {
var f = function(el) {
return Y.Dom.getXY(el)[0];
};
return Y.Dom.batch(el, f, Y.Dom, true);
},
/**
* Gets the current Y position of an element based on page coordinates. Element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
* @method getY
* @param {String | HTMLElement | Array} el Accepts a string to use as an ID, an actual DOM reference, or an Array of IDs and/or HTMLElements
* @return {Number | Array} The Y position of the element(s)
*/
getY: function(el) {
var f = function(el) {
return Y.Dom.getXY(el)[1];
};
return Y.Dom.batch(el, f, Y.Dom, true);
},
/**
* Set the position of an html element in page coordinates, regardless of how the element is positioned.
* The element(s) must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
* @method setXY
* @param {String | HTMLElement | Array} el Accepts a string to use as an ID, an actual DOM reference, or an Array of IDs and/or HTMLElements
* @param {Array} pos Contains X & Y values for new position (coordinates are page-based)
* @param {Boolean} noRetry By default we try and set the position a second time if the first fails
*/
setXY: function(el, pos, noRetry) {
var f = function(el) {
var style_pos = this.getStyle(el, 'position');
if (style_pos == 'static') { // default to relative
this.setStyle(el, 'position', 'relative');
style_pos = 'relative';
}
var pageXY = this.getXY(el);
if (pageXY === false) { // has to be part of doc to have pageXY
YAHOO.log('setXY failed: element not available', 'error', 'Dom');
return false;
}
var delta = [ // assuming pixels; if not we will have to retry
parseInt( this.getStyle(el, 'left'), 10 ),
parseInt( this.getStyle(el, 'top'), 10 )
];
if ( isNaN(delta[0]) ) {// in case of 'auto'
delta[0] = (style_pos == 'relative') ? 0 : el.offsetLeft;
}
if ( isNaN(delta[1]) ) { // in case of 'auto'
delta[1] = (style_pos == 'relative') ? 0 : el.offsetTop;
}
if (pos[0] !== null) { el.style.left = pos[0] - pageXY[0] + delta[0] + 'px'; }
if (pos[1] !== null) { el.style.top = pos[1] - pageXY[1] + delta[1] + 'px'; }
if (!noRetry) {
var newXY = this.getXY(el);
// if retry is true, try one more time if we miss
if ( (pos[0] !== null && newXY[0] != pos[0]) ||
(pos[1] !== null && newXY[1] != pos[1]) ) {
this.setXY(el, pos, true);
}
}
YAHOO.log('setXY setting position to ' + pos, 'info', 'Dom');
};
Y.Dom.batch(el, f, Y.Dom, true);
},
/**
* Set the X position of an html element in page coordinates, regardless of how the element is positioned.
* The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
* @method setX
* @param {String | HTMLElement | Array} el Accepts a string to use as an ID, an actual DOM reference, or an Array of IDs and/or HTMLElements.
* @param {Int} x The value to use as the X coordinate for the element(s).
*/
setX: function(el, x) {
Y.Dom.setXY(el, [x, null]);
},
/**
* Set the Y position of an html element in page coordinates, regardless of how the element is positioned.
* The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
* @method setY
* @param {String | HTMLElement | Array} el Accepts a string to use as an ID, an actual DOM reference, or an Array of IDs and/or HTMLElements.
* @param {Int} x To use as the Y coordinate for the element(s).
*/
setY: function(el, y) {
Y.Dom.setXY(el, [null, y]);
},
/**
* Returns the region position of the given element.
* The element must be part of the DOM tree to have a region (display:none or elements not appended return false).
* @method getRegion
* @param {String | HTMLElement | Array} el Accepts a string to use as an ID, an actual DOM reference, or an Array of IDs and/or HTMLElements.
* @return {Region | Array} A Region or array of Region instances containing "top, left, bottom, right" member data.
*/
getRegion: function(el) {
var f = function(el) {
if ( (el.parentNode === null || el.offsetParent === null ||
this.getStyle(el, 'display') == 'none') && el != el.ownerDocument.body) {
YAHOO.log('getRegion failed: element not available', 'error', 'Dom');
return false;
}
var region = Y.Region.getRegion(el);
YAHOO.log('getRegion returning ' + region, 'info', 'Dom');
return region;
};
return Y.Dom.batch(el, f, Y.Dom, true);
},
/**
* Returns the width of the client (viewport).
* @method getClientWidth
* @deprecated Now using getViewportWidth. This interface left intact for back compat.
* @return {Int} The width of the viewable area of the page.
*/
getClientWidth: function() {
return Y.Dom.getViewportWidth();
},
/**
* Returns the height of the client (viewport).
* @method getClientHeight
* @deprecated Now using getViewportHeight. This interface left intact for back compat.
* @return {Int} The height of the viewable area of the page.
*/
getClientHeight: function() {
return Y.Dom.getViewportHeight();
},
/**
* Returns a array of HTMLElements with the given class.
* For optimized performance, include a tag and/or root node when possible.
* @method getElementsByClassName
* @param {String} className The class name to match against
* @param {String} tag (optional) The tag name of the elements being collected
* @param {String | HTMLElement} root (optional) The HTMLElement or an ID to use as the starting point
* @param {Function} apply (optional) A function to apply to each element when found
* @return {Array} An array of elements that have the given class name
*/
getElementsByClassName: function(className, tag, root, apply) {
tag = tag || '*';
root = (root) ? Y.Dom.get(root) : null || document;
if (!root) {
return [];
}
var nodes = [],
elements = root.getElementsByTagName(tag),
re = getClassRegEx(className);
for (var i = 0, len = elements.length; i < len; ++i) {
if ( re.test(elements[i].className) ) {
nodes[nodes.length] = elements[i];
if (apply) {
apply.call(elements[i], elements[i]);
}
}
}
return nodes;
},
/**
* Determines whether an HTMLElement has the given className.
* @method hasClass
* @param {String | HTMLElement | Array} el The element or collection to test
* @param {String} className the class name to search for
* @return {Boolean | Array} A boolean value or array of boolean values
*/
hasClass: function(el, className) {
var re = getClassRegEx(className);
var f = function(el) {
YAHOO.log('hasClass returning ' + re.test(el.className), 'info', 'Dom');
return re.test(el.className);
};
return Y.Dom.batch(el, f, Y.Dom, true);
},
/**
* Adds a class name to a given element or collection of elements.
* @method addClass
* @param {String | HTMLElement | Array} el The element or collection to add the class to
* @param {String} className the class name to add to the class attribute
* @return {Boolean | Array} A pass/fail boolean or array of booleans
*/
addClass: function(el, className) {
var f = function(el) {
if (this.hasClass(el, className)) {
return false; // already present
}
YAHOO.log('addClass adding ' + className, 'info', 'Dom');
el.className = YAHOO.lang.trim([el.className, className].join(' '));
return true;
};
return Y.Dom.batch(el, f, Y.Dom, true);
},
/**
* Removes a class name from a given element or collection of elements.
* @method removeClass
* @param {String | HTMLElement | Array} el The element or collection to remove the class from
* @param {String} className the class name to remove from the class attribute
* @return {Boolean | Array} A pass/fail boolean or array of booleans
*/
removeClass: function(el, className) {
var re = getClassRegEx(className);
var f = function(el) {
if (!className || !this.hasClass(el, className)) {
return false; // not present
}
YAHOO.log('removeClass removing ' + className, 'info', 'Dom');
var c = el.className;
el.className = c.replace(re, ' ');
if ( this.hasClass(el, className) ) { // in case of multiple adjacent
this.removeClass(el, className);
}
el.className = YAHOO.lang.trim(el.className); // remove any trailing spaces
return true;
};
return Y.Dom.batch(el, f, Y.Dom, true);
},
/**
* Replace a class with another class for a given element or collection of elements.
* If no oldClassName is present, the newClassName is simply added.
* @method replaceClass
* @param {String | HTMLElement | Array} el The element or collection to remove the class from
* @param {String} oldClassName the class name to be replaced
* @param {String} newClassName the class name that will be replacing the old class name
* @return {Boolean | Array} A pass/fail boolean or array of booleans
*/
replaceClass: function(el, oldClassName, newClassName) {
if (!newClassName || oldClassName === newClassName) { // avoid infinite loop
return false;
}
var re = getClassRegEx(oldClassName);
var f = function(el) {
YAHOO.log('replaceClass replacing ' + oldClassName + ' with ' + newClassName, 'info', 'Dom');
if ( !this.hasClass(el, oldClassName) ) {
this.addClass(el, newClassName); // just add it if nothing to replace
return true; // NOTE: return
}
el.className = el.className.replace(re, ' ' + newClassName + ' ');
if ( this.hasClass(el, oldClassName) ) { // in case of multiple adjacent
this.replaceClass(el, oldClassName, newClassName);
}
el.className = YAHOO.lang.trim(el.className); // remove any trailing spaces
return true;
};
return Y.Dom.batch(el, f, Y.Dom, true);
},
/**
* Returns an ID and applies it to the element "el", if provided.
* @method generateId
* @param {String | HTMLElement | Array} el (optional) An optional element array of elements to add an ID to (no ID is added if one is already present).
* @param {String} prefix (optional) an optional prefix to use (defaults to "yui-gen").
* @return {String | Array} The generated ID, or array of generated IDs (or original ID if already present on an element)
*/
generateId: function(el, prefix) {
prefix = prefix || 'yui-gen';
var f = function(el) {
if (el && el.id) { // do not override existing ID
YAHOO.log('generateId returning existing id ' + el.id, 'info', 'Dom');
return el.id;
}
var id = prefix + YAHOO.env._id_counter++;
YAHOO.log('generateId generating ' + id, 'info', 'Dom');
if (el) {
el.id = id;
}
return id;
};
// batch fails when no element, so just generate and return single ID
return Y.Dom.batch(el, f, Y.Dom, true) || f.apply(Y.Dom, arguments);
},
/**
* Determines whether an HTMLElement is an ancestor of another HTML element in the DOM hierarchy.
* @method isAncestor
* @param {String | HTMLElement} haystack The possible ancestor
* @param {String | HTMLElement} needle The possible descendent
* @return {Boolean} Whether or not the haystack is an ancestor of needle
*/
isAncestor: function(haystack, needle) {
haystack = Y.Dom.get(haystack);
needle = Y.Dom.get(needle);
if (!haystack || !needle) {
return false;
}
if (haystack.contains && needle.nodeType && !isSafari) { // safari contains is broken
YAHOO.log('isAncestor returning ' + haystack.contains(needle), 'info', 'Dom');
return haystack.contains(needle);
}
else if ( haystack.compareDocumentPosition && needle.nodeType ) {
YAHOO.log('isAncestor returning ' + !!(haystack.compareDocumentPosition(needle) & 16), 'info', 'Dom');
return !!(haystack.compareDocumentPosition(needle) & 16);
} else if (needle.nodeType) {
// fallback to crawling up (safari)
return !!this.getAncestorBy(needle, function(el) {
return el == haystack;
});
}
YAHOO.log('isAncestor failed; most likely needle is not an HTMLElement', 'error', 'Dom');
return false;
},
/**
* Determines whether an HTMLElement is present in the current document.
* @method inDocument
* @param {String | HTMLElement} el The element to search for
* @return {Boolean} Whether or not the element is present in the current document
*/
inDocument: function(el) {
return this.isAncestor(document.documentElement, el);
},
/**
* Returns a array of HTMLElements that pass the test applied by supplied boolean method.
* For optimized performance, include a tag and/or root node when possible.
* @method getElementsBy
* @param {Function} method - A boolean method for testing elements which receives the element as its only argument.
* @param {String} tag (optional) The tag name of the elements being collected
* @param {String | HTMLElement} root (optional) The HTMLElement or an ID to use as the starting point
* @param {Function} apply (optional) A function to apply to each element when found
* @return {Array} Array of HTMLElements
*/
getElementsBy: function(method, tag, root, apply) {
tag = tag || '*';
root = (root) ? Y.Dom.get(root) : null || document;
if (!root) {
return [];
}
var nodes = [],
elements = root.getElementsByTagName(tag);
for (var i = 0, len = elements.length; i < len; ++i) {
if ( method(elements[i]) ) {
nodes[nodes.length] = elements[i];
if (apply) {
apply(elements[i]);
}
}
}
YAHOO.log('getElementsBy returning ' + nodes, 'info', 'Dom');
return nodes;
},
/**
* Runs the supplied method against each item in the Collection/Array.
* The method is called with the element(s) as the first arg, and the optional param as the second ( method(el, o) ).
* @method batch
* @param {String | HTMLElement | Array} el (optional) An element or array of elements to apply the method to
* @param {Function} method The method to apply to the element(s)
* @param {Any} o (optional) An optional arg that is passed to the supplied method
* @param {Boolean} override (optional) Whether or not to override the scope of "method" with "o"
* @return {Any | Array} The return value(s) from the supplied method
*/
batch: function(el, method, o, override) {
el = (el && (el.tagName || el.item)) ? el : Y.Dom.get(el); // skip get() when possible
if (!el || !method) {
YAHOO.log('batch failed: invalid arguments', 'error', 'Dom');
return false;
}
var scope = (override) ? o : window;
if (el.tagName || el.length === undefined) { // element or not array-like
return method.call(scope, el, o);
}
var collection = [];
for (var i = 0, len = el.length; i < len; ++i) {
collection[collection.length] = method.call(scope, el[i], o);
}
return collection;
},
/**
* Returns the height of the document.
* @method getDocumentHeight
* @return {Int} The height of the actual document (which includes the body and its margin).
*/
getDocumentHeight: function() {
var scrollHeight = (document.compatMode != 'CSS1Compat') ? document.body.scrollHeight : document.documentElement.scrollHeight;
var h = Math.max(scrollHeight, Y.Dom.getViewportHeight());
YAHOO.log('getDocumentHeight returning ' + h, 'info', 'Dom');
return h;
},
/**
* Returns the width of the document.
* @method getDocumentWidth
* @return {Int} The width of the actual document (which includes the body and its margin).
*/
getDocumentWidth: function() {
var scrollWidth = (document.compatMode != 'CSS1Compat') ? document.body.scrollWidth : document.documentElement.scrollWidth;
var w = Math.max(scrollWidth, Y.Dom.getViewportWidth());
YAHOO.log('getDocumentWidth returning ' + w, 'info', 'Dom');
return w;
},
/**
* Returns the current height of the viewport.
* @method getViewportHeight
* @return {Int} The height of the viewable area of the page (excludes scrollbars).
*/
getViewportHeight: function() {
var height = self.innerHeight; // Safari, Opera
var mode = document.compatMode;
if ( (mode || isIE) && !isOpera ) { // IE, Gecko
height = (mode == 'CSS1Compat') ?
document.documentElement.clientHeight : // Standards
document.body.clientHeight; // Quirks
}
YAHOO.log('getViewportHeight returning ' + height, 'info', 'Dom');
return height;
},
/**
* Returns the current width of the viewport.
* @method getViewportWidth
* @return {Int} The width of the viewable area of the page (excludes scrollbars).
*/
getViewportWidth: function() {
var width = self.innerWidth; // Safari
var mode = document.compatMode;
if (mode || isIE) { // IE, Gecko, Opera
width = (mode == 'CSS1Compat') ?
document.documentElement.clientWidth : // Standards
document.body.clientWidth; // Quirks
}
YAHOO.log('getViewportWidth returning ' + width, 'info', 'Dom');
return width;
},
/**
* Returns the nearest ancestor that passes the test applied by supplied boolean method.
* For performance reasons, IDs are not accepted and argument validation omitted.
* @method getAncestorBy
* @param {HTMLElement} node The HTMLElement to use as the starting point
* @param {Function} method - A boolean method for testing elements which receives the element as its only argument.
* @return {Object} HTMLElement or null if not found
*/
getAncestorBy: function(node, method) {
while (node = node.parentNode) { // NOTE: assignment
if ( testElement(node, method) ) {
YAHOO.log('getAncestorBy returning ' + node, 'info', 'Dom');
return node;
}
}
YAHOO.log('getAncestorBy returning null (no ancestor passed test)', 'error', 'Dom');
return null;
},
/**
* Returns the nearest ancestor with the given className.
* @method getAncestorByClassName
* @param {String | HTMLElement} node The HTMLElement or an ID to use as the starting point
* @param {String} className
* @return {Object} HTMLElement
*/
getAncestorByClassName: function(node, className) {
node = Y.Dom.get(node);
if (!node) {
YAHOO.log('getAncestorByClassName failed: invalid node argument', 'error', 'Dom');
return null;
}
var method = function(el) { return Y.Dom.hasClass(el, className); };
return Y.Dom.getAncestorBy(node, method);
},
/**
* Returns the nearest ancestor with the given tagName.
* @method getAncestorByTagName
* @param {String | HTMLElement} node The HTMLElement or an ID to use as the starting point
* @param {String} tagName
* @return {Object} HTMLElement
*/
getAncestorByTagName: function(node, tagName) {
node = Y.Dom.get(node);
if (!node) {
YAHOO.log('getAncestorByTagName failed: invalid node argument', 'error', 'Dom');
return null;
}
var method = function(el) {
return el.tagName && el.tagName.toUpperCase() == tagName.toUpperCase();
};
return Y.Dom.getAncestorBy(node, method);
},
/**
* Returns the previous sibling that is an HTMLElement.
* For performance reasons, IDs are not accepted and argument validation omitted.
* Returns the nearest HTMLElement sibling if no method provided.
* @method getPreviousSiblingBy
* @param {HTMLElement} node The HTMLElement to use as the starting point
* @param {Function} method A boolean function used to test siblings
* that receives the sibling node being tested as its only argument
* @return {Object} HTMLElement or null if not found
*/
getPreviousSiblingBy: function(node, method) {
while (node) {
node = node.previousSibling;
if ( testElement(node, method) ) {
return node;
}
}
return null;
},
/**
* Returns the previous sibling that is an HTMLElement
* @method getPreviousSibling
* @param {String | HTMLElement} node The HTMLElement or an ID to use as the starting point
* @return {Object} HTMLElement or null if not found
*/
getPreviousSibling: function(node) {
node = Y.Dom.get(node);
if (!node) {
YAHOO.log('getPreviousSibling failed: invalid node argument', 'error', 'Dom');
return null;
}
return Y.Dom.getPreviousSiblingBy(node);
},
/**
* Returns the next HTMLElement sibling that passes the boolean method.
* For performance reasons, IDs are not accepted and argument validation omitted.
* Returns the nearest HTMLElement sibling if no method provided.
* @method getNextSiblingBy
* @param {HTMLElement} node The HTMLElement to use as the starting point
* @param {Function} method A boolean function used to test siblings
* that receives the sibling node being tested as its only argument
* @return {Object} HTMLElement or null if not found
*/
getNextSiblingBy: function(node, method) {
while (node) {
node = node.nextSibling;
if ( testElement(node, method) ) {
return node;
}
}
return null;
},
/**
* Returns the next sibling that is an HTMLElement
* @method getNextSibling
* @param {String | HTMLElement} node The HTMLElement or an ID to use as the starting point
* @return {Object} HTMLElement or null if not found
*/
getNextSibling: function(node) {
node = Y.Dom.get(node);
if (!node) {
YAHOO.log('getNextSibling failed: invalid node argument', 'error', 'Dom');
return null;
}
return Y.Dom.getNextSiblingBy(node);
},
/**
* Returns the first HTMLElement child that passes the test method.
* @method getFirstChildBy
* @param {HTMLElement} node The HTMLElement to use as the starting point
* @param {Function} method A boolean function used to test children
* that receives the node being tested as its only argument
* @return {Object} HTMLElement or null if not found
*/
getFirstChildBy: function(node, method) {
var child = ( testElement(node.firstChild, method) ) ? node.firstChild : null;
return child || Y.Dom.getNextSiblingBy(node.firstChild, method);
},
/**
* Returns the first HTMLElement child.
* @method getFirstChild
* @param {String | HTMLElement} node The HTMLElement or an ID to use as the starting point
* @return {Object} HTMLElement or null if not found
*/
getFirstChild: function(node, method) {
node = Y.Dom.get(node);
if (!node) {
YAHOO.log('getFirstChild failed: invalid node argument', 'error', 'Dom');
return null;
}
return Y.Dom.getFirstChildBy(node);
},
/**
* Returns the last HTMLElement child that passes the test method.
* @method getLastChildBy
* @param {HTMLElement} node The HTMLElement to use as the starting point
* @param {Function} method A boolean function used to test children
* that receives the node being tested as its only argument
* @return {Object} HTMLElement or null if not found
*/
getLastChildBy: function(node, method) {
if (!node) {
YAHOO.log('getLastChild failed: invalid node argument', 'error', 'Dom');
return null;
}
var child = ( testElement(node.lastChild, method) ) ? node.lastChild : null;
return child || Y.Dom.getPreviousSiblingBy(node.lastChild, method);
},
/**
* Returns the last HTMLElement child.
* @method getLastChild
* @param {String | HTMLElement} node The HTMLElement or an ID to use as the starting point
* @return {Object} HTMLElement or null if not found
*/
getLastChild: function(node) {
node = Y.Dom.get(node);
return Y.Dom.getLastChildBy(node);
},
/**
* Returns an array of HTMLElement childNodes that pass the test method.
* @method getChildrenBy
* @param {HTMLElement} node The HTMLElement to start from
* @param {Function} method A boolean function used to test children
* that receives the node being tested as its only argument
* @return {Array} A static array of HTMLElements
*/
getChildrenBy: function(node, method) {
var child = Y.Dom.getFirstChildBy(node, method);
var children = child ? [child] : [];
Y.Dom.getNextSiblingBy(child, function(node) {
if ( !method || method(node) ) {
children[children.length] = node;
}
return false; // fail test to collect all children
});
return children;
},
/**
* Returns an array of HTMLElement childNodes.
* @method getChildren
* @param {String | HTMLElement} node The HTMLElement or an ID to use as the starting point
* @return {Array} A static array of HTMLElements
*/
getChildren: function(node) {
node = Y.Dom.get(node);
if (!node) {
YAHOO.log('getChildren failed: invalid node argument', 'error', 'Dom');
}
return Y.Dom.getChildrenBy(node);
},
/**
* Returns the left scroll value of the document
* @method getDocumentScrollLeft
* @param {HTMLDocument} document (optional) The document to get the scroll value of
* @return {Int} The amount that the document is scrolled to the left
*/
getDocumentScrollLeft: function(doc) {
doc = doc || document;
return Math.max(doc.documentElement.scrollLeft, doc.body.scrollLeft);
},
/**
* Returns the top scroll value of the document
* @method getDocumentScrollTop
* @param {HTMLDocument} document (optional) The document to get the scroll value of
* @return {Int} The amount that the document is scrolled to the top
*/
getDocumentScrollTop: function(doc) {
doc = doc || document;
return Math.max(doc.documentElement.scrollTop, doc.body.scrollTop);
},
/**
* Inserts the new node as the previous sibling of the reference node
* @method insertBefore
* @param {String | HTMLElement} newNode The node to be inserted
* @param {String | HTMLElement} referenceNode The node to insert the new node before
* @return {HTMLElement} The node that was inserted (or null if insert fails)
*/
insertBefore: function(newNode, referenceNode) {
newNode = Y.Dom.get(newNode);
referenceNode = Y.Dom.get(referenceNode);
if (!newNode || !referenceNode || !referenceNode.parentNode) {
YAHOO.log('insertAfter failed: missing or invalid arg(s)', 'error', 'Dom');
return null;
}
return referenceNode.parentNode.insertBefore(newNode, referenceNode);
},
/**
* Inserts the new node as the next sibling of the reference node
* @method insertAfter
* @param {String | HTMLElement} newNode The node to be inserted
* @param {String | HTMLElement} referenceNode The node to insert the new node after
* @return {HTMLElement} The node that was inserted (or null if insert fails)
*/
insertAfter: function(newNode, referenceNode) {
newNode = Y.Dom.get(newNode);
referenceNode = Y.Dom.get(referenceNode);
if (!newNode || !referenceNode || !referenceNode.parentNode) {
YAHOO.log('insertAfter failed: missing or invalid arg(s)', 'error', 'Dom');
return null;
}
if (referenceNode.nextSibling) {
return referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
} else {
return referenceNode.parentNode.appendChild(newNode);
}
},
/**
* Creates a Region based on the viewport relative to the document.
* @method getClientRegion
* @return {Region} A Region object representing the viewport which accounts for document scroll
*/
getClientRegion: function() {
var t = Y.Dom.getDocumentScrollTop(),
l = Y.Dom.getDocumentScrollLeft(),
r = Y.Dom.getViewportWidth() + l,
b = Y.Dom.getViewportHeight() + t;
return new Y.Region(t, r, b, l);
}
};
var getXY = function() {
if (document.documentElement.getBoundingClientRect) { // IE
return function(el) {
var box = el.getBoundingClientRect();
var rootNode = el.ownerDocument;
return [box.left + Y.Dom.getDocumentScrollLeft(rootNode), box.top +
Y.Dom.getDocumentScrollTop(rootNode)];
};
} else {
return function(el) { // manually calculate by crawling up offsetParents
var pos = [el.offsetLeft, el.offsetTop];
var parentNode = el.offsetParent;
// safari: subtract body offsets if el is abs (or any offsetParent), unless body is offsetParent
var accountForBody = (isSafari &&
Y.Dom.getStyle(el, 'position') == 'absolute' &&
el.offsetParent == el.ownerDocument.body);
if (parentNode != el) {
while (parentNode) {
pos[0] += parentNode.offsetLeft;
pos[1] += parentNode.offsetTop;
if (!accountForBody && isSafari &&
Y.Dom.getStyle(parentNode,'position') == 'absolute' ) {
accountForBody = true;
}
parentNode = parentNode.offsetParent;
}
}
if (accountForBody) { //safari doubles in this case
pos[0] -= el.ownerDocument.body.offsetLeft;
pos[1] -= el.ownerDocument.body.offsetTop;
}
parentNode = el.parentNode;
// account for any scrolled ancestors
while ( parentNode.tagName && !patterns.ROOT_TAG.test(parentNode.tagName) )
{
if (parentNode.scrollTop || parentNode.scrollLeft) {
// work around opera inline/table scrollLeft/Top bug (false reports offset as scroll)
if (!patterns.OP_SCROLL.test(Y.Dom.getStyle(parentNode, 'display'))) {
if (!isOpera || Y.Dom.getStyle(parentNode, 'overflow') !== 'visible') { // opera inline-block misreports when visible
pos[0] -= parentNode.scrollLeft;
pos[1] -= parentNode.scrollTop;
}
}
}
parentNode = parentNode.parentNode;
}
return pos;
};
}
}() // NOTE: Executing for loadtime branching
})();
/**
* A region is a representation of an object on a grid. It is defined
* by the top, right, bottom, left extents, so is rectangular by default. If
* other shapes are required, this class could be extended to support it.
* @namespace YAHOO.util
* @class Region
* @param {Int} t the top extent
* @param {Int} r the right extent
* @param {Int} b the bottom extent
* @param {Int} l the left extent
* @constructor
*/
YAHOO.util.Region = function(t, r, b, l) {
/**
* The region's top extent
* @property top
* @type Int
*/
this.top = t;
/**
* The region's top extent as index, for symmetry with set/getXY
* @property 1
* @type Int
*/
this[1] = t;
/**
* The region's right extent
* @property right
* @type int
*/
this.right = r;
/**
* The region's bottom extent
* @property bottom
* @type Int
*/
this.bottom = b;
/**
* The region's left extent
* @property left
* @type Int
*/
this.left = l;
/**
* The region's left extent as index, for symmetry with set/getXY
* @property 0
* @type Int
*/
this[0] = l;
};
/**
* Returns true if this region contains the region passed in
* @method contains
* @param {Region} region The region to evaluate
* @return {Boolean} True if the region is contained with this region,
* else false
*/
YAHOO.util.Region.prototype.contains = function(region) {
return ( region.left >= this.left &&
region.right <= this.right &&
region.top >= this.top &&
region.bottom <= this.bottom );
// this.logger.debug("does " + this + " contain " + region + " ... " + ret);
};
/**
* Returns the area of the region
* @method getArea
* @return {Int} the region's area
*/
YAHOO.util.Region.prototype.getArea = function() {
return ( (this.bottom - this.top) * (this.right - this.left) );
};
/**
* Returns the region where the passed in region overlaps with this one
* @method intersect
* @param {Region} region The region that intersects
* @return {Region} The overlap region, or null if there is no overlap
*/
YAHOO.util.Region.prototype.intersect = function(region) {
var t = Math.max( this.top, region.top );
var r = Math.min( this.right, region.right );
var b = Math.min( this.bottom, region.bottom );
var l = Math.max( this.left, region.left );
if (b >= t && r >= l) {
return new YAHOO.util.Region(t, r, b, l);
} else {
return null;
}
};
/**
* Returns the region representing the smallest region that can contain both
* the passed in region and this region.
* @method union
* @param {Region} region The region that to create the union with
* @return {Region} The union region
*/
YAHOO.util.Region.prototype.union = function(region) {
var t = Math.min( this.top, region.top );
var r = Math.max( this.right, region.right );
var b = Math.max( this.bottom, region.bottom );
var l = Math.min( this.left, region.left );
return new YAHOO.util.Region(t, r, b, l);
};
/**
* toString
* @method toString
* @return string the region properties
*/
YAHOO.util.Region.prototype.toString = function() {
return ( "Region {" +
"top: " + this.top +
", right: " + this.right +
", bottom: " + this.bottom +
", left: " + this.left +
"}" );
};
/**
* Returns a region that is occupied by the DOM element
* @method getRegion
* @param {HTMLElement} el The element
* @return {Region} The region that the element occupies
* @static
*/
YAHOO.util.Region.getRegion = function(el) {
var p = YAHOO.util.Dom.getXY(el);
var t = p[1];
var r = p[0] + el.offsetWidth;
var b = p[1] + el.offsetHeight;
var l = p[0];
return new YAHOO.util.Region(t, r, b, l);
};
/////////////////////////////////////////////////////////////////////////////
/**
* A point is a region that is special in that it represents a single point on
* the grid.
* @namespace YAHOO.util
* @class Point
* @param {Int} x The X position of the point
* @param {Int} y The Y position of the point
* @constructor
* @extends YAHOO.util.Region
*/
YAHOO.util.Point = function(x, y) {
if (YAHOO.lang.isArray(x)) { // accept input from Dom.getXY, Event.getXY, etc.
y = x[1]; // dont blow away x yet
x = x[0];
}
/**
* The X position of the point, which is also the right, left and index zero (for Dom.getXY symmetry)
* @property x
* @type Int
*/
this.x = this.right = this.left = this[0] = x;
/**
* The Y position of the point, which is also the top, bottom and index one (for Dom.getXY symmetry)
* @property y
* @type Int
*/
this.y = this.top = this.bottom = this[1] = y;
};
YAHOO.util.Point.prototype = new YAHOO.util.Region();
YAHOO.register("dom", YAHOO.util.Dom, {version: "2.5.2", build: "1076"});
| SuriyaaKudoIsc/wikia-app-test | resources/wikia/libraries/yui/dom/dom-debug.js | JavaScript | gpl-2.0 | 51,341 |
// Do not edit this file; automatically generated by build.py.
'use strict';
Blockly.Blocks.colour={};Blockly.Constants={};Blockly.Constants.Colour={};Blockly.Constants.Colour.HUE=20;
Blockly.defineBlocksWithJsonArray([{type:"colour_picker",message0:"%1",args0:[{type:"field_colour",name:"COLOUR",colour:"#ff0000"}],output:"Colour",colour:"%{BKY_COLOUR_HUE}",helpUrl:"%{BKY_COLOUR_PICKER_HELPURL}",tooltip:"%{BKY_COLOUR_PICKER_TOOLTIP}",extensions:["parent_tooltip_when_inline"]},{type:"colour_random",message0:"%{BKY_COLOUR_RANDOM_TITLE}",output:"Colour",colour:"%{BKY_COLOUR_HUE}",helpUrl:"%{BKY_COLOUR_RANDOM_HELPURL}",tooltip:"%{BKY_COLOUR_RANDOM_TOOLTIP}"},{type:"colour_rgb",message0:"%{BKY_COLOUR_RGB_TITLE} %{BKY_COLOUR_RGB_RED} %1 %{BKY_COLOUR_RGB_GREEN} %2 %{BKY_COLOUR_RGB_BLUE} %3",
args0:[{type:"input_value",name:"RED",check:"Number",align:"RIGHT"},{type:"input_value",name:"GREEN",check:"Number",align:"RIGHT"},{type:"input_value",name:"BLUE",check:"Number",align:"RIGHT"}],output:"Colour",colour:"%{BKY_COLOUR_HUE}",helpUrl:"%{BKY_COLOUR_RGB_HELPURL}",tooltip:"%{BKY_COLOUR_RGB_TOOLTIP}"},{type:"colour_blend",message0:"%{BKY_COLOUR_BLEND_TITLE} %{BKY_COLOUR_BLEND_COLOUR1} %1 %{BKY_COLOUR_BLEND_COLOUR2} %2 %{BKY_COLOUR_BLEND_RATIO} %3",args0:[{type:"input_value",name:"COLOUR1",
check:"Colour",align:"RIGHT"},{type:"input_value",name:"COLOUR2",check:"Colour",align:"RIGHT"},{type:"input_value",name:"RATIO",check:"Number",align:"RIGHT"}],output:"Colour",colour:"%{BKY_COLOUR_HUE}",helpUrl:"%{BKY_COLOUR_BLEND_HELPURL}",tooltip:"%{BKY_COLOUR_BLEND_TOOLTIP}"}]);Blockly.Blocks.lists={};Blockly.Constants.Lists={};Blockly.Constants.Lists.HUE=260;
Blockly.defineBlocksWithJsonArray([{type:"lists_create_empty",message0:"%{BKY_LISTS_CREATE_EMPTY_TITLE}",output:"Array",colour:"%{BKY_LISTS_HUE}",tooltip:"%{BKY_LISTS_CREATE_EMPTY_TOOLTIP}",helpUrl:"%{BKY_LISTS_CREATE_EMPTY_HELPURL}"},{type:"lists_repeat",message0:"%{BKY_LISTS_REPEAT_TITLE}",args0:[{type:"input_value",name:"ITEM"},{type:"input_value",name:"NUM",check:"Number"}],output:"Array",colour:"%{BKY_LISTS_HUE}",tooltip:"%{BKY_LISTS_REPEAT_TOOLTIP}",helpUrl:"%{BKY_LISTS_REPEAT_HELPURL}"},{type:"lists_reverse",
message0:"%{BKY_LISTS_REVERSE_MESSAGE0}",args0:[{type:"input_value",name:"LIST",check:"Array"}],output:"Array",inputsInline:!0,colour:"%{BKY_LISTS_HUE}",tooltip:"%{BKY_LISTS_REVERSE_TOOLTIP}",helpUrl:"%{BKY_LISTS_REVERSE_HELPURL}"},{type:"lists_isEmpty",message0:"%{BKY_LISTS_ISEMPTY_TITLE}",args0:[{type:"input_value",name:"VALUE",check:["String","Array"]}],output:"Boolean",colour:"%{BKY_LISTS_HUE}",tooltip:"%{BKY_LISTS_ISEMPTY_TOOLTIP}",helpUrl:"%{BKY_LISTS_ISEMPTY_HELPURL}"},{type:"lists_length",
message0:"%{BKY_LISTS_LENGTH_TITLE}",args0:[{type:"input_value",name:"VALUE",check:["String","Array"]}],output:"Number",colour:"%{BKY_LISTS_HUE}",tooltip:"%{BKY_LISTS_LENGTH_TOOLTIP}",helpUrl:"%{BKY_LISTS_LENGTH_HELPURL}"}]);
Blockly.Blocks.lists_create_with={init:function(){this.setHelpUrl(Blockly.Msg.LISTS_CREATE_WITH_HELPURL);this.setColour(Blockly.Msg.LISTS_HUE);this.itemCount_=3;this.updateShape_();this.setOutput(!0,"Array");this.setMutator(new Blockly.Mutator(["lists_create_with_item"]));this.setTooltip(Blockly.Msg.LISTS_CREATE_WITH_TOOLTIP)},mutationToDom:function(){var a=document.createElement("mutation");a.setAttribute("items",this.itemCount_);return a},domToMutation:function(a){this.itemCount_=parseInt(a.getAttribute("items"),
10);this.updateShape_()},decompose:function(a){var b=a.newBlock("lists_create_with_container");b.initSvg();for(var c=b.getInput("STACK").connection,e=0;e<this.itemCount_;e++){var d=a.newBlock("lists_create_with_item");d.initSvg();c.connect(d.previousConnection);c=d.nextConnection}return b},compose:function(a){var b=a.getInputTargetBlock("STACK");for(a=[];b;)a.push(b.valueConnection_),b=b.nextConnection&&b.nextConnection.targetBlock();for(b=0;b<this.itemCount_;b++){var c=this.getInput("ADD"+b).connection.targetConnection;
c&&-1==a.indexOf(c)&&c.disconnect()}this.itemCount_=a.length;this.updateShape_();for(b=0;b<this.itemCount_;b++)Blockly.Mutator.reconnect(a[b],this,"ADD"+b)},saveConnections:function(a){a=a.getInputTargetBlock("STACK");for(var b=0;a;){var c=this.getInput("ADD"+b);a.valueConnection_=c&&c.connection.targetConnection;b++;a=a.nextConnection&&a.nextConnection.targetBlock()}},updateShape_:function(){this.itemCount_&&this.getInput("EMPTY")?this.removeInput("EMPTY"):this.itemCount_||this.getInput("EMPTY")||
this.appendDummyInput("EMPTY").appendField(Blockly.Msg.LISTS_CREATE_EMPTY_TITLE);for(var a=0;a<this.itemCount_;a++)if(!this.getInput("ADD"+a)){var b=this.appendValueInput("ADD"+a);0==a&&b.appendField(Blockly.Msg.LISTS_CREATE_WITH_INPUT_WITH)}for(;this.getInput("ADD"+a);)this.removeInput("ADD"+a),a++}};
Blockly.Blocks.lists_create_with_container={init:function(){this.setColour(Blockly.Msg.LISTS_HUE);this.appendDummyInput().appendField(Blockly.Msg.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD);this.appendStatementInput("STACK");this.setTooltip(Blockly.Msg.LISTS_CREATE_WITH_CONTAINER_TOOLTIP);this.contextMenu=!1}};
Blockly.Blocks.lists_create_with_item={init:function(){this.setColour(Blockly.Msg.LISTS_HUE);this.appendDummyInput().appendField(Blockly.Msg.LISTS_CREATE_WITH_ITEM_TITLE);this.setPreviousStatement(!0);this.setNextStatement(!0);this.setTooltip(Blockly.Msg.LISTS_CREATE_WITH_ITEM_TOOLTIP);this.contextMenu=!1}};
Blockly.Blocks.lists_indexOf={init:function(){var a=[[Blockly.Msg.LISTS_INDEX_OF_FIRST,"FIRST"],[Blockly.Msg.LISTS_INDEX_OF_LAST,"LAST"]];this.setHelpUrl(Blockly.Msg.LISTS_INDEX_OF_HELPURL);this.setColour(Blockly.Msg.LISTS_HUE);this.setOutput(!0,"Number");this.appendValueInput("VALUE").setCheck("Array").appendField(Blockly.Msg.LISTS_INDEX_OF_INPUT_IN_LIST);this.appendValueInput("FIND").appendField(new Blockly.FieldDropdown(a),"END");this.setInputsInline(!0);var b=this;this.setTooltip(function(){return Blockly.Msg.LISTS_INDEX_OF_TOOLTIP.replace("%1",
b.workspace.options.oneBasedIndex?"0":"-1")})}};
Blockly.Blocks.lists_getIndex={init:function(){var a=[[Blockly.Msg.LISTS_GET_INDEX_GET,"GET"],[Blockly.Msg.LISTS_GET_INDEX_GET_REMOVE,"GET_REMOVE"],[Blockly.Msg.LISTS_GET_INDEX_REMOVE,"REMOVE"]];this.WHERE_OPTIONS=[[Blockly.Msg.LISTS_GET_INDEX_FROM_START,"FROM_START"],[Blockly.Msg.LISTS_GET_INDEX_FROM_END,"FROM_END"],[Blockly.Msg.LISTS_GET_INDEX_FIRST,"FIRST"],[Blockly.Msg.LISTS_GET_INDEX_LAST,"LAST"],[Blockly.Msg.LISTS_GET_INDEX_RANDOM,"RANDOM"]];this.setHelpUrl(Blockly.Msg.LISTS_GET_INDEX_HELPURL);this.setColour(Blockly.Msg.LISTS_HUE);
a=new Blockly.FieldDropdown(a,function(a){this.sourceBlock_.updateStatement_("REMOVE"==a)});this.appendValueInput("VALUE").setCheck("Array").appendField(Blockly.Msg.LISTS_GET_INDEX_INPUT_IN_LIST);this.appendDummyInput().appendField(a,"MODE").appendField("","SPACE");this.appendDummyInput("AT");Blockly.Msg.LISTS_GET_INDEX_TAIL&&this.appendDummyInput("TAIL").appendField(Blockly.Msg.LISTS_GET_INDEX_TAIL);this.setInputsInline(!0);this.setOutput(!0);this.updateAt_(!0);var b=this;this.setTooltip(function(){var a=
b.getFieldValue("MODE"),e=b.getFieldValue("WHERE"),d="";switch(a+" "+e){case "GET FROM_START":case "GET FROM_END":d=Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FROM;break;case "GET FIRST":d=Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FIRST;break;case "GET LAST":d=Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_LAST;break;case "GET RANDOM":d=Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_RANDOM;break;case "GET_REMOVE FROM_START":case "GET_REMOVE FROM_END":d=Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FROM;break;case "GET_REMOVE FIRST":d=
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FIRST;break;case "GET_REMOVE LAST":d=Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_LAST;break;case "GET_REMOVE RANDOM":d=Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_RANDOM;break;case "REMOVE FROM_START":case "REMOVE FROM_END":d=Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FROM;break;case "REMOVE FIRST":d=Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FIRST;break;case "REMOVE LAST":d=Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_LAST;break;case "REMOVE RANDOM":d=
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_RANDOM}if("FROM_START"==e||"FROM_END"==e)d+=" "+("FROM_START"==e?Blockly.Msg.LISTS_INDEX_FROM_START_TOOLTIP:Blockly.Msg.LISTS_INDEX_FROM_END_TOOLTIP).replace("%1",b.workspace.options.oneBasedIndex?"#1":"#0");return d})},mutationToDom:function(){var a=document.createElement("mutation");a.setAttribute("statement",!this.outputConnection);var b=this.getInput("AT").type==Blockly.INPUT_VALUE;a.setAttribute("at",b);return a},domToMutation:function(a){var b="true"==
a.getAttribute("statement");this.updateStatement_(b);a="false"!=a.getAttribute("at");this.updateAt_(a)},updateStatement_:function(a){a!=!this.outputConnection&&(this.unplug(!0,!0),a?(this.setOutput(!1),this.setPreviousStatement(!0),this.setNextStatement(!0)):(this.setPreviousStatement(!1),this.setNextStatement(!1),this.setOutput(!0)))},updateAt_:function(a){this.removeInput("AT");this.removeInput("ORDINAL",!0);a?(this.appendValueInput("AT").setCheck("Number"),Blockly.Msg.ORDINAL_NUMBER_SUFFIX&&this.appendDummyInput("ORDINAL").appendField(Blockly.Msg.ORDINAL_NUMBER_SUFFIX)):
this.appendDummyInput("AT");var b=new Blockly.FieldDropdown(this.WHERE_OPTIONS,function(b){var c="FROM_START"==b||"FROM_END"==b;if(c!=a){var d=this.sourceBlock_;d.updateAt_(c);d.setFieldValue(b,"WHERE");return null}});this.getInput("AT").appendField(b,"WHERE");Blockly.Msg.LISTS_GET_INDEX_TAIL&&this.moveInputBefore("TAIL",null)}};
Blockly.Blocks.lists_setIndex={init:function(){var a=[[Blockly.Msg.LISTS_SET_INDEX_SET,"SET"],[Blockly.Msg.LISTS_SET_INDEX_INSERT,"INSERT"]];this.WHERE_OPTIONS=[[Blockly.Msg.LISTS_GET_INDEX_FROM_START,"FROM_START"],[Blockly.Msg.LISTS_GET_INDEX_FROM_END,"FROM_END"],[Blockly.Msg.LISTS_GET_INDEX_FIRST,"FIRST"],[Blockly.Msg.LISTS_GET_INDEX_LAST,"LAST"],[Blockly.Msg.LISTS_GET_INDEX_RANDOM,"RANDOM"]];this.setHelpUrl(Blockly.Msg.LISTS_SET_INDEX_HELPURL);this.setColour(Blockly.Msg.LISTS_HUE);this.appendValueInput("LIST").setCheck("Array").appendField(Blockly.Msg.LISTS_SET_INDEX_INPUT_IN_LIST);
this.appendDummyInput().appendField(new Blockly.FieldDropdown(a),"MODE").appendField("","SPACE");this.appendDummyInput("AT");this.appendValueInput("TO").appendField(Blockly.Msg.LISTS_SET_INDEX_INPUT_TO);this.setInputsInline(!0);this.setPreviousStatement(!0);this.setNextStatement(!0);this.setTooltip(Blockly.Msg.LISTS_SET_INDEX_TOOLTIP);this.updateAt_(!0);var b=this;this.setTooltip(function(){var a=b.getFieldValue("MODE"),e=b.getFieldValue("WHERE"),d="";switch(a+" "+e){case "SET FROM_START":case "SET FROM_END":d=
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FROM;break;case "SET FIRST":d=Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FIRST;break;case "SET LAST":d=Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_LAST;break;case "SET RANDOM":d=Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_RANDOM;break;case "INSERT FROM_START":case "INSERT FROM_END":d=Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FROM;break;case "INSERT FIRST":d=Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FIRST;break;case "INSERT LAST":d=Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_LAST;
break;case "INSERT RANDOM":d=Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_RANDOM}if("FROM_START"==e||"FROM_END"==e)d+=" "+Blockly.Msg.LISTS_INDEX_FROM_START_TOOLTIP.replace("%1",b.workspace.options.oneBasedIndex?"#1":"#0");return d})},mutationToDom:function(){var a=document.createElement("mutation"),b=this.getInput("AT").type==Blockly.INPUT_VALUE;a.setAttribute("at",b);return a},domToMutation:function(a){a="false"!=a.getAttribute("at");this.updateAt_(a)},updateAt_:function(a){this.removeInput("AT");
this.removeInput("ORDINAL",!0);a?(this.appendValueInput("AT").setCheck("Number"),Blockly.Msg.ORDINAL_NUMBER_SUFFIX&&this.appendDummyInput("ORDINAL").appendField(Blockly.Msg.ORDINAL_NUMBER_SUFFIX)):this.appendDummyInput("AT");var b=new Blockly.FieldDropdown(this.WHERE_OPTIONS,function(b){var c="FROM_START"==b||"FROM_END"==b;if(c!=a){var d=this.sourceBlock_;d.updateAt_(c);d.setFieldValue(b,"WHERE");return null}});this.moveInputBefore("AT","TO");this.getInput("ORDINAL")&&this.moveInputBefore("ORDINAL",
"TO");this.getInput("AT").appendField(b,"WHERE")}};
Blockly.Blocks.lists_getSublist={init:function(){this.WHERE_OPTIONS_1=[[Blockly.Msg.LISTS_GET_SUBLIST_START_FROM_START,"FROM_START"],[Blockly.Msg.LISTS_GET_SUBLIST_START_FROM_END,"FROM_END"],[Blockly.Msg.LISTS_GET_SUBLIST_START_FIRST,"FIRST"]];this.WHERE_OPTIONS_2=[[Blockly.Msg.LISTS_GET_SUBLIST_END_FROM_START,"FROM_START"],[Blockly.Msg.LISTS_GET_SUBLIST_END_FROM_END,"FROM_END"],[Blockly.Msg.LISTS_GET_SUBLIST_END_LAST,"LAST"]];this.setHelpUrl(Blockly.Msg.LISTS_GET_SUBLIST_HELPURL);this.setColour(Blockly.Msg.LISTS_HUE);
this.appendValueInput("LIST").setCheck("Array").appendField(Blockly.Msg.LISTS_GET_SUBLIST_INPUT_IN_LIST);this.appendDummyInput("AT1");this.appendDummyInput("AT2");Blockly.Msg.LISTS_GET_SUBLIST_TAIL&&this.appendDummyInput("TAIL").appendField(Blockly.Msg.LISTS_GET_SUBLIST_TAIL);this.setInputsInline(!0);this.setOutput(!0,"Array");this.updateAt_(1,!0);this.updateAt_(2,!0);this.setTooltip(Blockly.Msg.LISTS_GET_SUBLIST_TOOLTIP)},mutationToDom:function(){var a=document.createElement("mutation"),b=this.getInput("AT1").type==
Blockly.INPUT_VALUE;a.setAttribute("at1",b);b=this.getInput("AT2").type==Blockly.INPUT_VALUE;a.setAttribute("at2",b);return a},domToMutation:function(a){var b="true"==a.getAttribute("at1");a="true"==a.getAttribute("at2");this.updateAt_(1,b);this.updateAt_(2,a)},updateAt_:function(a,b){this.removeInput("AT"+a);this.removeInput("ORDINAL"+a,!0);b?(this.appendValueInput("AT"+a).setCheck("Number"),Blockly.Msg.ORDINAL_NUMBER_SUFFIX&&this.appendDummyInput("ORDINAL"+a).appendField(Blockly.Msg.ORDINAL_NUMBER_SUFFIX)):
this.appendDummyInput("AT"+a);var c=new Blockly.FieldDropdown(this["WHERE_OPTIONS_"+a],function(c){var d="FROM_START"==c||"FROM_END"==c;if(d!=b){var e=this.sourceBlock_;e.updateAt_(a,d);e.setFieldValue(c,"WHERE"+a);return null}});this.getInput("AT"+a).appendField(c,"WHERE"+a);1==a&&(this.moveInputBefore("AT1","AT2"),this.getInput("ORDINAL1")&&this.moveInputBefore("ORDINAL1","AT2"));Blockly.Msg.LISTS_GET_SUBLIST_TAIL&&this.moveInputBefore("TAIL",null)}};
Blockly.Blocks.lists_sort={init:function(){this.jsonInit({message0:Blockly.Msg.LISTS_SORT_TITLE,args0:[{type:"field_dropdown",name:"TYPE",options:[[Blockly.Msg.LISTS_SORT_TYPE_NUMERIC,"NUMERIC"],[Blockly.Msg.LISTS_SORT_TYPE_TEXT,"TEXT"],[Blockly.Msg.LISTS_SORT_TYPE_IGNORECASE,"IGNORE_CASE"]]},{type:"field_dropdown",name:"DIRECTION",options:[[Blockly.Msg.LISTS_SORT_ORDER_ASCENDING,"1"],[Blockly.Msg.LISTS_SORT_ORDER_DESCENDING,"-1"]]},{type:"input_value",name:"LIST",check:"Array"}],output:"Array",colour:Blockly.Msg.LISTS_HUE,
tooltip:Blockly.Msg.LISTS_SORT_TOOLTIP,helpUrl:Blockly.Msg.LISTS_SORT_HELPURL})}};
Blockly.Blocks.lists_split={init:function(){var a=this,b=new Blockly.FieldDropdown([[Blockly.Msg.LISTS_SPLIT_LIST_FROM_TEXT,"SPLIT"],[Blockly.Msg.LISTS_SPLIT_TEXT_FROM_LIST,"JOIN"]],function(b){a.updateType_(b)});this.setHelpUrl(Blockly.Msg.LISTS_SPLIT_HELPURL);this.setColour(Blockly.Msg.LISTS_HUE);this.appendValueInput("INPUT").setCheck("String").appendField(b,"MODE");this.appendValueInput("DELIM").setCheck("String").appendField(Blockly.Msg.LISTS_SPLIT_WITH_DELIMITER);this.setInputsInline(!0);this.setOutput(!0,
"Array");this.setTooltip(function(){var b=a.getFieldValue("MODE");if("SPLIT"==b)return Blockly.Msg.LISTS_SPLIT_TOOLTIP_SPLIT;if("JOIN"==b)return Blockly.Msg.LISTS_SPLIT_TOOLTIP_JOIN;throw Error("Unknown mode: "+b);})},updateType_:function(a){"SPLIT"==a?(this.outputConnection.setCheck("Array"),this.getInput("INPUT").setCheck("String")):(this.outputConnection.setCheck("String"),this.getInput("INPUT").setCheck("Array"))},mutationToDom:function(){var a=document.createElement("mutation");a.setAttribute("mode",
this.getFieldValue("MODE"));return a},domToMutation:function(a){this.updateType_(a.getAttribute("mode"))}};Blockly.Blocks.logic={};Blockly.Constants.Logic={};Blockly.Constants.Logic.HUE=210;
Blockly.defineBlocksWithJsonArray([{type:"logic_boolean",message0:"%1",args0:[{type:"field_dropdown",name:"BOOL",options:[["%{BKY_LOGIC_BOOLEAN_TRUE}","TRUE"],["%{BKY_LOGIC_BOOLEAN_FALSE}","FALSE"]]}],output:"Boolean",colour:"%{BKY_LOGIC_HUE}",tooltip:"%{BKY_LOGIC_BOOLEAN_TOOLTIP}",helpUrl:"%{BKY_LOGIC_BOOLEAN_HELPURL}"},{type:"controls_if",message0:"%{BKY_CONTROLS_IF_MSG_IF} %1",args0:[{type:"input_value",name:"IF0",check:"Boolean"}],message1:"%{BKY_CONTROLS_IF_MSG_THEN} %1",args1:[{type:"input_statement",
name:"DO0"}],previousStatement:null,nextStatement:null,colour:"%{BKY_LOGIC_HUE}",helpUrl:"%{BKY_CONTROLS_IF_HELPURL}",mutator:"controls_if_mutator",extensions:["controls_if_tooltip"]},{type:"controls_ifelse",message0:"%{BKY_CONTROLS_IF_MSG_IF} %1",args0:[{type:"input_value",name:"IF0",check:"Boolean"}],message1:"%{BKY_CONTROLS_IF_MSG_THEN} %1",args1:[{type:"input_statement",name:"DO0"}],message2:"%{BKY_CONTROLS_IF_MSG_ELSE} %1",args2:[{type:"input_statement",name:"ELSE"}],previousStatement:null,nextStatement:null,
colour:"%{BKY_LOGIC_HUE}",tooltip:"%{BKYCONTROLS_IF_TOOLTIP_2}",helpUrl:"%{BKY_CONTROLS_IF_HELPURL}",extensions:["controls_if_tooltip"]},{type:"logic_compare",message0:"%1 %2 %3",args0:[{type:"input_value",name:"A"},{type:"field_dropdown",name:"OP",options:[["=","EQ"],["\u2260","NEQ"],["\u200f<","LT"],["\u200f\u2264","LTE"],["\u200f>","GT"],["\u200f\u2265","GTE"]]},{type:"input_value",name:"B"}],inputsInline:!0,output:"Boolean",colour:"%{BKY_LOGIC_HUE}",helpUrl:"%{BKY_LOGIC_COMPARE_HELPURL}",extensions:["logic_compare",
"logic_op_tooltip"]},{type:"logic_operation",message0:"%1 %2 %3",args0:[{type:"input_value",name:"A",check:"Boolean"},{type:"field_dropdown",name:"OP",options:[["%{BKY_LOGIC_OPERATION_AND}","AND"],["%{BKY_LOGIC_OPERATION_OR}","OR"]]},{type:"input_value",name:"B",check:"Boolean"}],inputsInline:!0,output:"Boolean",colour:"%{BKY_LOGIC_HUE}",helpUrl:"%{BKY_LOGIC_OPERATION_HELPURL}",extensions:["logic_op_tooltip"]},{type:"logic_negate",message0:"%{BKY_LOGIC_NEGATE_TITLE}",args0:[{type:"input_value",name:"BOOL",
check:"Boolean"}],output:"Boolean",colour:"%{BKY_LOGIC_HUE}",tooltip:"%{BKY_LOGIC_NEGATE_TOOLTIP}",helpUrl:"%{BKY_LOGIC_NEGATE_HELPURL}"},{type:"logic_null",message0:"%{BKY_LOGIC_NULL}",output:null,colour:"%{BKY_LOGIC_HUE}",tooltip:"%{BKY_LOGIC_NULL_TOOLTIP}",helpUrl:"%{BKY_LOGIC_NULL_HELPURL}"},{type:"logic_ternary",message0:"%{BKY_LOGIC_TERNARY_CONDITION} %1",args0:[{type:"input_value",name:"IF",check:"Boolean"}],message1:"%{BKY_LOGIC_TERNARY_IF_TRUE} %1",args1:[{type:"input_value",name:"THEN"}],
message2:"%{BKY_LOGIC_TERNARY_IF_FALSE} %1",args2:[{type:"input_value",name:"ELSE"}],output:null,colour:"%{BKY_LOGIC_HUE}",tooltip:"%{BKY_LOGIC_TERNARY_TOOLTIP}",helpUrl:"%{BKY_LOGIC_TERNARY_HELPURL}",extensions:["logic_ternary"]}]);
Blockly.defineBlocksWithJsonArray([{type:"controls_if_if",message0:"%{BKY_CONTROLS_IF_IF_TITLE_IF}",nextStatement:null,enableContextMenu:!1,colour:"%{BKY_LOGIC_HUE}",tooltip:"%{BKY_CONTROLS_IF_IF_TOOLTIP}"},{type:"controls_if_elseif",message0:"%{BKY_CONTROLS_IF_ELSEIF_TITLE_ELSEIF}",previousStatement:null,nextStatement:null,enableContextMenu:!1,colour:"%{BKY_LOGIC_HUE}",tooltip:"%{BKY_CONTROLS_IF_ELSEIF_TOOLTIP}"},{type:"controls_if_else",message0:"%{BKY_CONTROLS_IF_ELSE_TITLE_ELSE}",previousStatement:null,
enableContextMenu:!1,colour:"%{BKY_LOGIC_HUE}",tooltip:"%{BKY_CONTROLS_IF_ELSE_TOOLTIP}"}]);Blockly.Constants.Logic.TOOLTIPS_BY_OP={EQ:"%{BKY_LOGIC_COMPARE_TOOLTIP_EQ}",NEQ:"%{BKY_LOGIC_COMPARE_TOOLTIP_NEQ}",LT:"%{BKY_LOGIC_COMPARE_TOOLTIP_LT}",LTE:"%{BKY_LOGIC_COMPARE_TOOLTIP_LTE}",GT:"%{BKY_LOGIC_COMPARE_TOOLTIP_GT}",GTE:"%{BKY_LOGIC_COMPARE_TOOLTIP_GTE}",AND:"%{BKY_LOGIC_OPERATION_TOOLTIP_AND}",OR:"%{BKY_LOGIC_OPERATION_TOOLTIP_OR}"};
Blockly.Extensions.register("logic_op_tooltip",Blockly.Extensions.buildTooltipForDropdown("OP",Blockly.Constants.Logic.TOOLTIPS_BY_OP));
Blockly.Constants.Logic.CONTROLS_IF_MUTATOR_MIXIN={elseifCount_:0,elseCount_:0,mutationToDom:function(){if(!this.elseifCount_&&!this.elseCount_)return null;var a=document.createElement("mutation");this.elseifCount_&&a.setAttribute("elseif",this.elseifCount_);this.elseCount_&&a.setAttribute("else",1);return a},domToMutation:function(a){this.elseifCount_=parseInt(a.getAttribute("elseif"),10)||0;this.elseCount_=parseInt(a.getAttribute("else"),10)||0;this.updateShape_()},decompose:function(a){var b=a.newBlock("controls_if_if");
b.initSvg();for(var c=b.nextConnection,e=1;e<=this.elseifCount_;e++){var d=a.newBlock("controls_if_elseif");d.initSvg();c.connect(d.previousConnection);c=d.nextConnection}this.elseCount_&&(a=a.newBlock("controls_if_else"),a.initSvg(),c.connect(a.previousConnection));return b},compose:function(a){var b=a.nextConnection.targetBlock();this.elseCount_=this.elseifCount_=0;a=[null];for(var c=[null],e=null;b;){switch(b.type){case "controls_if_elseif":this.elseifCount_++;a.push(b.valueConnection_);c.push(b.statementConnection_);
break;case "controls_if_else":this.elseCount_++;e=b.statementConnection_;break;default:throw TypeError("Unknown block type: "+b.type);}b=b.nextConnection&&b.nextConnection.targetBlock()}this.updateShape_();for(b=1;b<=this.elseifCount_;b++)Blockly.Mutator.reconnect(a[b],this,"IF"+b),Blockly.Mutator.reconnect(c[b],this,"DO"+b);Blockly.Mutator.reconnect(e,this,"ELSE")},saveConnections:function(a){a=a.nextConnection.targetBlock();for(var b=1;a;){switch(a.type){case "controls_if_elseif":var c=this.getInput("IF"+
b),e=this.getInput("DO"+b);a.valueConnection_=c&&c.connection.targetConnection;a.statementConnection_=e&&e.connection.targetConnection;b++;break;case "controls_if_else":e=this.getInput("ELSE");a.statementConnection_=e&&e.connection.targetConnection;break;default:throw TypeError("Unknown block type: "+a.type);}a=a.nextConnection&&a.nextConnection.targetBlock()}},updateShape_:function(){this.getInput("ELSE")&&this.removeInput("ELSE");for(var a=1;this.getInput("IF"+a);)this.removeInput("IF"+a),this.removeInput("DO"+
a),a++;for(a=1;a<=this.elseifCount_;a++)this.appendValueInput("IF"+a).setCheck("Boolean").appendField(Blockly.Msg.CONTROLS_IF_MSG_ELSEIF),this.appendStatementInput("DO"+a).appendField(Blockly.Msg.CONTROLS_IF_MSG_THEN);this.elseCount_&&this.appendStatementInput("ELSE").appendField(Blockly.Msg.CONTROLS_IF_MSG_ELSE)}};Blockly.Extensions.registerMutator("controls_if_mutator",Blockly.Constants.Logic.CONTROLS_IF_MUTATOR_MIXIN,null,["controls_if_elseif","controls_if_else"]);
Blockly.Constants.Logic.CONTROLS_IF_TOOLTIP_EXTENSION=function(){this.setTooltip(function(){if(this.elseifCount_||this.elseCount_){if(!this.elseifCount_&&this.elseCount_)return Blockly.Msg.CONTROLS_IF_TOOLTIP_2;if(this.elseifCount_&&!this.elseCount_)return Blockly.Msg.CONTROLS_IF_TOOLTIP_3;if(this.elseifCount_&&this.elseCount_)return Blockly.Msg.CONTROLS_IF_TOOLTIP_4}else return Blockly.Msg.CONTROLS_IF_TOOLTIP_1;return""}.bind(this))};Blockly.Extensions.register("controls_if_tooltip",Blockly.Constants.Logic.CONTROLS_IF_TOOLTIP_EXTENSION);
Blockly.Constants.Logic.LOGIC_COMPARE_ONCHANGE_MIXIN={onchange:function(a){this.prevBlocks_||(this.prevBlocks_=[null,null]);var b=this.getInputTargetBlock("A"),c=this.getInputTargetBlock("B");b&&c&&!b.outputConnection.checkType_(c.outputConnection)&&(Blockly.Events.setGroup(a.group),a=this.prevBlocks_[0],a!==b&&(b.unplug(),a&&!a.isShadow()&&this.getInput("A").connection.connect(a.outputConnection)),b=this.prevBlocks_[1],b!==c&&(c.unplug(),b&&!b.isShadow()&&this.getInput("B").connection.connect(b.outputConnection)),
this.bumpNeighbours_(),Blockly.Events.setGroup(!1));this.prevBlocks_[0]=this.getInputTargetBlock("A");this.prevBlocks_[1]=this.getInputTargetBlock("B")}};Blockly.Constants.Logic.LOGIC_COMPARE_EXTENSION=function(){this.mixin(Blockly.Constants.Logic.LOGIC_COMPARE_ONCHANGE_MIXIN)};Blockly.Extensions.register("logic_compare",Blockly.Constants.Logic.LOGIC_COMPARE_EXTENSION);
Blockly.Constants.Logic.LOGIC_TERNARY_ONCHANGE_MIXIN={prevParentConnection_:null,onchange:function(a){var b=this.getInputTargetBlock("THEN"),c=this.getInputTargetBlock("ELSE"),e=this.outputConnection.targetConnection;if((b||c)&&e)for(var d=0;2>d;d++){var f=1==d?b:c;f&&!f.outputConnection.checkType_(e)&&(Blockly.Events.setGroup(a.group),e===this.prevParentConnection_?(this.unplug(),e.getSourceBlock().bumpNeighbours_()):(f.unplug(),f.bumpNeighbours_()),Blockly.Events.setGroup(!1))}this.prevParentConnection_=
e}};Blockly.Extensions.registerMixin("logic_ternary",Blockly.Constants.Logic.LOGIC_TERNARY_ONCHANGE_MIXIN);Blockly.Blocks.loops={};Blockly.Constants.Loops={};Blockly.Constants.Loops.HUE=120;
Blockly.defineBlocksWithJsonArray([{type:"controls_repeat_ext",message0:"%{BKY_CONTROLS_REPEAT_TITLE}",args0:[{type:"input_value",name:"TIMES",check:"Number"}],message1:"%{BKY_CONTROLS_REPEAT_INPUT_DO} %1",args1:[{type:"input_statement",name:"DO"}],previousStatement:null,nextStatement:null,colour:"%{BKY_LOOPS_HUE}",tooltip:"%{BKY_CONTROLS_REPEAT_TOOLTIP}",helpUrl:"%{BKY_CONTROLS_REPEAT_HELPURL}"},{type:"controls_repeat",message0:"%{BKY_CONTROLS_REPEAT_TITLE}",args0:[{type:"field_number",name:"TIMES",
value:10,min:0,precision:1}],message1:"%{BKY_CONTROLS_REPEAT_INPUT_DO} %1",args1:[{type:"input_statement",name:"DO"}],previousStatement:null,nextStatement:null,colour:"%{BKY_LOOPS_HUE}",tooltip:"%{BKY_CONTROLS_REPEAT_TOOLTIP}",helpUrl:"%{BKY_CONTROLS_REPEAT_HELPURL}"},{type:"controls_whileUntil",message0:"%1 %2",args0:[{type:"field_dropdown",name:"MODE",options:[["%{BKY_CONTROLS_WHILEUNTIL_OPERATOR_WHILE}","WHILE"],["%{BKY_CONTROLS_WHILEUNTIL_OPERATOR_UNTIL}","UNTIL"]]},{type:"input_value",name:"BOOL",
check:"Boolean"}],message1:"%{BKY_CONTROLS_REPEAT_INPUT_DO} %1",args1:[{type:"input_statement",name:"DO"}],previousStatement:null,nextStatement:null,colour:"%{BKY_LOOPS_HUE}",helpUrl:"%{BKY_CONTROLS_WHILEUNTIL_HELPURL}",extensions:["controls_whileUntil_tooltip"]},{type:"controls_for",message0:"%{BKY_CONTROLS_FOR_TITLE}",args0:[{type:"field_variable",name:"VAR",variable:null},{type:"input_value",name:"FROM",check:"Number",align:"RIGHT"},{type:"input_value",name:"TO",check:"Number",align:"RIGHT"},{type:"input_value",
name:"BY",check:"Number",align:"RIGHT"}],message1:"%{BKY_CONTROLS_REPEAT_INPUT_DO} %1",args1:[{type:"input_statement",name:"DO"}],inputsInline:!0,previousStatement:null,nextStatement:null,colour:"%{BKY_LOOPS_HUE}",helpUrl:"%{BKY_CONTROLS_FOR_HELPURL}",extensions:["contextMenu_newGetVariableBlock","controls_for_tooltip"]},{type:"controls_forEach",message0:"%{BKY_CONTROLS_FOREACH_TITLE}",args0:[{type:"field_variable",name:"VAR",variable:null},{type:"input_value",name:"LIST",check:"Array"}],message1:"%{BKY_CONTROLS_REPEAT_INPUT_DO} %1",
args1:[{type:"input_statement",name:"DO"}],previousStatement:null,nextStatement:null,colour:"%{BKY_LOOPS_HUE}",helpUrl:"%{BKY_CONTROLS_FOREACH_HELPURL}",extensions:["contextMenu_newGetVariableBlock","controls_forEach_tooltip"]},{type:"controls_flow_statements",message0:"%1",args0:[{type:"field_dropdown",name:"FLOW",options:[["%{BKY_CONTROLS_FLOW_STATEMENTS_OPERATOR_BREAK}","BREAK"],["%{BKY_CONTROLS_FLOW_STATEMENTS_OPERATOR_CONTINUE}","CONTINUE"]]}],previousStatement:null,colour:"%{BKY_LOOPS_HUE}",
helpUrl:"%{BKY_CONTROLS_FLOW_STATEMENTS_HELPURL}",extensions:["controls_flow_tooltip","controls_flow_in_loop_check"]}]);Blockly.Constants.Loops.WHILE_UNTIL_TOOLTIPS={WHILE:"%{BKY_CONTROLS_WHILEUNTIL_TOOLTIP_WHILE}",UNTIL:"%{BKY_CONTROLS_WHILEUNTIL_TOOLTIP_UNTIL}"};Blockly.Extensions.register("controls_whileUntil_tooltip",Blockly.Extensions.buildTooltipForDropdown("MODE",Blockly.Constants.Loops.WHILE_UNTIL_TOOLTIPS));
Blockly.Constants.Loops.BREAK_CONTINUE_TOOLTIPS={BREAK:"%{BKY_CONTROLS_FLOW_STATEMENTS_TOOLTIP_BREAK}",CONTINUE:"%{BKY_CONTROLS_FLOW_STATEMENTS_TOOLTIP_CONTINUE}"};Blockly.Extensions.register("controls_flow_tooltip",Blockly.Extensions.buildTooltipForDropdown("FLOW",Blockly.Constants.Loops.BREAK_CONTINUE_TOOLTIPS));
Blockly.Constants.Loops.CUSTOM_CONTEXT_MENU_CREATE_VARIABLES_GET_MIXIN={customContextMenu:function(a){if(!this.isInFlyout){var b=this.getField("VAR").getVariable(),c=b.name;if(!this.isCollapsed()&&null!=c){var e={enabled:!0};e.text=Blockly.Msg.VARIABLES_SET_CREATE_GET.replace("%1",c);b=Blockly.Variables.generateVariableFieldDom(b);c=document.createElement("block");c.setAttribute("type","variables_get");c.appendChild(b);e.callback=Blockly.ContextMenu.callbackFactory(this,c);a.push(e)}}}};
Blockly.Extensions.registerMixin("contextMenu_newGetVariableBlock",Blockly.Constants.Loops.CUSTOM_CONTEXT_MENU_CREATE_VARIABLES_GET_MIXIN);Blockly.Extensions.register("controls_for_tooltip",Blockly.Extensions.buildTooltipWithFieldText("%{BKY_CONTROLS_FOR_TOOLTIP}","VAR"));Blockly.Extensions.register("controls_forEach_tooltip",Blockly.Extensions.buildTooltipWithFieldText("%{BKY_CONTROLS_FOREACH_TOOLTIP}","VAR"));
Blockly.Constants.Loops.CONTROL_FLOW_IN_LOOP_CHECK_MIXIN={LOOP_TYPES:["controls_repeat","controls_repeat_ext","controls_forEach","controls_for","controls_whileUntil"],onchange:function(){if(this.workspace.isDragging&&!this.workspace.isDragging()){var a=!1,b=this;do{if(-1!=this.LOOP_TYPES.indexOf(b.type)){a=!0;break}b=b.getSurroundParent()}while(b);a?(this.setWarningText(null),this.isInFlyout||this.setDisabled(!1)):(this.setWarningText(Blockly.Msg.CONTROLS_FLOW_STATEMENTS_WARNING),this.isInFlyout||
this.getInheritedDisabled()||this.setDisabled(!0))}}};Blockly.Extensions.registerMixin("controls_flow_in_loop_check",Blockly.Constants.Loops.CONTROL_FLOW_IN_LOOP_CHECK_MIXIN);Blockly.Blocks.math={};Blockly.Constants.Math={};Blockly.Constants.Math.HUE=230;
Blockly.defineBlocksWithJsonArray([{type:"math_number",message0:"%1",args0:[{type:"field_number",name:"NUM",value:0}],output:"Number",colour:"%{BKY_MATH_HUE}",helpUrl:"%{BKY_MATH_NUMBER_HELPURL}",tooltip:"%{BKY_MATH_NUMBER_TOOLTIP}",extensions:["parent_tooltip_when_inline"]},{type:"math_arithmetic",message0:"%1 %2 %3",args0:[{type:"input_value",name:"A",check:"Number"},{type:"field_dropdown",name:"OP",options:[["%{BKY_MATH_ADDITION_SYMBOL}","ADD"],["%{BKY_MATH_SUBTRACTION_SYMBOL}","MINUS"],["%{BKY_MATH_MULTIPLICATION_SYMBOL}",
"MULTIPLY"],["%{BKY_MATH_DIVISION_SYMBOL}","DIVIDE"],["%{BKY_MATH_POWER_SYMBOL}","POWER"]]},{type:"input_value",name:"B",check:"Number"}],inputsInline:!0,output:"Number",colour:"%{BKY_MATH_HUE}",helpUrl:"%{BKY_MATH_ARITHMETIC_HELPURL}",extensions:["math_op_tooltip"]},{type:"math_single",message0:"%1 %2",args0:[{type:"field_dropdown",name:"OP",options:[["%{BKY_MATH_SINGLE_OP_ROOT}","ROOT"],["%{BKY_MATH_SINGLE_OP_ABSOLUTE}","ABS"],["-","NEG"],["ln","LN"],["log10","LOG10"],["e^","EXP"],["10^","POW10"]]},
{type:"input_value",name:"NUM",check:"Number"}],output:"Number",colour:"%{BKY_MATH_HUE}",helpUrl:"%{BKY_MATH_SINGLE_HELPURL}",extensions:["math_op_tooltip"]},{type:"math_trig",message0:"%1 %2",args0:[{type:"field_dropdown",name:"OP",options:[["%{BKY_MATH_TRIG_SIN}","SIN"],["%{BKY_MATH_TRIG_COS}","COS"],["%{BKY_MATH_TRIG_TAN}","TAN"],["%{BKY_MATH_TRIG_ASIN}","ASIN"],["%{BKY_MATH_TRIG_ACOS}","ACOS"],["%{BKY_MATH_TRIG_ATAN}","ATAN"]]},{type:"input_value",name:"NUM",check:"Number"}],output:"Number",colour:"%{BKY_MATH_HUE}",
helpUrl:"%{BKY_MATH_TRIG_HELPURL}",extensions:["math_op_tooltip"]},{type:"math_constant",message0:"%1",args0:[{type:"field_dropdown",name:"CONSTANT",options:[["\u03c0","PI"],["e","E"],["\u03c6","GOLDEN_RATIO"],["sqrt(2)","SQRT2"],["sqrt(\u00bd)","SQRT1_2"],["\u221e","INFINITY"]]}],output:"Number",colour:"%{BKY_MATH_HUE}",tooltip:"%{BKY_MATH_CONSTANT_TOOLTIP}",helpUrl:"%{BKY_MATH_CONSTANT_HELPURL}"},{type:"math_number_property",message0:"%1 %2",args0:[{type:"input_value",name:"NUMBER_TO_CHECK",check:"Number"},
{type:"field_dropdown",name:"PROPERTY",options:[["%{BKY_MATH_IS_EVEN}","EVEN"],["%{BKY_MATH_IS_ODD}","ODD"],["%{BKY_MATH_IS_PRIME}","PRIME"],["%{BKY_MATH_IS_WHOLE}","WHOLE"],["%{BKY_MATH_IS_POSITIVE}","POSITIVE"],["%{BKY_MATH_IS_NEGATIVE}","NEGATIVE"],["%{BKY_MATH_IS_DIVISIBLE_BY}","DIVISIBLE_BY"]]}],inputsInline:!0,output:"Boolean",colour:"%{BKY_MATH_HUE}",tooltip:"%{BKY_MATH_IS_TOOLTIP}",mutator:"math_is_divisibleby_mutator"},{type:"math_change",message0:"%{BKY_MATH_CHANGE_TITLE}",args0:[{type:"field_variable",
name:"VAR",variable:"%{BKY_MATH_CHANGE_TITLE_ITEM}"},{type:"input_value",name:"DELTA",check:"Number"}],previousStatement:null,nextStatement:null,colour:"%{BKY_VARIABLES_HUE}",helpUrl:"%{BKY_MATH_CHANGE_HELPURL}",extensions:["math_change_tooltip"]},{type:"math_round",message0:"%1 %2",args0:[{type:"field_dropdown",name:"OP",options:[["%{BKY_MATH_ROUND_OPERATOR_ROUND}","ROUND"],["%{BKY_MATH_ROUND_OPERATOR_ROUNDUP}","ROUNDUP"],["%{BKY_MATH_ROUND_OPERATOR_ROUNDDOWN}","ROUNDDOWN"]]},{type:"input_value",
name:"NUM",check:"Number"}],output:"Number",colour:"%{BKY_MATH_HUE}",helpUrl:"%{BKY_MATH_ROUND_HELPURL}",tooltip:"%{BKY_MATH_ROUND_TOOLTIP}"},{type:"math_on_list",message0:"%1 %2",args0:[{type:"field_dropdown",name:"OP",options:[["%{BKY_MATH_ONLIST_OPERATOR_SUM}","SUM"],["%{BKY_MATH_ONLIST_OPERATOR_MIN}","MIN"],["%{BKY_MATH_ONLIST_OPERATOR_MAX}","MAX"],["%{BKY_MATH_ONLIST_OPERATOR_AVERAGE}","AVERAGE"],["%{BKY_MATH_ONLIST_OPERATOR_MEDIAN}","MEDIAN"],["%{BKY_MATH_ONLIST_OPERATOR_MODE}","MODE"],["%{BKY_MATH_ONLIST_OPERATOR_STD_DEV}",
"STD_DEV"],["%{BKY_MATH_ONLIST_OPERATOR_RANDOM}","RANDOM"]]},{type:"input_value",name:"LIST",check:"Array"}],output:"Number",colour:"%{BKY_MATH_HUE}",helpUrl:"%{BKY_MATH_ONLIST_HELPURL}",mutator:"math_modes_of_list_mutator",extensions:["math_op_tooltip"]},{type:"math_modulo",message0:"%{BKY_MATH_MODULO_TITLE}",args0:[{type:"input_value",name:"DIVIDEND",check:"Number"},{type:"input_value",name:"DIVISOR",check:"Number"}],inputsInline:!0,output:"Number",colour:"%{BKY_MATH_HUE}",tooltip:"%{BKY_MATH_MODULO_TOOLTIP}",
helpUrl:"%{BKY_MATH_MODULO_HELPURL}"},{type:"math_constrain",message0:"%{BKY_MATH_CONSTRAIN_TITLE}",args0:[{type:"input_value",name:"VALUE",check:"Number"},{type:"input_value",name:"LOW",check:"Number"},{type:"input_value",name:"HIGH",check:"Number"}],inputsInline:!0,output:"Number",colour:"%{BKY_MATH_HUE}",tooltip:"%{BKY_MATH_CONSTRAIN_TOOLTIP}",helpUrl:"%{BKY_MATH_CONSTRAIN_HELPURL}"},{type:"math_random_int",message0:"%{BKY_MATH_RANDOM_INT_TITLE}",args0:[{type:"input_value",name:"FROM",check:"Number"},
{type:"input_value",name:"TO",check:"Number"}],inputsInline:!0,output:"Number",colour:"%{BKY_MATH_HUE}",tooltip:"%{BKY_MATH_RANDOM_INT_TOOLTIP}",helpUrl:"%{BKY_MATH_RANDOM_INT_HELPURL}"},{type:"math_random_float",message0:"%{BKY_MATH_RANDOM_FLOAT_TITLE_RANDOM}",output:"Number",colour:"%{BKY_MATH_HUE}",tooltip:"%{BKY_MATH_RANDOM_FLOAT_TOOLTIP}",helpUrl:"%{BKY_MATH_RANDOM_FLOAT_HELPURL}"}]);
Blockly.Constants.Math.TOOLTIPS_BY_OP={ADD:"%{BKY_MATH_ARITHMETIC_TOOLTIP_ADD}",MINUS:"%{BKY_MATH_ARITHMETIC_TOOLTIP_MINUS}",MULTIPLY:"%{BKY_MATH_ARITHMETIC_TOOLTIP_MULTIPLY}",DIVIDE:"%{BKY_MATH_ARITHMETIC_TOOLTIP_DIVIDE}",POWER:"%{BKY_MATH_ARITHMETIC_TOOLTIP_POWER}",ROOT:"%{BKY_MATH_SINGLE_TOOLTIP_ROOT}",ABS:"%{BKY_MATH_SINGLE_TOOLTIP_ABS}",NEG:"%{BKY_MATH_SINGLE_TOOLTIP_NEG}",LN:"%{BKY_MATH_SINGLE_TOOLTIP_LN}",LOG10:"%{BKY_MATH_SINGLE_TOOLTIP_LOG10}",EXP:"%{BKY_MATH_SINGLE_TOOLTIP_EXP}",POW10:"%{BKY_MATH_SINGLE_TOOLTIP_POW10}",
SIN:"%{BKY_MATH_TRIG_TOOLTIP_SIN}",COS:"%{BKY_MATH_TRIG_TOOLTIP_COS}",TAN:"%{BKY_MATH_TRIG_TOOLTIP_TAN}",ASIN:"%{BKY_MATH_TRIG_TOOLTIP_ASIN}",ACOS:"%{BKY_MATH_TRIG_TOOLTIP_ACOS}",ATAN:"%{BKY_MATH_TRIG_TOOLTIP_ATAN}",SUM:"%{BKY_MATH_ONLIST_TOOLTIP_SUM}",MIN:"%{BKY_MATH_ONLIST_TOOLTIP_MIN}",MAX:"%{BKY_MATH_ONLIST_TOOLTIP_MAX}",AVERAGE:"%{BKY_MATH_ONLIST_TOOLTIP_AVERAGE}",MEDIAN:"%{BKY_MATH_ONLIST_TOOLTIP_MEDIAN}",MODE:"%{BKY_MATH_ONLIST_TOOLTIP_MODE}",STD_DEV:"%{BKY_MATH_ONLIST_TOOLTIP_STD_DEV}",RANDOM:"%{BKY_MATH_ONLIST_TOOLTIP_RANDOM}"};
Blockly.Extensions.register("math_op_tooltip",Blockly.Extensions.buildTooltipForDropdown("OP",Blockly.Constants.Math.TOOLTIPS_BY_OP));
Blockly.Constants.Math.IS_DIVISIBLEBY_MUTATOR_MIXIN={mutationToDom:function(){var a=document.createElement("mutation"),b="DIVISIBLE_BY"==this.getFieldValue("PROPERTY");a.setAttribute("divisor_input",b);return a},domToMutation:function(a){a="true"==a.getAttribute("divisor_input");this.updateShape_(a)},updateShape_:function(a){var b=this.getInput("DIVISOR");a?b||this.appendValueInput("DIVISOR").setCheck("Number"):b&&this.removeInput("DIVISOR")}};
Blockly.Constants.Math.IS_DIVISIBLE_MUTATOR_EXTENSION=function(){this.getField("PROPERTY").setValidator(function(a){this.sourceBlock_.updateShape_("DIVISIBLE_BY"==a)})};Blockly.Extensions.registerMutator("math_is_divisibleby_mutator",Blockly.Constants.Math.IS_DIVISIBLEBY_MUTATOR_MIXIN,Blockly.Constants.Math.IS_DIVISIBLE_MUTATOR_EXTENSION);Blockly.Extensions.register("math_change_tooltip",Blockly.Extensions.buildTooltipWithFieldText("%{BKY_MATH_CHANGE_TOOLTIP}","VAR"));
Blockly.Constants.Math.LIST_MODES_MUTATOR_MIXIN={updateType_:function(a){"MODE"==a?this.outputConnection.setCheck("Array"):this.outputConnection.setCheck("Number")},mutationToDom:function(){var a=document.createElement("mutation");a.setAttribute("op",this.getFieldValue("OP"));return a},domToMutation:function(a){this.updateType_(a.getAttribute("op"))}};Blockly.Constants.Math.LIST_MODES_MUTATOR_EXTENSION=function(){this.getField("OP").setValidator(function(a){this.updateType_(a)}.bind(this))};
Blockly.Extensions.registerMutator("math_modes_of_list_mutator",Blockly.Constants.Math.LIST_MODES_MUTATOR_MIXIN,Blockly.Constants.Math.LIST_MODES_MUTATOR_EXTENSION);Blockly.Blocks.procedures={};
Blockly.Blocks.procedures_defnoreturn={init:function(){var a=new Blockly.FieldTextInput("",Blockly.Procedures.rename);a.setSpellcheck(!1);this.appendDummyInput().appendField(Blockly.Msg.PROCEDURES_DEFNORETURN_TITLE).appendField(a,"NAME").appendField("","PARAMS");this.setMutator(new Blockly.Mutator(["procedures_mutatorarg"]));(this.workspace.options.comments||this.workspace.options.parentWorkspace&&this.workspace.options.parentWorkspace.options.comments)&&Blockly.Msg.PROCEDURES_DEFNORETURN_COMMENT&&this.setCommentText(Blockly.Msg.PROCEDURES_DEFNORETURN_COMMENT);
this.setColour(Blockly.Msg.PROCEDURES_HUE);this.setTooltip(Blockly.Msg.PROCEDURES_DEFNORETURN_TOOLTIP);this.setHelpUrl(Blockly.Msg.PROCEDURES_DEFNORETURN_HELPURL);this.arguments_=[];this.argumentVarModels_=[];this.setStatements_(!0);this.statementConnection_=null},setStatements_:function(a){this.hasStatements_!==a&&(a?(this.appendStatementInput("STACK").appendField(Blockly.Msg.PROCEDURES_DEFNORETURN_DO),this.getInput("RETURN")&&this.moveInputBefore("STACK","RETURN")):this.removeInput("STACK",!0),
this.hasStatements_=a)},updateParams_:function(){for(var a=!1,b={},c=0;c<this.arguments_.length;c++){if(b["arg_"+this.arguments_[c].toLowerCase()]){a=!0;break}b["arg_"+this.arguments_[c].toLowerCase()]=!0}a?this.setWarningText(Blockly.Msg.PROCEDURES_DEF_DUPLICATE_WARNING):this.setWarningText(null);a="";this.arguments_.length&&(a=Blockly.Msg.PROCEDURES_BEFORE_PARAMS+" "+this.arguments_.join(", "));Blockly.Events.disable();try{this.setFieldValue(a,"PARAMS")}finally{Blockly.Events.enable()}},mutationToDom:function(a){var b=
document.createElement("mutation");a&&b.setAttribute("name",this.getFieldValue("NAME"));for(var c=0;c<this.argumentVarModels_.length;c++){var e=document.createElement("arg"),d=this.argumentVarModels_[c];e.setAttribute("name",d.name);e.setAttribute("varid",d.getId());a&&this.paramIds_&&e.setAttribute("paramId",this.paramIds_[c]);b.appendChild(e)}this.hasStatements_||b.setAttribute("statements","false");return b},domToMutation:function(a){this.arguments_=[];this.argumentVarModels_=[];for(var b=0,c;c=
a.childNodes[b];b++)if("arg"==c.nodeName.toLowerCase()){var e=c.getAttribute("name");c=c.getAttribute("varid")||c.getAttribute("varId");this.arguments_.push(e);e=Blockly.Variables.getOrCreateVariablePackage(this.workspace,c,e,"");this.argumentVarModels_.push(e)}this.updateParams_();Blockly.Procedures.mutateCallers(this);this.setStatements_("false"!==a.getAttribute("statements"))},decompose:function(a){var b=a.newBlock("procedures_mutatorcontainer");b.initSvg();this.getInput("RETURN")?b.setFieldValue(this.hasStatements_?
"TRUE":"FALSE","STATEMENTS"):b.getInput("STATEMENT_INPUT").setVisible(!1);for(var c=b.getInput("STACK").connection,e=0;e<this.arguments_.length;e++){var d=a.newBlock("procedures_mutatorarg");d.initSvg();d.setFieldValue(this.arguments_[e],"NAME");d.oldLocation=e;c.connect(d.previousConnection);c=d.nextConnection}Blockly.Procedures.mutateCallers(this);return b},compose:function(a){this.arguments_=[];this.paramIds_=[];this.argumentVarModels_=[];for(var b=a.getInputTargetBlock("STACK");b;){var c=b.getFieldValue("NAME");
this.arguments_.push(c);c=this.workspace.getVariable(c,"");this.argumentVarModels_.push(c);this.paramIds_.push(b.id);b=b.nextConnection&&b.nextConnection.targetBlock()}this.updateParams_();Blockly.Procedures.mutateCallers(this);a=a.getFieldValue("STATEMENTS");if(null!==a&&(a="TRUE"==a,this.hasStatements_!=a))if(a)this.setStatements_(!0),Blockly.Mutator.reconnect(this.statementConnection_,this,"STACK"),this.statementConnection_=null;else{a=this.getInput("STACK").connection;if(this.statementConnection_=
a.targetConnection)a=a.targetBlock(),a.unplug(),a.bumpNeighbours_();this.setStatements_(!1)}},getProcedureDef:function(){return[this.getFieldValue("NAME"),this.arguments_,!1]},getVars:function(){return this.arguments_},getVarModels:function(){return this.argumentVarModels_},renameVarById:function(a,b){var c=this.workspace.getVariableById(a);if(""==c.type){c=c.name;for(var e=this.workspace.getVariableById(b),d=!1,f=0;f<this.argumentVarModels_.length;f++)this.argumentVarModels_[f].getId()==a&&(this.arguments_[f]=
e.name,this.argumentVarModels_[f]=e,d=!0);d&&this.displayRenamedVar_(c,e.name)}},updateVarName:function(a){for(var b=a.name,c=!1,e=0;e<this.argumentVarModels_.length;e++)if(this.argumentVarModels_[e].getId()==a.getId()){var d=this.arguments_[e];this.arguments_[e]=b;c=!0}c&&this.displayRenamedVar_(d,b)},displayRenamedVar_:function(a,b){this.updateParams_();if(this.mutator.isVisible())for(var c=this.mutator.workspace_.getAllBlocks(),e=0,d;d=c[e];e++)"procedures_mutatorarg"==d.type&&Blockly.Names.equals(a,
d.getFieldValue("NAME"))&&d.setFieldValue(b,"NAME")},customContextMenu:function(a){if(!this.isInFlyout){var b={enabled:!0},c=this.getFieldValue("NAME");b.text=Blockly.Msg.PROCEDURES_CREATE_DO.replace("%1",c);var e=document.createElement("mutation");e.setAttribute("name",c);for(var d=0;d<this.arguments_.length;d++)c=document.createElement("arg"),c.setAttribute("name",this.arguments_[d]),e.appendChild(c);c=document.createElement("block");c.setAttribute("type",this.callType_);c.appendChild(e);b.callback=
Blockly.ContextMenu.callbackFactory(this,c);a.push(b);if(!this.isCollapsed())for(d=0;d<this.argumentVarModels_.length;d++)b={enabled:!0},e=this.argumentVarModels_[d],c=e.name,b.text=Blockly.Msg.VARIABLES_SET_CREATE_GET.replace("%1",c),e=Blockly.Variables.generateVariableFieldDom(e),c=document.createElement("block"),c.setAttribute("type","variables_get"),c.appendChild(e),b.callback=Blockly.ContextMenu.callbackFactory(this,c),a.push(b)}},callType_:"procedures_callnoreturn"};
Blockly.Blocks.procedures_defreturn={init:function(){var a=new Blockly.FieldTextInput("",Blockly.Procedures.rename);a.setSpellcheck(!1);this.appendDummyInput().appendField(Blockly.Msg.PROCEDURES_DEFRETURN_TITLE).appendField(a,"NAME").appendField("","PARAMS");this.appendValueInput("RETURN").setAlign(Blockly.ALIGN_RIGHT).appendField(Blockly.Msg.PROCEDURES_DEFRETURN_RETURN);this.setMutator(new Blockly.Mutator(["procedures_mutatorarg"]));(this.workspace.options.comments||this.workspace.options.parentWorkspace&&
this.workspace.options.parentWorkspace.options.comments)&&Blockly.Msg.PROCEDURES_DEFRETURN_COMMENT&&this.setCommentText(Blockly.Msg.PROCEDURES_DEFRETURN_COMMENT);this.setColour(Blockly.Msg.PROCEDURES_HUE);this.setTooltip(Blockly.Msg.PROCEDURES_DEFRETURN_TOOLTIP);this.setHelpUrl(Blockly.Msg.PROCEDURES_DEFRETURN_HELPURL);this.arguments_=[];this.argumentVarModels_=[];this.setStatements_(!0);this.statementConnection_=null},setStatements_:Blockly.Blocks.procedures_defnoreturn.setStatements_,updateParams_:Blockly.Blocks.procedures_defnoreturn.updateParams_,
mutationToDom:Blockly.Blocks.procedures_defnoreturn.mutationToDom,domToMutation:Blockly.Blocks.procedures_defnoreturn.domToMutation,decompose:Blockly.Blocks.procedures_defnoreturn.decompose,compose:Blockly.Blocks.procedures_defnoreturn.compose,getProcedureDef:function(){return[this.getFieldValue("NAME"),this.arguments_,!0]},getVars:Blockly.Blocks.procedures_defnoreturn.getVars,getVarModels:Blockly.Blocks.procedures_defnoreturn.getVarModels,renameVarById:Blockly.Blocks.procedures_defnoreturn.renameVarById,
updateVarName:Blockly.Blocks.procedures_defnoreturn.updateVarName,displayRenamedVar_:Blockly.Blocks.procedures_defnoreturn.displayRenamedVar_,customContextMenu:Blockly.Blocks.procedures_defnoreturn.customContextMenu,callType_:"procedures_callreturn"};
Blockly.Blocks.procedures_mutatorcontainer={init:function(){this.appendDummyInput().appendField(Blockly.Msg.PROCEDURES_MUTATORCONTAINER_TITLE);this.appendStatementInput("STACK");this.appendDummyInput("STATEMENT_INPUT").appendField(Blockly.Msg.PROCEDURES_ALLOW_STATEMENTS).appendField(new Blockly.FieldCheckbox("TRUE"),"STATEMENTS");this.setColour(Blockly.Msg.PROCEDURES_HUE);this.setTooltip(Blockly.Msg.PROCEDURES_MUTATORCONTAINER_TOOLTIP);this.contextMenu=!1}};
Blockly.Blocks.procedures_mutatorarg={init:function(){var a=new Blockly.FieldTextInput("x",this.validator_);a.oldShowEditorFn_=a.showEditor_;a.showEditor_=function(){this.createdVariables_=[];this.oldShowEditorFn_()};this.appendDummyInput().appendField(Blockly.Msg.PROCEDURES_MUTATORARG_TITLE).appendField(a,"NAME");this.setPreviousStatement(!0);this.setNextStatement(!0);this.setColour(Blockly.Msg.PROCEDURES_HUE);this.setTooltip(Blockly.Msg.PROCEDURES_MUTATORARG_TOOLTIP);this.contextMenu=!1;a.onFinishEditing_=
this.deleteIntermediateVars_;a.createdVariables_=[];a.onFinishEditing_("x")},validator_:function(a){var b=Blockly.Mutator.findParentWs(this.sourceBlock_.workspace);a=a.replace(/[\s\xa0]+/g," ").replace(/^ | $/g,"");if(!a)return null;var c=b.getVariable(a,"");c&&c.name!=a&&b.renameVarById(c.getId(),a);c||(c=b.createVariable(a,""))&&this.createdVariables_&&this.createdVariables_.push(c);return a},deleteIntermediateVars_:function(a){var b=Blockly.Mutator.findParentWs(this.sourceBlock_.workspace);if(b)for(var c=
0;c<this.createdVariables_.length;c++){var e=this.createdVariables_[c];e.name!=a&&b.deleteVariableById(e.getId())}}};
Blockly.Blocks.procedures_callnoreturn={init:function(){this.appendDummyInput("TOPROW").appendField(this.id,"NAME");this.setPreviousStatement(!0);this.setNextStatement(!0);this.setColour(Blockly.Msg.PROCEDURES_HUE);this.setHelpUrl(Blockly.Msg.PROCEDURES_CALLNORETURN_HELPURL);this.arguments_=[];this.argumentVarModels_=[];this.quarkConnections_={};this.quarkIds_=null;this.previousDisabledState_=!1},getProcedureCall:function(){return this.getFieldValue("NAME")},renameProcedure:function(a,b){Blockly.Names.equals(a,
this.getProcedureCall())&&(this.setFieldValue(b,"NAME"),this.setTooltip((this.outputConnection?Blockly.Msg.PROCEDURES_CALLRETURN_TOOLTIP:Blockly.Msg.PROCEDURES_CALLNORETURN_TOOLTIP).replace("%1",b)))},setProcedureParameters_:function(a,b){var c=Blockly.Procedures.getDefinition(this.getProcedureCall(),this.workspace),e=c&&c.mutator&&c.mutator.isVisible();e||(this.quarkConnections_={},this.quarkIds_=null);if(b)if(a.join("\n")==this.arguments_.join("\n"))this.quarkIds_=b;else{if(b.length!=a.length)throw RangeError("paramNames and paramIds must be the same length.");
this.setCollapsed(!1);this.quarkIds_||(this.quarkConnections_={},this.quarkIds_=[]);c=this.rendered;this.rendered=!1;for(var d=0;d<this.arguments_.length;d++){var f=this.getInput("ARG"+d);f&&(f=f.connection.targetConnection,this.quarkConnections_[this.quarkIds_[d]]=f,e&&f&&-1==b.indexOf(this.quarkIds_[d])&&(f.disconnect(),f.getSourceBlock().bumpNeighbours_()))}this.arguments_=[].concat(a);this.argumentVarModels_=[];for(d=0;d<this.arguments_.length;d++)e=Blockly.Variables.getOrCreateVariablePackage(this.workspace,
null,this.arguments_[d],""),this.argumentVarModels_.push(e);this.updateShape_();if(this.quarkIds_=b)for(d=0;d<this.arguments_.length;d++)e=this.quarkIds_[d],e in this.quarkConnections_&&(f=this.quarkConnections_[e],Blockly.Mutator.reconnect(f,this,"ARG"+d)||delete this.quarkConnections_[e]);(this.rendered=c)&&this.render()}},updateShape_:function(){for(var a=0;a<this.arguments_.length;a++){var b=this.getField("ARGNAME"+a);if(b){Blockly.Events.disable();try{b.setValue(this.arguments_[a])}finally{Blockly.Events.enable()}}else b=
new Blockly.FieldLabel(this.arguments_[a]),this.appendValueInput("ARG"+a).setAlign(Blockly.ALIGN_RIGHT).appendField(b,"ARGNAME"+a).init()}for(;this.getInput("ARG"+a);)this.removeInput("ARG"+a),a++;if(a=this.getInput("TOPROW"))this.arguments_.length?this.getField("WITH")||(a.appendField(Blockly.Msg.PROCEDURES_CALL_BEFORE_PARAMS,"WITH"),a.init()):this.getField("WITH")&&a.removeField("WITH")},mutationToDom:function(){var a=document.createElement("mutation");a.setAttribute("name",this.getProcedureCall());
for(var b=0;b<this.arguments_.length;b++){var c=document.createElement("arg");c.setAttribute("name",this.arguments_[b]);a.appendChild(c)}return a},domToMutation:function(a){var b=a.getAttribute("name");this.renameProcedure(this.getProcedureCall(),b);b=[];for(var c=[],e=0,d;d=a.childNodes[e];e++)"arg"==d.nodeName.toLowerCase()&&(b.push(d.getAttribute("name")),c.push(d.getAttribute("paramId")));this.setProcedureParameters_(b,c)},getVarModels:function(){return this.argumentVarModels_},onchange:function(a){if(this.workspace&&
!this.workspace.isFlyout&&a.recordUndo)if(a.type==Blockly.Events.BLOCK_CREATE&&-1!=a.ids.indexOf(this.id)){var b=this.getProcedureCall();b=Blockly.Procedures.getDefinition(b,this.workspace);!b||b.type==this.defType_&&JSON.stringify(b.arguments_)==JSON.stringify(this.arguments_)||(b=null);if(!b){Blockly.Events.setGroup(a.group);a=document.createElement("xml");b=document.createElement("block");b.setAttribute("type",this.defType_);var c=this.getRelativeToSurfaceXY(),e=c.y+2*Blockly.SNAP_RADIUS;b.setAttribute("x",
c.x+Blockly.SNAP_RADIUS*(this.RTL?-1:1));b.setAttribute("y",e);c=this.mutationToDom();b.appendChild(c);c=document.createElement("field");c.setAttribute("name","NAME");c.appendChild(document.createTextNode(this.getProcedureCall()));b.appendChild(c);a.appendChild(b);Blockly.Xml.domToWorkspace(a,this.workspace);Blockly.Events.setGroup(!1)}}else a.type==Blockly.Events.BLOCK_DELETE?(b=this.getProcedureCall(),b=Blockly.Procedures.getDefinition(b,this.workspace),b||(Blockly.Events.setGroup(a.group),this.dispose(!0,
!1),Blockly.Events.setGroup(!1))):a.type==Blockly.Events.CHANGE&&"disabled"==a.element&&(b=this.getProcedureCall(),(b=Blockly.Procedures.getDefinition(b,this.workspace))&&b.id==a.blockId&&((b=Blockly.Events.getGroup())&&console.log("Saw an existing group while responding to a definition change"),Blockly.Events.setGroup(a.group),a.newValue?(this.previousDisabledState_=this.disabled,this.setDisabled(!0)):this.setDisabled(this.previousDisabledState_),Blockly.Events.setGroup(b)))},customContextMenu:function(a){var b=
{enabled:!0};b.text=Blockly.Msg.PROCEDURES_HIGHLIGHT_DEF;var c=this.getProcedureCall(),e=this.workspace;b.callback=function(){var a=Blockly.Procedures.getDefinition(c,e);a&&(e.centerOnBlock(a.id),a.select())};a.push(b)},defType_:"procedures_defnoreturn"};
Blockly.Blocks.procedures_callreturn={init:function(){this.appendDummyInput("TOPROW").appendField("","NAME");this.setOutput(!0);this.setColour(Blockly.Msg.PROCEDURES_HUE);this.setHelpUrl(Blockly.Msg.PROCEDURES_CALLRETURN_HELPURL);this.arguments_=[];this.quarkConnections_={};this.quarkIds_=null;this.previousDisabledState_=!1},getProcedureCall:Blockly.Blocks.procedures_callnoreturn.getProcedureCall,renameProcedure:Blockly.Blocks.procedures_callnoreturn.renameProcedure,setProcedureParameters_:Blockly.Blocks.procedures_callnoreturn.setProcedureParameters_,
updateShape_:Blockly.Blocks.procedures_callnoreturn.updateShape_,mutationToDom:Blockly.Blocks.procedures_callnoreturn.mutationToDom,domToMutation:Blockly.Blocks.procedures_callnoreturn.domToMutation,getVarModels:Blockly.Blocks.procedures_callnoreturn.getVarModels,onchange:Blockly.Blocks.procedures_callnoreturn.onchange,customContextMenu:Blockly.Blocks.procedures_callnoreturn.customContextMenu,defType_:"procedures_defreturn"};
Blockly.Blocks.procedures_ifreturn={init:function(){this.appendValueInput("CONDITION").setCheck("Boolean").appendField(Blockly.Msg.CONTROLS_IF_MSG_IF);this.appendValueInput("VALUE").appendField(Blockly.Msg.PROCEDURES_DEFRETURN_RETURN);this.setInputsInline(!0);this.setPreviousStatement(!0);this.setNextStatement(!0);this.setColour(Blockly.Msg.PROCEDURES_HUE);this.setTooltip(Blockly.Msg.PROCEDURES_IFRETURN_TOOLTIP);this.setHelpUrl(Blockly.Msg.PROCEDURES_IFRETURN_HELPURL);this.hasReturnValue_=!0},mutationToDom:function(){var a=
document.createElement("mutation");a.setAttribute("value",Number(this.hasReturnValue_));return a},domToMutation:function(a){this.hasReturnValue_=1==a.getAttribute("value");this.hasReturnValue_||(this.removeInput("VALUE"),this.appendDummyInput("VALUE").appendField(Blockly.Msg.PROCEDURES_DEFRETURN_RETURN))},onchange:function(){if(this.workspace.isDragging&&!this.workspace.isDragging()){var a=!1,b=this;do{if(-1!=this.FUNCTION_TYPES.indexOf(b.type)){a=!0;break}b=b.getSurroundParent()}while(b);a?("procedures_defnoreturn"==
b.type&&this.hasReturnValue_?(this.removeInput("VALUE"),this.appendDummyInput("VALUE").appendField(Blockly.Msg.PROCEDURES_DEFRETURN_RETURN),this.hasReturnValue_=!1):"procedures_defreturn"!=b.type||this.hasReturnValue_||(this.removeInput("VALUE"),this.appendValueInput("VALUE").appendField(Blockly.Msg.PROCEDURES_DEFRETURN_RETURN),this.hasReturnValue_=!0),this.setWarningText(null),this.isInFlyout||this.setDisabled(!1)):(this.setWarningText(Blockly.Msg.PROCEDURES_IFRETURN_WARNING),this.isInFlyout||this.getInheritedDisabled()||
this.setDisabled(!0))}},FUNCTION_TYPES:["procedures_defnoreturn","procedures_defreturn"]};Blockly.Blocks.texts={};Blockly.Constants.Text={};Blockly.Constants.Text.HUE=160;
Blockly.defineBlocksWithJsonArray([{type:"text",message0:"%1",args0:[{type:"field_input",name:"TEXT",text:""}],output:"String",colour:"%{BKY_TEXTS_HUE}",helpUrl:"%{BKY_TEXT_TEXT_HELPURL}",tooltip:"%{BKY_TEXT_TEXT_TOOLTIP}",extensions:["text_quotes","parent_tooltip_when_inline"]},{type:"text_join",message0:"",output:"String",colour:"%{BKY_TEXTS_HUE}",helpUrl:"%{BKY_TEXT_JOIN_HELPURL}",tooltip:"%{BKY_TEXT_JOIN_TOOLTIP}",mutator:"text_join_mutator"},{type:"text_create_join_container",message0:"%{BKY_TEXT_CREATE_JOIN_TITLE_JOIN} %1 %2",
args0:[{type:"input_dummy"},{type:"input_statement",name:"STACK"}],colour:"%{BKY_TEXTS_HUE}",tooltip:"%{BKY_TEXT_CREATE_JOIN_TOOLTIP}",enableContextMenu:!1},{type:"text_create_join_item",message0:"%{BKY_TEXT_CREATE_JOIN_ITEM_TITLE_ITEM}",previousStatement:null,nextStatement:null,colour:"%{BKY_TEXTS_HUE}",tooltip:"%{BKY_TEXT_CREATE_JOIN_ITEM_TOOLTIP}",enableContextMenu:!1},{type:"text_append",message0:"%{BKY_TEXT_APPEND_TITLE}",args0:[{type:"field_variable",name:"VAR",variable:"%{BKY_TEXT_APPEND_VARIABLE}"},
{type:"input_value",name:"TEXT"}],previousStatement:null,nextStatement:null,colour:"%{BKY_TEXTS_HUE}",extensions:["text_append_tooltip"]},{type:"text_length",message0:"%{BKY_TEXT_LENGTH_TITLE}",args0:[{type:"input_value",name:"VALUE",check:["String","Array"]}],output:"Number",colour:"%{BKY_TEXTS_HUE}",tooltip:"%{BKY_TEXT_LENGTH_TOOLTIP}",helpUrl:"%{BKY_TEXT_LENGTH_HELPURL}"},{type:"text_isEmpty",message0:"%{BKY_TEXT_ISEMPTY_TITLE}",args0:[{type:"input_value",name:"VALUE",check:["String","Array"]}],
output:"Boolean",colour:"%{BKY_TEXTS_HUE}",tooltip:"%{BKY_TEXT_ISEMPTY_TOOLTIP}",helpUrl:"%{BKY_TEXT_ISEMPTY_HELPURL}"},{type:"text_indexOf",message0:"%{BKY_TEXT_INDEXOF_TITLE}",args0:[{type:"input_value",name:"VALUE",check:"String"},{type:"field_dropdown",name:"END",options:[["%{BKY_TEXT_INDEXOF_OPERATOR_FIRST}","FIRST"],["%{BKY_TEXT_INDEXOF_OPERATOR_LAST}","LAST"]]},{type:"input_value",name:"FIND",check:"String"}],output:"Number",colour:"%{BKY_TEXTS_HUE}",helpUrl:"%{BKY_TEXT_INDEXOF_HELPURL}",inputsInline:!0,
extensions:["text_indexOf_tooltip"]},{type:"text_charAt",message0:"%{BKY_TEXT_CHARAT_TITLE}",args0:[{type:"input_value",name:"VALUE",check:"String"},{type:"field_dropdown",name:"WHERE",options:[["%{BKY_TEXT_CHARAT_FROM_START}","FROM_START"],["%{BKY_TEXT_CHARAT_FROM_END}","FROM_END"],["%{BKY_TEXT_CHARAT_FIRST}","FIRST"],["%{BKY_TEXT_CHARAT_LAST}","LAST"],["%{BKY_TEXT_CHARAT_RANDOM}","RANDOM"]]}],output:"String",colour:"%{BKY_TEXTS_HUE}",helpUrl:"%{BKY_TEXT_CHARAT_HELPURL}",inputsInline:!0,mutator:"text_charAt_mutator"}]);
Blockly.Blocks.text_getSubstring={init:function(){this.WHERE_OPTIONS_1=[[Blockly.Msg.TEXT_GET_SUBSTRING_START_FROM_START,"FROM_START"],[Blockly.Msg.TEXT_GET_SUBSTRING_START_FROM_END,"FROM_END"],[Blockly.Msg.TEXT_GET_SUBSTRING_START_FIRST,"FIRST"]];this.WHERE_OPTIONS_2=[[Blockly.Msg.TEXT_GET_SUBSTRING_END_FROM_START,"FROM_START"],[Blockly.Msg.TEXT_GET_SUBSTRING_END_FROM_END,"FROM_END"],[Blockly.Msg.TEXT_GET_SUBSTRING_END_LAST,"LAST"]];this.setHelpUrl(Blockly.Msg.TEXT_GET_SUBSTRING_HELPURL);this.setColour(Blockly.Msg.TEXTS_HUE);
this.appendValueInput("STRING").setCheck("String").appendField(Blockly.Msg.TEXT_GET_SUBSTRING_INPUT_IN_TEXT);this.appendDummyInput("AT1");this.appendDummyInput("AT2");Blockly.Msg.TEXT_GET_SUBSTRING_TAIL&&this.appendDummyInput("TAIL").appendField(Blockly.Msg.TEXT_GET_SUBSTRING_TAIL);this.setInputsInline(!0);this.setOutput(!0,"String");this.updateAt_(1,!0);this.updateAt_(2,!0);this.setTooltip(Blockly.Msg.TEXT_GET_SUBSTRING_TOOLTIP)},mutationToDom:function(){var a=document.createElement("mutation"),
b=this.getInput("AT1").type==Blockly.INPUT_VALUE;a.setAttribute("at1",b);b=this.getInput("AT2").type==Blockly.INPUT_VALUE;a.setAttribute("at2",b);return a},domToMutation:function(a){var b="true"==a.getAttribute("at1");a="true"==a.getAttribute("at2");this.updateAt_(1,b);this.updateAt_(2,a)},updateAt_:function(a,b){this.removeInput("AT"+a);this.removeInput("ORDINAL"+a,!0);b?(this.appendValueInput("AT"+a).setCheck("Number"),Blockly.Msg.ORDINAL_NUMBER_SUFFIX&&this.appendDummyInput("ORDINAL"+a).appendField(Blockly.Msg.ORDINAL_NUMBER_SUFFIX)):
this.appendDummyInput("AT"+a);2==a&&Blockly.Msg.TEXT_GET_SUBSTRING_TAIL&&(this.removeInput("TAIL",!0),this.appendDummyInput("TAIL").appendField(Blockly.Msg.TEXT_GET_SUBSTRING_TAIL));var c=new Blockly.FieldDropdown(this["WHERE_OPTIONS_"+a],function(c){var d="FROM_START"==c||"FROM_END"==c;if(d!=b){var e=this.sourceBlock_;e.updateAt_(a,d);e.setFieldValue(c,"WHERE"+a);return null}});this.getInput("AT"+a).appendField(c,"WHERE"+a);1==a&&(this.moveInputBefore("AT1","AT2"),this.getInput("ORDINAL1")&&this.moveInputBefore("ORDINAL1",
"AT2"))}};Blockly.Blocks.text_changeCase={init:function(){var a=[[Blockly.Msg.TEXT_CHANGECASE_OPERATOR_UPPERCASE,"UPPERCASE"],[Blockly.Msg.TEXT_CHANGECASE_OPERATOR_LOWERCASE,"LOWERCASE"],[Blockly.Msg.TEXT_CHANGECASE_OPERATOR_TITLECASE,"TITLECASE"]];this.setHelpUrl(Blockly.Msg.TEXT_CHANGECASE_HELPURL);this.setColour(Blockly.Msg.TEXTS_HUE);this.appendValueInput("TEXT").setCheck("String").appendField(new Blockly.FieldDropdown(a),"CASE");this.setOutput(!0,"String");this.setTooltip(Blockly.Msg.TEXT_CHANGECASE_TOOLTIP)}};
Blockly.Blocks.text_trim={init:function(){var a=[[Blockly.Msg.TEXT_TRIM_OPERATOR_BOTH,"BOTH"],[Blockly.Msg.TEXT_TRIM_OPERATOR_LEFT,"LEFT"],[Blockly.Msg.TEXT_TRIM_OPERATOR_RIGHT,"RIGHT"]];this.setHelpUrl(Blockly.Msg.TEXT_TRIM_HELPURL);this.setColour(Blockly.Msg.TEXTS_HUE);this.appendValueInput("TEXT").setCheck("String").appendField(new Blockly.FieldDropdown(a),"MODE");this.setOutput(!0,"String");this.setTooltip(Blockly.Msg.TEXT_TRIM_TOOLTIP)}};
Blockly.Blocks.text_print={init:function(){this.jsonInit({message0:Blockly.Msg.TEXT_PRINT_TITLE,args0:[{type:"input_value",name:"TEXT"}],previousStatement:null,nextStatement:null,colour:Blockly.Msg.TEXTS_HUE,tooltip:Blockly.Msg.TEXT_PRINT_TOOLTIP,helpUrl:Blockly.Msg.TEXT_PRINT_HELPURL})}};
Blockly.Blocks.text_prompt_ext={init:function(){var a=[[Blockly.Msg.TEXT_PROMPT_TYPE_TEXT,"TEXT"],[Blockly.Msg.TEXT_PROMPT_TYPE_NUMBER,"NUMBER"]];this.setHelpUrl(Blockly.Msg.TEXT_PROMPT_HELPURL);this.setColour(Blockly.Msg.TEXTS_HUE);var b=this;a=new Blockly.FieldDropdown(a,function(a){b.updateType_(a)});this.appendValueInput("TEXT").appendField(a,"TYPE");this.setOutput(!0,"String");this.setTooltip(function(){return"TEXT"==b.getFieldValue("TYPE")?Blockly.Msg.TEXT_PROMPT_TOOLTIP_TEXT:Blockly.Msg.TEXT_PROMPT_TOOLTIP_NUMBER})},
updateType_:function(a){this.outputConnection.setCheck("NUMBER"==a?"Number":"String")},mutationToDom:function(){var a=document.createElement("mutation");a.setAttribute("type",this.getFieldValue("TYPE"));return a},domToMutation:function(a){this.updateType_(a.getAttribute("type"))}};
Blockly.Blocks.text_prompt={init:function(){this.mixin(Blockly.Constants.Text.QUOTE_IMAGE_MIXIN);var a=[[Blockly.Msg.TEXT_PROMPT_TYPE_TEXT,"TEXT"],[Blockly.Msg.TEXT_PROMPT_TYPE_NUMBER,"NUMBER"]],b=this;this.setHelpUrl(Blockly.Msg.TEXT_PROMPT_HELPURL);this.setColour(Blockly.Msg.TEXTS_HUE);a=new Blockly.FieldDropdown(a,function(a){b.updateType_(a)});this.appendDummyInput().appendField(a,"TYPE").appendField(this.newQuote_(!0)).appendField(new Blockly.FieldTextInput(""),"TEXT").appendField(this.newQuote_(!1));
this.setOutput(!0,"String");this.setTooltip(function(){return"TEXT"==b.getFieldValue("TYPE")?Blockly.Msg.TEXT_PROMPT_TOOLTIP_TEXT:Blockly.Msg.TEXT_PROMPT_TOOLTIP_NUMBER})},updateType_:Blockly.Blocks.text_prompt_ext.updateType_,mutationToDom:Blockly.Blocks.text_prompt_ext.mutationToDom,domToMutation:Blockly.Blocks.text_prompt_ext.domToMutation};
Blockly.Blocks.text_count={init:function(){this.jsonInit({message0:Blockly.Msg.TEXT_COUNT_MESSAGE0,args0:[{type:"input_value",name:"SUB",check:"String"},{type:"input_value",name:"TEXT",check:"String"}],output:"Number",inputsInline:!0,colour:Blockly.Msg.TEXTS_HUE,tooltip:Blockly.Msg.TEXT_COUNT_TOOLTIP,helpUrl:Blockly.Msg.TEXT_COUNT_HELPURL})}};
Blockly.Blocks.text_replace={init:function(){this.jsonInit({message0:Blockly.Msg.TEXT_REPLACE_MESSAGE0,args0:[{type:"input_value",name:"FROM",check:"String"},{type:"input_value",name:"TO",check:"String"},{type:"input_value",name:"TEXT",check:"String"}],output:"String",inputsInline:!0,colour:Blockly.Msg.TEXTS_HUE,tooltip:Blockly.Msg.TEXT_REPLACE_TOOLTIP,helpUrl:Blockly.Msg.TEXT_REPLACE_HELPURL})}};
Blockly.Blocks.text_reverse={init:function(){this.jsonInit({message0:Blockly.Msg.TEXT_REVERSE_MESSAGE0,args0:[{type:"input_value",name:"TEXT",check:"String"}],output:"String",inputsInline:!0,colour:Blockly.Msg.TEXTS_HUE,tooltip:Blockly.Msg.TEXT_REVERSE_TOOLTIP,helpUrl:Blockly.Msg.TEXT_REVERSE_HELPURL})}};
Blockly.Constants.Text.QUOTE_IMAGE_MIXIN={QUOTE_IMAGE_LEFT_DATAURI:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAKCAQAAAAqJXdxAAAAn0lEQVQI1z3OMa5BURSF4f/cQhAKjUQhuQmFNwGJEUi0RKN5rU7FHKhpjEH3TEMtkdBSCY1EIv8r7nFX9e29V7EBAOvu7RPjwmWGH/VuF8CyN9/OAdvqIXYLvtRaNjx9mMTDyo+NjAN1HNcl9ZQ5oQMM3dgDUqDo1l8DzvwmtZN7mnD+PkmLa+4mhrxVA9fRowBWmVBhFy5gYEjKMfz9AylsaRRgGzvZAAAAAElFTkSuQmCC",QUOTE_IMAGE_RIGHT_DATAURI:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAKCAQAAAAqJXdxAAAAqUlEQVQI1z3KvUpCcRiA8ef9E4JNHhI0aFEacm1o0BsI0Slx8wa8gLauoDnoBhq7DcfWhggONDmJJgqCPA7neJ7p934EOOKOnM8Q7PDElo/4x4lFb2DmuUjcUzS3URnGib9qaPNbuXvBO3sGPHJDRG6fGVdMSeWDP2q99FQdFrz26Gu5Tq7dFMzUvbXy8KXeAj57cOklgA+u1B5AoslLtGIHQMaCVnwDnADZIFIrXsoXrgAAAABJRU5ErkJggg==",
QUOTE_IMAGE_WIDTH:12,QUOTE_IMAGE_HEIGHT:12,quoteField_:function(a){for(var b=0,c;c=this.inputList[b];b++)for(var e=0,d;d=c.fieldRow[e];e++)if(a==d.name){c.insertFieldAt(e,this.newQuote_(!0));c.insertFieldAt(e+2,this.newQuote_(!1));return}console.warn('field named "'+a+'" not found in '+this.toDevString())},newQuote_:function(a){a=this.RTL?!a:a;return new Blockly.FieldImage(a?this.QUOTE_IMAGE_LEFT_DATAURI:this.QUOTE_IMAGE_RIGHT_DATAURI,this.QUOTE_IMAGE_WIDTH,this.QUOTE_IMAGE_HEIGHT,a?"\u201c":"\u201d")}};
Blockly.Constants.Text.TEXT_QUOTES_EXTENSION=function(){this.mixin(Blockly.Constants.Text.QUOTE_IMAGE_MIXIN);this.quoteField_("TEXT")};
Blockly.Constants.Text.TEXT_JOIN_MUTATOR_MIXIN={mutationToDom:function(){var a=document.createElement("mutation");a.setAttribute("items",this.itemCount_);return a},domToMutation:function(a){this.itemCount_=parseInt(a.getAttribute("items"),10);this.updateShape_()},decompose:function(a){var b=a.newBlock("text_create_join_container");b.initSvg();for(var c=b.getInput("STACK").connection,e=0;e<this.itemCount_;e++){var d=a.newBlock("text_create_join_item");d.initSvg();c.connect(d.previousConnection);c=
d.nextConnection}return b},compose:function(a){var b=a.getInputTargetBlock("STACK");for(a=[];b;)a.push(b.valueConnection_),b=b.nextConnection&&b.nextConnection.targetBlock();for(b=0;b<this.itemCount_;b++){var c=this.getInput("ADD"+b).connection.targetConnection;c&&-1==a.indexOf(c)&&c.disconnect()}this.itemCount_=a.length;this.updateShape_();for(b=0;b<this.itemCount_;b++)Blockly.Mutator.reconnect(a[b],this,"ADD"+b)},saveConnections:function(a){a=a.getInputTargetBlock("STACK");for(var b=0;a;){var c=
this.getInput("ADD"+b);a.valueConnection_=c&&c.connection.targetConnection;b++;a=a.nextConnection&&a.nextConnection.targetBlock()}},updateShape_:function(){this.itemCount_&&this.getInput("EMPTY")?this.removeInput("EMPTY"):this.itemCount_||this.getInput("EMPTY")||this.appendDummyInput("EMPTY").appendField(this.newQuote_(!0)).appendField(this.newQuote_(!1));for(var a=0;a<this.itemCount_;a++)if(!this.getInput("ADD"+a)){var b=this.appendValueInput("ADD"+a);0==a&&b.appendField(Blockly.Msg.TEXT_JOIN_TITLE_CREATEWITH)}for(;this.getInput("ADD"+
a);)this.removeInput("ADD"+a),a++}};Blockly.Constants.Text.TEXT_JOIN_EXTENSION=function(){this.mixin(Blockly.Constants.Text.QUOTE_IMAGE_MIXIN);this.itemCount_=2;this.updateShape_();this.setMutator(new Blockly.Mutator(["text_create_join_item"]))};Blockly.Extensions.register("text_append_tooltip",Blockly.Extensions.buildTooltipWithFieldText("%{BKY_TEXT_APPEND_TOOLTIP}","VAR"));
Blockly.Constants.Text.TEXT_INDEXOF_TOOLTIP_EXTENSION=function(){var a=this;this.setTooltip(function(){return Blockly.Msg.TEXT_INDEXOF_TOOLTIP.replace("%1",a.workspace.options.oneBasedIndex?"0":"-1")})};
Blockly.Constants.Text.TEXT_CHARAT_MUTATOR_MIXIN={mutationToDom:function(){var a=document.createElement("mutation");a.setAttribute("at",!!this.isAt_);return a},domToMutation:function(a){a="false"!=a.getAttribute("at");this.updateAt_(a)},updateAt_:function(a){this.removeInput("AT",!0);this.removeInput("ORDINAL",!0);a&&(this.appendValueInput("AT").setCheck("Number"),Blockly.Msg.ORDINAL_NUMBER_SUFFIX&&this.appendDummyInput("ORDINAL").appendField(Blockly.Msg.ORDINAL_NUMBER_SUFFIX));Blockly.Msg.TEXT_CHARAT_TAIL&&
(this.removeInput("TAIL",!0),this.appendDummyInput("TAIL").appendField(Blockly.Msg.TEXT_CHARAT_TAIL));this.isAt_=a}};
Blockly.Constants.Text.TEXT_CHARAT_EXTENSION=function(){this.getField("WHERE").setValidator(function(a){var b="FROM_START"==a||"FROM_END"==a;if(b!=this.isAt_){var e=this.sourceBlock_;e.updateAt_(b);e.setFieldValue(a,"WHERE");return null}});this.updateAt_(!0);var a=this;this.setTooltip(function(){var b=a.getFieldValue("WHERE"),c=Blockly.Msg.TEXT_CHARAT_TOOLTIP;("FROM_START"==b||"FROM_END"==b)&&(b="FROM_START"==b?Blockly.Msg.LISTS_INDEX_FROM_START_TOOLTIP:Blockly.Msg.LISTS_INDEX_FROM_END_TOOLTIP)&&
(c+=" "+b.replace("%1",a.workspace.options.oneBasedIndex?"#1":"#0"));return c})};Blockly.Extensions.register("text_indexOf_tooltip",Blockly.Constants.Text.TEXT_INDEXOF_TOOLTIP_EXTENSION);Blockly.Extensions.register("text_quotes",Blockly.Constants.Text.TEXT_QUOTES_EXTENSION);Blockly.Extensions.registerMutator("text_join_mutator",Blockly.Constants.Text.TEXT_JOIN_MUTATOR_MIXIN,Blockly.Constants.Text.TEXT_JOIN_EXTENSION);
Blockly.Extensions.registerMutator("text_charAt_mutator",Blockly.Constants.Text.TEXT_CHARAT_MUTATOR_MIXIN,Blockly.Constants.Text.TEXT_CHARAT_EXTENSION);Blockly.Blocks.variables={};Blockly.Constants.Variables={};Blockly.Constants.Variables.HUE=330;
Blockly.defineBlocksWithJsonArray([{type:"variables_get",message0:"%1",args0:[{type:"field_variable",name:"VAR",variable:"%{BKY_VARIABLES_DEFAULT_NAME}"}],output:null,colour:"%{BKY_VARIABLES_HUE}",helpUrl:"%{BKY_VARIABLES_GET_HELPURL}",tooltip:"%{BKY_VARIABLES_GET_TOOLTIP}",extensions:["contextMenu_variableSetterGetter"]},{type:"variables_set",message0:"%{BKY_VARIABLES_SET}",args0:[{type:"field_variable",name:"VAR",variable:"%{BKY_VARIABLES_DEFAULT_NAME}"},{type:"input_value",name:"VALUE"}],previousStatement:null,
nextStatement:null,colour:"%{BKY_VARIABLES_HUE}",tooltip:"%{BKY_VARIABLES_SET_TOOLTIP}",helpUrl:"%{BKY_VARIABLES_SET_HELPURL}",extensions:["contextMenu_variableSetterGetter"]}]);
Blockly.Constants.Variables.CUSTOM_CONTEXT_MENU_VARIABLE_GETTER_SETTER_MIXIN={customContextMenu:function(a){if(!this.isInFlyout){if("variables_get"==this.type)var b="variables_set",c=Blockly.Msg.VARIABLES_GET_CREATE_SET;else b="variables_get",c=Blockly.Msg.VARIABLES_SET_CREATE_GET;var e={enabled:0<this.workspace.remainingCapacity()},d=this.getField("VAR").getText();e.text=c.replace("%1",d);c=document.createElement("field");c.setAttribute("name","VAR");c.appendChild(document.createTextNode(d));d=document.createElement("block");
d.setAttribute("type",b);d.appendChild(c);e.callback=Blockly.ContextMenu.callbackFactory(this,d);a.push(e)}}};Blockly.Extensions.registerMixin("contextMenu_variableSetterGetter",Blockly.Constants.Variables.CUSTOM_CONTEXT_MENU_VARIABLE_GETTER_SETTER_MIXIN);
Blockly.Constants.VariablesDynamic={};Blockly.Constants.VariablesDynamic.HUE=310;
Blockly.defineBlocksWithJsonArray([{type:"variables_get_dynamic",message0:"%1",args0:[{type:"field_variable",name:"VAR",variable:"%{BKY_VARIABLES_DEFAULT_NAME}"}],output:null,colour:"%{BKY_VARIABLES_DYNAMIC_HUE}",helpUrl:"%{BKY_VARIABLES_GET_HELPURL}",tooltip:"%{BKY_VARIABLES_GET_TOOLTIP}",extensions:["contextMenu_variableDynamicSetterGetter"]},{type:"variables_set_dynamic",message0:"%{BKY_VARIABLES_SET}",args0:[{type:"field_variable",name:"VAR",variable:"%{BKY_VARIABLES_DEFAULT_NAME}"},{type:"input_value",
name:"VALUE"}],previousStatement:null,nextStatement:null,colour:"%{BKY_VARIABLES_DYNAMIC_HUE}",tooltip:"%{BKY_VARIABLES_SET_TOOLTIP}",helpUrl:"%{BKY_VARIABLES_SET_HELPURL}",extensions:["contextMenu_variableDynamicSetterGetter"]}]);
Blockly.Constants.VariablesDynamic.CUSTOM_CONTEXT_MENU_VARIABLE_GETTER_SETTER_MIXIN={customContextMenu:function(a){if(!this.isInFlyout){if("variables_get_dynamic"==this.type){var b="variables_set_dynamic";var c=Blockly.Msg.VARIABLES_GET_CREATE_SET}else b="variables_get_dynamic",c=Blockly.Msg.VARIABLES_SET_CREATE_GET;var e={enabled:0<this.workspace.remainingCapacity()},d=this.getField("VAR").getText();e.text=c.replace("%1",d);c=document.createElement("field");c.setAttribute("name","VAR");c.appendChild(document.createTextNode(d));
d=document.createElement("block");d.setAttribute("type",b);d.appendChild(c);e.callback=Blockly.ContextMenu.callbackFactory(this,d);a.push(e)}},onchange:function(){var a=this.getFieldValue("VAR");a=this.workspace.getVariableById(a);"variables_get_dynamic"==this.type?this.outputConnection.setCheck(a.type):this.getInput("VALUE").connection.setCheck(a.type)}};Blockly.Extensions.registerMixin("contextMenu_variableDynamicSetterGetter",Blockly.Constants.VariablesDynamic.CUSTOM_CONTEXT_MENU_VARIABLE_GETTER_SETTER_MIXIN); | jjalling/domoticz | www/js/blockly/blocks_compressed.js | JavaScript | gpl-3.0 | 71,738 |
/*!
* Copyright 2019 Hitachi Vantara. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
define([
"angular"
], function (angular) {
/**
* @param {Function} $document - Angular wrapper for window.document.
* @return {Object} - context directive
*/
function context($document) {
return {
restrict: "A",
link: function (scope, element, attrs) {
var contextMenu = angular.element(document.querySelector('#' + attrs.context));
element.bind('contextmenu', function (event) {
scope.$apply(function () {
event.stopPropagation();
event.preventDefault();
var contextHeight = contextMenu.outerHeight();
var contextWidth = contextMenu.outerWidth();
var documentHeight = $document.height();
var documentWidth = $document.width();
var contextY = event.clientY + contextHeight > documentHeight ? documentHeight - contextHeight : event.clientY;
var contextX = event.clientX + contextWidth > documentWidth ? documentWidth - contextWidth : event.clientX;
contextMenu.css({
'display': 'block',
'top': contextY + 'px',
'left': contextX + 'px'
})
});
});
angular.element($document).bind('click', function (event) {
contextMenu.css({
'display': 'none'
});
});
angular.element($document).bind('keydown', function (event) {
if (event.keyCode === 27) {
contextMenu.css({
'display': 'none'
});
}
});
}
};
}
return {
name: "context",
options: ["$document", context]
};
});
| ddiroma/pentaho-kettle | plugins/file-open-save-new/core/src/main/javascript/app/shared/directives/context.directive.js | JavaScript | apache-2.0 | 2,261 |
var typing_status = require('js/typing_status');
function return_false() { return false; }
function return_true() { return true; }
function return_alice() { return "alice"; }
function return_bob() { return "bob"; }
function make_time(secs) {
// make times semi-realistic
return 1000000 + 1000 * secs;
}
function returns_time(secs) {
return function () { return make_time(secs); };
}
(function test_basics() {
// invalid conversation basically does nothing
var worker = {
get_recipient: return_alice,
is_valid_conversation: return_false,
};
typing_status.handle_text_input(worker);
// Start setting up more testing state.
typing_status.initialize_state();
var events = {};
function set_timeout(f, delay) {
assert.equal(delay, 5000);
events.idle_callback = f;
return 'idle_timer_stub';
}
function clear_timeout() {
events.timer_cleared = true;
}
global.patch_builtin('setTimeout', set_timeout);
global.patch_builtin('clearTimeout', clear_timeout);
function notify_server_start(recipient) {
assert.equal(recipient, "alice");
events.started = true;
}
function notify_server_stop(recipient) {
assert.equal(recipient, "alice");
events.stopped = true;
}
function clear_events() {
events.idle_callback = undefined;
events.started = false;
events.stopped = false;
events.timer_cleared = false;
}
function call_handler() {
clear_events();
typing_status.handle_text_input(worker);
}
function call_stop() {
clear_events();
typing_status.stop(worker);
}
worker = {
get_recipient: return_alice,
is_valid_conversation: return_true,
get_current_time: returns_time(5),
notify_server_start: notify_server_start,
notify_server_stop: notify_server_stop,
};
// Start talking to alice.
call_handler();
assert.deepEqual(typing_status.state, {
next_send_start_time: make_time(5 + 10),
idle_timer: 'idle_timer_stub',
current_recipient: 'alice',
});
assert.deepEqual(events, {
idle_callback: events.idle_callback,
started: true,
stopped: false,
timer_cleared: false,
});
assert(events.idle_callback);
// type again 3 seconds later
worker.get_current_time = returns_time(8);
call_handler();
assert.deepEqual(typing_status.state, {
next_send_start_time: make_time(5 + 10),
idle_timer: 'idle_timer_stub',
current_recipient: 'alice',
});
assert.deepEqual(events, {
idle_callback: events.idle_callback,
started: false,
stopped: false,
timer_cleared: true,
});
assert(events.idle_callback);
// type after 15 secs, so that we can notify the server
// again
worker.get_current_time = returns_time(18);
call_handler();
assert.deepEqual(typing_status.state, {
next_send_start_time: make_time(18 + 10),
idle_timer: 'idle_timer_stub',
current_recipient: 'alice',
});
assert.deepEqual(events, {
idle_callback: events.idle_callback,
started: true,
stopped: false,
timer_cleared: true,
});
// Now call alice's idle callback that we captured earlier.
var callback = events.idle_callback;
clear_events();
callback();
assert.deepEqual(typing_status.state, {
next_send_start_time: undefined,
idle_timer: undefined,
current_recipient: undefined,
});
assert.deepEqual(events, {
idle_callback: undefined,
started: false,
stopped: true,
timer_cleared: true,
});
// Call stop with nothing going on.
call_stop();
assert.deepEqual(typing_status.state, {
next_send_start_time: undefined,
idle_timer: undefined,
current_recipient: undefined,
});
assert.deepEqual(events, {
idle_callback: undefined,
started: false,
stopped: false,
timer_cleared: false,
});
// Start talking to alice again.
worker.get_current_time = returns_time(50);
call_handler();
assert.deepEqual(typing_status.state, {
next_send_start_time: make_time(50 + 10),
idle_timer: 'idle_timer_stub',
current_recipient: 'alice',
});
assert.deepEqual(events, {
idle_callback: events.idle_callback,
started: true,
stopped: false,
timer_cleared: false,
});
assert(events.idle_callback);
// Explicitly stop alice.
call_stop();
assert.deepEqual(typing_status.state, {
next_send_start_time: undefined,
idle_timer: undefined,
current_recipient: undefined,
});
assert.deepEqual(events, {
idle_callback: undefined,
started: false,
stopped: true,
timer_cleared: true,
});
// Start talking to alice again.
worker.get_current_time = returns_time(80);
call_handler();
assert.deepEqual(typing_status.state, {
next_send_start_time: make_time(80 + 10),
idle_timer: 'idle_timer_stub',
current_recipient: 'alice',
});
assert.deepEqual(events, {
idle_callback: events.idle_callback,
started: true,
stopped: false,
timer_cleared: false,
});
assert(events.idle_callback);
// Switch to an invalid conversation.
worker.get_recipient = function () {
return 'not-alice';
};
worker.is_valid_conversation = return_false;
call_handler();
assert.deepEqual(typing_status.state, {
next_send_start_time: undefined,
idle_timer: undefined,
current_recipient: undefined,
});
assert.deepEqual(events, {
idle_callback: undefined,
started: false,
stopped: true,
timer_cleared: true,
});
// Switch to another invalid conversation.
worker.get_recipient = function () {
return 'another-bogus-one';
};
worker.is_valid_conversation = return_false;
call_handler();
assert.deepEqual(typing_status.state, {
next_send_start_time: undefined,
idle_timer: undefined,
current_recipient: undefined,
});
assert.deepEqual(events, {
idle_callback: undefined,
started: false,
stopped: false,
timer_cleared: false,
});
// Start talking to alice again.
worker.get_recipient = return_alice;
worker.is_valid_conversation = return_true;
worker.get_current_time = returns_time(170);
call_handler();
assert.deepEqual(typing_status.state, {
next_send_start_time: make_time(170 + 10),
idle_timer: 'idle_timer_stub',
current_recipient: 'alice',
});
assert.deepEqual(events, {
idle_callback: events.idle_callback,
started: true,
stopped: false,
timer_cleared: false,
});
assert(events.idle_callback);
// Switch to bob now.
worker.get_recipient = return_bob;
worker.is_valid_conversation = return_true;
worker.get_current_time = returns_time(171);
worker.notify_server_start = function (recipient) {
assert.equal(recipient, "bob");
events.started = true;
};
call_handler();
assert.deepEqual(typing_status.state, {
next_send_start_time: make_time(171 + 10),
idle_timer: 'idle_timer_stub',
current_recipient: 'bob',
});
assert.deepEqual(events, {
idle_callback: events.idle_callback,
started: true,
stopped: true,
timer_cleared: true,
});
assert(events.idle_callback);
}());
| SmartPeople/zulip | frontend_tests/node_tests/typing_status.js | JavaScript | apache-2.0 | 7,740 |
#!/usr/bin/env node
var tests = require("./hardcoded_tests.js");
var runTest = require(".//hardcoded_test_runner.js");
var colors = require("colors");
var parseArgs = require("minimist");
var failures = {};
var num_successes = 0;
var num_failures = 0;
var argv = parseArgs(
process.argv.slice(2),
{string: ["filter"]}
);
var todo = {};
function escape_content(content) {
return content
.replace(/[\\]/g, '\\\\')
.replace(/[\/]/g, '\\/')
.replace(/[\b]/g, '\\b')
.replace(/[\f]/g, '\\f')
.replace(/[\n]/g, '\\n')
.replace(/[\r]/g, '\\r')
.replace(/[\t]/g, '\\t');
}
function test_section(section) {
console.log("===%s===".bold, section);
for (var content in tests[section]) {
test = {
content: content,
spec: tests[section][content]
};
test.dumpAst = argv.dumpAst;
test.jsonErrors = argv.jsonErrors;
test.showDifferences = argv.showDifferences;
var name = escape_content(test.content);
process.stdout.write("RUNNING".yellow + " " + name + "\r");
var result = runTest(test);
if (result.passed) {
console.log('%s: "%s"', 'PASSED'.green, name);
num_successes++;
} else {
console.log('%s: "%s"', 'FAILED'.redBG.white, name);
num_failures++;
failures[section] = failures[section] || {};
failures[section][test.content] = result;
}
}
}
function go() {
if (typeof argv.filter == "string") {
var regex = new RegExp(argv.filter);
for (section in tests) {
if (tests.hasOwnProperty(section)) {
var foundOne = false;
for (test in tests[section]) {
if (test.match(regex)) {
foundOne = true;
} else {
delete tests[section][test];
}
}
if (!foundOne) {
delete tests[section];
}
}
}
} else if (typeof argv.filter != "undefined") {
console.log("Filter must be a string, given %s", typeof argv.filter);
return usage();
}
for (prop in tests) {
if (todo[prop]) {
delete tests[prop];
}
}
if (argv.dumpAst) {
var num_tests = 0;
for (prop in tests) {
if (tests.hasOwnProperty(prop)) {
num_tests += tests[prop].length;
}
}
if (num_tests > 20) {
console.log(
"Oh summer child, you really don't want to dump the Ast for %d tests. " +
"Try using --filter to run fewer tests",
num_tests
);
return usage();
}
}
for (prop in tests) {
if (tests.hasOwnProperty(prop)) {
test_section(prop);
}
}
console.log("%d/%d tests passed", num_successes, num_successes + num_failures);
if (num_failures > 0) {
console.log("*** %d TESTS FAILED! ***".redBG.white, num_failures);
for (section in failures) {
if (failures.hasOwnProperty(section)) {
console.log("===%s Failures===".bold, section);
for (test in failures[section]) {
if (failures[section].hasOwnProperty(test)) {
var result = failures[section][test];
console.log('Test failure: "%s"'.redBG.white, escape_content(test));
console.log(result.output);
}
}
}
}
process.exit(1);
}
}
function usage() {
console.log("usage: %s [OPTIONS]", process.argv[0]);
console.log("Supported options");
console.log("\t--dumpAst", "Dumps the esprima & flow ASTs before each test");
console.log("\t--filter=regex", "Only run tests that match the regex");
console.log("\t--jsonErrors", "Output errors in json format");
}
if (argv.help) {
usage();
} else {
go();
}
| bowlofstew/kythe | third_party/flow/src/parser/test/run_hardcoded_tests.js | JavaScript | apache-2.0 | 3,592 |
//// [tests/cases/compiler/allowSyntheticDefaultImports7.ts] ////
//// [b.d.ts]
export function foo();
export function bar();
//// [a.ts]
import { default as Foo } from "./b";
Foo.bar();
Foo.foo();
//// [a.js]
System.register(["./b"], function (exports_1, context_1) {
"use strict";
var __moduleName = context_1 && context_1.id;
var b_1;
return {
setters: [
function (b_1_1) {
b_1 = b_1_1;
}
],
execute: function () {
b_1["default"].bar();
b_1["default"].foo();
}
};
});
| vilic/TypeScript | tests/baselines/reference/allowSyntheticDefaultImports7.js | JavaScript | apache-2.0 | 615 |
Clazz.declarePackage ("javajs.swing");
Clazz.load (["javajs.swing.AbstractButton"], "javajs.swing.JCheckBox", null, function () {
c$ = Clazz.declareType (javajs.swing, "JCheckBox", javajs.swing.AbstractButton);
Clazz.makeConstructor (c$,
function () {
Clazz.superConstructor (this, javajs.swing.JCheckBox, ["chkJCB"]);
});
Clazz.overrideMethod (c$, "toHTML",
function () {
var s = "<label><input type=checkbox id='" + this.id + "' class='JCheckBox' style='" + this.getCSSstyle (0, 0) + "' " + (this.selected ? "checked='checked' " : "") + "onclick='SwingController.click(this)'>" + this.text + "</label>";
return s;
});
});
| bas-rustenburg/jsmol-local | j2s/javajs/swing/JCheckBox.js | JavaScript | bsd-2-clause | 626 |
/**
* @author Tim Knip / http://www.floorplanner.com/ / tim at floorplanner.com
*/
THREE.ColladaLoader = function () {
var COLLADA = null;
var scene = null;
var daeScene;
var readyCallbackFunc = null;
var sources = {};
var images = {};
var animations = {};
var controllers = {};
var geometries = {};
var materials = {};
var effects = {};
var cameras = {};
var lights = {};
var animData;
var visualScenes;
var baseUrl;
var morphs;
var skins;
var flip_uv = true;
var preferredShading = THREE.SmoothShading;
var options = {
// Force Geometry to always be centered at the local origin of the
// containing Mesh.
centerGeometry: false,
// Axis conversion is done for geometries, animations, and controllers.
// If we ever pull cameras or lights out of the COLLADA file, they'll
// need extra work.
convertUpAxis: false,
subdivideFaces: true,
upAxis: 'Y',
// For reflective or refractive materials we'll use this cubemap
defaultEnvMap: null
};
var colladaUnit = 1.0;
var colladaUp = 'Y';
var upConversion = null;
function load ( url, readyCallback, progressCallback ) {
var length = 0;
if ( document.implementation && document.implementation.createDocument ) {
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if( request.readyState == 4 ) {
if( request.status == 0 || request.status == 200 ) {
if ( request.responseXML ) {
readyCallbackFunc = readyCallback;
parse( request.responseXML, undefined, url );
} else if ( request.responseText ) {
readyCallbackFunc = readyCallback;
var xmlParser = new DOMParser();
var responseXML = xmlParser.parseFromString( request.responseText, "application/xml" );
parse( responseXML, undefined, url );
} else {
console.error( "ColladaLoader: Empty or non-existing file (" + url + ")" );
}
}
} else if ( request.readyState == 3 ) {
if ( progressCallback ) {
if ( length == 0 ) {
length = request.getResponseHeader( "Content-Length" );
}
progressCallback( { total: length, loaded: request.responseText.length } );
}
}
}
request.open( "GET", url, true );
request.send( null );
} else {
alert( "Don't know how to parse XML!" );
}
};
function parse( doc, callBack, url ) {
COLLADA = doc;
callBack = callBack || readyCallbackFunc;
if ( url !== undefined ) {
var parts = url.split( '/' );
parts.pop();
baseUrl = ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
}
parseAsset();
setUpConversion();
images = parseLib( "//dae:library_images/dae:image", _Image, "image" );
materials = parseLib( "//dae:library_materials/dae:material", Material, "material" );
effects = parseLib( "//dae:library_effects/dae:effect", Effect, "effect" );
geometries = parseLib( "//dae:library_geometries/dae:geometry", Geometry, "geometry" );
cameras = parseLib( ".//dae:library_cameras/dae:camera", Camera, "camera" );
lights = parseLib( ".//dae:library_lights/dae:light", Light, "light" );
controllers = parseLib( "//dae:library_controllers/dae:controller", Controller, "controller" );
animations = parseLib( "//dae:library_animations/dae:animation", Animation, "animation" );
visualScenes = parseLib( ".//dae:library_visual_scenes/dae:visual_scene", VisualScene, "visual_scene" );
morphs = [];
skins = [];
daeScene = parseScene();
scene = new THREE.Object3D();
for ( var i = 0; i < daeScene.nodes.length; i ++ ) {
scene.add( createSceneGraph( daeScene.nodes[ i ] ) );
}
// unit conversion
scene.scale.multiplyScalar( colladaUnit );
createAnimations();
var result = {
scene: scene,
morphs: morphs,
skins: skins,
animations: animData,
dae: {
images: images,
materials: materials,
cameras: cameras,
lights: lights,
effects: effects,
geometries: geometries,
controllers: controllers,
animations: animations,
visualScenes: visualScenes,
scene: daeScene
}
};
if ( callBack ) {
callBack( result );
}
return result;
};
function setPreferredShading ( shading ) {
preferredShading = shading;
};
function parseAsset () {
var elements = COLLADA.evaluate( '//dae:asset', COLLADA, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null );
var element = elements.iterateNext();
if ( element && element.childNodes ) {
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
switch ( child.nodeName ) {
case 'unit':
var meter = child.getAttribute( 'meter' );
if ( meter ) {
colladaUnit = parseFloat( meter );
}
break;
case 'up_axis':
colladaUp = child.textContent.charAt(0);
break;
}
}
}
};
function parseLib ( q, classSpec, prefix ) {
var elements = COLLADA.evaluate(q, COLLADA, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null) ;
var lib = {};
var element = elements.iterateNext();
var i = 0;
while ( element ) {
var daeElement = ( new classSpec() ).parse( element );
if ( !daeElement.id || daeElement.id.length == 0 ) daeElement.id = prefix + ( i ++ );
lib[ daeElement.id ] = daeElement;
element = elements.iterateNext();
}
return lib;
};
function parseScene() {
var sceneElement = COLLADA.evaluate( './/dae:scene/dae:instance_visual_scene', COLLADA, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null ).iterateNext();
if ( sceneElement ) {
var url = sceneElement.getAttribute( 'url' ).replace( /^#/, '' );
return visualScenes[ url.length > 0 ? url : 'visual_scene0' ];
} else {
return null;
}
};
function createAnimations() {
animData = [];
// fill in the keys
recurseHierarchy( scene );
};
function recurseHierarchy( node ) {
var n = daeScene.getChildById( node.name, true ),
newData = null;
if ( n && n.keys ) {
newData = {
fps: 60,
hierarchy: [ {
node: n,
keys: n.keys,
sids: n.sids
} ],
node: node,
name: 'animation_' + node.name,
length: 0
};
animData.push(newData);
for ( var i = 0, il = n.keys.length; i < il; i++ ) {
newData.length = Math.max( newData.length, n.keys[i].time );
}
} else {
newData = {
hierarchy: [ {
keys: [],
sids: []
} ]
}
}
for ( var i = 0, il = node.children.length; i < il; i++ ) {
var d = recurseHierarchy( node.children[i] );
for ( var j = 0, jl = d.hierarchy.length; j < jl; j ++ ) {
newData.hierarchy.push( {
keys: [],
sids: []
} );
}
}
return newData;
};
function calcAnimationBounds () {
var start = 1000000;
var end = -start;
var frames = 0;
for ( var id in animations ) {
var animation = animations[ id ];
for ( var i = 0; i < animation.sampler.length; i ++ ) {
var sampler = animation.sampler[ i ];
sampler.create();
start = Math.min( start, sampler.startTime );
end = Math.max( end, sampler.endTime );
frames = Math.max( frames, sampler.input.length );
}
}
return { start:start, end:end, frames:frames };
};
function createMorph ( geometry, ctrl ) {
var morphCtrl = ctrl instanceof InstanceController ? controllers[ ctrl.url ] : ctrl;
if ( !morphCtrl || !morphCtrl.morph ) {
console.log("could not find morph controller!");
return;
}
var morph = morphCtrl.morph;
for ( var i = 0; i < morph.targets.length; i ++ ) {
var target_id = morph.targets[ i ];
var daeGeometry = geometries[ target_id ];
if ( !daeGeometry.mesh ||
!daeGeometry.mesh.primitives ||
!daeGeometry.mesh.primitives.length ) {
continue;
}
var target = daeGeometry.mesh.primitives[ 0 ].geometry;
if ( target.vertices.length === geometry.vertices.length ) {
geometry.morphTargets.push( { name: "target_1", vertices: target.vertices } );
}
}
geometry.morphTargets.push( { name: "target_Z", vertices: geometry.vertices } );
};
function createSkin ( geometry, ctrl, applyBindShape ) {
var skinCtrl = controllers[ ctrl.url ];
if ( !skinCtrl || !skinCtrl.skin ) {
console.log( "could not find skin controller!" );
return;
}
if ( !ctrl.skeleton || !ctrl.skeleton.length ) {
console.log( "could not find the skeleton for the skin!" );
return;
}
var skin = skinCtrl.skin;
var skeleton = daeScene.getChildById( ctrl.skeleton[ 0 ] );
var hierarchy = [];
applyBindShape = applyBindShape !== undefined ? applyBindShape : true;
var bones = [];
geometry.skinWeights = [];
geometry.skinIndices = [];
//createBones( geometry.bones, skin, hierarchy, skeleton, null, -1 );
//createWeights( skin, geometry.bones, geometry.skinIndices, geometry.skinWeights );
/*
geometry.animation = {
name: 'take_001',
fps: 30,
length: 2,
JIT: true,
hierarchy: hierarchy
};
*/
if ( applyBindShape ) {
for ( var i = 0; i < geometry.vertices.length; i ++ ) {
geometry.vertices[ i ].applyMatrix4( skin.bindShapeMatrix );
}
}
};
function setupSkeleton ( node, bones, frame, parent ) {
node.world = node.world || new THREE.Matrix4();
node.world.copy( node.matrix );
if ( node.channels && node.channels.length ) {
var channel = node.channels[ 0 ];
var m = channel.sampler.output[ frame ];
if ( m instanceof THREE.Matrix4 ) {
node.world.copy( m );
}
}
if ( parent ) {
node.world.multiplyMatrices( parent, node.world );
}
bones.push( node );
for ( var i = 0; i < node.nodes.length; i ++ ) {
setupSkeleton( node.nodes[ i ], bones, frame, node.world );
}
};
function setupSkinningMatrices ( bones, skin ) {
// FIXME: this is dumb...
for ( var i = 0; i < bones.length; i ++ ) {
var bone = bones[ i ];
var found = -1;
if ( bone.type != 'JOINT' ) continue;
for ( var j = 0; j < skin.joints.length; j ++ ) {
if ( bone.sid == skin.joints[ j ] ) {
found = j;
break;
}
}
if ( found >= 0 ) {
var inv = skin.invBindMatrices[ found ];
bone.invBindMatrix = inv;
bone.skinningMatrix = new THREE.Matrix4();
bone.skinningMatrix.multiplyMatrices(bone.world, inv); // (IBMi * JMi)
bone.weights = [];
for ( var j = 0; j < skin.weights.length; j ++ ) {
for (var k = 0; k < skin.weights[ j ].length; k ++) {
var w = skin.weights[ j ][ k ];
if ( w.joint == found ) {
bone.weights.push( w );
}
}
}
} else {
throw 'ColladaLoader: Could not find joint \'' + bone.sid + '\'.';
}
}
};
function applySkin ( geometry, instanceCtrl, frame ) {
var skinController = controllers[ instanceCtrl.url ];
frame = frame !== undefined ? frame : 40;
if ( !skinController || !skinController.skin ) {
console.log( 'ColladaLoader: Could not find skin controller.' );
return;
}
if ( !instanceCtrl.skeleton || !instanceCtrl.skeleton.length ) {
console.log( 'ColladaLoader: Could not find the skeleton for the skin. ' );
return;
}
var animationBounds = calcAnimationBounds();
var skeleton = daeScene.getChildById( instanceCtrl.skeleton[0], true ) ||
daeScene.getChildBySid( instanceCtrl.skeleton[0], true );
var i, j, w, vidx, weight;
var v = new THREE.Vector3(), o, s;
// move vertices to bind shape
for ( i = 0; i < geometry.vertices.length; i ++ ) {
geometry.vertices[i].applyMatrix4( skinController.skin.bindShapeMatrix );
}
// process animation, or simply pose the rig if no animation
for ( frame = 0; frame < animationBounds.frames; frame ++ ) {
var bones = [];
var skinned = [];
// zero skinned vertices
for ( i = 0; i < geometry.vertices.length; i++ ) {
skinned.push( new THREE.Vector3() );
}
// process the frame and setup the rig with a fresh
// transform, possibly from the bone's animation channel(s)
setupSkeleton( skeleton, bones, frame );
setupSkinningMatrices( bones, skinController.skin );
// skin 'm
for ( i = 0; i < bones.length; i ++ ) {
if ( bones[ i ].type != 'JOINT' ) continue;
for ( j = 0; j < bones[ i ].weights.length; j ++ ) {
w = bones[ i ].weights[ j ];
vidx = w.index;
weight = w.weight;
o = geometry.vertices[vidx];
s = skinned[vidx];
v.x = o.x;
v.y = o.y;
v.z = o.z;
v.applyMatrix4( bones[i].skinningMatrix );
s.x += (v.x * weight);
s.y += (v.y * weight);
s.z += (v.z * weight);
}
}
geometry.morphTargets.push( { name: "target_" + frame, vertices: skinned } );
}
};
function createSceneGraph ( node, parent ) {
var obj = new THREE.Object3D();
var skinned = false;
var skinController;
var morphController;
var i, j;
// FIXME: controllers
for ( i = 0; i < node.controllers.length; i ++ ) {
var controller = controllers[ node.controllers[ i ].url ];
switch ( controller.type ) {
case 'skin':
if ( geometries[ controller.skin.source ] ) {
var inst_geom = new InstanceGeometry();
inst_geom.url = controller.skin.source;
inst_geom.instance_material = node.controllers[ i ].instance_material;
node.geometries.push( inst_geom );
skinned = true;
skinController = node.controllers[ i ];
} else if ( controllers[ controller.skin.source ] ) {
// urgh: controller can be chained
// handle the most basic case...
var second = controllers[ controller.skin.source ];
morphController = second;
// skinController = node.controllers[i];
if ( second.morph && geometries[ second.morph.source ] ) {
var inst_geom = new InstanceGeometry();
inst_geom.url = second.morph.source;
inst_geom.instance_material = node.controllers[ i ].instance_material;
node.geometries.push( inst_geom );
}
}
break;
case 'morph':
if ( geometries[ controller.morph.source ] ) {
var inst_geom = new InstanceGeometry();
inst_geom.url = controller.morph.source;
inst_geom.instance_material = node.controllers[ i ].instance_material;
node.geometries.push( inst_geom );
morphController = node.controllers[ i ];
}
console.log( 'ColladaLoader: Morph-controller partially supported.' );
default:
break;
}
}
// FIXME: multi-material mesh?
// geometries
var double_sided_materials = {};
for ( i = 0; i < node.geometries.length; i ++ ) {
var instance_geometry = node.geometries[i];
var instance_materials = instance_geometry.instance_material;
var geometry = geometries[ instance_geometry.url ];
var used_materials = {};
var used_materials_array = [];
var num_materials = 0;
var first_material;
if ( geometry ) {
if ( !geometry.mesh || !geometry.mesh.primitives )
continue;
if ( obj.name.length == 0 ) {
obj.name = geometry.id;
}
// collect used fx for this geometry-instance
if ( instance_materials ) {
for ( j = 0; j < instance_materials.length; j ++ ) {
var instance_material = instance_materials[ j ];
var mat = materials[ instance_material.target ];
var effect_id = mat.instance_effect.url;
var shader = effects[ effect_id ].shader;
var material3js = shader.material;
if ( geometry.doubleSided ) {
if ( !( material3js in double_sided_materials ) ) {
var _copied_material = material3js.clone();
_copied_material.side = THREE.DoubleSide;
double_sided_materials[ material3js ] = _copied_material;
}
material3js = double_sided_materials[ material3js ];
}
material3js.opacity = !material3js.opacity ? 1 : material3js.opacity;
used_materials[ instance_material.symbol ] = num_materials;
used_materials_array.push( material3js );
first_material = material3js;
first_material.name = mat.name == null || mat.name === '' ? mat.id : mat.name;
num_materials ++;
}
}
var mesh;
var material = first_material || new THREE.MeshLambertMaterial( { color: 0xdddddd, shading: THREE.FlatShading, side: geometry.doubleSided ? THREE.DoubleSide : THREE.FrontSide } );
var geom = geometry.mesh.geometry3js;
if ( num_materials > 1 ) {
material = new THREE.MeshFaceMaterial( used_materials_array );
for ( j = 0; j < geom.faces.length; j ++ ) {
var face = geom.faces[ j ];
face.materialIndex = used_materials[ face.daeMaterial ]
}
}
if ( skinController !== undefined ) {
applySkin( geom, skinController );
material.morphTargets = true;
mesh = new THREE.SkinnedMesh( geom, material, false );
mesh.skeleton = skinController.skeleton;
mesh.skinController = controllers[ skinController.url ];
mesh.skinInstanceController = skinController;
mesh.name = 'skin_' + skins.length;
skins.push( mesh );
} else if ( morphController !== undefined ) {
createMorph( geom, morphController );
material.morphTargets = true;
mesh = new THREE.Mesh( geom, material );
mesh.name = 'morph_' + morphs.length;
morphs.push( mesh );
} else {
mesh = new THREE.Mesh( geom, material );
// mesh.geom.name = geometry.id;
}
node.geometries.length > 1 ? obj.add( mesh ) : obj = mesh;
}
}
for ( i = 0; i < node.cameras.length; i ++ ) {
var params = cameras[node.cameras[i].url];
obj = new THREE.PerspectiveCamera(params.fov, params.aspect_ratio, params.znear, params.zfar);
}
for ( i = 0; i < node.lights.length; i ++ ) {
var params = lights[node.lights[i].url];
switch ( params.technique ) {
case 'ambient':
obj = new THREE.AmbientLight(params.color);
break;
case 'point':
obj = new THREE.PointLight(params.color);
break;
case 'directional':
obj = new THREE.DirectionalLight(params.color);
break;
}
}
obj.name = node.name || node.id || "";
obj.matrix = node.matrix;
var props = node.matrix.decompose();
obj.position = props[ 0 ];
obj.quaternion = props[ 1 ];
obj.useQuaternion = true;
obj.scale = props[ 2 ];
if ( options.centerGeometry && obj.geometry ) {
var delta = THREE.GeometryUtils.center( obj.geometry );
delta.multiply( obj.scale );
delta.applyQuaternion( obj.quaternion );
obj.position.sub( delta );
}
for ( i = 0; i < node.nodes.length; i ++ ) {
obj.add( createSceneGraph( node.nodes[i], node ) );
}
return obj;
};
function getJointId( skin, id ) {
for ( var i = 0; i < skin.joints.length; i ++ ) {
if ( skin.joints[ i ] == id ) {
return i;
}
}
};
function getLibraryNode( id ) {
return COLLADA.evaluate( './/dae:library_nodes//dae:node[@id=\'' + id + '\']', COLLADA, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null ).iterateNext();
};
function getChannelsForNode (node ) {
var channels = [];
var startTime = 1000000;
var endTime = -1000000;
for ( var id in animations ) {
var animation = animations[id];
for ( var i = 0; i < animation.channel.length; i ++ ) {
var channel = animation.channel[i];
var sampler = animation.sampler[i];
var id = channel.target.split('/')[0];
if ( id == node.id ) {
sampler.create();
channel.sampler = sampler;
startTime = Math.min(startTime, sampler.startTime);
endTime = Math.max(endTime, sampler.endTime);
channels.push(channel);
}
}
}
if ( channels.length ) {
node.startTime = startTime;
node.endTime = endTime;
}
return channels;
};
function calcFrameDuration( node ) {
var minT = 10000000;
for ( var i = 0; i < node.channels.length; i ++ ) {
var sampler = node.channels[i].sampler;
for ( var j = 0; j < sampler.input.length - 1; j ++ ) {
var t0 = sampler.input[ j ];
var t1 = sampler.input[ j + 1 ];
minT = Math.min( minT, t1 - t0 );
}
}
return minT;
};
function calcMatrixAt( node, t ) {
var animated = {};
var i, j;
for ( i = 0; i < node.channels.length; i ++ ) {
var channel = node.channels[ i ];
animated[ channel.sid ] = channel;
}
var matrix = new THREE.Matrix4();
for ( i = 0; i < node.transforms.length; i ++ ) {
var transform = node.transforms[ i ];
var channel = animated[ transform.sid ];
if ( channel !== undefined ) {
var sampler = channel.sampler;
var value;
for ( j = 0; j < sampler.input.length - 1; j ++ ) {
if ( sampler.input[ j + 1 ] > t ) {
value = sampler.output[ j ];
//console.log(value.flatten)
break;
}
}
if ( value !== undefined ) {
if ( value instanceof THREE.Matrix4 ) {
matrix.multiplyMatrices( matrix, value );
} else {
// FIXME: handle other types
matrix.multiplyMatrices( matrix, transform.matrix );
}
} else {
matrix.multiplyMatrices( matrix, transform.matrix );
}
} else {
matrix.multiplyMatrices( matrix, transform.matrix );
}
}
return matrix;
};
function bakeAnimations ( node ) {
if ( node.channels && node.channels.length ) {
var keys = [],
sids = [];
for ( var i = 0, il = node.channels.length; i < il; i++ ) {
var channel = node.channels[i],
fullSid = channel.fullSid,
sampler = channel.sampler,
input = sampler.input,
transform = node.getTransformBySid( channel.sid ),
member;
if ( channel.arrIndices ) {
member = [];
for ( var j = 0, jl = channel.arrIndices.length; j < jl; j++ ) {
member[ j ] = getConvertedIndex( channel.arrIndices[ j ] );
}
} else {
member = getConvertedMember( channel.member );
}
if ( transform ) {
if ( sids.indexOf( fullSid ) === -1 ) {
sids.push( fullSid );
}
for ( var j = 0, jl = input.length; j < jl; j++ ) {
var time = input[j],
data = sampler.getData( transform.type, j ),
key = findKey( keys, time );
if ( !key ) {
key = new Key( time );
var timeNdx = findTimeNdx( keys, time );
keys.splice( timeNdx == -1 ? keys.length : timeNdx, 0, key );
}
key.addTarget( fullSid, transform, member, data );
}
} else {
console.log( 'Could not find transform "' + channel.sid + '" in node ' + node.id );
}
}
// post process
for ( var i = 0; i < sids.length; i++ ) {
var sid = sids[ i ];
for ( var j = 0; j < keys.length; j++ ) {
var key = keys[ j ];
if ( !key.hasTarget( sid ) ) {
interpolateKeys( keys, key, j, sid );
}
}
}
node.keys = keys;
node.sids = sids;
}
};
function findKey ( keys, time) {
var retVal = null;
for ( var i = 0, il = keys.length; i < il && retVal == null; i++ ) {
var key = keys[i];
if ( key.time === time ) {
retVal = key;
} else if ( key.time > time ) {
break;
}
}
return retVal;
};
function findTimeNdx ( keys, time) {
var ndx = -1;
for ( var i = 0, il = keys.length; i < il && ndx == -1; i++ ) {
var key = keys[i];
if ( key.time >= time ) {
ndx = i;
}
}
return ndx;
};
function interpolateKeys ( keys, key, ndx, fullSid ) {
var prevKey = getPrevKeyWith( keys, fullSid, ndx ? ndx-1 : 0 ),
nextKey = getNextKeyWith( keys, fullSid, ndx+1 );
if ( prevKey && nextKey ) {
var scale = (key.time - prevKey.time) / (nextKey.time - prevKey.time),
prevTarget = prevKey.getTarget( fullSid ),
nextData = nextKey.getTarget( fullSid ).data,
prevData = prevTarget.data,
data;
if ( prevTarget.type === 'matrix' ) {
data = prevData;
} else if ( prevData.length ) {
data = [];
for ( var i = 0; i < prevData.length; ++i ) {
data[ i ] = prevData[ i ] + ( nextData[ i ] - prevData[ i ] ) * scale;
}
} else {
data = prevData + ( nextData - prevData ) * scale;
}
key.addTarget( fullSid, prevTarget.transform, prevTarget.member, data );
}
};
// Get next key with given sid
function getNextKeyWith( keys, fullSid, ndx ) {
for ( ; ndx < keys.length; ndx++ ) {
var key = keys[ ndx ];
if ( key.hasTarget( fullSid ) ) {
return key;
}
}
return null;
};
// Get previous key with given sid
function getPrevKeyWith( keys, fullSid, ndx ) {
ndx = ndx >= 0 ? ndx : ndx + keys.length;
for ( ; ndx >= 0; ndx-- ) {
var key = keys[ ndx ];
if ( key.hasTarget( fullSid ) ) {
return key;
}
}
return null;
};
function _Image() {
this.id = "";
this.init_from = "";
};
_Image.prototype.parse = function(element) {
this.id = element.getAttribute('id');
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
if ( child.nodeName == 'init_from' ) {
this.init_from = child.textContent;
}
}
return this;
};
function Controller() {
this.id = "";
this.name = "";
this.type = "";
this.skin = null;
this.morph = null;
};
Controller.prototype.parse = function( element ) {
this.id = element.getAttribute('id');
this.name = element.getAttribute('name');
this.type = "none";
for ( var i = 0; i < element.childNodes.length; i++ ) {
var child = element.childNodes[ i ];
switch ( child.nodeName ) {
case 'skin':
this.skin = (new Skin()).parse(child);
this.type = child.nodeName;
break;
case 'morph':
this.morph = (new Morph()).parse(child);
this.type = child.nodeName;
break;
default:
break;
}
}
return this;
};
function Morph() {
this.method = null;
this.source = null;
this.targets = null;
this.weights = null;
};
Morph.prototype.parse = function( element ) {
var sources = {};
var inputs = [];
var i;
this.method = element.getAttribute( 'method' );
this.source = element.getAttribute( 'source' ).replace( /^#/, '' );
for ( i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
if ( child.nodeType != 1 ) continue;
switch ( child.nodeName ) {
case 'source':
var source = ( new Source() ).parse( child );
sources[ source.id ] = source;
break;
case 'targets':
inputs = this.parseInputs( child );
break;
default:
console.log( child.nodeName );
break;
}
}
for ( i = 0; i < inputs.length; i ++ ) {
var input = inputs[ i ];
var source = sources[ input.source ];
switch ( input.semantic ) {
case 'MORPH_TARGET':
this.targets = source.read();
break;
case 'MORPH_WEIGHT':
this.weights = source.read();
break;
default:
break;
}
}
return this;
};
Morph.prototype.parseInputs = function(element) {
var inputs = [];
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[i];
if ( child.nodeType != 1) continue;
switch ( child.nodeName ) {
case 'input':
inputs.push( (new Input()).parse(child) );
break;
default:
break;
}
}
return inputs;
};
function Skin() {
this.source = "";
this.bindShapeMatrix = null;
this.invBindMatrices = [];
this.joints = [];
this.weights = [];
};
Skin.prototype.parse = function( element ) {
var sources = {};
var joints, weights;
this.source = element.getAttribute( 'source' ).replace( /^#/, '' );
this.invBindMatrices = [];
this.joints = [];
this.weights = [];
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[i];
if ( child.nodeType != 1 ) continue;
switch ( child.nodeName ) {
case 'bind_shape_matrix':
var f = _floats(child.textContent);
this.bindShapeMatrix = getConvertedMat4( f );
break;
case 'source':
var src = new Source().parse(child);
sources[ src.id ] = src;
break;
case 'joints':
joints = child;
break;
case 'vertex_weights':
weights = child;
break;
default:
console.log( child.nodeName );
break;
}
}
this.parseJoints( joints, sources );
this.parseWeights( weights, sources );
return this;
};
Skin.prototype.parseJoints = function ( element, sources ) {
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
if ( child.nodeType != 1 ) continue;
switch ( child.nodeName ) {
case 'input':
var input = ( new Input() ).parse( child );
var source = sources[ input.source ];
if ( input.semantic == 'JOINT' ) {
this.joints = source.read();
} else if ( input.semantic == 'INV_BIND_MATRIX' ) {
this.invBindMatrices = source.read();
}
break;
default:
break;
}
}
};
Skin.prototype.parseWeights = function ( element, sources ) {
var v, vcount, inputs = [];
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
if ( child.nodeType != 1 ) continue;
switch ( child.nodeName ) {
case 'input':
inputs.push( ( new Input() ).parse( child ) );
break;
case 'v':
v = _ints( child.textContent );
break;
case 'vcount':
vcount = _ints( child.textContent );
break;
default:
break;
}
}
var index = 0;
for ( var i = 0; i < vcount.length; i ++ ) {
var numBones = vcount[i];
var vertex_weights = [];
for ( var j = 0; j < numBones; j++ ) {
var influence = {};
for ( var k = 0; k < inputs.length; k ++ ) {
var input = inputs[ k ];
var value = v[ index + input.offset ];
switch ( input.semantic ) {
case 'JOINT':
influence.joint = value;//this.joints[value];
break;
case 'WEIGHT':
influence.weight = sources[ input.source ].data[ value ];
break;
default:
break;
}
}
vertex_weights.push( influence );
index += inputs.length;
}
for ( var j = 0; j < vertex_weights.length; j ++ ) {
vertex_weights[ j ].index = i;
}
this.weights.push( vertex_weights );
}
};
function VisualScene () {
this.id = "";
this.name = "";
this.nodes = [];
this.scene = new THREE.Object3D();
};
VisualScene.prototype.getChildById = function( id, recursive ) {
for ( var i = 0; i < this.nodes.length; i ++ ) {
var node = this.nodes[ i ].getChildById( id, recursive );
if ( node ) {
return node;
}
}
return null;
};
VisualScene.prototype.getChildBySid = function( sid, recursive ) {
for ( var i = 0; i < this.nodes.length; i ++ ) {
var node = this.nodes[ i ].getChildBySid( sid, recursive );
if ( node ) {
return node;
}
}
return null;
};
VisualScene.prototype.parse = function( element ) {
this.id = element.getAttribute( 'id' );
this.name = element.getAttribute( 'name' );
this.nodes = [];
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
if ( child.nodeType != 1 ) continue;
switch ( child.nodeName ) {
case 'node':
this.nodes.push( ( new Node() ).parse( child ) );
break;
default:
break;
}
}
return this;
};
function Node() {
this.id = "";
this.name = "";
this.sid = "";
this.nodes = [];
this.controllers = [];
this.transforms = [];
this.geometries = [];
this.channels = [];
this.matrix = new THREE.Matrix4();
};
Node.prototype.getChannelForTransform = function( transformSid ) {
for ( var i = 0; i < this.channels.length; i ++ ) {
var channel = this.channels[i];
var parts = channel.target.split('/');
var id = parts.shift();
var sid = parts.shift();
var dotSyntax = (sid.indexOf(".") >= 0);
var arrSyntax = (sid.indexOf("(") >= 0);
var arrIndices;
var member;
if ( dotSyntax ) {
parts = sid.split(".");
sid = parts.shift();
member = parts.shift();
} else if ( arrSyntax ) {
arrIndices = sid.split("(");
sid = arrIndices.shift();
for ( var j = 0; j < arrIndices.length; j ++ ) {
arrIndices[ j ] = parseInt( arrIndices[ j ].replace( /\)/, '' ) );
}
}
if ( sid == transformSid ) {
channel.info = { sid: sid, dotSyntax: dotSyntax, arrSyntax: arrSyntax, arrIndices: arrIndices };
return channel;
}
}
return null;
};
Node.prototype.getChildById = function ( id, recursive ) {
if ( this.id == id ) {
return this;
}
if ( recursive ) {
for ( var i = 0; i < this.nodes.length; i ++ ) {
var n = this.nodes[ i ].getChildById( id, recursive );
if ( n ) {
return n;
}
}
}
return null;
};
Node.prototype.getChildBySid = function ( sid, recursive ) {
if ( this.sid == sid ) {
return this;
}
if ( recursive ) {
for ( var i = 0; i < this.nodes.length; i ++ ) {
var n = this.nodes[ i ].getChildBySid( sid, recursive );
if ( n ) {
return n;
}
}
}
return null;
};
Node.prototype.getTransformBySid = function ( sid ) {
for ( var i = 0; i < this.transforms.length; i ++ ) {
if ( this.transforms[ i ].sid == sid ) return this.transforms[ i ];
}
return null;
};
Node.prototype.parse = function( element ) {
var url;
this.id = element.getAttribute('id');
this.sid = element.getAttribute('sid');
this.name = element.getAttribute('name');
this.type = element.getAttribute('type');
this.type = this.type == 'JOINT' ? this.type : 'NODE';
this.nodes = [];
this.transforms = [];
this.geometries = [];
this.cameras = [];
this.lights = [];
this.controllers = [];
this.matrix = new THREE.Matrix4();
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
if ( child.nodeType != 1 ) continue;
switch ( child.nodeName ) {
case 'node':
this.nodes.push( ( new Node() ).parse( child ) );
break;
case 'instance_camera':
this.cameras.push( ( new InstanceCamera() ).parse( child ) );
break;
case 'instance_light':
this.lights.push( ( new InstanceLight() ).parse( child ) );
break;
case 'instance_controller':
this.controllers.push( ( new InstanceController() ).parse( child ) );
break;
case 'instance_geometry':
this.geometries.push( ( new InstanceGeometry() ).parse( child ) );
break;
case 'instance_node':
url = child.getAttribute( 'url' ).replace( /^#/, '' );
var iNode = getLibraryNode( url );
if ( iNode ) {
this.nodes.push( ( new Node() ).parse( iNode )) ;
}
break;
case 'rotate':
case 'translate':
case 'scale':
case 'matrix':
case 'lookat':
case 'skew':
this.transforms.push( ( new Transform() ).parse( child ) );
break;
case 'extra':
break;
default:
console.log( child.nodeName );
break;
}
}
this.channels = getChannelsForNode( this );
bakeAnimations( this );
this.updateMatrix();
return this;
};
Node.prototype.updateMatrix = function () {
this.matrix.identity();
for ( var i = 0; i < this.transforms.length; i ++ ) {
this.transforms[ i ].apply( this.matrix );
}
};
function Transform () {
this.sid = "";
this.type = "";
this.data = [];
this.obj = null;
};
Transform.prototype.parse = function ( element ) {
this.sid = element.getAttribute( 'sid' );
this.type = element.nodeName;
this.data = _floats( element.textContent );
this.convert();
return this;
};
Transform.prototype.convert = function () {
switch ( this.type ) {
case 'matrix':
this.obj = getConvertedMat4( this.data );
break;
case 'rotate':
this.angle = THREE.Math.degToRad( this.data[3] );
case 'translate':
fixCoords( this.data, -1 );
this.obj = new THREE.Vector3( this.data[ 0 ], this.data[ 1 ], this.data[ 2 ] );
break;
case 'scale':
fixCoords( this.data, 1 );
this.obj = new THREE.Vector3( this.data[ 0 ], this.data[ 1 ], this.data[ 2 ] );
break;
default:
console.log( 'Can not convert Transform of type ' + this.type );
break;
}
};
Transform.prototype.apply = function () {
var m1 = new THREE.Matrix4();
return function ( matrix ) {
switch ( this.type ) {
case 'matrix':
matrix.multiply( this.obj );
break;
case 'translate':
matrix.multiply( m1.makeTranslation( this.obj.x, this.obj.y, this.obj.z ) );
break;
case 'rotate':
matrix.multiply( m1.makeRotationAxis( this.obj, this.angle ) );
break;
case 'scale':
matrix.scale( this.obj );
break;
}
};
}();
Transform.prototype.update = function ( data, member ) {
var members = [ 'X', 'Y', 'Z', 'ANGLE' ];
switch ( this.type ) {
case 'matrix':
if ( ! member ) {
this.obj.copy( data );
} else if ( member.length === 1 ) {
switch ( member[ 0 ] ) {
case 0:
this.obj.n11 = data[ 0 ];
this.obj.n21 = data[ 1 ];
this.obj.n31 = data[ 2 ];
this.obj.n41 = data[ 3 ];
break;
case 1:
this.obj.n12 = data[ 0 ];
this.obj.n22 = data[ 1 ];
this.obj.n32 = data[ 2 ];
this.obj.n42 = data[ 3 ];
break;
case 2:
this.obj.n13 = data[ 0 ];
this.obj.n23 = data[ 1 ];
this.obj.n33 = data[ 2 ];
this.obj.n43 = data[ 3 ];
break;
case 3:
this.obj.n14 = data[ 0 ];
this.obj.n24 = data[ 1 ];
this.obj.n34 = data[ 2 ];
this.obj.n44 = data[ 3 ];
break;
}
} else if ( member.length === 2 ) {
var propName = 'n' + ( member[ 0 ] + 1 ) + ( member[ 1 ] + 1 );
this.obj[ propName ] = data;
} else {
console.log('Incorrect addressing of matrix in transform.');
}
break;
case 'translate':
case 'scale':
if ( Object.prototype.toString.call( member ) === '[object Array]' ) {
member = members[ member[ 0 ] ];
}
switch ( member ) {
case 'X':
this.obj.x = data;
break;
case 'Y':
this.obj.y = data;
break;
case 'Z':
this.obj.z = data;
break;
default:
this.obj.x = data[ 0 ];
this.obj.y = data[ 1 ];
this.obj.z = data[ 2 ];
break;
}
break;
case 'rotate':
if ( Object.prototype.toString.call( member ) === '[object Array]' ) {
member = members[ member[ 0 ] ];
}
switch ( member ) {
case 'X':
this.obj.x = data;
break;
case 'Y':
this.obj.y = data;
break;
case 'Z':
this.obj.z = data;
break;
case 'ANGLE':
this.angle = THREE.Math.degToRad( data );
break;
default:
this.obj.x = data[ 0 ];
this.obj.y = data[ 1 ];
this.obj.z = data[ 2 ];
this.angle = THREE.Math.degToRad( data[ 3 ] );
break;
}
break;
}
};
function InstanceController() {
this.url = "";
this.skeleton = [];
this.instance_material = [];
};
InstanceController.prototype.parse = function ( element ) {
this.url = element.getAttribute('url').replace(/^#/, '');
this.skeleton = [];
this.instance_material = [];
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'skeleton':
this.skeleton.push( child.textContent.replace(/^#/, '') );
break;
case 'bind_material':
var instances = COLLADA.evaluate( './/dae:instance_material', child, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null );
if ( instances ) {
var instance = instances.iterateNext();
while ( instance ) {
this.instance_material.push( (new InstanceMaterial()).parse(instance) );
instance = instances.iterateNext();
}
}
break;
case 'extra':
break;
default:
break;
}
}
return this;
};
function InstanceMaterial () {
this.symbol = "";
this.target = "";
};
InstanceMaterial.prototype.parse = function ( element ) {
this.symbol = element.getAttribute('symbol');
this.target = element.getAttribute('target').replace(/^#/, '');
return this;
};
function InstanceGeometry() {
this.url = "";
this.instance_material = [];
};
InstanceGeometry.prototype.parse = function ( element ) {
this.url = element.getAttribute('url').replace(/^#/, '');
this.instance_material = [];
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[i];
if ( child.nodeType != 1 ) continue;
if ( child.nodeName == 'bind_material' ) {
var instances = COLLADA.evaluate( './/dae:instance_material', child, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null );
if ( instances ) {
var instance = instances.iterateNext();
while ( instance ) {
this.instance_material.push( (new InstanceMaterial()).parse(instance) );
instance = instances.iterateNext();
}
}
break;
}
}
return this;
};
function Geometry() {
this.id = "";
this.mesh = null;
};
Geometry.prototype.parse = function ( element ) {
this.id = element.getAttribute('id');
extractDoubleSided( this, element );
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[i];
switch ( child.nodeName ) {
case 'mesh':
this.mesh = (new Mesh(this)).parse(child);
break;
case 'extra':
// console.log( child );
break;
default:
break;
}
}
return this;
};
function Mesh( geometry ) {
this.geometry = geometry.id;
this.primitives = [];
this.vertices = null;
this.geometry3js = null;
};
Mesh.prototype.parse = function( element ) {
this.primitives = [];
var i, j;
for ( i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
switch ( child.nodeName ) {
case 'source':
_source( child );
break;
case 'vertices':
this.vertices = ( new Vertices() ).parse( child );
break;
case 'triangles':
this.primitives.push( ( new Triangles().parse( child ) ) );
break;
case 'polygons':
this.primitives.push( ( new Polygons().parse( child ) ) );
break;
case 'polylist':
this.primitives.push( ( new Polylist().parse( child ) ) );
break;
default:
break;
}
}
this.geometry3js = new THREE.Geometry();
var vertexData = sources[ this.vertices.input['POSITION'].source ].data;
for ( i = 0; i < vertexData.length; i += 3 ) {
this.geometry3js.vertices.push( getConvertedVec3( vertexData, i ).clone() );
}
for ( i = 0; i < this.primitives.length; i ++ ) {
var primitive = this.primitives[ i ];
primitive.setVertices( this.vertices );
this.handlePrimitive( primitive, this.geometry3js );
}
this.geometry3js.computeCentroids();
this.geometry3js.computeFaceNormals();
if ( this.geometry3js.calcNormals ) {
this.geometry3js.computeVertexNormals();
delete this.geometry3js.calcNormals;
}
this.geometry3js.computeBoundingBox();
return this;
};
Mesh.prototype.handlePrimitive = function( primitive, geom ) {
var j, k, pList = primitive.p, inputs = primitive.inputs;
var input, index, idx32;
var source, numParams;
var vcIndex = 0, vcount = 3, maxOffset = 0;
var texture_sets = [];
for ( j = 0; j < inputs.length; j ++ ) {
input = inputs[ j ];
var offset = input.offset + 1;
maxOffset = (maxOffset < offset)? offset : maxOffset;
switch ( input.semantic ) {
case 'TEXCOORD':
texture_sets.push( input.set );
break;
}
}
for ( var pCount = 0; pCount < pList.length; ++pCount ) {
var p = pList[ pCount ], i = 0;
while ( i < p.length ) {
var vs = [];
var ns = [];
var ts = null;
var cs = [];
if ( primitive.vcount ) {
vcount = primitive.vcount.length ? primitive.vcount[ vcIndex ++ ] : primitive.vcount;
} else {
vcount = p.length / maxOffset;
}
for ( j = 0; j < vcount; j ++ ) {
for ( k = 0; k < inputs.length; k ++ ) {
input = inputs[ k ];
source = sources[ input.source ];
index = p[ i + ( j * maxOffset ) + input.offset ];
numParams = source.accessor.params.length;
idx32 = index * numParams;
switch ( input.semantic ) {
case 'VERTEX':
vs.push( index );
break;
case 'NORMAL':
ns.push( getConvertedVec3( source.data, idx32 ) );
break;
case 'TEXCOORD':
ts = ts || { };
if ( ts[ input.set ] === undefined ) ts[ input.set ] = [];
// invert the V
ts[ input.set ].push( new THREE.Vector2( source.data[ idx32 ], source.data[ idx32 + 1 ] ) );
break;
case 'COLOR':
cs.push( new THREE.Color().setRGB( source.data[ idx32 ], source.data[ idx32 + 1 ], source.data[ idx32 + 2 ] ) );
break;
default:
break;
}
}
}
if ( ns.length == 0 ) {
// check the vertices inputs
input = this.vertices.input.NORMAL;
if ( input ) {
source = sources[ input.source ];
numParams = source.accessor.params.length;
for ( var ndx = 0, len = vs.length; ndx < len; ndx++ ) {
ns.push( getConvertedVec3( source.data, vs[ ndx ] * numParams ) );
}
} else {
geom.calcNormals = true;
}
}
if ( !ts ) {
ts = { };
// check the vertices inputs
input = this.vertices.input.TEXCOORD;
if ( input ) {
texture_sets.push( input.set );
source = sources[ input.source ];
numParams = source.accessor.params.length;
for ( var ndx = 0, len = vs.length; ndx < len; ndx++ ) {
idx32 = vs[ ndx ] * numParams;
if ( ts[ input.set ] === undefined ) ts[ input.set ] = [ ];
// invert the V
ts[ input.set ].push( new THREE.Vector2( source.data[ idx32 ], 1.0 - source.data[ idx32 + 1 ] ) );
}
}
}
if ( cs.length == 0 ) {
// check the vertices inputs
input = this.vertices.input.COLOR;
if ( input ) {
source = sources[ input.source ];
numParams = source.accessor.params.length;
for ( var ndx = 0, len = vs.length; ndx < len; ndx++ ) {
idx32 = vs[ ndx ] * numParams;
cs.push( new THREE.Color().setRGB( source.data[ idx32 ], source.data[ idx32 + 1 ], source.data[ idx32 + 2 ] ) );
}
}
}
var face = null, faces = [], uv, uvArr;
if ( vcount === 3 ) {
faces.push( new THREE.Face3( vs[0], vs[1], vs[2], ns, cs.length ? cs : new THREE.Color() ) );
} else if ( vcount === 4 ) {
faces.push( new THREE.Face4( vs[0], vs[1], vs[2], vs[3], ns, cs.length ? cs : new THREE.Color() ) );
} else if ( vcount > 4 && options.subdivideFaces ) {
var clr = cs.length ? cs : new THREE.Color(),
vec1, vec2, vec3, v1, v2, norm;
// subdivide into multiple Face3s
for ( k = 1; k < vcount - 1; ) {
// FIXME: normals don't seem to be quite right
faces.push( new THREE.Face3( vs[0], vs[k], vs[k+1], [ ns[0], ns[k++], ns[k] ], clr ) );
}
}
if ( faces.length ) {
for ( var ndx = 0, len = faces.length; ndx < len; ndx ++ ) {
face = faces[ndx];
face.daeMaterial = primitive.material;
geom.faces.push( face );
for ( k = 0; k < texture_sets.length; k++ ) {
uv = ts[ texture_sets[k] ];
if ( vcount > 4 ) {
// Grab the right UVs for the vertices in this face
uvArr = [ uv[0], uv[ndx+1], uv[ndx+2] ];
} else if ( vcount === 4 ) {
uvArr = [ uv[0], uv[1], uv[2], uv[3] ];
} else {
uvArr = [ uv[0], uv[1], uv[2] ];
}
if ( !geom.faceVertexUvs[k] ) {
geom.faceVertexUvs[k] = [];
}
geom.faceVertexUvs[k].push( uvArr );
}
}
} else {
console.log( 'dropped face with vcount ' + vcount + ' for geometry with id: ' + geom.id );
}
i += maxOffset * vcount;
}
}
};
function Polygons () {
this.material = "";
this.count = 0;
this.inputs = [];
this.vcount = null;
this.p = [];
this.geometry = new THREE.Geometry();
};
Polygons.prototype.setVertices = function ( vertices ) {
for ( var i = 0; i < this.inputs.length; i ++ ) {
if ( this.inputs[ i ].source == vertices.id ) {
this.inputs[ i ].source = vertices.input[ 'POSITION' ].source;
}
}
};
Polygons.prototype.parse = function ( element ) {
this.material = element.getAttribute( 'material' );
this.count = _attr_as_int( element, 'count', 0 );
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
switch ( child.nodeName ) {
case 'input':
this.inputs.push( ( new Input() ).parse( element.childNodes[ i ] ) );
break;
case 'vcount':
this.vcount = _ints( child.textContent );
break;
case 'p':
this.p.push( _ints( child.textContent ) );
break;
case 'ph':
console.warn( 'polygon holes not yet supported!' );
break;
default:
break;
}
}
return this;
};
function Polylist () {
Polygons.call( this );
this.vcount = [];
};
Polylist.prototype = Object.create( Polygons.prototype );
function Triangles () {
Polygons.call( this );
this.vcount = 3;
};
Triangles.prototype = Object.create( Polygons.prototype );
function Accessor() {
this.source = "";
this.count = 0;
this.stride = 0;
this.params = [];
};
Accessor.prototype.parse = function ( element ) {
this.params = [];
this.source = element.getAttribute( 'source' );
this.count = _attr_as_int( element, 'count', 0 );
this.stride = _attr_as_int( element, 'stride', 0 );
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
if ( child.nodeName == 'param' ) {
var param = {};
param[ 'name' ] = child.getAttribute( 'name' );
param[ 'type' ] = child.getAttribute( 'type' );
this.params.push( param );
}
}
return this;
};
function Vertices() {
this.input = {};
};
Vertices.prototype.parse = function ( element ) {
this.id = element.getAttribute('id');
for ( var i = 0; i < element.childNodes.length; i ++ ) {
if ( element.childNodes[i].nodeName == 'input' ) {
var input = ( new Input() ).parse( element.childNodes[ i ] );
this.input[ input.semantic ] = input;
}
}
return this;
};
function Input () {
this.semantic = "";
this.offset = 0;
this.source = "";
this.set = 0;
};
Input.prototype.parse = function ( element ) {
this.semantic = element.getAttribute('semantic');
this.source = element.getAttribute('source').replace(/^#/, '');
this.set = _attr_as_int(element, 'set', -1);
this.offset = _attr_as_int(element, 'offset', 0);
if ( this.semantic == 'TEXCOORD' && this.set < 0 ) {
this.set = 0;
}
return this;
};
function Source ( id ) {
this.id = id;
this.type = null;
};
Source.prototype.parse = function ( element ) {
this.id = element.getAttribute( 'id' );
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[i];
switch ( child.nodeName ) {
case 'bool_array':
this.data = _bools( child.textContent );
this.type = child.nodeName;
break;
case 'float_array':
this.data = _floats( child.textContent );
this.type = child.nodeName;
break;
case 'int_array':
this.data = _ints( child.textContent );
this.type = child.nodeName;
break;
case 'IDREF_array':
case 'Name_array':
this.data = _strings( child.textContent );
this.type = child.nodeName;
break;
case 'technique_common':
for ( var j = 0; j < child.childNodes.length; j ++ ) {
if ( child.childNodes[ j ].nodeName == 'accessor' ) {
this.accessor = ( new Accessor() ).parse( child.childNodes[ j ] );
break;
}
}
break;
default:
// console.log(child.nodeName);
break;
}
}
return this;
};
Source.prototype.read = function () {
var result = [];
//for (var i = 0; i < this.accessor.params.length; i++) {
var param = this.accessor.params[ 0 ];
//console.log(param.name + " " + param.type);
switch ( param.type ) {
case 'IDREF':
case 'Name': case 'name':
case 'float':
return this.data;
case 'float4x4':
for ( var j = 0; j < this.data.length; j += 16 ) {
var s = this.data.slice( j, j + 16 );
var m = getConvertedMat4( s );
result.push( m );
}
break;
default:
console.log( 'ColladaLoader: Source: Read dont know how to read ' + param.type + '.' );
break;
}
//}
return result;
};
function Material () {
this.id = "";
this.name = "";
this.instance_effect = null;
};
Material.prototype.parse = function ( element ) {
this.id = element.getAttribute( 'id' );
this.name = element.getAttribute( 'name' );
for ( var i = 0; i < element.childNodes.length; i ++ ) {
if ( element.childNodes[ i ].nodeName == 'instance_effect' ) {
this.instance_effect = ( new InstanceEffect() ).parse( element.childNodes[ i ] );
break;
}
}
return this;
};
function ColorOrTexture () {
this.color = new THREE.Color();
this.color.setRGB( Math.random(), Math.random(), Math.random() );
this.color.a = 1.0;
this.texture = null;
this.texcoord = null;
this.texOpts = null;
};
ColorOrTexture.prototype.isColor = function () {
return ( this.texture == null );
};
ColorOrTexture.prototype.isTexture = function () {
return ( this.texture != null );
};
ColorOrTexture.prototype.parse = function ( element ) {
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
if ( child.nodeType != 1 ) continue;
switch ( child.nodeName ) {
case 'color':
var rgba = _floats( child.textContent );
this.color = new THREE.Color();
this.color.setRGB( rgba[0], rgba[1], rgba[2] );
this.color.a = rgba[3];
break;
case 'texture':
this.texture = child.getAttribute('texture');
this.texcoord = child.getAttribute('texcoord');
// Defaults from:
// https://collada.org/mediawiki/index.php/Maya_texture_placement_MAYA_extension
this.texOpts = {
offsetU: 0,
offsetV: 0,
repeatU: 1,
repeatV: 1,
wrapU: 1,
wrapV: 1,
};
this.parseTexture( child );
break;
default:
break;
}
}
return this;
};
ColorOrTexture.prototype.parseTexture = function ( element ) {
if ( ! element.childNodes ) return this;
// This should be supported by Maya, 3dsMax, and MotionBuilder
if ( element.childNodes[1] && element.childNodes[1].nodeName === 'extra' ) {
element = element.childNodes[1];
if ( element.childNodes[1] && element.childNodes[1].nodeName === 'technique' ) {
element = element.childNodes[1];
}
}
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
switch ( child.nodeName ) {
case 'offsetU':
case 'offsetV':
case 'repeatU':
case 'repeatV':
this.texOpts[ child.nodeName ] = parseFloat( child.textContent );
break;
case 'wrapU':
case 'wrapV':
this.texOpts[ child.nodeName ] = parseInt( child.textContent );
break;
default:
this.texOpts[ child.nodeName ] = child.textContent;
break;
}
}
return this;
};
function Shader ( type, effect ) {
this.type = type;
this.effect = effect;
this.material = null;
};
Shader.prototype.parse = function ( element ) {
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
if ( child.nodeType != 1 ) continue;
switch ( child.nodeName ) {
case 'ambient':
case 'emission':
case 'diffuse':
case 'specular':
case 'transparent':
this[ child.nodeName ] = ( new ColorOrTexture() ).parse( child );
break;
case 'shininess':
case 'reflectivity':
case 'index_of_refraction':
case 'transparency':
var f = evaluateXPath( child, './/dae:float' );
if ( f.length > 0 )
this[ child.nodeName ] = parseFloat( f[ 0 ].textContent );
break;
default:
break;
}
}
this.create();
return this;
};
Shader.prototype.create = function() {
var props = {};
var transparent = ( this['transparency'] !== undefined && this['transparency'] < 1.0 );
for ( var prop in this ) {
switch ( prop ) {
case 'ambient':
case 'emission':
case 'diffuse':
case 'specular':
var cot = this[ prop ];
if ( cot instanceof ColorOrTexture ) {
if ( cot.isTexture() ) {
var samplerId = cot.texture;
var surfaceId = this.effect.sampler[samplerId].source;
if ( surfaceId ) {
var surface = this.effect.surface[surfaceId];
var image = images[surface.init_from];
if (image) {
var texture = THREE.ImageUtils.loadTexture(baseUrl + image.init_from);
texture.wrapS = cot.texOpts.wrapU ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
texture.wrapT = cot.texOpts.wrapV ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
texture.offset.x = cot.texOpts.offsetU;
texture.offset.y = cot.texOpts.offsetV;
texture.repeat.x = cot.texOpts.repeatU;
texture.repeat.y = cot.texOpts.repeatV;
props['map'] = texture;
// Texture with baked lighting?
if (prop === 'emission') props['emissive'] = 0xffffff;
}
}
} else if ( prop === 'diffuse' || !transparent ) {
if ( prop === 'emission' ) {
props[ 'emissive' ] = cot.color.getHex();
} else {
props[ prop ] = cot.color.getHex();
}
}
}
break;
case 'shininess':
props[ prop ] = this[ prop ];
break;
case 'reflectivity':
props[ prop ] = this[ prop ];
if( props[ prop ] > 0.0 ) props['envMap'] = options.defaultEnvMap;
props['combine'] = THREE.MixOperation; //mix regular shading with reflective component
break;
case 'index_of_refraction':
props[ 'refractionRatio' ] = this[ prop ]; //TODO: "index_of_refraction" becomes "refractionRatio" in shader, but I'm not sure if the two are actually comparable
if ( this[ prop ] !== 1.0 ) props['envMap'] = options.defaultEnvMap;
break;
case 'transparency':
if ( transparent ) {
props[ 'transparent' ] = true;
props[ 'opacity' ] = this[ prop ];
transparent = true;
}
break;
default:
break;
}
}
props[ 'shading' ] = preferredShading;
props[ 'side' ] = this.effect.doubleSided ? THREE.DoubleSide : THREE.FrontSide;
switch ( this.type ) {
case 'constant':
if (props.emissive != undefined) props.color = props.emissive;
this.material = new THREE.MeshBasicMaterial( props );
break;
case 'phong':
case 'blinn':
if (props.diffuse != undefined) props.color = props.diffuse;
this.material = new THREE.MeshPhongMaterial( props );
break;
case 'lambert':
default:
if (props.diffuse != undefined) props.color = props.diffuse;
this.material = new THREE.MeshLambertMaterial( props );
break;
}
return this.material;
};
function Surface ( effect ) {
this.effect = effect;
this.init_from = null;
this.format = null;
};
Surface.prototype.parse = function ( element ) {
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
if ( child.nodeType != 1 ) continue;
switch ( child.nodeName ) {
case 'init_from':
this.init_from = child.textContent;
break;
case 'format':
this.format = child.textContent;
break;
default:
console.log( "unhandled Surface prop: " + child.nodeName );
break;
}
}
return this;
};
function Sampler2D ( effect ) {
this.effect = effect;
this.source = null;
this.wrap_s = null;
this.wrap_t = null;
this.minfilter = null;
this.magfilter = null;
this.mipfilter = null;
};
Sampler2D.prototype.parse = function ( element ) {
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
if ( child.nodeType != 1 ) continue;
switch ( child.nodeName ) {
case 'source':
this.source = child.textContent;
break;
case 'minfilter':
this.minfilter = child.textContent;
break;
case 'magfilter':
this.magfilter = child.textContent;
break;
case 'mipfilter':
this.mipfilter = child.textContent;
break;
case 'wrap_s':
this.wrap_s = child.textContent;
break;
case 'wrap_t':
this.wrap_t = child.textContent;
break;
default:
console.log( "unhandled Sampler2D prop: " + child.nodeName );
break;
}
}
return this;
};
function Effect () {
this.id = "";
this.name = "";
this.shader = null;
this.surface = {};
this.sampler = {};
};
Effect.prototype.create = function () {
if ( this.shader == null ) {
return null;
}
};
Effect.prototype.parse = function ( element ) {
this.id = element.getAttribute( 'id' );
this.name = element.getAttribute( 'name' );
extractDoubleSided( this, element );
this.shader = null;
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
if ( child.nodeType != 1 ) continue;
switch ( child.nodeName ) {
case 'profile_COMMON':
this.parseTechnique( this.parseProfileCOMMON( child ) );
break;
default:
break;
}
}
return this;
};
Effect.prototype.parseNewparam = function ( element ) {
var sid = element.getAttribute( 'sid' );
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
if ( child.nodeType != 1 ) continue;
switch ( child.nodeName ) {
case 'surface':
this.surface[sid] = ( new Surface( this ) ).parse( child );
break;
case 'sampler2D':
this.sampler[sid] = ( new Sampler2D( this ) ).parse( child );
break;
case 'extra':
break;
default:
console.log( child.nodeName );
break;
}
}
};
Effect.prototype.parseProfileCOMMON = function ( element ) {
var technique;
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
if ( child.nodeType != 1 ) continue;
switch ( child.nodeName ) {
case 'profile_COMMON':
this.parseProfileCOMMON( child );
break;
case 'technique':
technique = child;
break;
case 'newparam':
this.parseNewparam( child );
break;
case 'image':
var _image = ( new _Image() ).parse( child );
images[ _image.id ] = _image;
break;
case 'extra':
break;
default:
console.log( child.nodeName );
break;
}
}
return technique;
};
Effect.prototype.parseTechnique= function ( element ) {
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[i];
if ( child.nodeType != 1 ) continue;
switch ( child.nodeName ) {
case 'constant':
case 'lambert':
case 'blinn':
case 'phong':
this.shader = ( new Shader( child.nodeName, this ) ).parse( child );
break;
default:
break;
}
}
};
function InstanceEffect () {
this.url = "";
};
InstanceEffect.prototype.parse = function ( element ) {
this.url = element.getAttribute( 'url' ).replace( /^#/, '' );
return this;
};
function Animation() {
this.id = "";
this.name = "";
this.source = {};
this.sampler = [];
this.channel = [];
};
Animation.prototype.parse = function ( element ) {
this.id = element.getAttribute( 'id' );
this.name = element.getAttribute( 'name' );
this.source = {};
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
if ( child.nodeType != 1 ) continue;
switch ( child.nodeName ) {
case 'animation':
var anim = ( new Animation() ).parse( child );
for ( var src in anim.source ) {
this.source[ src ] = anim.source[ src ];
}
for ( var j = 0; j < anim.channel.length; j ++ ) {
this.channel.push( anim.channel[ j ] );
this.sampler.push( anim.sampler[ j ] );
}
break;
case 'source':
var src = ( new Source() ).parse( child );
this.source[ src.id ] = src;
break;
case 'sampler':
this.sampler.push( ( new Sampler( this ) ).parse( child ) );
break;
case 'channel':
this.channel.push( ( new Channel( this ) ).parse( child ) );
break;
default:
break;
}
}
return this;
};
function Channel( animation ) {
this.animation = animation;
this.source = "";
this.target = "";
this.fullSid = null;
this.sid = null;
this.dotSyntax = null;
this.arrSyntax = null;
this.arrIndices = null;
this.member = null;
};
Channel.prototype.parse = function ( element ) {
this.source = element.getAttribute( 'source' ).replace( /^#/, '' );
this.target = element.getAttribute( 'target' );
var parts = this.target.split( '/' );
var id = parts.shift();
var sid = parts.shift();
var dotSyntax = ( sid.indexOf(".") >= 0 );
var arrSyntax = ( sid.indexOf("(") >= 0 );
if ( dotSyntax ) {
parts = sid.split(".");
this.sid = parts.shift();
this.member = parts.shift();
} else if ( arrSyntax ) {
var arrIndices = sid.split("(");
this.sid = arrIndices.shift();
for (var j = 0; j < arrIndices.length; j ++ ) {
arrIndices[j] = parseInt( arrIndices[j].replace(/\)/, '') );
}
this.arrIndices = arrIndices;
} else {
this.sid = sid;
}
this.fullSid = sid;
this.dotSyntax = dotSyntax;
this.arrSyntax = arrSyntax;
return this;
};
function Sampler ( animation ) {
this.id = "";
this.animation = animation;
this.inputs = [];
this.input = null;
this.output = null;
this.strideOut = null;
this.interpolation = null;
this.startTime = null;
this.endTime = null;
this.duration = 0;
};
Sampler.prototype.parse = function ( element ) {
this.id = element.getAttribute( 'id' );
this.inputs = [];
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
if ( child.nodeType != 1 ) continue;
switch ( child.nodeName ) {
case 'input':
this.inputs.push( (new Input()).parse( child ) );
break;
default:
break;
}
}
return this;
};
Sampler.prototype.create = function () {
for ( var i = 0; i < this.inputs.length; i ++ ) {
var input = this.inputs[ i ];
var source = this.animation.source[ input.source ];
switch ( input.semantic ) {
case 'INPUT':
this.input = source.read();
break;
case 'OUTPUT':
this.output = source.read();
this.strideOut = source.accessor.stride;
break;
case 'INTERPOLATION':
this.interpolation = source.read();
break;
case 'IN_TANGENT':
break;
case 'OUT_TANGENT':
break;
default:
console.log(input.semantic);
break;
}
}
this.startTime = 0;
this.endTime = 0;
this.duration = 0;
if ( this.input.length ) {
this.startTime = 100000000;
this.endTime = -100000000;
for ( var i = 0; i < this.input.length; i ++ ) {
this.startTime = Math.min( this.startTime, this.input[ i ] );
this.endTime = Math.max( this.endTime, this.input[ i ] );
}
this.duration = this.endTime - this.startTime;
}
};
Sampler.prototype.getData = function ( type, ndx ) {
var data;
if ( type === 'matrix' && this.strideOut === 16 ) {
data = this.output[ ndx ];
} else if ( this.strideOut > 1 ) {
data = [];
ndx *= this.strideOut;
for ( var i = 0; i < this.strideOut; ++i ) {
data[ i ] = this.output[ ndx + i ];
}
if ( this.strideOut === 3 ) {
switch ( type ) {
case 'rotate':
case 'translate':
fixCoords( data, -1 );
break;
case 'scale':
fixCoords( data, 1 );
break;
}
} else if ( this.strideOut === 4 && type === 'matrix' ) {
fixCoords( data, -1 );
}
} else {
data = this.output[ ndx ];
}
return data;
};
function Key ( time ) {
this.targets = [];
this.time = time;
};
Key.prototype.addTarget = function ( fullSid, transform, member, data ) {
this.targets.push( {
sid: fullSid,
member: member,
transform: transform,
data: data
} );
};
Key.prototype.apply = function ( opt_sid ) {
for ( var i = 0; i < this.targets.length; ++i ) {
var target = this.targets[ i ];
if ( !opt_sid || target.sid === opt_sid ) {
target.transform.update( target.data, target.member );
}
}
};
Key.prototype.getTarget = function ( fullSid ) {
for ( var i = 0; i < this.targets.length; ++i ) {
if ( this.targets[ i ].sid === fullSid ) {
return this.targets[ i ];
}
}
return null;
};
Key.prototype.hasTarget = function ( fullSid ) {
for ( var i = 0; i < this.targets.length; ++i ) {
if ( this.targets[ i ].sid === fullSid ) {
return true;
}
}
return false;
};
// TODO: Currently only doing linear interpolation. Should support full COLLADA spec.
Key.prototype.interpolate = function ( nextKey, time ) {
for ( var i = 0; i < this.targets.length; ++i ) {
var target = this.targets[ i ],
nextTarget = nextKey.getTarget( target.sid ),
data;
if ( target.transform.type !== 'matrix' && nextTarget ) {
var scale = ( time - this.time ) / ( nextKey.time - this.time ),
nextData = nextTarget.data,
prevData = target.data;
// check scale error
if ( scale < 0 || scale > 1 ) {
console.log( "Key.interpolate: Warning! Scale out of bounds:" + scale );
scale = scale < 0 ? 0 : 1;
}
if ( prevData.length ) {
data = [];
for ( var j = 0; j < prevData.length; ++j ) {
data[ j ] = prevData[ j ] + ( nextData[ j ] - prevData[ j ] ) * scale;
}
} else {
data = prevData + ( nextData - prevData ) * scale;
}
} else {
data = target.data;
}
target.transform.update( data, target.member );
}
};
// Camera
function Camera() {
this.id = "";
this.name = "";
this.technique = "";
};
Camera.prototype.parse = function ( element ) {
this.id = element.getAttribute( 'id' );
this.name = element.getAttribute( 'name' );
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
if ( child.nodeType != 1 ) continue;
switch ( child.nodeName ) {
case 'optics':
this.parseOptics( child );
break;
}
}
return this;
};
Camera.prototype.parseOptics = function ( element ) {
for ( var i = 0; i < element.childNodes.length; i ++ ) {
if ( element.childNodes[ i ].nodeName == 'technique_common' ) {
var technique = element.childNodes[ i ];
for ( var j = 0; j < technique.childNodes.length; j ++ ) {
this.technique = technique.childNodes[ j ].nodeName;
if ( this.technique == 'perspective' ) {
var perspective = technique.childNodes[ j ];
for ( var k = 0; k < perspective.childNodes.length; k ++ ) {
var param = perspective.childNodes[ k ];
switch ( param.nodeName ) {
case 'yfov':
this.yfov = param.textContent;
break;
case 'xfov':
this.xfov = param.textContent;
break;
case 'znear':
this.znear = param.textContent;
break;
case 'zfar':
this.zfar = param.textContent;
break;
case 'aspect_ratio':
this.aspect_ratio = param.textContent;
break;
}
}
} else if ( this.technique == 'orthographic' ) {
var orthographic = technique.childNodes[ j ];
for ( var k = 0; k < orthographic.childNodes.length; k ++ ) {
var param = orthographic.childNodes[ k ];
switch ( param.nodeName ) {
case 'xmag':
this.xmag = param.textContent;
break;
case 'ymag':
this.ymag = param.textContent;
break;
case 'znear':
this.znear = param.textContent;
break;
case 'zfar':
this.zfar = param.textContent;
break;
case 'aspect_ratio':
this.aspect_ratio = param.textContent;
break;
}
}
}
}
}
}
return this;
};
function InstanceCamera() {
this.url = "";
};
InstanceCamera.prototype.parse = function ( element ) {
this.url = element.getAttribute('url').replace(/^#/, '');
return this;
};
// Light
function Light() {
this.id = "";
this.name = "";
this.technique = "";
};
Light.prototype.parse = function ( element ) {
this.id = element.getAttribute( 'id' );
this.name = element.getAttribute( 'name' );
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
if ( child.nodeType != 1 ) continue;
switch ( child.nodeName ) {
case 'technique_common':
this.parseTechnique( child );
break;
}
}
return this;
};
Light.prototype.parseTechnique = function ( element ) {
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
switch ( child.nodeName ) {
case 'ambient':
case 'point':
case 'directional':
this.technique = child.nodeName;
for ( var k = 0; k < child.childNodes.length; k ++ ) {
var param = child.childNodes[ k ];
switch ( param.nodeName ) {
case 'color':
var vector = new THREE.Vector3().fromArray( _floats( param.textContent ) );
this.color = new THREE.Color().setRGB( vector.x, vector.y, vector.z );
break;
}
}
break;
}
}
};
function InstanceLight() {
this.url = "";
};
InstanceLight.prototype.parse = function ( element ) {
this.url = element.getAttribute('url').replace(/^#/, '');
return this;
};
function _source( element ) {
var id = element.getAttribute( 'id' );
if ( sources[ id ] != undefined ) {
return sources[ id ];
}
sources[ id ] = ( new Source(id )).parse( element );
return sources[ id ];
};
function _nsResolver( nsPrefix ) {
if ( nsPrefix == "dae" ) {
return "http://www.collada.org/2005/11/COLLADASchema";
}
return null;
};
function _bools( str ) {
var raw = _strings( str );
var data = [];
for ( var i = 0, l = raw.length; i < l; i ++ ) {
data.push( (raw[i] == 'true' || raw[i] == '1') ? true : false );
}
return data;
};
function _floats( str ) {
var raw = _strings(str);
var data = [];
for ( var i = 0, l = raw.length; i < l; i ++ ) {
data.push( parseFloat( raw[ i ] ) );
}
return data;
};
function _ints( str ) {
var raw = _strings( str );
var data = [];
for ( var i = 0, l = raw.length; i < l; i ++ ) {
data.push( parseInt( raw[ i ], 10 ) );
}
return data;
};
function _strings( str ) {
return ( str.length > 0 ) ? _trimString( str ).split( /\s+/ ) : [];
};
function _trimString( str ) {
return str.replace( /^\s+/, "" ).replace( /\s+$/, "" );
};
function _attr_as_float( element, name, defaultValue ) {
if ( element.hasAttribute( name ) ) {
return parseFloat( element.getAttribute( name ) );
} else {
return defaultValue;
}
};
function _attr_as_int( element, name, defaultValue ) {
if ( element.hasAttribute( name ) ) {
return parseInt( element.getAttribute( name ), 10) ;
} else {
return defaultValue;
}
};
function _attr_as_string( element, name, defaultValue ) {
if ( element.hasAttribute( name ) ) {
return element.getAttribute( name );
} else {
return defaultValue;
}
};
function _format_float( f, num ) {
if ( f === undefined ) {
var s = '0.';
while ( s.length < num + 2 ) {
s += '0';
}
return s;
}
num = num || 2;
var parts = f.toString().split( '.' );
parts[ 1 ] = parts.length > 1 ? parts[ 1 ].substr( 0, num ) : "0";
while( parts[ 1 ].length < num ) {
parts[ 1 ] += '0';
}
return parts.join( '.' );
};
function evaluateXPath( node, query ) {
var instances = COLLADA.evaluate( query, node, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null );
var inst = instances.iterateNext();
var result = [];
while ( inst ) {
result.push( inst );
inst = instances.iterateNext();
}
return result;
};
function extractDoubleSided( obj, element ) {
obj.doubleSided = false;
var node = COLLADA.evaluate( './/dae:extra//dae:double_sided', element, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null );
if ( node ) {
node = node.iterateNext();
if ( node && parseInt( node.textContent, 10 ) === 1 ) {
obj.doubleSided = true;
}
}
};
// Up axis conversion
function setUpConversion() {
if ( !options.convertUpAxis || colladaUp === options.upAxis ) {
upConversion = null;
} else {
switch ( colladaUp ) {
case 'X':
upConversion = options.upAxis === 'Y' ? 'XtoY' : 'XtoZ';
break;
case 'Y':
upConversion = options.upAxis === 'X' ? 'YtoX' : 'YtoZ';
break;
case 'Z':
upConversion = options.upAxis === 'X' ? 'ZtoX' : 'ZtoY';
break;
}
}
};
function fixCoords( data, sign ) {
if ( !options.convertUpAxis || colladaUp === options.upAxis ) {
return;
}
switch ( upConversion ) {
case 'XtoY':
var tmp = data[ 0 ];
data[ 0 ] = sign * data[ 1 ];
data[ 1 ] = tmp;
break;
case 'XtoZ':
var tmp = data[ 2 ];
data[ 2 ] = data[ 1 ];
data[ 1 ] = data[ 0 ];
data[ 0 ] = tmp;
break;
case 'YtoX':
var tmp = data[ 0 ];
data[ 0 ] = data[ 1 ];
data[ 1 ] = sign * tmp;
break;
case 'YtoZ':
var tmp = data[ 1 ];
data[ 1 ] = sign * data[ 2 ];
data[ 2 ] = tmp;
break;
case 'ZtoX':
var tmp = data[ 0 ];
data[ 0 ] = data[ 1 ];
data[ 1 ] = data[ 2 ];
data[ 2 ] = tmp;
break;
case 'ZtoY':
var tmp = data[ 1 ];
data[ 1 ] = data[ 2 ];
data[ 2 ] = sign * tmp;
break;
}
};
function getConvertedVec3( data, offset ) {
var arr = [ data[ offset ], data[ offset + 1 ], data[ offset + 2 ] ];
fixCoords( arr, -1 );
return new THREE.Vector3( arr[ 0 ], arr[ 1 ], arr[ 2 ] );
};
function getConvertedMat4( data ) {
if ( options.convertUpAxis ) {
// First fix rotation and scale
// Columns first
var arr = [ data[ 0 ], data[ 4 ], data[ 8 ] ];
fixCoords( arr, -1 );
data[ 0 ] = arr[ 0 ];
data[ 4 ] = arr[ 1 ];
data[ 8 ] = arr[ 2 ];
arr = [ data[ 1 ], data[ 5 ], data[ 9 ] ];
fixCoords( arr, -1 );
data[ 1 ] = arr[ 0 ];
data[ 5 ] = arr[ 1 ];
data[ 9 ] = arr[ 2 ];
arr = [ data[ 2 ], data[ 6 ], data[ 10 ] ];
fixCoords( arr, -1 );
data[ 2 ] = arr[ 0 ];
data[ 6 ] = arr[ 1 ];
data[ 10 ] = arr[ 2 ];
// Rows second
arr = [ data[ 0 ], data[ 1 ], data[ 2 ] ];
fixCoords( arr, -1 );
data[ 0 ] = arr[ 0 ];
data[ 1 ] = arr[ 1 ];
data[ 2 ] = arr[ 2 ];
arr = [ data[ 4 ], data[ 5 ], data[ 6 ] ];
fixCoords( arr, -1 );
data[ 4 ] = arr[ 0 ];
data[ 5 ] = arr[ 1 ];
data[ 6 ] = arr[ 2 ];
arr = [ data[ 8 ], data[ 9 ], data[ 10 ] ];
fixCoords( arr, -1 );
data[ 8 ] = arr[ 0 ];
data[ 9 ] = arr[ 1 ];
data[ 10 ] = arr[ 2 ];
// Now fix translation
arr = [ data[ 3 ], data[ 7 ], data[ 11 ] ];
fixCoords( arr, -1 );
data[ 3 ] = arr[ 0 ];
data[ 7 ] = arr[ 1 ];
data[ 11 ] = arr[ 2 ];
}
return new THREE.Matrix4(
data[0], data[1], data[2], data[3],
data[4], data[5], data[6], data[7],
data[8], data[9], data[10], data[11],
data[12], data[13], data[14], data[15]
);
};
function getConvertedIndex( index ) {
if ( index > -1 && index < 3 ) {
var members = ['X', 'Y', 'Z'],
indices = { X: 0, Y: 1, Z: 2 };
index = getConvertedMember( members[ index ] );
index = indices[ index ];
}
return index;
};
function getConvertedMember( member ) {
if ( options.convertUpAxis ) {
switch ( member ) {
case 'X':
switch ( upConversion ) {
case 'XtoY':
case 'XtoZ':
case 'YtoX':
member = 'Y';
break;
case 'ZtoX':
member = 'Z';
break;
}
break;
case 'Y':
switch ( upConversion ) {
case 'XtoY':
case 'YtoX':
case 'ZtoX':
member = 'X';
break;
case 'XtoZ':
case 'YtoZ':
case 'ZtoY':
member = 'Z';
break;
}
break;
case 'Z':
switch ( upConversion ) {
case 'XtoZ':
member = 'X';
break;
case 'YtoZ':
case 'ZtoX':
case 'ZtoY':
member = 'Y';
break;
}
break;
}
}
return member;
};
return {
load: load,
parse: parse,
setPreferredShading: setPreferredShading,
applySkin: applySkin,
geometries : geometries,
options: options
};
};
| krris/3d-bin-packing | visual/app/js/loaders/ColladaLoader.js | JavaScript | mit | 81,501 |
var Emitter = require('emitter-component');
var Hammer = require('../module/hammer');
var moment = require('../module/moment');
var util = require('../util');
var DataSet = require('../DataSet');
var DataView = require('../DataView');
var Range = require('./Range');
var Core = require('./Core');
var TimeAxis = require('./component/TimeAxis');
var CurrentTime = require('./component/CurrentTime');
var CustomTime = require('./component/CustomTime');
var LineGraph = require('./component/LineGraph');
var Configurator = require('../shared/Configurator');
var Validator = require('../shared/Validator').default;
var printStyle = require('../shared/Validator').printStyle;
var allOptions = require('./optionsGraph2d').allOptions;
var configureOptions = require('./optionsGraph2d').configureOptions;
/**
* Create a timeline visualization
* @param {HTMLElement} container
* @param {vis.DataSet | Array} [items]
* @param {Object} [options] See Graph2d.setOptions for the available options.
* @constructor
* @extends Core
*/
function Graph2d (container, items, groups, options) {
// if the third element is options, the forth is groups (optionally);
if (!(Array.isArray(groups) || groups instanceof DataSet || groups instanceof DataView) && groups instanceof Object) {
var forthArgument = options;
options = groups;
groups = forthArgument;
}
var me = this;
this.defaultOptions = {
start: null,
end: null,
autoResize: true,
orientation: {
axis: 'bottom', // axis orientation: 'bottom', 'top', or 'both'
item: 'bottom' // not relevant for Graph2d
},
moment: moment,
width: null,
height: null,
maxHeight: null,
minHeight: null
};
this.options = util.deepExtend({}, this.defaultOptions);
// Create the DOM, props, and emitter
this._create(container);
// all components listed here will be repainted automatically
this.components = [];
this.body = {
dom: this.dom,
domProps: this.props,
emitter: {
on: this.on.bind(this),
off: this.off.bind(this),
emit: this.emit.bind(this)
},
hiddenDates: [],
util: {
toScreen: me._toScreen.bind(me),
toGlobalScreen: me._toGlobalScreen.bind(me), // this refers to the root.width
toTime: me._toTime.bind(me),
toGlobalTime : me._toGlobalTime.bind(me)
}
};
// range
this.range = new Range(this.body);
this.components.push(this.range);
this.body.range = this.range;
// time axis
this.timeAxis = new TimeAxis(this.body);
this.components.push(this.timeAxis);
//this.body.util.snap = this.timeAxis.snap.bind(this.timeAxis);
// current time bar
this.currentTime = new CurrentTime(this.body);
this.components.push(this.currentTime);
// item set
this.linegraph = new LineGraph(this.body);
this.components.push(this.linegraph);
this.itemsData = null; // DataSet
this.groupsData = null; // DataSet
this.on('tap', function (event) {
me.emit('click', me.getEventProperties(event))
});
this.on('doubletap', function (event) {
me.emit('doubleClick', me.getEventProperties(event))
});
this.dom.root.oncontextmenu = function (event) {
me.emit('contextmenu', me.getEventProperties(event))
};
// apply options
if (options) {
this.setOptions(options);
}
// IMPORTANT: THIS HAPPENS BEFORE SET ITEMS!
if (groups) {
this.setGroups(groups);
}
// create itemset
if (items) {
this.setItems(items);
}
// draw for the first time
this._redraw();
}
// Extend the functionality from Core
Graph2d.prototype = new Core();
Graph2d.prototype.setOptions = function (options) {
// validate options
let errorFound = Validator.validate(options, allOptions);
if (errorFound === true) {
console.log('%cErrors have been found in the supplied options object.', printStyle);
}
Core.prototype.setOptions.call(this, options);
};
/**
* Set items
* @param {vis.DataSet | Array | null} items
*/
Graph2d.prototype.setItems = function(items) {
var initialLoad = (this.itemsData == null);
// convert to type DataSet when needed
var newDataSet;
if (!items) {
newDataSet = null;
}
else if (items instanceof DataSet || items instanceof DataView) {
newDataSet = items;
}
else {
// turn an array into a dataset
newDataSet = new DataSet(items, {
type: {
start: 'Date',
end: 'Date'
}
});
}
// set items
this.itemsData = newDataSet;
this.linegraph && this.linegraph.setItems(newDataSet);
if (initialLoad) {
if (this.options.start != undefined || this.options.end != undefined) {
var start = this.options.start != undefined ? this.options.start : null;
var end = this.options.end != undefined ? this.options.end : null;
this.setWindow(start, end, {animation: false});
}
else {
this.fit({animation: false});
}
}
};
/**
* Set groups
* @param {vis.DataSet | Array} groups
*/
Graph2d.prototype.setGroups = function(groups) {
// convert to type DataSet when needed
var newDataSet;
if (!groups) {
newDataSet = null;
}
else if (groups instanceof DataSet || groups instanceof DataView) {
newDataSet = groups;
}
else {
// turn an array into a dataset
newDataSet = new DataSet(groups);
}
this.groupsData = newDataSet;
this.linegraph.setGroups(newDataSet);
};
/**
* Returns an object containing an SVG element with the icon of the group (size determined by iconWidth and iconHeight), the label of the group (content) and the yAxisOrientation of the group (left or right).
* @param groupId
* @param width
* @param height
*/
Graph2d.prototype.getLegend = function(groupId, width, height) {
if (width === undefined) {width = 15;}
if (height === undefined) {height = 15;}
if (this.linegraph.groups[groupId] !== undefined) {
return this.linegraph.groups[groupId].getLegend(width,height);
}
else {
return "cannot find group:'" + groupId + "'";
}
};
/**
* This checks if the visible option of the supplied group (by ID) is true or false.
* @param groupId
* @returns {*}
*/
Graph2d.prototype.isGroupVisible = function(groupId) {
if (this.linegraph.groups[groupId] !== undefined) {
return (this.linegraph.groups[groupId].visible && (this.linegraph.options.groups.visibility[groupId] === undefined || this.linegraph.options.groups.visibility[groupId] == true));
}
else {
return false;
}
};
/**
* Get the data range of the item set.
* @returns {{min: Date, max: Date}} range A range with a start and end Date.
* When no minimum is found, min==null
* When no maximum is found, max==null
*/
Graph2d.prototype.getDataRange = function() {
var min = null;
var max = null;
// calculate min from start filed
for (var groupId in this.linegraph.groups) {
if (this.linegraph.groups.hasOwnProperty(groupId)) {
if (this.linegraph.groups[groupId].visible == true) {
for (var i = 0; i < this.linegraph.groups[groupId].itemsData.length; i++) {
var item = this.linegraph.groups[groupId].itemsData[i];
var value = util.convert(item.x, 'Date').valueOf();
min = min == null ? value : min > value ? value : min;
max = max == null ? value : max < value ? value : max;
}
}
}
}
return {
min: (min != null) ? new Date(min) : null,
max: (max != null) ? new Date(max) : null
};
};
/**
* Generate Timeline related information from an event
* @param {Event} event
* @return {Object} An object with related information, like on which area
* The event happened, whether clicked on an item, etc.
*/
Graph2d.prototype.getEventProperties = function (event) {
var clientX = event.center ? event.center.x : event.clientX;
var clientY = event.center ? event.center.y : event.clientY;
var x = clientX - util.getAbsoluteLeft(this.dom.centerContainer);
var y = clientY - util.getAbsoluteTop(this.dom.centerContainer);
var time = this._toTime(x);
var customTime = CustomTime.customTimeFromTarget(event);
var element = util.getTarget(event);
var what = null;
if (util.hasParent(element, this.timeAxis.dom.foreground)) {what = 'axis';}
else if (this.timeAxis2 && util.hasParent(element, this.timeAxis2.dom.foreground)) {what = 'axis';}
else if (util.hasParent(element, this.linegraph.yAxisLeft.dom.frame)) {what = 'data-axis';}
else if (util.hasParent(element, this.linegraph.yAxisRight.dom.frame)) {what = 'data-axis';}
else if (util.hasParent(element, this.linegraph.legendLeft.dom.frame)) {what = 'legend';}
else if (util.hasParent(element, this.linegraph.legendRight.dom.frame)) {what = 'legend';}
else if (customTime != null) {what = 'custom-time';}
else if (util.hasParent(element, this.currentTime.bar)) {what = 'current-time';}
else if (util.hasParent(element, this.dom.center)) {what = 'background';}
var value = [];
var yAxisLeft = this.linegraph.yAxisLeft;
var yAxisRight = this.linegraph.yAxisRight;
if (!yAxisLeft.hidden) {
value.push(yAxisLeft.screenToValue(y));
}
if (!yAxisRight.hidden) {
value.push(yAxisRight.screenToValue(y));
}
return {
event: event,
what: what,
pageX: event.srcEvent ? event.srcEvent.pageX : event.pageX,
pageY: event.srcEvent ? event.srcEvent.pageY : event.pageY,
x: x,
y: y,
time: time,
value: value
}
};
/**
* Load a configurator
* @return {Object}
* @private
*/
Graph2d.prototype._createConfigurator = function () {
return new Configurator(this, this.dom.container, configureOptions);
};
module.exports = Graph2d;
| brandune/librenms | lib/vis/lib/timeline/Graph2d.js | JavaScript | gpl-3.0 | 9,773 |
/* The Editor object manages the content of the editable frame. It
* catches events, colours nodes, and indents lines. This file also
* holds some functions for transforming arbitrary DOM structures into
* plain sequences of <span> and <br> elements
*/
var internetExplorer = document.selection && window.ActiveXObject && /MSIE/.test(navigator.userAgent);
var webkit = /AppleWebKit/.test(navigator.userAgent);
var safari = /Apple Computers, Inc/.test(navigator.vendor);
var gecko = /gecko\/(\d{8})/i.test(navigator.userAgent);
// Make sure a string does not contain two consecutive 'collapseable'
// whitespace characters.
function makeWhiteSpace(n) {
var buffer = [], nb = true;
for (; n > 0; n--) {
buffer.push((nb || n == 1) ? nbsp : " ");
nb = !nb;
}
return buffer.join("");
}
// Create a set of white-space characters that will not be collapsed
// by the browser, but will not break text-wrapping either.
function fixSpaces(string) {
if (string.charAt(0) == " ") string = nbsp + string.slice(1);
return string.replace(/\t/g, function(){return makeWhiteSpace(indentUnit);})
.replace(/[ \u00a0]{2,}/g, function(s) {return makeWhiteSpace(s.length);});
}
function cleanText(text) {
return text.replace(/\u00a0/g, " ").replace(/\u200b/g, "");
}
// Create a SPAN node with the expected properties for document part
// spans.
function makePartSpan(value, doc) {
var text = value;
if (value.nodeType == 3) text = value.nodeValue;
else value = doc.createTextNode(text);
var span = doc.createElement("SPAN");
span.isPart = true;
span.appendChild(value);
span.currentText = text;
return span;
}
// On webkit, when the last BR of the document does not have text
// behind it, the cursor can not be put on the line after it. This
// makes pressing enter at the end of the document occasionally do
// nothing (or at least seem to do nothing). To work around it, this
// function makes sure the document ends with a span containing a
// zero-width space character. The traverseDOM iterator filters such
// character out again, so that the parsers won't see them. This
// function is called from a few strategic places to make sure the
// zwsp is restored after the highlighting process eats it.
var webkitLastLineHack = webkit ?
function(container) {
var last = container.lastChild;
if (!last || !last.isPart || last.textContent != "\u200b")
container.appendChild(makePartSpan("\u200b", container.ownerDocument));
} : function() {};
var Editor = (function(){
// The HTML elements whose content should be suffixed by a newline
// when converting them to flat text.
var newlineElements = {"P": true, "DIV": true, "LI": true};
function asEditorLines(string) {
var tab = makeWhiteSpace(indentUnit);
return map(string.replace(/\t/g, tab).replace(/\u00a0/g, " ").replace(/\r\n?/g, "\n").split("\n"), fixSpaces);
}
// Helper function for traverseDOM. Flattens an arbitrary DOM node
// into an array of textnodes and <br> tags.
function simplifyDOM(root, atEnd) {
var doc = root.ownerDocument;
var result = [];
var leaving = true;
function simplifyNode(node, top) {
if (node.nodeType == 3) {
var text = node.nodeValue = fixSpaces(node.nodeValue.replace(/[\r\u200b]/g, "").replace(/\n/g, " "));
if (text.length) leaving = false;
result.push(node);
}
else if (isBR(node) && node.childNodes.length == 0) {
leaving = true;
result.push(node);
}
else {
forEach(node.childNodes, simplifyNode);
if (!leaving && newlineElements.hasOwnProperty(node.nodeName.toUpperCase())) {
leaving = true;
if (!atEnd || !top)
result.push(doc.createElement("BR"));
}
}
}
simplifyNode(root, true);
return result;
}
// Creates a MochiKit-style iterator that goes over a series of DOM
// nodes. The values it yields are strings, the textual content of
// the nodes. It makes sure that all nodes up to and including the
// one whose text is being yielded have been 'normalized' to be just
// <span> and <br> elements.
// See the story.html file for some short remarks about the use of
// continuation-passing style in this iterator.
function traverseDOM(start){
function _yield(value, c){cc = c; return value;}
function push(fun, arg, c){return function(){return fun(arg, c);};}
function stop(){cc = stop; throw StopIteration;};
var cc = push(scanNode, start, stop);
var owner = start.ownerDocument;
var nodeQueue = [];
// Create a function that can be used to insert nodes after the
// one given as argument.
function pointAt(node){
var parent = node.parentNode;
var next = node.nextSibling;
return function(newnode) {
parent.insertBefore(newnode, next);
};
}
var point = null;
// This an Opera-specific hack -- always insert an empty span
// between two BRs, because Opera's cursor code gets terribly
// confused when the cursor is between two BRs.
var afterBR = true;
// Insert a normalized node at the current point. If it is a text
// node, wrap it in a <span>, and give that span a currentText
// property -- this is used to cache the nodeValue, because
// directly accessing nodeValue is horribly slow on some browsers.
// The dirty property is used by the highlighter to determine
// which parts of the document have to be re-highlighted.
function insertPart(part){
var text = "\n";
if (part.nodeType == 3) {
select.snapshotChanged();
part = makePartSpan(part, owner);
text = part.currentText;
afterBR = false;
}
else {
if (afterBR && window.opera)
point(makePartSpan("", owner));
afterBR = true;
}
part.dirty = true;
nodeQueue.push(part);
point(part);
return text;
}
// Extract the text and newlines from a DOM node, insert them into
// the document, and yield the textual content. Used to replace
// non-normalized nodes.
function writeNode(node, c, end) {
var toYield = [];
forEach(simplifyDOM(node, end), function(part) {
toYield.push(insertPart(part));
});
return _yield(toYield.join(""), c);
}
// Check whether a node is a normalized <span> element.
function partNode(node){
if (node.isPart && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
node.currentText = node.firstChild.nodeValue;
return !/[\n\t\r]/.test(node.currentText);
}
return false;
}
// Handle a node. Add its successor to the continuation if there
// is one, find out whether the node is normalized. If it is,
// yield its content, otherwise, normalize it (writeNode will take
// care of yielding).
function scanNode(node, c){
if (node.nextSibling)
c = push(scanNode, node.nextSibling, c);
if (partNode(node)){
nodeQueue.push(node);
afterBR = false;
return _yield(node.currentText, c);
}
else if (isBR(node)) {
if (afterBR && window.opera)
node.parentNode.insertBefore(makePartSpan("", owner), node);
nodeQueue.push(node);
afterBR = true;
return _yield("\n", c);
}
else {
var end = !node.nextSibling;
point = pointAt(node);
removeElement(node);
return writeNode(node, c, end);
}
}
// MochiKit iterators are objects with a next function that
// returns the next value or throws StopIteration when there are
// no more values.
return {next: function(){return cc();}, nodes: nodeQueue};
}
// Determine the text size of a processed node.
function nodeSize(node) {
return isBR(node) ? 1 : node.currentText.length;
}
// Search backwards through the top-level nodes until the next BR or
// the start of the frame.
function startOfLine(node) {
while (node && !isBR(node)) node = node.previousSibling;
return node;
}
function endOfLine(node, container) {
if (!node) node = container.firstChild;
else if (isBR(node)) node = node.nextSibling;
while (node && !isBR(node)) node = node.nextSibling;
return node;
}
function time() {return new Date().getTime();}
// Client interface for searching the content of the editor. Create
// these by calling CodeMirror.getSearchCursor. To use, call
// findNext on the resulting object -- this returns a boolean
// indicating whether anything was found, and can be called again to
// skip to the next find. Use the select and replace methods to
// actually do something with the found locations.
function SearchCursor(editor, string, fromCursor, caseFold) {
this.editor = editor;
this.caseFold = caseFold;
if (caseFold) string = string.toLowerCase();
this.history = editor.history;
this.history.commit();
// Are we currently at an occurrence of the search string?
this.atOccurrence = false;
// The object stores a set of nodes coming after its current
// position, so that when the current point is taken out of the
// DOM tree, we can still try to continue.
this.fallbackSize = 15;
var cursor;
// Start from the cursor when specified and a cursor can be found.
if (fromCursor && (cursor = select.cursorPos(this.editor.container))) {
this.line = cursor.node;
this.offset = cursor.offset;
}
else {
this.line = null;
this.offset = 0;
}
this.valid = !!string;
// Create a matcher function based on the kind of string we have.
var target = string.split("\n"), self = this;
this.matches = (target.length == 1) ?
// For one-line strings, searching can be done simply by calling
// indexOf on the current line.
function() {
var line = cleanText(self.history.textAfter(self.line).slice(self.offset));
var match = (self.caseFold ? line.toLowerCase() : line).indexOf(string);
if (match > -1)
return {from: {node: self.line, offset: self.offset + match},
to: {node: self.line, offset: self.offset + match + string.length}};
} :
// Multi-line strings require internal iteration over lines, and
// some clunky checks to make sure the first match ends at the
// end of the line and the last match starts at the start.
function() {
var firstLine = cleanText(self.history.textAfter(self.line).slice(self.offset));
var match = (self.caseFold ? firstLine.toLowerCase() : firstLine).lastIndexOf(target[0]);
if (match == -1 || match != firstLine.length - target[0].length)
return false;
var startOffset = self.offset + match;
var line = self.history.nodeAfter(self.line);
for (var i = 1; i < target.length - 1; i++) {
var lineText = cleanText(self.history.textAfter(line));
if ((self.caseFold ? lineText.toLowerCase() : lineText) != target[i])
return false;
line = self.history.nodeAfter(line);
}
var lastLine = cleanText(self.history.textAfter(line));
if ((self.caseFold ? lastLine.toLowerCase() : lastLine).indexOf(target[target.length - 1]) != 0)
return false;
return {from: {node: self.line, offset: startOffset},
to: {node: line, offset: target[target.length - 1].length}};
};
}
SearchCursor.prototype = {
findNext: function() {
if (!this.valid) return false;
this.atOccurrence = false;
var self = this;
// Go back to the start of the document if the current line is
// no longer in the DOM tree.
if (this.line && !this.line.parentNode) {
this.line = null;
this.offset = 0;
}
// Set the cursor's position one character after the given
// position.
function saveAfter(pos) {
if (self.history.textAfter(pos.node).length > pos.offset) {
self.line = pos.node;
self.offset = pos.offset + 1;
}
else {
self.line = self.history.nodeAfter(pos.node);
self.offset = 0;
}
}
while (true) {
var match = this.matches();
// Found the search string.
if (match) {
this.atOccurrence = match;
saveAfter(match.from);
return true;
}
this.line = this.history.nodeAfter(this.line);
this.offset = 0;
// End of document.
if (!this.line) {
this.valid = false;
return false;
}
}
},
select: function() {
if (this.atOccurrence) {
select.setCursorPos(this.editor.container, this.atOccurrence.from, this.atOccurrence.to);
select.scrollToCursor(this.editor.container);
}
},
replace: function(string) {
if (this.atOccurrence) {
var end = this.editor.replaceRange(this.atOccurrence.from, this.atOccurrence.to, string);
this.line = end.node;
this.offset = end.offset;
this.atOccurrence = false;
}
}
};
// The Editor object is the main inside-the-iframe interface.
function Editor(options) {
this.options = options;
window.indentUnit = options.indentUnit;
this.parent = parent;
this.doc = document;
var container = this.container = this.doc.body;
this.win = window;
this.history = new History(container, options.undoDepth, options.undoDelay, this);
var self = this;
if (!Editor.Parser)
throw "No parser loaded.";
if (options.parserConfig && Editor.Parser.configure)
Editor.Parser.configure(options.parserConfig);
if (!options.readOnly)
select.setCursorPos(container, {node: null, offset: 0});
this.dirty = [];
this.importCode(options.content || "");
this.history.onChange = options.onChange;
if (!options.readOnly) {
if (options.continuousScanning !== false) {
this.scanner = this.documentScanner(options.passTime);
this.delayScanning();
}
function setEditable() {
// In IE, designMode frames can not run any scripts, so we use
// contentEditable instead.
if (document.body.contentEditable != undefined && internetExplorer)
document.body.contentEditable = "true";
else
document.designMode = "on";
document.documentElement.style.borderWidth = "0";
if (!options.textWrapping)
container.style.whiteSpace = "nowrap";
}
// If setting the frame editable fails, try again when the user
// focus it (happens when the frame is not visible on
// initialisation, in Firefox).
try {
setEditable();
}
catch(e) {
var focusEvent = addEventHandler(document, "focus", function() {
focusEvent();
setEditable();
}, true);
}
addEventHandler(document, "keydown", method(this, "keyDown"));
addEventHandler(document, "keypress", method(this, "keyPress"));
addEventHandler(document, "keyup", method(this, "keyUp"));
function cursorActivity() {self.cursorActivity(false);}
addEventHandler(document.body, "mouseup", cursorActivity);
addEventHandler(document.body, "cut", cursorActivity);
// workaround for a gecko bug [?] where going forward and then
// back again breaks designmode (no more cursor)
if (gecko)
addEventHandler(this.win, "pagehide", function(){self.unloaded = true;});
addEventHandler(document.body, "paste", function(event) {
cursorActivity();
var text = null;
try {
var clipboardData = event.clipboardData || window.clipboardData;
if (clipboardData) text = clipboardData.getData('Text');
}
catch(e) {}
if (text !== null) {
event.stop();
self.replaceSelection(text);
select.scrollToCursor(self.container);
}
});
if (this.options.autoMatchParens)
addEventHandler(document.body, "click", method(this, "scheduleParenHighlight"));
}
else if (!options.textWrapping) {
container.style.whiteSpace = "nowrap";
}
}
function isSafeKey(code) {
return (code >= 16 && code <= 18) || // shift, control, alt
(code >= 33 && code <= 40); // arrows, home, end
}
Editor.prototype = {
// Import a piece of code into the editor.
importCode: function(code) {
this.history.push(null, null, asEditorLines(code));
this.history.reset();
},
// Extract the code from the editor.
getCode: function() {
if (!this.container.firstChild)
return "";
var accum = [];
select.markSelection(this.win);
forEach(traverseDOM(this.container.firstChild), method(accum, "push"));
webkitLastLineHack(this.container);
select.selectMarked();
return cleanText(accum.join(""));
},
checkLine: function(node) {
if (node === false || !(node == null || node.parentNode == this.container))
throw parent.CodeMirror.InvalidLineHandle;
},
cursorPosition: function(start) {
if (start == null) start = true;
var pos = select.cursorPos(this.container, start);
if (pos) return {line: pos.node, character: pos.offset};
else return {line: null, character: 0};
},
firstLine: function() {
return null;
},
lastLine: function() {
if (this.container.lastChild) return startOfLine(this.container.lastChild);
else return null;
},
nextLine: function(line) {
this.checkLine(line);
var end = endOfLine(line, this.container);
return end || false;
},
prevLine: function(line) {
this.checkLine(line);
if (line == null) return false;
return startOfLine(line.previousSibling);
},
selectLines: function(startLine, startOffset, endLine, endOffset) {
this.checkLine(startLine);
var start = {node: startLine, offset: startOffset}, end = null;
if (endOffset !== undefined) {
this.checkLine(endLine);
end = {node: endLine, offset: endOffset};
}
select.setCursorPos(this.container, start, end);
select.scrollToCursor(this.container);
},
lineContent: function(line) {
var accum = [];
for (line = line ? line.nextSibling : this.container.firstChild;
line && !isBR(line); line = line.nextSibling)
accum.push(nodeText(line));
return cleanText(accum.join(""));
},
setLineContent: function(line, content) {
this.history.commit();
this.replaceRange({node: line, offset: 0},
{node: line, offset: this.history.textAfter(line).length},
content);
this.addDirtyNode(line);
this.scheduleHighlight();
},
removeLine: function(line) {
var node = line ? line.nextSibling : this.container.firstChild;
while (node) {
var next = node.nextSibling;
removeElement(node);
if (isBR(node)) break;
node = next;
}
this.addDirtyNode(line);
this.scheduleHighlight();
},
insertIntoLine: function(line, position, content) {
var before = null;
if (position == "end") {
before = endOfLine(line, this.container);
}
else {
for (var cur = line ? line.nextSibling : this.container.firstChild; cur; cur = cur.nextSibling) {
if (position == 0) {
before = cur;
break;
}
var text = nodeText(cur);
if (text.length > position) {
before = cur.nextSibling;
content = text.slice(0, position) + content + text.slice(position);
removeElement(cur);
break;
}
position -= text.length;
}
}
var lines = asEditorLines(content), doc = this.container.ownerDocument;
for (var i = 0; i < lines.length; i++) {
if (i > 0) this.container.insertBefore(doc.createElement("BR"), before);
this.container.insertBefore(makePartSpan(lines[i], doc), before);
}
this.addDirtyNode(line);
this.scheduleHighlight();
},
// Retrieve the selected text.
selectedText: function() {
var h = this.history;
h.commit();
var start = select.cursorPos(this.container, true),
end = select.cursorPos(this.container, false);
if (!start || !end) return "";
if (start.node == end.node)
return h.textAfter(start.node).slice(start.offset, end.offset);
var text = [h.textAfter(start.node).slice(start.offset)];
for (var pos = h.nodeAfter(start.node); pos != end.node; pos = h.nodeAfter(pos))
text.push(h.textAfter(pos));
text.push(h.textAfter(end.node).slice(0, end.offset));
return cleanText(text.join("\n"));
},
// Replace the selection with another piece of text.
replaceSelection: function(text) {
this.history.commit();
var start = select.cursorPos(this.container, true),
end = select.cursorPos(this.container, false);
if (!start || !end) return;
end = this.replaceRange(start, end, text);
select.setCursorPos(this.container, end);
webkitLastLineHack(this.container);
},
reroutePasteEvent: function() {
if (this.capturingPaste || window.opera) return;
this.capturingPaste = true;
var te = parent.document.createElement("TEXTAREA");
te.style.position = "absolute";
te.style.left = "-10000px";
te.style.width = "10px";
te.style.top = nodeTop(frameElement) + "px";
var wrap = window.frameElement.CodeMirror.wrapping;
wrap.parentNode.insertBefore(te, wrap);
parent.focus();
te.focus();
var self = this;
this.parent.setTimeout(function() {
self.capturingPaste = false;
self.win.focus();
if (self.selectionSnapshot) // IE hack
self.win.select.setBookmark(self.container, self.selectionSnapshot);
var text = te.value;
if (text) {
self.replaceSelection(text);
select.scrollToCursor(self.container);
}
removeElement(te);
}, 10);
},
replaceRange: function(from, to, text) {
var lines = asEditorLines(text);
lines[0] = this.history.textAfter(from.node).slice(0, from.offset) + lines[0];
var lastLine = lines[lines.length - 1];
lines[lines.length - 1] = lastLine + this.history.textAfter(to.node).slice(to.offset);
var end = this.history.nodeAfter(to.node);
this.history.push(from.node, end, lines);
return {node: this.history.nodeBefore(end),
offset: lastLine.length};
},
getSearchCursor: function(string, fromCursor, caseFold) {
return new SearchCursor(this, string, fromCursor, caseFold);
},
// Re-indent the whole buffer
reindent: function() {
if (this.container.firstChild)
this.indentRegion(null, this.container.lastChild);
},
reindentSelection: function(direction) {
if (!select.somethingSelected(this.win)) {
this.indentAtCursor(direction);
}
else {
var start = select.selectionTopNode(this.container, true),
end = select.selectionTopNode(this.container, false);
if (start === false || end === false) return;
this.indentRegion(start, end, direction);
}
},
grabKeys: function(eventHandler, filter) {
this.frozen = eventHandler;
this.keyFilter = filter;
},
ungrabKeys: function() {
this.frozen = "leave";
this.keyFilter = null;
},
setParser: function(name) {
Editor.Parser = window[name];
if (this.container.firstChild) {
forEach(this.container.childNodes, function(n) {
if (n.nodeType != 3) n.dirty = true;
});
this.addDirtyNode(this.firstChild);
this.scheduleHighlight();
}
},
// Intercept enter and tab, and assign their new functions.
keyDown: function(event) {
if (this.frozen == "leave") this.frozen = null;
if (this.frozen && (!this.keyFilter || this.keyFilter(event.keyCode))) {
event.stop();
this.frozen(event);
return;
}
var code = event.keyCode;
// Don't scan when the user is typing.
this.delayScanning();
// Schedule a paren-highlight event, if configured.
if (this.options.autoMatchParens)
this.scheduleParenHighlight();
// The various checks for !altKey are there because AltGr sets both
// ctrlKey and altKey to true, and should not be recognised as
// Control.
if (code == 13) { // enter
if (event.ctrlKey && !event.altKey) {
this.reparseBuffer();
}
else {
select.insertNewlineAtCursor(this.win);
this.indentAtCursor();
select.scrollToCursor(this.container);
}
event.stop();
}
else if (code == 9 && this.options.tabMode != "default" && !event.ctrlKey) { // tab
this.handleTab(!event.shiftKey);
event.stop();
}
else if (code == 32 && event.shiftKey && this.options.tabMode == "default") { // space
this.handleTab(true);
event.stop();
}
else if (code == 36 && !event.shiftKey && !event.ctrlKey) { // home
if (this.home()) event.stop();
}
else if (code == 35 && !event.shiftKey && !event.ctrlKey) { // end
if (this.end()) event.stop();
}
else if ((code == 219 || code == 221) && event.ctrlKey && !event.altKey) { // [, ]
this.highlightParens(event.shiftKey, true);
event.stop();
}
else if (event.metaKey && !event.shiftKey && (code == 37 || code == 39)) { // Meta-left/right
var cursor = select.selectionTopNode(this.container);
if (cursor === false || !this.container.firstChild) return;
if (code == 37) select.focusAfterNode(startOfLine(cursor), this.container);
else {
var end = endOfLine(cursor, this.container);
select.focusAfterNode(end ? end.previousSibling : this.container.lastChild, this.container);
}
event.stop();
}
else if ((event.ctrlKey || event.metaKey) && !event.altKey) {
if ((event.shiftKey && code == 90) || code == 89) { // shift-Z, Y
select.scrollToNode(this.history.redo());
event.stop();
}
else if (code == 90 || (safari && code == 8)) { // Z, backspace
select.scrollToNode(this.history.undo());
event.stop();
}
else if (code == 83 && this.options.saveFunction) { // S
this.options.saveFunction();
event.stop();
}
else if (internetExplorer && code == 86) {
this.reroutePasteEvent();
}
}
},
// Check for characters that should re-indent the current line,
// and prevent Opera from handling enter and tab anyway.
keyPress: function(event) {
var electric = Editor.Parser.electricChars, self = this;
// Hack for Opera, and Firefox on OS X, in which stopping a
// keydown event does not prevent the associated keypress event
// from happening, so we have to cancel enter and tab again
// here.
if ((this.frozen && (!this.keyFilter || this.keyFilter(event.keyCode))) ||
event.code == 13 || (event.code == 9 && this.options.tabMode != "default") ||
(event.keyCode == 32 && event.shiftKey && this.options.tabMode == "default"))
event.stop();
else if (electric && electric.indexOf(event.character) != -1)
this.parent.setTimeout(function(){self.indentAtCursor(null);}, 0);
else if ((event.character == "v" || event.character == "V")
&& (event.ctrlKey || event.metaKey) && !event.altKey) // ctrl-V
this.reroutePasteEvent();
},
// Mark the node at the cursor dirty when a non-safe key is
// released.
keyUp: function(event) {
this.cursorActivity(isSafeKey(event.keyCode));
},
// Indent the line following a given <br>, or null for the first
// line. If given a <br> element, this must have been highlighted
// so that it has an indentation method. Returns the whitespace
// element that has been modified or created (if any).
indentLineAfter: function(start, direction) {
// whiteSpace is the whitespace span at the start of the line,
// or null if there is no such node.
var whiteSpace = start ? start.nextSibling : this.container.firstChild;
if (whiteSpace && !hasClass(whiteSpace, "whitespace"))
whiteSpace = null;
// Sometimes the start of the line can influence the correct
// indentation, so we retrieve it.
var firstText = whiteSpace ? whiteSpace.nextSibling : (start ? start.nextSibling : this.container.firstChild);
var nextChars = (start && firstText && firstText.currentText) ? firstText.currentText : "";
// Ask the lexical context for the correct indentation, and
// compute how much this differs from the current indentation.
var newIndent = 0, curIndent = whiteSpace ? whiteSpace.currentText.length : 0;
if (direction != null && this.options.tabMode == "shift")
newIndent = direction ? curIndent + indentUnit : Math.max(0, curIndent - indentUnit)
else if (start)
newIndent = start.indentation(nextChars, curIndent, direction);
else if (Editor.Parser.firstIndentation)
newIndent = Editor.Parser.firstIndentation(nextChars, curIndent, direction);
var indentDiff = newIndent - curIndent;
// If there is too much, this is just a matter of shrinking a span.
if (indentDiff < 0) {
if (newIndent == 0) {
if (firstText) select.snapshotMove(whiteSpace.firstChild, firstText.firstChild, 0);
removeElement(whiteSpace);
whiteSpace = null;
}
else {
select.snapshotMove(whiteSpace.firstChild, whiteSpace.firstChild, indentDiff, true);
whiteSpace.currentText = makeWhiteSpace(newIndent);
whiteSpace.firstChild.nodeValue = whiteSpace.currentText;
}
}
// Not enough...
else if (indentDiff > 0) {
// If there is whitespace, we grow it.
if (whiteSpace) {
whiteSpace.currentText = makeWhiteSpace(newIndent);
whiteSpace.firstChild.nodeValue = whiteSpace.currentText;
}
// Otherwise, we have to add a new whitespace node.
else {
whiteSpace = makePartSpan(makeWhiteSpace(newIndent), this.doc);
whiteSpace.className = "whitespace";
if (start) insertAfter(whiteSpace, start);
else this.container.insertBefore(whiteSpace, this.container.firstChild);
}
if (firstText) select.snapshotMove(firstText.firstChild, whiteSpace.firstChild, curIndent, false, true);
}
if (indentDiff != 0) this.addDirtyNode(start);
return whiteSpace;
},
// Re-highlight the selected part of the document.
highlightAtCursor: function() {
var pos = select.selectionTopNode(this.container, true);
var to = select.selectionTopNode(this.container, false);
if (pos === false || to === false) return false;
select.markSelection(this.win);
if (this.highlight(pos, endOfLine(to, this.container), true, 20) === false)
return false;
select.selectMarked();
return true;
},
// When tab is pressed with text selected, the whole selection is
// re-indented, when nothing is selected, the line with the cursor
// is re-indented.
handleTab: function(direction) {
if (this.options.tabMode == "spaces")
select.insertTabAtCursor(this.win);
else
this.reindentSelection(direction);
},
// Custom home behaviour that doesn't land the cursor in front of
// leading whitespace unless pressed twice.
home: function() {
var cur = select.selectionTopNode(this.container, true), start = cur;
if (cur === false || !(!cur || cur.isPart || isBR(cur)) || !this.container.firstChild)
return false;
while (cur && !isBR(cur)) cur = cur.previousSibling;
var next = cur ? cur.nextSibling : this.container.firstChild;
if (next && next != start && next.isPart && hasClass(next, "whitespace"))
select.focusAfterNode(next, this.container);
else
select.focusAfterNode(cur, this.container);
select.scrollToCursor(this.container);
return true;
},
// Some browsers (Opera) don't manage to handle the end key
// properly in the face of vertical scrolling.
end: function() {
var cur = select.selectionTopNode(this.container, true);
if (cur === false) return false;
cur = endOfLine(cur, this.container);
if (!cur) return false;
select.focusAfterNode(cur.previousSibling, this.container);
select.scrollToCursor(this.container);
return true;
},
// Delay (or initiate) the next paren highlight event.
scheduleParenHighlight: function() {
if (this.parenEvent) this.parent.clearTimeout(this.parenEvent);
var self = this;
this.parenEvent = this.parent.setTimeout(function(){self.highlightParens();}, 300);
},
// Take the token before the cursor. If it contains a character in
// '()[]{}', search for the matching paren/brace/bracket, and
// highlight them in green for a moment, or red if no proper match
// was found.
highlightParens: function(jump, fromKey) {
var self = this;
// give the relevant nodes a colour.
function highlight(node, ok) {
if (!node) return;
if (self.options.markParen) {
self.options.markParen(node, ok);
}
else {
node.style.fontWeight = "bold";
node.style.color = ok ? "#8F8" : "#F88";
}
}
function unhighlight(node) {
if (!node) return;
if (self.options.unmarkParen) {
self.options.unmarkParen(node);
}
else {
node.style.fontWeight = "";
node.style.color = "";
}
}
if (!fromKey && self.highlighted) {
unhighlight(self.highlighted[0]);
unhighlight(self.highlighted[1]);
}
if (!window.select) return;
// Clear the event property.
if (this.parenEvent) this.parent.clearTimeout(this.parenEvent);
this.parenEvent = null;
// Extract a 'paren' from a piece of text.
function paren(node) {
if (node.currentText) {
var match = node.currentText.match(/^[\s\u00a0]*([\(\)\[\]{}])[\s\u00a0]*$/);
return match && match[1];
}
}
// Determine the direction a paren is facing.
function forward(ch) {
return /[\(\[\{]/.test(ch);
}
var ch, cursor = select.selectionTopNode(this.container, true);
if (!cursor || !this.highlightAtCursor()) return;
cursor = select.selectionTopNode(this.container, true);
if (!(cursor && ((ch = paren(cursor)) || (cursor = cursor.nextSibling) && (ch = paren(cursor)))))
return;
// We only look for tokens with the same className.
var className = cursor.className, dir = forward(ch), match = matching[ch];
// Since parts of the document might not have been properly
// highlighted, and it is hard to know in advance which part we
// have to scan, we just try, and when we find dirty nodes we
// abort, parse them, and re-try.
function tryFindMatch() {
var stack = [], ch, ok = true;
for (var runner = cursor; runner; runner = dir ? runner.nextSibling : runner.previousSibling) {
if (runner.className == className && isSpan(runner) && (ch = paren(runner))) {
if (forward(ch) == dir)
stack.push(ch);
else if (!stack.length)
ok = false;
else if (stack.pop() != matching[ch])
ok = false;
if (!stack.length) break;
}
else if (runner.dirty || !isSpan(runner) && !isBR(runner)) {
return {node: runner, status: "dirty"};
}
}
return {node: runner, status: runner && ok};
}
while (true) {
var found = tryFindMatch();
if (found.status == "dirty") {
this.highlight(found.node, endOfLine(found.node));
// Needed because in some corner cases a highlight does not
// reach a node.
found.node.dirty = false;
continue;
}
else {
highlight(cursor, found.status);
highlight(found.node, found.status);
if (fromKey)
self.parent.setTimeout(function() {unhighlight(cursor); unhighlight(found.node);}, 500);
else
self.highlighted = [cursor, found.node];
if (jump && found.node)
select.focusAfterNode(found.node.previousSibling, this.container);
break;
}
}
},
// Adjust the amount of whitespace at the start of the line that
// the cursor is on so that it is indented properly.
indentAtCursor: function(direction) {
if (!this.container.firstChild) return;
// The line has to have up-to-date lexical information, so we
// highlight it first.
if (!this.highlightAtCursor()) return;
var cursor = select.selectionTopNode(this.container, false);
// If we couldn't determine the place of the cursor,
// there's nothing to indent.
if (cursor === false)
return;
var lineStart = startOfLine(cursor);
var whiteSpace = this.indentLineAfter(lineStart, direction);
if (cursor == lineStart && whiteSpace)
cursor = whiteSpace;
// This means the indentation has probably messed up the cursor.
if (cursor == whiteSpace)
select.focusAfterNode(cursor, this.container);
},
// Indent all lines whose start falls inside of the current
// selection.
indentRegion: function(start, end, direction) {
var current = (start = startOfLine(start)), before = start && startOfLine(start.previousSibling);
if (!isBR(end)) end = endOfLine(end, this.container);
this.addDirtyNode(start);
do {
var next = endOfLine(current, this.container);
if (current) this.highlight(before, next, true);
this.indentLineAfter(current, direction);
before = current;
current = next;
} while (current != end);
select.setCursorPos(this.container, {node: start, offset: 0}, {node: end, offset: 0});
},
// Find the node that the cursor is in, mark it as dirty, and make
// sure a highlight pass is scheduled.
cursorActivity: function(safe) {
// pagehide event hack above
if (this.unloaded) {
this.win.document.designMode = "off";
this.win.document.designMode = "on";
this.unloaded = false;
}
if (internetExplorer) {
this.container.createTextRange().execCommand("unlink");
this.selectionSnapshot = select.getBookmark(this.container);
}
var activity = this.options.cursorActivity;
if (!safe || activity) {
var cursor = select.selectionTopNode(this.container, false);
if (cursor === false || !this.container.firstChild) return;
cursor = cursor || this.container.firstChild;
if (activity) activity(cursor);
if (!safe) {
this.scheduleHighlight();
this.addDirtyNode(cursor);
}
}
},
reparseBuffer: function() {
forEach(this.container.childNodes, function(node) {node.dirty = true;});
if (this.container.firstChild)
this.addDirtyNode(this.container.firstChild);
},
// Add a node to the set of dirty nodes, if it isn't already in
// there.
addDirtyNode: function(node) {
node = node || this.container.firstChild;
if (!node) return;
for (var i = 0; i < this.dirty.length; i++)
if (this.dirty[i] == node) return;
if (node.nodeType != 3)
node.dirty = true;
this.dirty.push(node);
},
allClean: function() {
return !this.dirty.length;
},
// Cause a highlight pass to happen in options.passDelay
// milliseconds. Clear the existing timeout, if one exists. This
// way, the passes do not happen while the user is typing, and
// should as unobtrusive as possible.
scheduleHighlight: function() {
// Timeouts are routed through the parent window, because on
// some browsers designMode windows do not fire timeouts.
var self = this;
this.parent.clearTimeout(this.highlightTimeout);
this.highlightTimeout = this.parent.setTimeout(function(){self.highlightDirty();}, this.options.passDelay);
},
// Fetch one dirty node, and remove it from the dirty set.
getDirtyNode: function() {
while (this.dirty.length > 0) {
var found = this.dirty.pop();
// IE8 sometimes throws an unexplainable 'invalid argument'
// exception for found.parentNode
try {
// If the node has been coloured in the meantime, or is no
// longer in the document, it should not be returned.
while (found && found.parentNode != this.container)
found = found.parentNode;
if (found && (found.dirty || found.nodeType == 3))
return found;
} catch (e) {}
}
return null;
},
// Pick dirty nodes, and highlight them, until options.passTime
// milliseconds have gone by. The highlight method will continue
// to next lines as long as it finds dirty nodes. It returns
// information about the place where it stopped. If there are
// dirty nodes left after this function has spent all its lines,
// it shedules another highlight to finish the job.
highlightDirty: function(force) {
// Prevent FF from raising an error when it is firing timeouts
// on a page that's no longer loaded.
if (!window.select) return false;
if (!this.options.readOnly) select.markSelection(this.win);
var start, endTime = force ? null : time() + this.options.passTime;
while ((time() < endTime || force) && (start = this.getDirtyNode())) {
var result = this.highlight(start, endTime);
if (result && result.node && result.dirty)
this.addDirtyNode(result.node);
}
if (!this.options.readOnly) select.selectMarked();
if (start) this.scheduleHighlight();
return this.dirty.length == 0;
},
// Creates a function that, when called through a timeout, will
// continuously re-parse the document.
documentScanner: function(passTime) {
var self = this, pos = null;
return function() {
// FF timeout weirdness workaround.
if (!window.select) return;
// If the current node is no longer in the document... oh
// well, we start over.
if (pos && pos.parentNode != self.container)
pos = null;
select.markSelection(self.win);
var result = self.highlight(pos, time() + passTime, true);
select.selectMarked();
var newPos = result ? (result.node && result.node.nextSibling) : null;
pos = (pos == newPos) ? null : newPos;
self.delayScanning();
};
},
// Starts the continuous scanning process for this document after
// a given interval.
delayScanning: function() {
if (this.scanner) {
this.parent.clearTimeout(this.documentScan);
this.documentScan = this.parent.setTimeout(this.scanner, this.options.continuousScanning);
}
},
// The function that does the actual highlighting/colouring (with
// help from the parser and the DOM normalizer). Its interface is
// rather overcomplicated, because it is used in different
// situations: ensuring that a certain line is highlighted, or
// highlighting up to X milliseconds starting from a certain
// point. The 'from' argument gives the node at which it should
// start. If this is null, it will start at the beginning of the
// document. When a timestamp is given with the 'target' argument,
// it will stop highlighting at that time. If this argument holds
// a DOM node, it will highlight until it reaches that node. If at
// any time it comes across two 'clean' lines (no dirty nodes), it
// will stop, except when 'cleanLines' is true. maxBacktrack is
// the maximum number of lines to backtrack to find an existing
// parser instance. This is used to give up in situations where a
// highlight would take too long and freeze the browser interface.
highlight: function(from, target, cleanLines, maxBacktrack){
var container = this.container, self = this, active = this.options.activeTokens;
var endTime = (typeof target == "number" ? target : null);
if (!container.firstChild)
return false;
// Backtrack to the first node before from that has a partial
// parse stored.
while (from && (!from.parserFromHere || from.dirty)) {
if (maxBacktrack != null && isBR(from) && (--maxBacktrack) < 0)
return false;
from = from.previousSibling;
}
// If we are at the end of the document, do nothing.
if (from && !from.nextSibling)
return false;
// Check whether a part (<span> node) and the corresponding token
// match.
function correctPart(token, part){
return !part.reduced && part.currentText == token.value && part.className == token.style;
}
// Shorten the text associated with a part by chopping off
// characters from the front. Note that only the currentText
// property gets changed. For efficiency reasons, we leave the
// nodeValue alone -- we set the reduced flag to indicate that
// this part must be replaced.
function shortenPart(part, minus){
part.currentText = part.currentText.substring(minus);
part.reduced = true;
}
// Create a part corresponding to a given token.
function tokenPart(token){
var part = makePartSpan(token.value, self.doc);
part.className = token.style;
return part;
}
function maybeTouch(node) {
if (node) {
var old = node.oldNextSibling;
if (lineDirty || old === undefined || node.nextSibling != old)
self.history.touch(node);
node.oldNextSibling = node.nextSibling;
}
else {
var old = self.container.oldFirstChild;
if (lineDirty || old === undefined || self.container.firstChild != old)
self.history.touch(null);
self.container.oldFirstChild = self.container.firstChild;
}
}
// Get the token stream. If from is null, we start with a new
// parser from the start of the frame, otherwise a partial parse
// is resumed.
var traversal = traverseDOM(from ? from.nextSibling : container.firstChild),
stream = stringStream(traversal),
parsed = from ? from.parserFromHere(stream) : Editor.Parser.make(stream);
function surroundedByBRs(node) {
return (node.previousSibling == null || isBR(node.previousSibling)) &&
(node.nextSibling == null || isBR(node.nextSibling));
}
// parts is an interface to make it possible to 'delay' fetching
// the next DOM node until we are completely done with the one
// before it. This is necessary because often the next node is
// not yet available when we want to proceed past the current
// one.
var parts = {
current: null,
// Fetch current node.
get: function(){
if (!this.current)
this.current = traversal.nodes.shift();
return this.current;
},
// Advance to the next part (do not fetch it yet).
next: function(){
this.current = null;
},
// Remove the current part from the DOM tree, and move to the
// next.
remove: function(){
container.removeChild(this.get());
this.current = null;
},
// Advance to the next part that is not empty, discarding empty
// parts.
getNonEmpty: function(){
var part = this.get();
// Allow empty nodes when they are alone on a line, needed
// for the FF cursor bug workaround (see select.js,
// insertNewlineAtCursor).
while (part && isSpan(part) && part.currentText == "") {
// Leave empty nodes that are alone on a line alone in
// Opera, since that browsers doesn't deal well with
// having 2 BRs in a row.
if (window.opera && surroundedByBRs(part)) {
this.next();
part = this.get();
}
else {
var old = part;
this.remove();
part = this.get();
// Adjust selection information, if any. See select.js for details.
select.snapshotMove(old.firstChild, part && (part.firstChild || part), 0);
}
}
return part;
}
};
var lineDirty = false, prevLineDirty = true, lineNodes = 0;
// This forEach loops over the tokens from the parsed stream, and
// at the same time uses the parts object to proceed through the
// corresponding DOM nodes.
forEach(parsed, function(token){
var part = parts.getNonEmpty();
if (token.value == "\n"){
// The idea of the two streams actually staying synchronized
// is such a long shot that we explicitly check.
if (!isBR(part))
throw "Parser out of sync. Expected BR.";
if (part.dirty || !part.indentation) lineDirty = true;
maybeTouch(from);
from = part;
// Every <br> gets a copy of the parser state and a lexical
// context assigned to it. The first is used to be able to
// later resume parsing from this point, the second is used
// for indentation.
part.parserFromHere = parsed.copy();
part.indentation = token.indentation;
part.dirty = false;
// If the target argument wasn't an integer, go at least
// until that node.
if (endTime == null && part == target) throw StopIteration;
// A clean line with more than one node means we are done.
// Throwing a StopIteration is the way to break out of a
// MochiKit forEach loop.
if ((endTime != null && time() >= endTime) || (!lineDirty && !prevLineDirty && lineNodes > 1 && !cleanLines))
throw StopIteration;
prevLineDirty = lineDirty; lineDirty = false; lineNodes = 0;
parts.next();
}
else {
if (!isSpan(part))
throw "Parser out of sync. Expected SPAN.";
if (part.dirty)
lineDirty = true;
lineNodes++;
// If the part matches the token, we can leave it alone.
if (correctPart(token, part)){
part.dirty = false;
parts.next();
}
// Otherwise, we have to fix it.
else {
lineDirty = true;
// Insert the correct part.
var newPart = tokenPart(token);
container.insertBefore(newPart, part);
if (active) active(newPart, token, self);
var tokensize = token.value.length;
var offset = 0;
// Eat up parts until the text for this token has been
// removed, adjusting the stored selection info (see
// select.js) in the process.
while (tokensize > 0) {
part = parts.get();
var partsize = part.currentText.length;
select.snapshotReplaceNode(part.firstChild, newPart.firstChild, tokensize, offset);
if (partsize > tokensize){
shortenPart(part, tokensize);
tokensize = 0;
}
else {
tokensize -= partsize;
offset += partsize;
parts.remove();
}
}
}
}
});
maybeTouch(from);
webkitLastLineHack(this.container);
// The function returns some status information that is used by
// hightlightDirty to determine whether and where it has to
// continue.
return {node: parts.getNonEmpty(),
dirty: lineDirty};
}
};
return Editor;
})();
addEventHandler(window, "load", function() {
var CodeMirror = window.frameElement.CodeMirror;
var e = CodeMirror.editor = new Editor(CodeMirror.options);
this.parent.setTimeout(method(CodeMirror, "init"), 0);
});
| Alex-Bond/Core-package | tests/editors/ckfinder/plugins/fileeditor/codemirror/js/editor.js | JavaScript | gpl-3.0 | 53,109 |
/*
Copyright (c) 2010, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.com/yui/license.html
version: 3.2.0
build: 2676
*/
YUI.add('querystring-stringify', function(Y) {
/**
* Provides Y.QueryString.stringify method for converting objects to Query Strings.
*
* @module querystring
* @submodule querystring-stringify
* @for QueryString
* @static
*/
var QueryString = Y.namespace("QueryString"),
stack = [],
L = Y.Lang;
/**
* Provides Y.QueryString.escape method to be able to override default encoding
* method. This is important in cases where non-standard delimiters are used, if
* the delimiters would not normally be handled properly by the builtin
* (en|de)codeURIComponent functions.
* Default: encodeURIComponent
* @module querystring
* @submodule querystring-stringify
* @for QueryString
* @static
**/
QueryString.escape = encodeURIComponent;
/**
* <p>Converts an arbitrary value to a Query String representation.</p>
*
* <p>Objects with cyclical references will trigger an exception.</p>
*
* @method stringify
* @param obj {Variant} any arbitrary value to convert to query string
* @param sep {String} (optional) Character that should join param k=v pairs together. Default: "&"
* @param eq {String} (optional) Character that should join keys to their values. Default: "="
* @param name {String} (optional) Name of the current key, for handling children recursively.
* @static
*/
QueryString.stringify = function (obj, c, name) {
var begin, end, i, l, n, s,
sep = c && c.sep ? c.sep : "&",
eq = c && c.eq ? c.eq : "=",
aK = c && c.arrayKey ? c.arrayKey : false;
if (L.isNull(obj) || L.isUndefined(obj) || L.isFunction(obj)) {
return name ? QueryString.escape(name) + eq : '';
}
if (L.isBoolean(obj) || Object.prototype.toString.call(obj) === '[object Boolean]') {
obj =+ obj;
}
if (L.isNumber(obj) || L.isString(obj)) {
return QueryString.escape(name) + eq + QueryString.escape(obj);
}
if (L.isArray(obj)) {
s = [];
name = aK ? name + '[]' : name;
l = obj.length;
for (i = 0; i < l; i++) {
s.push( QueryString.stringify(obj[i], c, name) );
}
return s.join(sep);
}
// now we know it's an object.
// Check for cyclical references in nested objects
for (i = stack.length - 1; i >= 0; --i) {
if (stack[i] === obj) {
throw new Error("QueryString.stringify. Cyclical reference");
}
}
stack.push(obj);
s = [];
begin = name ? name + '[' : '';
end = name ? ']' : '';
for (i in obj) {
if (obj.hasOwnProperty(i)) {
n = begin + i + end;
s.push(QueryString.stringify(obj[i], c, n));
}
}
stack.pop();
s = s.join(sep);
if (!s && name) {
return name + "=";
}
return s;
};
}, '3.2.0' );
| dhamma-dev/SEA | web/lib/yui/3.2.0/build/querystring/querystring-stringify.js | JavaScript | gpl-3.0 | 2,956 |
/**
* A test for ensuring that the WMS's registered in Known Layers are working as expected
*/
Ext.define('admin.tests.KnownLayerWMS', {
extend : 'admin.tests.SingleAJAXTest',
getTitle : function() {
return 'Known layer WMS availability';
},
getDescription : function() {
var baseDescription = 'This tests the backend connection to all web map services that belong to known layers. A simple GetMap and GetFeatureInfo request is with an artificial bounding box.';
baseDescription += this.callParent(arguments);
return baseDescription;
},
/**
* The entirety of our test is making a request to the controller and parsing the resposne
*/
startTest : function() {
//Init our params
var bbox = Ext.create('portal.util.BBox',{
eastBoundLongitude : 116,
westBoundLongitude : 115,
northBoundLatitude : -31,
southBoundLatitude : -32
}); //rough bounds around Perth, WA
var layerNames = [];
var serviceUrls = [];
var onlineResources = this._getKnownLayerOnlineResources('WMS');
if (onlineResources.length == 0) {
this._changeStatus(admin.tests.TestStatus.Unavailable);
return;
}
for (var i = 0; i < onlineResources.length; i++) {
layerNames.push(onlineResources[i].get('name'));
serviceUrls.push(onlineResources[i].get('url'));
}
//Run our test
this._singleAjaxTest('testWMS.diag', {
bbox : Ext.JSON.encode(bbox),
serviceUrls : serviceUrls,
layerNames : layerNames
});
}
}); | AuScope/VEGL-Portal | src/main/webapp/js/admin/tests/KnownLayerWMS.js | JavaScript | gpl-3.0 | 1,735 |
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var _this = this;
// Add a lambda to ensure global 'this' capture is triggered
(function () { return _this.window; });
// class inheritance to ensure __extends is emitted
var m;
(function (m) {
var base = /** @class */ (function () {
function base() {
}
return base;
}());
m.base = base;
var child = /** @class */ (function (_super) {
__extends(child, _super);
function child() {
return _super !== null && _super.apply(this, arguments) || this;
}
return child;
}(base));
m.child = child;
})(m || (m = {}));
| donaldpipowitch/TypeScript | tests/baselines/reference/project/prologueEmit/node/out.js | JavaScript | apache-2.0 | 1,219 |
/**
* Copyright 2012 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
DOMSnitch.Heuristics.Json = function() {
/*
this._dbg = DOMSnitch.Heuristics.LightDbg.getInstance();
document.addEventListener("Eval", this._handleEval.bind(this), true);
*/
// Workaround for eval().
// More info at http://radi.r-n-d.org/2011/02/evil-magic-of-eval.html
var collector = DOMSnitch.Heuristics.XhrCollector.getInstance();
collector.addListener(this._checkXhr.bind(this));
window.addEventListener("message", this._checkPostMsg.bind(this), true);
}
DOMSnitch.Heuristics.Json.prototype = {
_checkJsonValidity: function(recordInfo) {
if(!recordInfo.jsData) {
return;
}
var code = 0; // None
var notes = "";
var jsData = recordInfo.jsData;
var canParse = true;
var hasCode = false;
if(jsData[0] == "(" && jsData[jsData.length - 1] == ")") {
jsData = jsData.substring(1, jsData.length - 1);
}
if(this._isJson(jsData)) {
try {
JSON.parse(jsData);
} catch (e) {
canParse = false;
}
jsData = jsData.replace(/,\]/g, ",null]");
jsData = jsData.replace(/\[,/g, "[null,");
jsData = jsData.replace(/,,/g, ",null,");
jsData = jsData.replace(/,,/g, ",null,");
jsData = jsData.replace(/{([\w_]+):/g, "{\"$1\":");
jsData = jsData.replace(/,([\w_]+):/g, ",\"$1\":");
jsData = jsData.replace(/'(\w+)'/g, "\"$1\"");
try {
JSON.parse(jsData);
} catch (e) {
hasCode = true;
}
if(!canParse) {
code = 2; // Medium
notes += "Malformed JSON object.\n";
}
if(!canParse && hasCode) {
code = 2; // Medium
notes += "Found code in JSON object.\n";
}
}
if(code > 1) {
var data = "JSON object:\n" + recordInfo.jsData;
if(!!recordInfo.debugInfo) {
data += "\n\n-----\n\n";
data += "Raw stack trace:\n" + recordInfo.debugInfo;
}
var record = {
documentUrl: location.href,
type: recordInfo.type,
data: data,
callStack: [],
gid: recordInfo.globalId,
env: {},
scanInfo: {code: code, notes: notes}
};
this._report(record);
}
},
_checkPostMsg: function(event) {
var code = this._stripBreakers(event.data);
var globalId = event.origin + "#InvalidJson";
window.setTimeout(
this._checkJsonValidity.bind(
this,
{
jsData: code,
globalId: globalId,
type: "Invalid JSON"
}
),
10
);
},
_checkXhr: function(event) {
var xhr = event.xhr;
var code = this._stripBreakers(xhr.responseBody);
var globalId = xhr.requestUrl + "#InvalidJson";
window.setTimeout(
this._checkJsonValidity.bind(
this,
{
jsData: code,
globalId: globalId,
type: "Invalid JSON"
}
),
10
);
},
_handleEval: function(event) {
var elem = event.target.documentElement;
var args = JSON.parse(elem.getAttribute("evalArgs"));
var code = args[0];
var globalId = elem.getAttribute("evalGid");
var debugInfo = this._dbg.collectStackTrace();
elem.removeAttribute("evalArgs");
elem.removeAttribute("evalGid");
window.setTimeout(
this._checkJsonValidity.bind(
this,
{
jsData: code,
globalId: globalId,
type: "Invalid JSON",
debugInfo: debugInfo
}
),
10
);
},
_isJson: function(jsData) {
var seemsJson = /\{.+\}/.test(jsData);
seemsJson = seemsJson || /\[.+\]/.test(jsData);
seemsJson = seemsJson && !(/(function|while|if)[\s\w]*\(/.test(jsData));
seemsJson = seemsJson && !(/(try|else)\s*\{/.test(jsData));
return seemsJson;
},
_report: function(obj) {
chrome.extension.sendRequest({type: "log", record: obj});
},
_stripBreakers: function(jsData) {
var cIdx = jsData.indexOf("{");
var aIdx = jsData.indexOf("[");
var cfIdx = jsData.lastIndexOf("}");
var afIdx = jsData.lastIndexOf("]");
var idx = 0;
var fidx = 0;
if(cIdx > -1 && aIdx > -1) {
idx = cIdx > aIdx ? aIdx : cIdx;
} else if(cIdx > -1) {
idx = cIdx;
} else if(aIdx > -1) {
idx = aIdx;
}
return jsData.substring(idx);
}
} | wtanneb983/domsnitch | scanner/heuristics/Json.js | JavaScript | apache-2.0 | 5,031 |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is JavaScript Engine testing utilities.
*
* The Initial Developer of the Original Code is
* Mozilla Foundation.
* Portions created by the Initial Developer are Copyright (C) 2007
* the Initial Developer. All Rights Reserved.
*
* Contributor(s): Jesse Ruderman
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
//-----------------------------------------------------------------------------
var BUGNUMBER = 424311;
var summary = 'Do not assert: entry->kpc == ((PCVCAP_TAG(entry->vcap) > 1) ? (jsbytecode *) JSID_TO_ATOM(id) : cx->fp->regs->pc)';
var actual = 'No Crash';
var expect = 'No Crash';
//-----------------------------------------------------------------------------
test();
//-----------------------------------------------------------------------------
function test()
{
enterFunc ('test');
printBugNumber(BUGNUMBER);
printStatus (summary);
(function(){(function(){ constructor=({}); })()})();
reportCompare(expect, actual, summary);
exitFunc ('test');
}
| darkrsw/safe | tests/parser_tests/js/src/tests/js1_5/Regress/regress-424311.js | JavaScript | bsd-3-clause | 2,471 |
define(['exports'], function (exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var App = exports.App = function () {
function App() {
_classCallCheck(this, App);
this.firstName = 'John';
this.lastName = 'Doe';
}
App.prototype.mouseMove = function mouseMove(e) {
this.mouseX = e.clientX;
this.mouseY = e.clientY;
};
App.prototype.mouseMove200 = function mouseMove200(e) {
this.mouse200X = e.clientX;
this.mouse200Y = e.clientY;
};
App.prototype.mouseMove800 = function mouseMove800(e) {
this.mouse800X = e.clientX;
this.mouse800Y = e.clientY;
};
return App;
}();
}); | stl-florida/casestudy-riskmap | node_modules/aurelia-binding/doc/example-dist/binding-binding-behaviors/update-trigger/app.js | JavaScript | mit | 888 |
'use strict';
module.exports = function renderMenu(props) {
if (!props.menu) {
return;
}
return props.menu({
className: 'z-header-menu-column',
gridColumns: props.columns
});
}; | pombredanne/react-datagrid | lib/render/renderMenu.js | JavaScript | mit | 219 |
( function ( $ ) {
'use strict';
var asInScript2 = {
id: 'as-inscript2',
name: 'ইনস্ক্ৰিপ্ট ২',
description: 'Enhanced InScript keyboard for Assamese language',
date: '2013-02-09',
URL: 'http://github.com/wikimedia/jquery.ime',
author: 'Parag Nemade',
license: 'GPLv3',
version: '1.0',
patterns: [
[ '\\!', 'অ্যা' ],
[ '1', '১' ],
[ '2', '২' ],
[ '\\#', '্ৰ' ],
[ '3', '৩' ],
[ '\\$', 'ৰ্' ],
[ '4', '৪' ],
[ '\\%', 'জ্ঞ' ],
[ '5', '৫' ],
[ '\\^', 'ত্র' ],
[ '6', '৬' ],
[ '\\&', 'ক্ষ' ],
[ '7', '৭' ],
[ '\\*', 'শ্র' ],
[ '8', '৮' ],
[ '9', '৯' ],
[ '\\(', '(' ],
[ '\\)', ')' ],
[ '0', '০' ],
[ '\"', 'ঠ' ],
[ '\'', 'ট' ],
[ ',', ',' ],
[ '-', '-' ],
[ '\\.', '.' ],
[ '/', 'য়' ],
[ ':', 'ছ' ],
[ ';', 'চ' ],
[ '\\<', 'ষ' ],
[ '\\=', 'ৃ' ],
[ '\\+', 'ঋ' ],
[ '\\>', '।' ],
[ '\\?', 'য' ],
[ 'A', 'ও' ],
[ 'C', 'ণ' ],
[ 'D', 'অ' ],
[ 'E', 'আ' ],
[ 'F', 'ই' ],
[ 'G', 'উ' ],
[ 'H', 'ফ' ],
[ 'I', 'ঘ' ],
[ 'K', 'খ' ],
[ 'L', 'থ' ],
[ 'M', 'শ' ],
[ 'O', 'ধ' ],
[ 'P', 'ঝ' ],
[ 'Q', 'ঔ' ],
[ 'R', 'ঈ' ],
[ 'S', 'এ' ],
[ 'T', 'ঊ' ],
[ 'U', 'ঙ' ],
[ 'W', 'ঐ' ],
[ 'X', 'ঁ' ],
[ 'Y', 'ভ' ],
[ '\\{', 'ঢ' ],
[ '\\[', 'ড' ],
[ '\\}', 'ঞ' ],
[ '\\]', '়' ],
[ '\\_', 'ঃ' ],
[ 'a', 'ো' ],
[ 'b', 'ৱ' ],
[ 'c', 'ম' ],
[ 'd', '্' ],
[ 'e', 'া' ],
[ 'f', 'ি' ],
[ 'g', 'ু' ],
[ 'h', 'প' ],
[ 'i', 'গ' ],
[ 'j', 'ৰ' ],
[ 'k', 'ক' ],
[ 'l', 'ত' ],
[ 'm', 'স' ],
[ 'n', 'ল' ],
[ 'o', 'দ' ],
[ 'p', 'জ' ],
[ 'q', 'ৌ' ],
[ 'r', 'ী' ],
[ 's', 'ে' ],
[ 't', 'ূ' ],
[ 'u', 'হ' ],
[ 'v', 'ন' ],
[ 'w', 'ৈ' ],
[ 'x', 'ং' ],
[ 'y', 'ব' ],
[ 'z', 'ʼ' ]
],
patterns_x: [
[ '\\!', '৴' ],
[ '1', '\u200d' ],
[ '\\@', '৵' ],
[ '2', '\u200c' ],
[ '\\#', '৶' ],
[ '\\$', '৷' ],
[ '4', '₹' ],
[ '\\%', '৸' ],
[ '\\^', '৹' ],
[ ',', '৳' ],
[ '\\.', '॥' ],
[ '/', '্য' ],
[ '\\<', '৲' ],
[ '\\=', 'ৄ' ],
[ '\\+', 'ৠ' ],
[ '\\>', 'ঽ' ],
[ 'F', 'ঌ' ],
[ 'R', 'ৡ' ],
[ '\\{', 'ঢ়' ],
[ '\\[', 'ড়' ],
[ 'f', 'ৢ' ],
[ 'l', 'ৎ' ],
[ 'r', 'ৣ' ],
[ 'x', '৺' ]
]
};
$.ime.register( asInScript2 );
}( jQuery ) );
| BluePigeons/alltheunicode | libs/rules/as/as-inscript2.js | JavaScript | mit | 2,575 |
var config = require('../config')
var gulp = require('gulp')
var gulpSequence = require('gulp-sequence')
var getEnabledTasks = require('../lib/getEnabledTasks')
var productionTask = function(cb) {
var tasks = getEnabledTasks('production')
gulpSequence('clean', tasks.assetTasks, tasks.codeTasks, 'rev', 'static', cb)
}
gulp.task('production', productionTask)
module.exports = productionTask
| gautamgb/GBWebApp | gulpfile.js/tasks/production.js | JavaScript | mit | 411 |
/**
* @overview If this code is included on a page with wbads it will add the criteo data as global
* targeting params to all ad slots rendered on the page.
*
* Set the globals window.CRTG_* prior to including this script
* so the criteo tags are properly added.
*
* This script must be included AFTER wbads is included.
*
* @todo: consider rewriting all wbads and plugins as amd modules or at least with umd
*
* @requires window.CRTG_NID
* @requires window.CRTG_COOKIE_NAME
* @optional window.CRTG_VAR_NAME - defaults to 'crtg_content'
* @requires window.wbads
*/
/*jslint browser: true, devel: true, todo: true, regexp: true */
/*global wbads: true */
window.CRTG_NID = window.CRTG_NID || false;
window.CRTG_COOKIE_NAME = window.CRTG_COOKIE_NAME || false;
window.CRTG_VAR_NAME = window.CRTG_VAR_NAME || 'crtg_content';
(function(w, d, wbads) {
'use strict';
var ctagId = 'criteo-js',
ctag = d.getElementById(ctagId);
if (ctag) {
if (!w.CRTG_NID) {
w.CRTG_NID = ctag.getAttribute('data-nid') || false;
}
if (!w.CRTG_COOKIE_NAME) {
w.CRTG_COOKIE_NAME = ctag.getAttribute('data-cookie-name') || false;
}
}
if (!w.CRTG_NID || !w.CRTG_COOKIE_NAME || !w.CRTG_VAR_NAME) {
return;
}
if (!ctag) {
ctag = d.createElement('script');
ctag.type = 'text/javascript';
ctag.id = ctagId;
ctag.async = true;
ctag.setAttribute('class', ctagId);
ctag.setAttribute('data-nid', w.CRTG_NID);
ctag.setAttribute('data-cookie-name', w.CRTG_COOKIE_NAME);
ctag.setAttribute('data-var-name', w.CRTG_VAR_NAME);
var rnd = Math.floor(Math.random() * 99999999999);
var url = location.protocol + '//rtax.criteo.com/delivery/rta/rta.js?netId=' + encodeURIComponent(w.CRTG_NID);
url += '&cookieName=' + encodeURIComponent(w.CRTG_COOKIE_NAME);
url += '&rnd=' + rnd;
url += '&varName=' + encodeURIComponent(w.CRTG_VAR_NAME);
ctag.src = url;
d.getElementsByTagName('head')[0].appendChild(ctag);
}
/**
* Get the criteo cookie value.
*
* @param {string} cookieName
* @returns {string}
*/
function getCookie(cookieName) {
var i, x, y, cookies = document.cookie.split(';');
for (i = 0; i < cookies.length; i++) {
x = cookies[i].substr(0, cookies[i].indexOf('='));
y = cookies[i].substr(cookies[i].indexOf('=') + 1);
x = x.replace(/^\s+|\s+$/g, '');
if (x == cookieName) {
return decodeURIComponent(y);
}
}
return'';
}
wbads.defineCallback('pre.enable.services', function() {
var parts, params = getCookie(w.CRTG_COOKIE_NAME).split(';');
for (var i = 0; i < params.length; i++) {
parts = params[i].split('=');
wbads.setGlobalTargetingParam('' + parts[0], '' + parts[1]);
}
});
}(window, document, window.wbads));
| wb-crowdfusion/wb-ads | view/shared/assets/js/wb/ads/latest/criteo.js | JavaScript | apache-2.0 | 3,021 |
/* global SnippetedMessages */
Template.snippetedMessages.helpers({
hasMessages() {
return SnippetedMessages.find({ snippeted:true, rid: this.rid }, { sort: { ts: -1 } }).count() > 0;
},
messages() {
return SnippetedMessages.find({ snippeted: true, rid: this.rid }, { sort: { ts: -1 } });
},
message() {
return _.extend(this, { customClass: 'snippeted' });
},
hasMore() {
return Template.instance().hasMore.get();
}
});
Template.snippetedMessages.onCreated(function() {
this.hasMore = new ReactiveVar(true);
this.limit = new ReactiveVar(50);
const self = this;
this.autorun(function() {
const data = Template.currentData();
self.subscribe('snippetedMessages', data.rid, self.limit.get(), function() {
if (SnippetedMessages.find({ snippeted: true, rid: data.rid }).count() < self.limit.get()) {
return self.hasMore.set(false);
}
});
});
});
| tntobias/Rocket.Chat | packages/rocketchat-message-snippet/client/tabBar/views/snippetedMessages.js | JavaScript | mit | 878 |
'use strict';
var origSymbol = typeof Symbol !== 'undefined' && Symbol;
var hasSymbolSham = require('./shams');
module.exports = function hasNativeSymbols() {
if (typeof origSymbol !== 'function') { return false; }
if (typeof Symbol !== 'function') { return false; }
if (typeof origSymbol('foo') !== 'symbol') { return false; }
if (typeof Symbol('bar') !== 'symbol') { return false; }
return hasSymbolSham();
};
| matryer/bitbar | xbarapp.com/node_modules/has-symbols/index.js | JavaScript | mit | 420 |
function runTest(config,qualifier) {
var testname = testnamePrefix( qualifier, config.keysystem ) + ', basic events';
var configuration = getSimpleConfigurationForContent( config.content );
if ( config.initDataType && config.initData ) configuration.initDataTypes = [ config.initDataType ]
async_test(function(test)
{
var initDataType;
var initData;
var mediaKeySession;
function processMessage(event)
{
assert_true(event instanceof window.MediaKeyMessageEvent);
assert_equals(event.target, mediaKeySession);
assert_equals(event.type, 'message');
assert_any( assert_equals,
event.messageType,
[ 'license-request', 'individualization-request' ] );
config.messagehandler( event.messageType, event.message ).then( function( response ) {
waitForEventAndRunStep('keystatuseschange', mediaKeySession, test.step_func(processKeyStatusesChange), test);
mediaKeySession.update( response ).catch(function(error) {
forceTestFailureFromPromise(test, error);
});
});
}
function processKeyStatusesChange(event)
{
assert_true(event instanceof Event);
assert_equals(event.target, mediaKeySession);
assert_equals(event.type, 'keystatuseschange');
test.done();
}
navigator.requestMediaKeySystemAccess( config.keysystem, [ configuration ] ).then(function(access) {
initDataType = access.getConfiguration().initDataTypes[0];
if ( config.initDataType && config.initData ) {
initData = config.initData;
} else {
initData = getInitData(config.content, initDataType);
}
return access.createMediaKeys();
}).then(test.step_func(function(mediaKeys) {
mediaKeySession = mediaKeys.createSession();
waitForEventAndRunStep('message', mediaKeySession, test.step_func(processMessage), test);
return mediaKeySession.generateRequest(initDataType, initData);
})).catch(test.step_func(function(error) {
forceTestFailureFromPromise(test, error);
}));
}, testname );
}
| bbansalWolfPack/servo | tests/wpt/web-platform-tests/encrypted-media/scripts/events.js | JavaScript | mpl-2.0 | 2,344 |
module.exports = {
initialize: function (success, fail, args, env) {
GeofenceComponent.GeofenceTrigger.register();
success && success();
},
addOrUpdate: function (success, fail, args, env) {
args.forEach(function (geo) {
var geoN = new GeofenceComponent.GeoNotification();
geoN.id = geo.id;
geoN.latitude = geo.latitude;
geoN.longitude = geo.longitude;
geoN.transitionType = geo.transitionType;
geoN.radius = geo.radius;
geoN.notificationText = geo.notification.text;
geoN.notificationTitle = geo.notification.title;
geoN.openAppOnClick = geo.notification.openAppOnClick;
geoN.data = JSON.stringify(geo.notification.data);
GeofenceComponent.GeoNotificationManager.addOrUpdate(geoN);
});
success && success();
},
remove: function (success, fail, args, env) {
args.forEach(function (geoId) {
GeofenceComponent.GeoNotificationManager.remove(geoId);
});
success && success();
},
removeAll: function (success, fail, args, env) {
GeofenceComponent.GeoNotificationManager.removeAll();
success && success();
}
};
require("cordova/exec/proxy").add("GeofencePlugin", module.exports);
| johnrobertcobbold/cordova-plugin-geofence | src/windows/GeofenceProxy.js | JavaScript | apache-2.0 | 1,337 |
// # Update Checking Service
//
// Makes a request to Ghost.org to check if there is a new version of Ghost available.
// The service is provided in return for users opting in to anonymous usage data collection.
//
// Blog owners can opt-out of update checks by setting `privacy: { useUpdateCheck: false }` in their config.js
//
// The data collected is as follows:
//
// - blog id - a hash of the blog hostname, pathname and dbHash. No identifiable info is stored.
// - ghost version
// - node version
// - npm version
// - env - production or development
// - database type - SQLite, MySQL, PostgreSQL
// - email transport - mail.options.service, or otherwise mail.transport
// - created date - database creation date
// - post count - total number of posts
// - user count - total number of users
// - theme - name of the currently active theme
// - apps - names of any active apps
var crypto = require('crypto'),
exec = require('child_process').exec,
https = require('http'),
moment = require('moment'),
semver = require('semver'),
Promise = require('bluebird'),
_ = require('lodash'),
url = require('url'),
api = require('./api'),
config = require('./config'),
errors = require('./errors'),
internal = {context: {internal: true}},
allowedCheckEnvironments = ['development', 'production'],
checkEndpoint = 'updates.ghostchina.com',
currentVersion = config.ghostVersion;
function updateCheckError(error) {
api.settings.edit(
{settings: [{key: 'nextUpdateCheck', value: Math.round(Date.now() / 1000 + 24 * 3600)}]},
internal
).catch(errors.rejectError);
errors.logError(
error,
'Checking for updates failed, your blog will continue to function.',
'If you get this error repeatedly, please seek help from https://ghost.org/forum.'
);
}
function updateCheckData() {
var data = {},
ops = [],
mailConfig = config.mail;
ops.push(api.settings.read(_.extend({key: 'dbHash'}, internal)).catch(errors.rejectError));
ops.push(api.settings.read(_.extend({key: 'activeTheme'}, internal)).catch(errors.rejectError));
ops.push(api.settings.read(_.extend({key: 'activeApps'}, internal))
.then(function (response) {
var apps = response.settings[0];
try {
apps = JSON.parse(apps.value);
} catch (e) {
return errors.rejectError(e);
}
return _.reduce(apps, function (memo, item) { return memo === '' ? memo + item : memo + ', ' + item; }, '');
}).catch(errors.rejectError));
ops.push(api.posts.browse().catch(errors.rejectError));
ops.push(api.users.browse(internal).catch(errors.rejectError));
ops.push(Promise.promisify(exec)('npm -v').catch(errors.rejectError));
data.ghost_version = currentVersion;
data.node_version = process.versions.node;
data.env = process.env.NODE_ENV;
data.database_type = config.database.client;
data.email_transport = mailConfig && (mailConfig.options && mailConfig.options.service ? mailConfig.options.service : mailConfig.transport);
return Promise.settle(ops).then(function (descriptors) {
var hash = descriptors[0].value().settings[0],
theme = descriptors[1].value().settings[0],
apps = descriptors[2].value(),
posts = descriptors[3].value(),
users = descriptors[4].value(),
npm = descriptors[5].value(),
blogUrl = url.parse(config.url),
blogId = blogUrl.hostname + blogUrl.pathname.replace(/\//, '') + hash.value;
data.blog_id = crypto.createHash('md5').update(blogId).digest('hex');
data.theme = theme ? theme.value : '';
data.apps = apps || '';
data.post_count = posts && posts.meta && posts.meta.pagination ? posts.meta.pagination.total : 0;
data.user_count = users && users.users && users.users.length ? users.users.length : 0;
data.blog_created_at = users && users.users && users.users[0] && users.users[0].created_at ? moment(users.users[0].created_at).unix() : '';
data.npm_version = _.isArray(npm) && npm[0] ? npm[0].toString().replace(/\n/, '') : '';
data.storage = (config.storage && config.storage.provider) || 'local-file-store';
data.blog_url = config.url;
return data;
}).catch(updateCheckError);
}
function updateCheckRequest() {
return updateCheckData().then(function then(reqData) {
var resData = '',
headers,
req;
reqData = JSON.stringify(reqData);
headers = {
'Content-Length': reqData.length
};
return new Promise(function p(resolve, reject) {
req = https.request({
hostname: checkEndpoint,
method: 'POST',
headers: headers
}, function handler(res) {
res.on('error', function onError(error) { reject(error); });
res.on('data', function onData(chunk) { resData += chunk; });
res.on('end', function onEnd() {
try {
resData = JSON.parse(resData);
resolve(resData);
} catch (e) {
reject('Unable to decode update response');
}
});
});
req.on('socket', function onSocket(socket) {
// Wait a maximum of 10seconds
socket.setTimeout(10000);
socket.on('timeout', function onTimeout() {
req.abort();
});
});
req.on('error', function onError(error) {
reject(error);
});
req.write(reqData);
req.end();
});
});
}
// ## Update Check Response
// Handles the response from the update check
// Does two things with the information received:
// 1. Updates the time we can next make a check
// 2. Checks if the version in the response is new, and updates the notification setting
function updateCheckResponse(response) {
var ops = [];
ops.push(
api.settings.edit(
{settings: [{key: 'nextUpdateCheck', value: response.next_check}]},
internal
).catch(errors.rejectError),
api.settings.edit(
{settings: [{key: 'displayUpdateNotification', value: response.version}]},
internal
).catch(errors.rejectError)
);
return Promise.settle(ops).then(function then(descriptors) {
descriptors.forEach(function forEach(d) {
if (d.isRejected()) {
errors.rejectError(d.reason());
}
});
});
}
function updateCheck() {
// The check will not happen if:
// 1. updateCheck is defined as false in config.js
// 2. we've already done a check this session
// 3. we're not in production or development mode
// TODO: need to remove config.updateCheck in favor of config.privacy.updateCheck in future version (it is now deprecated)
if (config.updateCheck === false || config.isPrivacyDisabled('useUpdateCheck') || _.indexOf(allowedCheckEnvironments, process.env.NODE_ENV) === -1) {
// No update check
return Promise.resolve();
} else {
return api.settings.read(_.extend({key: 'nextUpdateCheck'}, internal)).then(function then(result) {
var nextUpdateCheck = result.settings[0];
if (nextUpdateCheck && nextUpdateCheck.value && nextUpdateCheck.value > moment().unix()) {
// It's not time to check yet
return;
} else {
// We need to do a check
return updateCheckRequest()
.then(updateCheckResponse)
.catch(updateCheckError);
}
}).catch(updateCheckError);
}
}
function showUpdateNotification() {
return api.settings.read(_.extend({key: 'displayUpdateNotification'}, internal)).then(function then(response) {
var display = response.settings[0];
// Version 0.4 used boolean to indicate the need for an update. This special case is
// translated to the version string.
// TODO: remove in future version.
if (display.value === 'false' || display.value === 'true' || display.value === '1' || display.value === '0') {
display.value = '0.4.0';
}
if (display && display.value && currentVersion && semver.gt(display.value, currentVersion)) {
return display.value;
}
return false;
});
}
module.exports = updateCheck;
module.exports.showUpdateNotification = showUpdateNotification;
| moehub/openshift-ghost-quickstart | node_modules/ghost/core/server/update-check.js | JavaScript | mit | 8,968 |
/**
* @author mrdoob / http://mrdoob.com/
*/
var EventDispatcher=function(){};Object.assign(EventDispatcher.prototype,{addEventListener:function(i,t){void 0===this._listeners&&(this._listeners={});var e=this._listeners;void 0===e[i]&&(e[i]=[]),-1===e[i].indexOf(t)&&e[i].push(t)},hasEventListener:function(i,t){if(void 0===this._listeners)return!1;var e=this._listeners;return void 0!==e[i]&&-1!==e[i].indexOf(t)},removeEventListener:function(i,t){if(void 0!==this._listeners){var e=this._listeners[i];if(void 0!==e){var s=e.indexOf(t);-1!==s&&e.splice(s,1)}}},dispatchEvent:function(i){if(void 0!==this._listeners){var t=this._listeners[i.type];if(void 0!==t){i.target=this;var e=[],s=0,n=t.length;for(s=0;s<n;s++)e[s]=t[s];for(s=0;s<n;s++)e[s].call(this,i)}}}}); | cvazquezlos/LOGANALYZER | testloganalyzer-gui/documentation/js/libs/EventDispatcher.js | JavaScript | apache-2.0 | 767 |
/**
* lodash 3.0.3 (Custom Build) <https://lodash.com/>
* Build: `lodash modularize exports="npm" -o ./`
* Copyright 2012-2016 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
/** `Object#toString` result references. */
var boolTag = '[object Boolean]';
/** Used for built-in method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
* of values.
*/
var objectToString = objectProto.toString;
/**
* Checks if `value` is classified as a boolean primitive or object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isBoolean(false);
* // => true
*
* _.isBoolean(null);
* // => false
*/
function isBoolean(value) {
return value === true || value === false ||
(isObjectLike(value) && objectToString.call(value) == boolTag);
}
/**
* Checks if `value` is object-like. A value is object-like if it's not `null`
* and has a `typeof` result of "object".
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
* @example
*
* _.isObjectLike({});
* // => true
*
* _.isObjectLike([1, 2, 3]);
* // => true
*
* _.isObjectLike(_.noop);
* // => false
*
* _.isObjectLike(null);
* // => false
*/
function isObjectLike(value) {
return !!value && typeof value == 'object';
}
module.exports = isBoolean;
| mason-smith/netboox | server/node_modules/lodash.isboolean/index.js | JavaScript | mit | 1,819 |
/*
* Foundation Responsive Library
* http://foundation.zurb.com
* Copyright 2015, ZURB
* Free to use under the MIT license.
* http://www.opensource.org/licenses/mit-license.php
*/
(function ($, window, document, undefined) {
'use strict';
var header_helpers = function (class_array) {
var head = $('head');
head.prepend($.map(class_array, function (class_name) {
if (head.has('.' + class_name).length === 0) {
return '<meta class="' + class_name + '" />';
}
}));
};
header_helpers([
'foundation-mq-small',
'foundation-mq-small-only',
'foundation-mq-medium',
'foundation-mq-medium-only',
'foundation-mq-large',
'foundation-mq-large-only',
'foundation-mq-xlarge',
'foundation-mq-xlarge-only',
'foundation-mq-xxlarge',
'foundation-data-attribute-namespace']);
// Enable FastClick if present
$(function () {
if (typeof FastClick !== 'undefined') {
// Don't attach to body if undefined
if (typeof document.body !== 'undefined') {
FastClick.attach(document.body);
}
}
});
// private Fast Selector wrapper,
// returns jQuery object. Only use where
// getElementById is not available.
var S = function (selector, context) {
if (typeof selector === 'string') {
if (context) {
var cont;
if (context.jquery) {
cont = context[0];
if (!cont) {
return context;
}
} else {
cont = context;
}
return $(cont.querySelectorAll(selector));
}
return $(document.querySelectorAll(selector));
}
return $(selector, context);
};
// Namespace functions.
var attr_name = function (init) {
var arr = [];
if (!init) {
arr.push('data');
}
if (this.namespace.length > 0) {
arr.push(this.namespace);
}
arr.push(this.name);
return arr.join('-');
};
var add_namespace = function (str) {
var parts = str.split('-'),
i = parts.length,
arr = [];
while (i--) {
if (i !== 0) {
arr.push(parts[i]);
} else {
if (this.namespace.length > 0) {
arr.push(this.namespace, parts[i]);
} else {
arr.push(parts[i]);
}
}
}
return arr.reverse().join('-');
};
// Event binding and data-options updating.
var bindings = function (method, options) {
var self = this,
bind = function(){
var $this = S(this),
should_bind_events = !S(self).data(self.attr_name(true) + '-init');
$this.data(self.attr_name(true) + '-init', $.extend({}, self.settings, (options || method), self.data_options($this)));
if (should_bind_events) {
self.events(this);
}
};
if (S(this.scope).is('[' + this.attr_name() +']')) {
bind.call(this.scope);
} else {
S('[' + this.attr_name() +']', this.scope).each(bind);
}
// # Patch to fix #5043 to move this *after* the if/else clause in order for Backbone and similar frameworks to have improved control over event binding and data-options updating.
if (typeof method === 'string') {
return this[method].call(this, options);
}
};
var single_image_loaded = function (image, callback) {
function loaded () {
callback(image[0]);
}
function bindLoad () {
this.one('load', loaded);
if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) {
var src = this.attr( 'src' ),
param = src.match( /\?/ ) ? '&' : '?';
param += 'random=' + (new Date()).getTime();
this.attr('src', src + param);
}
}
if (!image.attr('src')) {
loaded();
return;
}
if (image[0].complete || image[0].readyState === 4) {
loaded();
} else {
bindLoad.call(image);
}
};
/*! matchMedia() polyfill - Test a CSS media type/query in JS. Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas, David Knight. Dual MIT/BSD license */
window.matchMedia || (window.matchMedia = function() {
"use strict";
// For browsers that support matchMedium api such as IE 9 and webkit
var styleMedia = (window.styleMedia || window.media);
// For those that don't support matchMedium
if (!styleMedia) {
var style = document.createElement('style'),
script = document.getElementsByTagName('script')[0],
info = null;
style.type = 'text/css';
style.id = 'matchmediajs-test';
script.parentNode.insertBefore(style, script);
// 'style.currentStyle' is used by IE <= 8 and 'window.getComputedStyle' for all other browsers
info = ('getComputedStyle' in window) && window.getComputedStyle(style, null) || style.currentStyle;
styleMedia = {
matchMedium: function(media) {
var text = '@media ' + media + '{ #matchmediajs-test { width: 1px; } }';
// 'style.styleSheet' is used by IE <= 8 and 'style.textContent' for all other browsers
if (style.styleSheet) {
style.styleSheet.cssText = text;
} else {
style.textContent = text;
}
// Test if media query is true or false
return info.width === '1px';
}
};
}
return function(media) {
return {
matches: styleMedia.matchMedium(media || 'all'),
media: media || 'all'
};
};
}());
/*
* jquery.requestAnimationFrame
* https://github.com/gnarf37/jquery-requestAnimationFrame
* Requires jQuery 1.8+
*
* Copyright (c) 2012 Corey Frang
* Licensed under the MIT license.
*/
(function(jQuery) {
// requestAnimationFrame polyfill adapted from Erik Möller
// fixes from Paul Irish and Tino Zijdel
// http://paulirish.com/2011/requestanimationframe-for-smart-animating/
// http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
var animating,
lastTime = 0,
vendors = ['webkit', 'moz'],
requestAnimationFrame = window.requestAnimationFrame,
cancelAnimationFrame = window.cancelAnimationFrame,
jqueryFxAvailable = 'undefined' !== typeof jQuery.fx;
for (; lastTime < vendors.length && !requestAnimationFrame; lastTime++) {
requestAnimationFrame = window[ vendors[lastTime] + 'RequestAnimationFrame' ];
cancelAnimationFrame = cancelAnimationFrame ||
window[ vendors[lastTime] + 'CancelAnimationFrame' ] ||
window[ vendors[lastTime] + 'CancelRequestAnimationFrame' ];
}
function raf() {
if (animating) {
requestAnimationFrame(raf);
if (jqueryFxAvailable) {
jQuery.fx.tick();
}
}
}
if (requestAnimationFrame) {
// use rAF
window.requestAnimationFrame = requestAnimationFrame;
window.cancelAnimationFrame = cancelAnimationFrame;
if (jqueryFxAvailable) {
jQuery.fx.timer = function (timer) {
if (timer() && jQuery.timers.push(timer) && !animating) {
animating = true;
raf();
}
};
jQuery.fx.stop = function () {
animating = false;
};
}
} else {
// polyfill
window.requestAnimationFrame = function (callback) {
var currTime = new Date().getTime(),
timeToCall = Math.max(0, 16 - (currTime - lastTime)),
id = window.setTimeout(function () {
callback(currTime + timeToCall);
}, timeToCall);
lastTime = currTime + timeToCall;
return id;
};
window.cancelAnimationFrame = function (id) {
clearTimeout(id);
};
}
}( $ ));
function removeQuotes (string) {
if (typeof string === 'string' || string instanceof String) {
string = string.replace(/^['\\/"]+|(;\s?})+|['\\/"]+$/g, '');
}
return string;
}
function MediaQuery(selector) {
this.selector = selector;
this.query = '';
}
MediaQuery.prototype.toString = function () {
return this.query || (this.query = S(this.selector).css('font-family').replace(/^[\/\\'"]+|(;\s?})+|[\/\\'"]+$/g, ''));
};
window.Foundation = {
name : 'Foundation',
version : '{{VERSION}}',
media_queries : {
'small' : new MediaQuery('.foundation-mq-small'),
'small-only' : new MediaQuery('.foundation-mq-small-only'),
'medium' : new MediaQuery('.foundation-mq-medium'),
'medium-only' : new MediaQuery('.foundation-mq-medium-only'),
'large' : new MediaQuery('.foundation-mq-large'),
'large-only' : new MediaQuery('.foundation-mq-large-only'),
'xlarge' : new MediaQuery('.foundation-mq-xlarge'),
'xlarge-only' : new MediaQuery('.foundation-mq-xlarge-only'),
'xxlarge' : new MediaQuery('.foundation-mq-xxlarge')
},
stylesheet : $('<style></style>').appendTo('head')[0].sheet,
global : {
namespace : undefined
},
init : function (scope, libraries, method, options, response) {
var args = [scope, method, options, response],
responses = [];
// check RTL
this.rtl = /rtl/i.test(S('html').attr('dir'));
// set foundation global scope
this.scope = scope || this.scope;
this.set_namespace();
if (libraries && typeof libraries === 'string' && !/reflow/i.test(libraries)) {
if (this.libs.hasOwnProperty(libraries)) {
responses.push(this.init_lib(libraries, args));
}
} else {
for (var lib in this.libs) {
responses.push(this.init_lib(lib, libraries));
}
}
S(window).on('load', function () {
S(window)
.trigger('resize.fndtn.clearing')
.trigger('resize.fndtn.dropdown')
.trigger('resize.fndtn.equalizer')
.trigger('resize.fndtn.interchange')
.trigger('resize.fndtn.joyride')
.trigger('resize.fndtn.magellan')
.trigger('resize.fndtn.topbar')
.trigger('resize.fndtn.slider');
});
return scope;
},
init_lib : function (lib, args) {
if (this.libs.hasOwnProperty(lib)) {
this.patch(this.libs[lib]);
if (args && args.hasOwnProperty(lib)) {
if (typeof this.libs[lib].settings !== 'undefined') {
$.extend(true, this.libs[lib].settings, args[lib]);
} else if (typeof this.libs[lib].defaults !== 'undefined') {
$.extend(true, this.libs[lib].defaults, args[lib]);
}
return this.libs[lib].init.apply(this.libs[lib], [this.scope, args[lib]]);
}
args = args instanceof Array ? args : new Array(args);
return this.libs[lib].init.apply(this.libs[lib], args);
}
return function () {};
},
patch : function (lib) {
lib.scope = this.scope;
lib.namespace = this.global.namespace;
lib.rtl = this.rtl;
lib['data_options'] = this.utils.data_options;
lib['attr_name'] = attr_name;
lib['add_namespace'] = add_namespace;
lib['bindings'] = bindings;
lib['S'] = this.utils.S;
},
inherit : function (scope, methods) {
var methods_arr = methods.split(' '),
i = methods_arr.length;
while (i--) {
if (this.utils.hasOwnProperty(methods_arr[i])) {
scope[methods_arr[i]] = this.utils[methods_arr[i]];
}
}
},
set_namespace : function () {
// Description:
// Don't bother reading the namespace out of the meta tag
// if the namespace has been set globally in javascript
//
// Example:
// Foundation.global.namespace = 'my-namespace';
// or make it an empty string:
// Foundation.global.namespace = '';
//
//
// If the namespace has not been set (is undefined), try to read it out of the meta element.
// Otherwise use the globally defined namespace, even if it's empty ('')
var namespace = ( this.global.namespace === undefined ) ? $('.foundation-data-attribute-namespace').css('font-family') : this.global.namespace;
// Finally, if the namsepace is either undefined or false, set it to an empty string.
// Otherwise use the namespace value.
this.global.namespace = ( namespace === undefined || /false/i.test(namespace) ) ? '' : namespace;
},
libs : {},
// methods that can be inherited in libraries
utils : {
// Description:
// Fast Selector wrapper returns jQuery object. Only use where getElementById
// is not available.
//
// Arguments:
// Selector (String): CSS selector describing the element(s) to be
// returned as a jQuery object.
//
// Scope (String): CSS selector describing the area to be searched. Default
// is document.
//
// Returns:
// Element (jQuery Object): jQuery object containing elements matching the
// selector within the scope.
S : S,
// Description:
// Executes a function a max of once every n milliseconds
//
// Arguments:
// Func (Function): Function to be throttled.
//
// Delay (Integer): Function execution threshold in milliseconds.
//
// Returns:
// Lazy_function (Function): Function with throttling applied.
throttle : function (func, delay) {
var timer = null;
return function () {
var context = this, args = arguments;
if (timer == null) {
timer = setTimeout(function () {
func.apply(context, args);
timer = null;
}, delay);
}
};
},
// Description:
// Executes a function when it stops being invoked for n seconds
// Modified version of _.debounce() http://underscorejs.org
//
// Arguments:
// Func (Function): Function to be debounced.
//
// Delay (Integer): Function execution threshold in milliseconds.
//
// Immediate (Bool): Whether the function should be called at the beginning
// of the delay instead of the end. Default is false.
//
// Returns:
// Lazy_function (Function): Function with debouncing applied.
debounce : function (func, delay, immediate) {
var timeout, result;
return function () {
var context = this, args = arguments;
var later = function () {
timeout = null;
if (!immediate) {
result = func.apply(context, args);
}
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, delay);
if (callNow) {
result = func.apply(context, args);
}
return result;
};
},
// Description:
// Parses data-options attribute
//
// Arguments:
// El (jQuery Object): Element to be parsed.
//
// Returns:
// Options (Javascript Object): Contents of the element's data-options
// attribute.
data_options : function (el, data_attr_name) {
data_attr_name = data_attr_name || 'options';
var opts = {}, ii, p, opts_arr,
data_options = function (el) {
var namespace = Foundation.global.namespace;
if (namespace.length > 0) {
return el.data(namespace + '-' + data_attr_name);
}
return el.data(data_attr_name);
};
var cached_options = data_options(el);
if (typeof cached_options === 'object') {
return cached_options;
}
opts_arr = (cached_options || ':').split(';');
ii = opts_arr.length;
function isNumber (o) {
return !isNaN (o - 0) && o !== null && o !== '' && o !== false && o !== true;
}
function trim (str) {
if (typeof str === 'string') {
return $.trim(str);
}
return str;
}
while (ii--) {
p = opts_arr[ii].split(':');
p = [p[0], p.slice(1).join(':')];
if (/true/i.test(p[1])) {
p[1] = true;
}
if (/false/i.test(p[1])) {
p[1] = false;
}
if (isNumber(p[1])) {
if (p[1].indexOf('.') === -1) {
p[1] = parseInt(p[1], 10);
} else {
p[1] = parseFloat(p[1]);
}
}
if (p.length === 2 && p[0].length > 0) {
opts[trim(p[0])] = trim(p[1]);
}
}
return opts;
},
// Description:
// Adds JS-recognizable media queries
//
// Arguments:
// Media (String): Key string for the media query to be stored as in
// Foundation.media_queries
//
// Class (String): Class name for the generated <meta> tag
register_media : function (media, media_class) {
if (Foundation.media_queries[media] === undefined) {
$('head').append('<meta class="' + media_class + '"/>');
Foundation.media_queries[media] = removeQuotes($('.' + media_class).css('font-family'));
}
},
// Description:
// Add custom CSS within a JS-defined media query
//
// Arguments:
// Rule (String): CSS rule to be appended to the document.
//
// Media (String): Optional media query string for the CSS rule to be
// nested under.
add_custom_rule : function (rule, media) {
if (media === undefined && Foundation.stylesheet) {
Foundation.stylesheet.insertRule(rule, Foundation.stylesheet.cssRules.length);
} else {
var query = Foundation.media_queries[media];
if (query !== undefined) {
Foundation.stylesheet.insertRule('@media ' +
Foundation.media_queries[media] + '{ ' + rule + ' }', Foundation.stylesheet.cssRules.length);
}
}
},
// Description:
// Performs a callback function when an image is fully loaded
//
// Arguments:
// Image (jQuery Object): Image(s) to check if loaded.
//
// Callback (Function): Function to execute when image is fully loaded.
image_loaded : function (images, callback) {
var self = this,
unloaded = images.length;
function pictures_has_height(images) {
var pictures_number = images.length;
for (var i = pictures_number - 1; i >= 0; i--) {
if(images.attr('height') === undefined) {
return false;
};
};
return true;
}
if (unloaded === 0 || pictures_has_height(images)) {
callback(images);
}
images.each(function () {
single_image_loaded(self.S(this), function () {
unloaded -= 1;
if (unloaded === 0) {
callback(images);
}
});
});
},
// Description:
// Returns a random, alphanumeric string
//
// Arguments:
// Length (Integer): Length of string to be generated. Defaults to random
// integer.
//
// Returns:
// Rand (String): Pseudo-random, alphanumeric string.
random_str : function () {
if (!this.fidx) {
this.fidx = 0;
}
this.prefix = this.prefix || [(this.name || 'F'), (+new Date).toString(36)].join('-');
return this.prefix + (this.fidx++).toString(36);
},
// Description:
// Helper for window.matchMedia
//
// Arguments:
// mq (String): Media query
//
// Returns:
// (Boolean): Whether the media query passes or not
match : function (mq) {
return window.matchMedia(mq).matches;
},
// Description:
// Helpers for checking Foundation default media queries with JS
//
// Returns:
// (Boolean): Whether the media query passes or not
is_small_up : function () {
return this.match(Foundation.media_queries.small);
},
is_medium_up : function () {
return this.match(Foundation.media_queries.medium);
},
is_large_up : function () {
return this.match(Foundation.media_queries.large);
},
is_xlarge_up : function () {
return this.match(Foundation.media_queries.xlarge);
},
is_xxlarge_up : function () {
return this.match(Foundation.media_queries.xxlarge);
},
is_small_only : function () {
return !this.is_medium_up() && !this.is_large_up() && !this.is_xlarge_up() && !this.is_xxlarge_up();
},
is_medium_only : function () {
return this.is_medium_up() && !this.is_large_up() && !this.is_xlarge_up() && !this.is_xxlarge_up();
},
is_large_only : function () {
return this.is_medium_up() && this.is_large_up() && !this.is_xlarge_up() && !this.is_xxlarge_up();
},
is_xlarge_only : function () {
return this.is_medium_up() && this.is_large_up() && this.is_xlarge_up() && !this.is_xxlarge_up();
},
is_xxlarge_only : function () {
return this.is_medium_up() && this.is_large_up() && this.is_xlarge_up() && this.is_xxlarge_up();
}
}
};
$.fn.foundation = function () {
var args = Array.prototype.slice.call(arguments, 0);
return this.each(function () {
Foundation.init.apply(Foundation, [this].concat(args));
return this;
});
};
}(jQuery, window, window.document));
| flavour/eden | static/scripts/foundation/foundation/foundation.js | JavaScript | mit | 21,868 |
/*
Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'newpage', 'da', {
toolbar: 'Ny side'
} );
| aodarc/flowers_room | styleguides/static/ckeditor/ckeditor/plugins/newpage/lang/da.js | JavaScript | mit | 216 |
export * from './calendar';
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoicHVibGljX2FwaS5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9hcHAvY29tcG9uZW50cy9jYWxlbmRhci9wdWJsaWNfYXBpLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBLGNBQWMsWUFBWSxDQUFDIiwic291cmNlc0NvbnRlbnQiOlsiZXhwb3J0ICogZnJvbSAnLi9jYWxlbmRhcic7Il19 | cdnjs/cdnjs | ajax/libs/primeng/12.2.3/esm2015/calendar/public_api.js | JavaScript | mit | 358 |
describe("setPathValues", function() {
require("./primitive.spec");
require("./atom.spec");
require("./expired.spec");
require("./branch.spec");
}); | darioajr/falcor | test/set/pathValues/index.js | JavaScript | apache-2.0 | 164 |
exports.BattleAbilities = {
"cutecharm": {
inherit: true,
onAfterDamage: function(damage, target, source, move) {
if (move && move.isContact) {
if (this.random(3) < 1) {
source.addVolatile('attract', target);
}
}
}
},
"effectspore": {
inherit: true,
onAfterDamage: function(damage, target, source, move) {
if (move && move.isContact && !source.status) {
var r = this.random(300);
if (r < 10) source.setStatus('slp');
else if (r < 20) source.setStatus('par');
else if (r < 30) source.setStatus('psn');
}
}
},
"flamebody": {
inherit: true,
onAfterDamage: function(damage, target, source, move) {
if (move && move.isContact) {
if (this.random(3) < 1) {
source.trySetStatus('brn', target, move);
}
}
}
},
"flashfire": {
inherit: true,
onTryHit: function(target, source, move) {
if (target !== source && move.type === 'Fire') {
if (move.id === 'willowisp' && (target.hasType('Fire') || target.status || target.volatiles['substitute'])) {
return;
}
if (!target.addVolatile('flashfire')) {
this.add('-immune', target, '[msg]');
}
return null;
}
}
},
"lightningrod": {
desc: "During double battles, this Pokemon draws any single-target Electric-type attack to itself. If an opponent uses an Electric-type attack that affects multiple Pokemon, those targets will be hit. This ability does not affect Electric Hidden Power or Judgment. The user is immune to Electric and its Special Attack is increased one stage when hit by one.",
shortDesc: "This Pokemon draws opposing Electric moves to itself.",
onFoeRedirectTargetPriority: 1,
onFoeRedirectTarget: function(target, source, source2, move) {
if (move.type !== 'Electric') return;
if (this.validTarget(this.effectData.target, source, move.target)) {
return this.effectData.target;
}
},
id: "lightningrod",
name: "Lightningrod",
rating: 3.5,
num: 32
},
"pickup": {
inherit: true,
onResidualOrder: null,
onResidualSubOrder: null,
onResidual: null
},
"poisonpoint": {
inherit: true,
onAfterDamage: function(damage, target, source, move) {
if (move && move.isContact) {
if (this.random(3) < 1) {
source.trySetStatus('psn', target, move);
}
}
}
},
"pressure": {
inherit: true,
onStart: null
},
"rockhead": {
inherit: true,
onModifyMove: function(move) {
if (move.id !== 'struggle') delete move.recoil;
}
},
"roughskin": {
inherit: true,
onAfterDamage: function(damage, target, source, move) {
if (source && source !== target && move && move.isContact) {
this.damage(source.maxhp/16, source, target);
}
}
},
"shadowtag": {
inherit: true,
onFoeModifyPokemon: function(pokemon) {
pokemon.trapped = true;
}
},
"static": {
inherit: true,
onAfterDamage: function(damage, target, source, effect) {
if (effect && effect.isContact) {
if (this.random(3) < 1) {
source.trySetStatus('par', target, effect);
}
}
}
},
"stench": {
inherit: true,
onModifyMove: function(){}
},
"sturdy": {
inherit: true,
onDamage: function(damage, target, source, effect) {
if (effect && effect.ohko) {
this.add('-activate',target,'Sturdy');
return 0;
}
}
},
"synchronize": {
inherit: true,
onAfterSetStatus: function(status, target, source) {
if (!source || source === target) return;
var status = status.id;
if (status === 'slp' || status === 'frz') return;
if (status === 'tox') status = 'psn';
source.trySetStatus(status);
}
},
"trace": {
inherit: true,
onUpdate: function(pokemon) {
var target = pokemon.side.foe.randomActive();
if (!target || target.fainted) return;
var ability = this.getAbility(target.ability);
var bannedAbilities = {forecast:1, multitype:1, trace:1};
if (bannedAbilities[target.ability]) {
return;
}
if (ability === 'Intimidate')
{
if (pokemon.setAbility('Illuminate')) { //Temporary fix so Intimidate doesn't activate in third gen when traced
this.add('-ability',pokemon, ability,'[from] ability: Trace','[of] '+target);
}
}
else if (pokemon.setAbility(ability)) {
this.add('-ability',pokemon, ability,'[from] ability: Trace','[of] '+target);
}
}
},
"voltabsorb": {
inherit: true,
onTryHit: function(target, source, move) {
if (target !== source && move.type === 'Electric' && move.id !== 'thunderwave') {
if (!this.heal(target.maxhp/4)) {
this.add('-immune', target, '[msg]');
}
return null;
}
}
}
};
| damokles/Pokemon-Showdown-master-1 | mods/gen3/abilities.js | JavaScript | mit | 4,550 |
define([
"dojo/_base/declare", // declare
"dojo/Deferred",
"dojo/_base/kernel", // kernel.deprecated
"dojo/_base/lang", // lang.mixin
"dojo/store/util/QueryResults",
"./_AutoCompleterMixin",
"./_ComboBoxMenu",
"../_HasDropDown",
"dojo/text!./templates/DropDownBox.html"
], function(declare, Deferred, kernel, lang, QueryResults, _AutoCompleterMixin, _ComboBoxMenu, _HasDropDown, template){
// module:
// dijit/form/ComboBoxMixin
return declare("dijit.form.ComboBoxMixin", [_HasDropDown, _AutoCompleterMixin], {
// summary:
// Provides main functionality of ComboBox widget
// dropDownClass: [protected extension] Function String
// Dropdown widget class used to select a date/time.
// Subclasses should specify this.
dropDownClass: _ComboBoxMenu,
// hasDownArrow: Boolean
// Set this textbox to have a down arrow button, to display the drop down list.
// Defaults to true.
hasDownArrow: true,
templateString: template,
baseClass: "dijitTextBox dijitComboBox",
/*=====
// store: [const] dojo/store/api/Store|dojo/data/api/Read
// Reference to data provider object used by this ComboBox.
//
// Should be dojo/store/api/Store, but dojo/data/api/Read supported
// for backwards compatibility.
store: null,
=====*/
// Set classes like dijitDownArrowButtonHover depending on
// mouse action over button node
cssStateNodes: {
"_buttonNode": "dijitDownArrowButton"
},
_setHasDownArrowAttr: function(/*Boolean*/ val){
this._set("hasDownArrow", val);
this._buttonNode.style.display = val ? "" : "none";
},
_showResultList: function(){
// hide the tooltip
this.displayMessage("");
this.inherited(arguments);
},
_setStoreAttr: function(store){
// For backwards-compatibility, accept dojo.data store in addition to dojo/store/api/Store. Remove in 2.0.
if(!store.get){
lang.mixin(store, {
_oldAPI: true,
get: function(id){
// summary:
// Retrieves an object by it's identity. This will trigger a fetchItemByIdentity.
// Like dojo/store/DataStore.get() except returns native item.
var deferred = new Deferred();
this.fetchItemByIdentity({
identity: id,
onItem: function(object){
deferred.resolve(object);
},
onError: function(error){
deferred.reject(error);
}
});
return deferred.promise;
},
query: function(query, options){
// summary:
// Queries the store for objects. Like dojo/store/DataStore.query()
// except returned Deferred contains array of native items.
var deferred = new Deferred(function(){ fetchHandle.abort && fetchHandle.abort(); });
deferred.total = new Deferred();
var fetchHandle = this.fetch(lang.mixin({
query: query,
onBegin: function(count){
deferred.total.resolve(count);
},
onComplete: function(results){
deferred.resolve(results);
},
onError: function(error){
deferred.reject(error);
}
}, options));
return QueryResults(deferred);
}
});
}
this._set("store", store);
},
postMixInProperties: function(){
// Since _setValueAttr() depends on this.store, _setStoreAttr() needs to execute first.
// Unfortunately, without special code, it ends up executing second.
var store = this.params.store || this.store;
if(store){
this._setStoreAttr(store);
}
this.inherited(arguments);
// User may try to access this.store.getValue() etc. in a custom labelFunc() function.
// It's not available with the new data store for handling inline <option> tags, so add it.
if(!this.params.store && !this.store._oldAPI){
var clazz = this.declaredClass;
lang.mixin(this.store, {
getValue: function(item, attr){
kernel.deprecated(clazz + ".store.getValue(item, attr) is deprecated for builtin store. Use item.attr directly", "", "2.0");
return item[attr];
},
getLabel: function(item){
kernel.deprecated(clazz + ".store.getLabel(item) is deprecated for builtin store. Use item.label directly", "", "2.0");
return item.name;
},
fetch: function(args){
kernel.deprecated(clazz + ".store.fetch() is deprecated for builtin store.", "Use store.query()", "2.0");
var shim = ["dojo/data/ObjectStore"]; // indirection so it doesn't get rolled into a build
require(shim, lang.hitch(this, function(ObjectStore){
new ObjectStore({objectStore: this}).fetch(args);
}));
}
});
}
}
});
});
| algogr/Site | web/js/dojo/dijit/form/ComboBoxMixin.js | JavaScript | mit | 4,578 |
// Copyright 2009 the Sputnik authors. All rights reserved.
/**
* Arguments : ()
*
* @path ch11/11.2/11.2.4/S11.2.4_A1.1_T1.js
* @description Function is declared with no FormalParameterList
*/
function f_arg() {
return arguments;
}
//CHECK#1
if (f_arg().length !== 0) {
$ERROR('#1: function f_arg() {return arguments;} f_arg().length === 0. Actual: ' + (f_arg().length));
}
//CHECK#2
if (f_arg()[0] !== undefined) {
$ERROR('#2: function f_arg() {return arguments;} f_arg()[0] === undefined. Actual: ' + (f_arg()[0]));
}
| Oceanswave/NiL.JS | Tests/tests/sputnik/ch11/11.2/11.2.4/S11.2.4_A1.1_T1.js | JavaScript | bsd-3-clause | 537 |
/**
* The examples provided by Facebook are for non-commercial testing and
* evaluation purposes only.
*
* Facebook reserves all rights not expressly granted.
*
* 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 NON INFRINGEMENT. IN NO EVENT SHALL
* FACEBOOK 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.
*
* @flow
*/
'use strict';
var React = require('react-native');
var {
AppRegistry,
ListView,
PixelRatio,
StyleSheet,
Text,
TextInput,
TouchableHighlight,
View,
} = React;
var NavigatorExample = require('./Navigator/NavigatorExample');
var { TestModule } = React.addons;
var createExamplePage = require('./createExamplePage');
var COMPONENTS = [
require('./ActivityIndicatorExample'),
require('./DatePickerExample'),
require('./ImageExample'),
require('./ListViewPagingExample'),
require('./ListViewSimpleExample'),
require('./MapViewExample'),
require('./NavigatorIOSExample'),
NavigatorExample,
require('./PickerExample'),
require('./ScrollViewExample'),
require('./SliderIOSExample'),
require('./SwitchExample'),
require('./TabBarExample'),
require('./TextExample.ios'),
require('./TextInputExample'),
require('./TouchableExample'),
require('./ViewExample'),
require('./WebViewExample'),
];
var APIS = [
require('./ActionSheetIOSExample'),
require('./AdSupportIOSExample'),
require('./AlertIOSExample'),
require('./AppStateIOSExample'),
require('./AsyncStorageExample'),
require('./BorderExample'),
require('./CameraRollExample.ios'),
require('./GeolocationExample'),
require('./LayoutExample'),
require('./NetInfoExample'),
require('./PointerEventsExample'),
require('./PushNotificationIOSExample'),
require('./StatusBarIOSExample'),
require('./ResponderExample'),
require('./TimerExample'),
require('./VibrationIOSExample'),
];
var ds = new ListView.DataSource({
rowHasChanged: (r1, r2) => r1 !== r2,
sectionHeaderHasChanged: (h1, h2) => h1 !== h2,
});
function makeRenderable(example: any): ReactClass<any, any, any> {
return example.examples ?
createExamplePage(null, example) :
example;
}
// Register suitable examples for snapshot tests
COMPONENTS.concat(APIS).forEach((Example) => {
if (Example.displayName) {
var Snapshotter = React.createClass({
componentDidMount: function() {
// View is still blank after first RAF :\
global.requestAnimationFrame(() =>
global.requestAnimationFrame(() => TestModule.verifySnapshot(
TestModule.markTestCompleted
)
));
},
render: function() {
var Renderable = makeRenderable(Example);
return <Renderable />;
},
});
AppRegistry.registerComponent(Example.displayName, () => Snapshotter);
}
});
class UIExplorerList extends React.Component {
constructor(props) {
super(props);
this.state = {
dataSource: ds.cloneWithRowsAndSections({
components: COMPONENTS,
apis: APIS,
}),
};
}
render() {
return (
<View style={styles.listContainer}>
<View style={styles.searchRow}>
<TextInput
autoCapitalize="none"
autoCorrect={false}
clearButtonMode="always"
onChangeText={this._search.bind(this)}
placeholder="Search..."
style={styles.searchTextInput}
/>
</View>
<ListView
style={styles.list}
dataSource={this.state.dataSource}
renderRow={this._renderRow.bind(this)}
renderSectionHeader={this._renderSectionHeader}
automaticallyAdjustContentInsets={false}
/>
</View>
);
}
_renderSectionHeader(data, section) {
return (
<View style={styles.sectionHeader}>
<Text style={styles.sectionHeaderTitle}>
{section.toUpperCase()}
</Text>
</View>
);
}
_renderRow(example, i) {
return (
<View key={i}>
<TouchableHighlight onPress={() => this._onPressRow(example)}>
<View style={styles.row}>
<Text style={styles.rowTitleText}>
{example.title}
</Text>
<Text style={styles.rowDetailText}>
{example.description}
</Text>
</View>
</TouchableHighlight>
<View style={styles.separator} />
</View>
);
}
_search(text) {
var regex = new RegExp(text, 'i');
var filter = (component) => regex.test(component.title);
this.setState({
dataSource: ds.cloneWithRowsAndSections({
components: COMPONENTS.filter(filter),
apis: APIS.filter(filter),
})
});
}
_onPressRow(example) {
if (example === NavigatorExample) {
this.props.onExternalExampleRequested(
NavigatorExample
);
return;
}
var Component = makeRenderable(example);
this.props.navigator.push({
title: Component.title,
component: Component,
});
}
}
var styles = StyleSheet.create({
listContainer: {
flex: 1,
},
list: {
backgroundColor: '#eeeeee',
},
sectionHeader: {
padding: 5,
},
group: {
backgroundColor: 'white',
},
sectionHeaderTitle: {
fontWeight: '500',
fontSize: 11,
},
row: {
backgroundColor: 'white',
justifyContent: 'center',
paddingHorizontal: 15,
paddingVertical: 8,
},
separator: {
height: 1 / PixelRatio.get(),
backgroundColor: '#bbbbbb',
marginLeft: 15,
},
rowTitleText: {
fontSize: 17,
fontWeight: '500',
},
rowDetailText: {
fontSize: 15,
color: '#888888',
lineHeight: 20,
},
searchRow: {
backgroundColor: '#eeeeee',
paddingTop: 75,
paddingLeft: 10,
paddingRight: 10,
paddingBottom: 10,
},
searchTextInput: {
backgroundColor: 'white',
borderColor: '#cccccc',
borderRadius: 3,
borderWidth: 1,
height: 30,
paddingLeft: 8,
},
});
module.exports = UIExplorerList;
| gregRV/rn-property-finder | Examples/UIExplorer/UIExplorerList.js | JavaScript | bsd-3-clause | 6,288 |
/// Copyright (c) 2012 Ecma International. All rights reserved.
/**
* @path ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-i-26.js
* @description Array.prototype.reduce - This object is the Arguments object which implements its own property get method (number of arguments equals number of parameters)
*/
function testcase() {
var testResult = false;
var initialValue = 0;
function callbackfn(prevVal, curVal, idx, obj) {
if (idx === 2) {
testResult = (curVal === 2);
}
}
var func = function (a, b, c) {
Array.prototype.reduce.call(arguments, callbackfn, initialValue);
};
func(0, 1, 2);
return testResult;
}
runTestCase(testcase);
| Oceanswave/NiL.JS | Tests/tests/sputnik/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-i-26.js | JavaScript | bsd-3-clause | 756 |
// Copyright 2009 the Sputnik authors. All rights reserved.
/**
* DecimalLiteral :: DecimalIntegerLiteral. DecimalDigigts ExponentPart
*
* @path ch07/7.8/7.8.3/S7.8.3_A3.4_T4.js
* @description ExponentPart :: E -DecimalDigits
*/
//CHECK#0
if (0.0E-1 !== 0) {
$ERROR('#0: 0.0E-1 === 0');
}
//CHECK#1
if (1.1E-1 !== 0.11) {
$ERROR('#1: 1.1E-1 === 0.11');
}
//CHECK#2
if (2.2E-1 !== 0.22) {
$ERROR('#2: 2.2E-1 === 0.22');
}
//CHECK#3
if (3.3E-1 !== 0.33) {
$ERROR('#3: 3.3E-1 === 0.33');
}
//CHECK#4
if (4.4E-1 !== 0.44) {
$ERROR('#4: 4.4E-1 === 0.44');
}
//CHECK#5
if (5.5E-1 !== 0.55) {
$ERROR('#5: 5.5E-1 === 0.55');
}
//CHECK#6
if (6.6E-1 !== 0.66) {
$ERROR('#6: 6.E-1 === 0.66');
}
//CHECK#7
if (7.7E-1 !== 0.77) {
$ERROR('#7: 7.7E-1 === 0.77');
}
//CHECK#8
if (8.8E-1 !== 0.88) {
$ERROR('#8: 8.8E-1 === 0.88');
}
//CHECK#9
if (9.9E-1 !== 0.99) {
$ERROR('#9: 9.9E-1 === 0.99');
}
| Oceanswave/NiL.JS | Tests/tests/sputnik/ch07/7.8/7.8.3/S7.8.3_A3.4_T4.js | JavaScript | bsd-3-clause | 919 |
var arrayAggregator = require('./_arrayAggregator'),
baseAggregator = require('./_baseAggregator'),
baseIteratee = require('./_baseIteratee'),
isArray = require('./isArray');
/**
* Creates a function like `_.groupBy`.
*
* @private
* @param {Function} setter The function to set accumulator values.
* @param {Function} [initializer] The accumulator object initializer.
* @returns {Function} Returns the new aggregator function.
*/
function createAggregator(setter, initializer) {
return function(collection, iteratee) {
var func = isArray(collection) ? arrayAggregator : baseAggregator,
accumulator = initializer ? initializer() : {};
return func(collection, setter, baseIteratee(iteratee, 2), accumulator);
};
}
module.exports = createAggregator;
| Moccine/global-service-plus.com | web/libariries/bootstrap/node_modules/zip-stream/node_modules/lodash/_createAggregator.js | JavaScript | mit | 812 |
angular.module('listDemo1', ['ngMaterial'])
.config(function($mdIconProvider) {
$mdIconProvider
.iconSet('communication', 'img/icons/sets/communication-icons.svg', 24);
})
.controller('AppCtrl', function($scope) {
var imagePath = 'img/60.jpeg';
$scope.phones = [
{
type: 'Home',
number: '(555) 251-1234',
options: {
icon: 'communication:phone'
}
},
{
type: 'Cell',
number: '(555) 786-9841',
options: {
icon: 'communication:phone',
avatarIcon: true
}
},
{
type: 'Office',
number: '(555) 314-1592',
options: {
face : imagePath
}
},
{
type: 'Offset',
number: '(555) 192-2010',
options: {
offset: true,
actionIcon: 'communication:phone'
}
}
];
$scope.todos = [
{
face : imagePath,
what: 'My quirky, joyful porg',
who: 'Kaguya w/ #qjporg',
when: '3:08PM',
notes: " I was lucky to find a quirky, joyful porg!"
},
{
face : imagePath,
what: 'Brunch this weekend?',
who: 'Min Li Chan',
when: '3:08PM',
notes: " I'll be in your neighborhood doing errands"
},
{
face : imagePath,
what: 'Brunch this weekend?',
who: 'Min Li Chan',
when: '3:08PM',
notes: " I'll be in your neighborhood doing errands"
},
{
face : imagePath,
what: 'Brunch this weekend?',
who: 'Min Li Chan',
when: '3:08PM',
notes: " I'll be in your neighborhood doing errands"
},
{
face : imagePath,
what: 'Brunch this weekend?',
who: 'Min Li Chan',
when: '3:08PM',
notes: " I'll be in your neighborhood doing errands"
},
];
});
| oostmeijer/material | src/components/list/demoBasicUsage/script.js | JavaScript | mit | 1,906 |
import React from 'react'
import { Router, Route, hashHistory } from 'react-router'
import Home from './components/ui/Home'
import About from './components/ui/About'
import MemberList from './components/ui/MemberList'
import { Left, Right, Whoops404 } from './components'
const routes = (
<Router history={hashHistory}>
<Route path="/" component={Home} />
<Route path="/" component={Left}>
<Route path="about" component={About} />
<Route path="members" component={MemberList} />
</Route>
<Route path="*" component={Whoops404} />
</Router>
)
export default routes | Raziyehbazargan/React.js_Essential_Training | Ch07/07_01/start/src/routes.js | JavaScript | mit | 624 |
/**
* FTScroller: touch and mouse-based scrolling for DOM elements larger than their containers.
*
* While this is a rewrite, it is heavily inspired by two projects:
* 1) Uxebu TouchScroll (https://github.com/davidaurelio/TouchScroll), BSD licensed:
* Copyright (c) 2010 uxebu Consulting Ltd. & Co. KG
* Copyright (c) 2010 David Aurelio
* 2) Zynga Scroller (https://github.com/zynga/scroller), MIT licensed:
* Copyright 2011, Zynga Inc.
* Copyright 2011, Deutsche Telekom AG
*
* Includes CubicBezier:
*
* Copyright (C) 2008 Apple Inc. All Rights Reserved.
* Copyright (C) 2010 David Aurelio. All Rights Reserved.
* Copyright (C) 2010 uxebu Consulting Ltd. & Co. KG. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC., DAVID AURELIO, AND UXEBU
* CONSULTING LTD. & CO. KG ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL APPLE INC. OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @copyright The Financial Times Ltd [All rights reserved]
* @codingstandard ftlabs-jslint
* @version 0.2.0
*/
/**
* @license FTScroller is (c) 2012 The Financial Times Ltd [All rights reserved] and licensed under the MIT license.
*
* Inspired by Uxebu TouchScroll, (c) 2010 uxebu Consulting Ltd. & Co. KG and David Aurelio, which is BSD licensed (https://github.com/davidaurelio/TouchScroll)
* Inspired by Zynga Scroller, (c) 2011 Zynga Inc and Deutsche Telekom AG, which is MIT licensed (https://github.com/zynga/scroller)
* Includes CubicBezier, (c) 2008 Apple Inc [All rights reserved], (c) 2010 David Aurelio and uxebu Consulting Ltd. & Co. KG. [All rights reserved], which is 2-clause BSD licensed (see above or https://github.com/davidaurelio/TouchScroll).
*/
/*jslint nomen: true, vars: true, browser: true, node: true, es5: true, continue: true, white: true*/
/*globals FTScrollerOptions*/
var FTScroller, CubicBezier;
(function () {
'use strict';
// Global flag to determine if any scroll is currently active. This prevents
// issues when using multiple scrollers, particularly when they're nested.
var _ftscrollerMoving = false;
// Determine whether pointer events or touch events can be used
var _trackPointerEvents = window.navigator.msPointerEnabled;
var _trackTouchEvents = !_trackPointerEvents && document.hasOwnProperty('ontouchstart');
// Determine whether to use modern hardware acceleration rules or dynamic/toggleable rules.
// Certain older browsers - particularly Android browsers - have problems with hardware
// acceleration, so being able to toggle the behaviour dynamically via a CSS cascade is desirable.
var _useToggleableHardwareAcceleration = !window.hasOwnProperty('ArrayBuffer');
// Feature detection
var _canClearSelection = (window.Selection && window.Selection.prototype.removeAllRanges);
// Determine the browser engine and prefix, trying to use the unprefixed version where available.
var _vendorCSSPrefix, _vendorStylePropertyPrefix, _vendorTransformLookup;
if (document.createElement('div').style.transform !== undefined) {
_vendorCSSPrefix = '';
_vendorStylePropertyPrefix = '';
_vendorTransformLookup = 'transform';
} else if (window.opera && Object.prototype.toString.call(window.opera) === '[object Opera]') {
_vendorCSSPrefix = '-o-';
_vendorStylePropertyPrefix = 'O';
_vendorTransformLookup = 'OTransform';
} else if (document.documentElement.style.MozTransform !== undefined) {
_vendorCSSPrefix = '-moz-';
_vendorStylePropertyPrefix = 'Moz';
_vendorTransformLookup = 'MozTransform';
} else if (document.documentElement.style.webkitTransform !== undefined) {
_vendorCSSPrefix = '-webkit-';
_vendorStylePropertyPrefix = 'webkit';
_vendorTransformLookup = '-webkit-transform';
} else if (typeof navigator.cpuClass === 'string') {
_vendorCSSPrefix = '-ms-';
_vendorStylePropertyPrefix = 'ms';
_vendorTransformLookup = '-ms-transform';
}
// If hardware acceleration is using the standard path, but perspective doesn't seem to be supported,
// 3D transforms likely aren't supported either
if (!_useToggleableHardwareAcceleration && document.createElement('div').style[_vendorStylePropertyPrefix + (_vendorStylePropertyPrefix ? 'P' : 'p') + 'erspective'] === undefined) {
_useToggleableHardwareAcceleration = true;
}
// Style prefixes
var _transformProperty = _vendorStylePropertyPrefix + (_vendorStylePropertyPrefix ? 'T' : 't') + 'ransform';
var _transitionProperty = _vendorStylePropertyPrefix + (_vendorStylePropertyPrefix ? 'T' : 't') + 'ransition';
var _translateRulePrefix = _useToggleableHardwareAcceleration ? 'translate(' : 'translate3d(';
var _transformPrefixes = { x: '', y: '0,' };
var _transformSuffixes = { x: ',0' + (_useToggleableHardwareAcceleration ? ')' : ',0)'), y: (_useToggleableHardwareAcceleration ? ')' : ',0)') };
// Constants. Note that the bezier curve should be changed along with the friction!
var _kFriction = 0.998;
var _kMinimumSpeed = 0.01;
// Create a global stylesheet to set up stylesheet rules and track dynamic entries
(function () {
var stylesheetContainerNode = document.getElementsByTagName('head')[0] || document.documentElement;
var newStyleNode = document.createElement('style');
var hardwareAccelerationRule;
var _styleText;
newStyleNode.type = 'text/css';
// Determine the hardware acceleration logic to use
if (_useToggleableHardwareAcceleration) {
hardwareAccelerationRule = _vendorCSSPrefix + 'transform-style: preserve-3d;';
} else {
hardwareAccelerationRule = _vendorCSSPrefix + 'transform: translateZ(0);';
}
// Add our rules
_styleText = [
'.ftscroller_scrolling { ' + _vendorCSSPrefix + 'user-select: none; cursor: all-scroll !important }',
'.ftscroller_container { overflow: hidden; position: relative; max-height: 100%; -webkit-tap-highlight-color: rgba(0, 0, 0, 0); -ms-touch-action: none }',
'.ftscroller_hwaccelerated { ' + hardwareAccelerationRule + ' }',
'.ftscroller_x, .ftscroller_y { position: relative; min-width: 100%; min-height: 100%; overflow: hidden }',
'.ftscroller_x { display: inline-block }',
'.ftscroller_scrollbar { pointer-events: none; position: absolute; width: 5px; height: 5px; border: 1px solid rgba(255, 255, 255, 0.15); -webkit-border-radius: 3px; border-radius: 6px; opacity: 0; ' + _vendorCSSPrefix + 'transition: opacity 350ms; z-index: 10 }',
'.ftscroller_scrollbarx { bottom: 2px; left: 2px }',
'.ftscroller_scrollbary { right: 2px; top: 2px }',
'.ftscroller_scrollbarinner { height: 100%; background: rgba(0,0,0,0.5); -webkit-border-radius: 2px; border-radius: 4px / 6px }',
'.ftscroller_scrolling .ftscroller_scrollbar { opacity: 1; ' + _vendorCSSPrefix + 'transition: none; -o-transition: all 0 none }',
'.ftscroller_scrolling .ftscroller_container .ftscroller_scrollbar { opacity: 0 }'
];
if (newStyleNode.styleSheet) {
newStyleNode.styleSheet.cssText = _styleText.join('\n');
} else {
newStyleNode.appendChild(document.createTextNode(_styleText.join('\n')));
}
// Add the stylesheet
stylesheetContainerNode.insertBefore(newStyleNode, stylesheetContainerNode.firstChild);
}());
/**
* Master constructor for the scrolling function, including which element to
* construct the scroller in, and any scrolling options.
* Note that app-wide options can also be set using a global FTScrollerOptions
* object.
*/
FTScroller = function (domNode, options) {
var key;
var destroy, setSnapSize, scrollTo, scrollBy, updateDimensions, addEventListener, removeEventListener, _startScroll, _updateScroll, _endScroll, _finalizeScroll, _interruptScroll, _flingScroll, _snapScroll, _getSnapPositionForPosition, _initializeDOM, _existingDOMValid, _domChanged, _updateDimensions, _updateScrollbarDimensions, _updateElementPosition, _updateSegments, _setAxisPosition, _scheduleAxisPosition, _fireEvent, _childFocused, _modifyDistanceBeyondBounds, _distancesBeyondBounds, _startAnimation, _scheduleRender, _cancelAnimation, _toggleEventHandlers, _onTouchStart, _onTouchMove, _onTouchEnd, _onMouseDown, _onMouseMove, _onMouseUp, _onPointerDown, _onPointerMove, _onPointerUp, _onPointerCancel, _onPointerCaptureEnd, _onClick, _onMouseScroll, _captureInput, _releaseInputCapture, _getBoundingRect;
/* Note that actual object instantiation occurs at the end of the closure to avoid jslint errors */
/* Options */
var _instanceOptions = {
// Whether to display scrollbars as appropriate
scrollbars: true,
// Enable scrolling on the X axis if content is available
scrollingX: true,
// Enable scrolling on the Y axis if content is available
scrollingY: true,
// The initial movement required to trigger a scroll, in pixels; this is the point at which
// the scroll is exclusive to this particular FTScroller instance.
scrollBoundary: 1,
// The initial movement required to trigger a visual indication that scrolling is occurring,
// in pixels. This is enforced to be less than or equal to the scrollBoundary, and is used to
// define when the scroller starts drawing changes in response to an input, even if the scroll
// is not treated as having begun/locked yet.
scrollResponseBoundary: 1,
// Whether to always enable scrolling, even if the content of the scroller does not
// require the scroller to function. This makes the scroller behave more like an
// element set to "overflow: scroll", with bouncing always occurring if enabled.
alwaysScroll: false,
// The content width to use when determining scroller dimensions. If this
// is false, the width will be detected based on the actual content.
contentWidth: undefined,
// The content height to use when determining scroller dimensions. If this
// is false, the height will be detected based on the actual content.
contentHeight: undefined,
// Enable snapping of content to 'pages' or a pixel grid
snapping: false,
// Define the horizontal interval of the pixel grid; snapping must be enabled for this to
// take effect. If this is not defined, snapping will use intervals based on container size.
snapSizeX: undefined,
// Define the vertical interval of the pixel grid; snapping must be enabled for this to
// take effect. If this is not defined, snapping will use intervals based on container size.
snapSizeY: undefined,
// Control whether snapping should be fully paginated, only ever flicking to the next page
// and not beyond. Snapping needs to be enabled for this to take effect.
paginatedSnap: false,
// Allow scroll bouncing and elasticity near the ends and grid
bouncing: true,
// Automatically detects changes to the contained markup and
// updates its dimensions whenever the content changes. This is
// set to false if a contentWidth or contentHeight are supplied.
updateOnChanges: true,
// Automatically catches changes to the window size and updates
// its dimensions.
updateOnWindowResize: false,
// The alignment to use if the content is smaller than the container;
// this also applies to initial positioning of scrollable content.
// Valid alignments are -1 (top or left), 0 (center), and 1 (bottom or right).
baseAlignments: { x: -1, y: -1 },
// Whether to use a window scroll flag, eg window.foo, to control whether
// to allow scrolling to start or now. If the window flag is set to true,
// this element will not start scrolling; this element will also toggle
// the variable while scrolling
windowScrollingActiveFlag: undefined,
// Instead of always using translate3d for transforms, a mix of translate3d
// and translate with a hardware acceleration class used to trigger acceleration
// is used; this is to allow CSS inheritance to be used to allow dynamic
// disabling of backing layers on older platforms.
hwAccelerationClass: 'ftscroller_hwaccelerated',
// While use of requestAnimationFrame is highly recommended on platforms
// which support it, it can result in the animation being a further half-frame
// behind the input method, increasing perceived lag slightly. To disable this,
// set this property to false.
enableRequestAnimationFrameSupport: true,
// Set the maximum time (ms) that a fling can take to complete; if
// this is not set, flings will complete instantly
maxFlingDuration: 1000
};
/* Local variables */
// Cache the DOM node and set up variables for other nodes
var _publicSelf;
var _self = this;
var _scrollableMasterNode = domNode;
var _containerNode;
var _contentParentNode;
var _scrollNodes = { x: null, y: null };
var _scrollbarNodes = { x: null, y: null };
// Dimensions of the container element and the content element
var _metrics = {
container: { x: null, y: null },
content: { x: null, y: null, rawX: null, rawY: null },
scrollEnd: { x: null, y: null }
};
// Snapping details
var _snapGridSize = {
x: false,
y: false,
userX: false,
userY: false
};
var _baseSegment = { x: 0, y: 0 };
var _activeSegment = { x: 0, y: 0 };
// Track the identifier of any input being tracked
var _inputIdentifier = false;
var _inputIndex = 0;
var _inputCaptured = false;
// Current scroll positions and tracking
var _isScrolling = false;
var _isDisplayingScroll = false;
var _isAnimating = false;
var _scrollbarsVisible = false;
var _baseScrollPosition = { x: 0, y: 0 };
var _lastScrollPosition = { x: 0, y: 0 };
var _scrollAtExtremity = { x: null, y: null };
var _preventClick = false;
var _timeouts = [];
var _hasBeenScrolled = false;
// Gesture details
var _baseScrollableAxes = {};
var _scrollableAxes = { x: true, y: true };
var _gestureStart = { x: 0, y: 0, t: 0 };
var _cumulativeScroll = { x: 0, y: 0 };
var _eventHistory = [];
var _kFlingBezier = new CubicBezier(0.1, 0.4, 0.3, 1);
var _kBounceBezier = new CubicBezier(0.7, 0, 0.9, 0.6);
var _kFlingTruncatedBezier = _kFlingBezier.divideAtT(0.97)[0];
var _kDecelerateBezier = new CubicBezier(0, 0.5, 0.5, 1);
// Allow certain events to be debounced
var _domChangeDebouncer = false;
var _scrollWheelEndDebouncer = false;
// Performance switches on browsers supporting requestAnimationFrame
var _animationFrameRequest = false;
var _animationTargetPosition = { x: 0, y: 0 };
var _reqAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame || false;
var _cancelAnimationFrame = window.cancelAnimationFrame || window.cancelRequestAnimationFrame || window.mozCancelAnimationFrame || window.mozCancelRequestAnimationFrame || window.webkitCancelAnimationFrame || window.webkitCancelRequestAnimationFrame || window.msCancelAnimationFrame || window.msCancelRequestAnimationFrame || false;
// Event listeners
var _eventListeners = {
'scrollstart': [],
'scroll': [],
'scrollend': [],
'segmentwillchange': [],
'segmentdidchange': [],
'reachedstart': [],
'reachedend': []
};
// MutationObserver instance, when supported and if DOM change sniffing is enabled
var _mutationObserver;
/* Parsing supplied options */
// Override default instance options with global - or closure'd - options
if (typeof FTScrollerOptions === 'object' && FTScrollerOptions) {
for (key in FTScrollerOptions) {
if (FTScrollerOptions.hasOwnProperty(key) && _instanceOptions.hasOwnProperty(key)) {
_instanceOptions[key] = FTScrollerOptions[key];
}
}
}
// Override default and global options with supplied options
if (options) {
for (key in options) {
if (options.hasOwnProperty(key) && _instanceOptions.hasOwnProperty(key)) {
_instanceOptions[key] = options[key];
}
}
// If snap grid size options were supplied, store them
if (options.hasOwnProperty('snapSizeX') && !isNaN(options.snapSizeX)) {
_snapGridSize.userX = _snapGridSize.x = options.snapSizeX;
}
if (options.hasOwnProperty('snapSizeY') && !isNaN(options.snapSizeY)) {
_snapGridSize.userY = _snapGridSize.y = options.snapSizeY;
}
// If content width and height were defined, disable updateOnChanges for performance
if (options.contentWidth && options.contentHeight) {
options.updateOnChanges = false;
}
}
// Validate the scroll response parameter
_instanceOptions.scrollResponseBoundary = Math.min(_instanceOptions.scrollBoundary, _instanceOptions.scrollResponseBoundary);
// Update base scrollable axes
if (_instanceOptions.scrollingX) {
_baseScrollableAxes.x = true;
}
if (_instanceOptions.scrollingY) {
_baseScrollableAxes.y = true;
}
/* Scoped Functions */
/**
* Unbinds all event listeners to prevent circular references preventing items
* from being deallocated, and clean up references to dom elements. Pass in
* "removeElements" to also remove FTScroller DOM elements for special reuse cases.
*/
destroy = function destroy(removeElements) {
var i, l;
_toggleEventHandlers(false);
_cancelAnimation();
if (_domChangeDebouncer) {
window.clearTimeout(_domChangeDebouncer);
_domChangeDebouncer = false;
}
for (i = 0, l = _timeouts.length; i < l; i = i + 1) {
window.clearTimeout(_timeouts[i]);
}
_timeouts.length = 0;
// Destroy DOM elements if required
if (removeElements && _scrollableMasterNode) {
while (_contentParentNode.firstChild) {
_scrollableMasterNode.appendChild(_contentParentNode.firstChild);
}
_scrollableMasterNode.removeChild(_containerNode);
}
_scrollableMasterNode = null;
_containerNode = null;
_contentParentNode = null;
_scrollNodes.x = null;
_scrollNodes.y = null;
_scrollbarNodes.x = null;
_scrollbarNodes.y = null;
for (i in _eventListeners) {
if (_eventListeners.hasOwnProperty(i)) {
_eventListeners[i].length = 0;
}
}
// If this is currently tracked as a scrolling instance, clear the flag
if (_ftscrollerMoving && _ftscrollerMoving === _self) {
_ftscrollerMoving = false;
if (_instanceOptions.windowScrollingActiveFlag) {
window[_instanceOptions.windowScrollingActiveFlag] = false;
}
}
};
/**
* Configures the snapping boundaries within the scrolling element if
* snapping is active. If this is never called, snapping defaults to
* using the bounding box, eg page-at-a-time.
*/
setSnapSize = function setSnapSize(width, height) {
_snapGridSize.userX = width;
_snapGridSize.userY = height;
_snapGridSize.x = width;
_snapGridSize.y = height;
// Ensure the content dimensions conform to the grid
_metrics.content.x = Math.ceil(_metrics.content.rawX / width) * width;
_metrics.content.y = Math.ceil(_metrics.content.rawY / height) * height;
_metrics.scrollEnd.x = _metrics.container.x - _metrics.content.x;
_metrics.scrollEnd.y = _metrics.container.y - _metrics.content.y;
_updateScrollbarDimensions();
// Snap to the new grid if necessary
_snapScroll();
_updateSegments(true);
};
/**
* Scroll to a supplied position, including whether or not to animate the
* scroll and how fast to perform the animation (pass in true to select a
* dynamic duration). The inputs will be constrained to bounds and snapped.
* If false is supplied for a position, that axis will not be scrolled.
*/
scrollTo = function scrollTo(left, top, animationDuration) {
var targetPosition, duration, positions, axis, maxDuration = 0, scrollPositionsToApply = {};
// If a manual scroll is in progress, cancel it
_endScroll(Date.now());
// Move supplied coordinates into an object for iteration, also inverting the values into
// our coordinate system
positions = {
x: -left,
y: -top
};
for (axis in _baseScrollableAxes) {
if (_baseScrollableAxes.hasOwnProperty(axis)) {
targetPosition = positions[axis];
if (targetPosition === false) {
continue;
}
// Constrain to bounds
targetPosition = Math.min(0, Math.max(_metrics.scrollEnd[axis], targetPosition));
// Snap if appropriate
if (_instanceOptions.snapping && _snapGridSize[axis]) {
targetPosition = Math.round(targetPosition / _snapGridSize[axis]) * _snapGridSize[axis];
}
// Get a duration
duration = animationDuration || 0;
if (duration === true) {
duration = Math.sqrt(Math.abs(_baseScrollPosition[axis] - targetPosition)) * 20;
}
// Trigger the position change
_setAxisPosition(axis, targetPosition, duration);
scrollPositionsToApply[axis] = targetPosition;
maxDuration = Math.max(maxDuration, duration);
}
}
// If the scroll had resulted in a change in position, perform some additional actions:
if (_baseScrollPosition.x !== positions.x || _baseScrollPosition.y !== positions.y) {
// Mark a scroll as having ever occurred
_hasBeenScrolled = true;
// If an animation duration is present, fire a scroll start event
_fireEvent('scrollstart', { scrollLeft: -_baseScrollPosition.x, scrollTop: -_baseScrollPosition.y });
}
if (maxDuration) {
_timeouts.push(setTimeout(function () {
var axis;
for (axis in scrollPositionsToApply) {
if (scrollPositionsToApply.hasOwnProperty(axis)) {
_lastScrollPosition[axis] = scrollPositionsToApply[axis];
}
}
_finalizeScroll();
}, maxDuration));
} else {
_finalizeScroll();
}
_fireEvent('scroll', { scrollLeft: -_baseScrollPosition.x, scrollTop: -_baseScrollPosition.y });
};
/**
* Alter the current scroll position, including whether or not to animate
* the scroll and how fast to perform the animation (pass in true to
* select a dynamic duration). The inputs will be checked against the
* current position.
*/
scrollBy = function scrollBy(horizontal, vertical, animationDuration) {
// Wrap the scrollTo function for simplicity
scrollTo(parseFloat(horizontal) - _baseScrollPosition.x, parseFloat(vertical) - _baseScrollPosition.y, animationDuration);
};
/**
* Provide a public method to detect changes in dimensions for either the content or the
* container.
*/
updateDimensions = function updateDimensions(contentWidth, contentHeight, ignoreSnapScroll) {
options.contentWidth = contentWidth || options.contentWidth;
options.contentHeight = contentHeight || options.contentHeight;
// Currently just wrap the private API
_updateDimensions(!!ignoreSnapScroll);
};
/**
* Add an event handler for a supported event. Current events include:
* scroll - fired whenever the scroll position changes
* scrollstart - fired when a scroll movement starts
* scrollend - fired when a scroll movement ends
* segmentwillchange - fired whenever the segment changes, including during scrolling
* segmentdidchange - fired when a segment has conclusively changed, after scrolling.
*/
addEventListener = function addEventListener(eventname, eventlistener) {
// Ensure this is a valid event
if (!_eventListeners.hasOwnProperty(eventname)) {
return false;
}
// Add the listener
_eventListeners[eventname].push(eventlistener);
return true;
};
/**
* Remove an event handler for a supported event. The listener must be exactly the same as
* an added listener to be removed.
*/
removeEventListener = function removeEventListener(eventname, eventlistener) {
var i;
// Ensure this is a valid event
if (!_eventListeners.hasOwnProperty(eventname)) {
return false;
}
for (i = _eventListeners[eventname].length; i >= 0; i = i - 1) {
if (_eventListeners[eventname][i] === eventlistener) {
_eventListeners[eventname].splice(i, 1);
}
}
return true;
};
/**
* Start a scroll tracking input - this could be mouse, webkit-style touch,
* or ms-style pointer events.
*/
_startScroll = function _startScroll(inputX, inputY, inputTime, rawEvent) {
var triggerScrollInterrupt = _isAnimating;
// Opera fix
if (inputTime <= 0) {
inputTime = Date.now();
}
// If a window scrolling flag is set, and evaluates to true, don't start checking touches
if (_instanceOptions.windowScrollingActiveFlag && window[_instanceOptions.windowScrollingActiveFlag]) {
return false;
}
// If an animation is in progress, stop the scroll.
if (triggerScrollInterrupt) {
_interruptScroll();
} else {
// Allow clicks again, but only if a scroll was not interrupted
_preventClick = false;
}
// Store the initial event coordinates
_gestureStart.x = inputX;
_gestureStart.y = inputY;
_gestureStart.t = inputTime;
_animationTargetPosition.x = _lastScrollPosition.x;
_animationTargetPosition.y = _lastScrollPosition.y;
// Clear event history and add the start touch
_eventHistory.length = 0;
_eventHistory.push({ x: inputX, y: inputY, t: inputTime });
if (triggerScrollInterrupt) {
_updateScroll(inputX, inputY, inputTime, rawEvent, triggerScrollInterrupt);
}
return true;
};
/**
* Continue a scroll as a result of an updated position
*/
_updateScroll = function _updateScroll(inputX, inputY, inputTime, rawEvent, scrollInterrupt) {
var axis, otherScrollerActive;
var initialScroll = false;
var gesture = {
x: inputX - _gestureStart.x,
y: inputY - _gestureStart.y
};
var targetPositions = { x: _baseScrollPosition.x + gesture.x, y: _baseScrollPosition.y + gesture.y };
var distancesBeyondBounds = _distancesBeyondBounds(targetPositions);
// Opera fix
if (inputTime <= 0) {
inputTime = Date.now();
}
// If scrolling has not yet locked to this scroller, check whether to stop scrolling
if (!_isScrolling) {
// Check the internal flag to determine if another FTScroller is scrolling
if (_ftscrollerMoving && _ftscrollerMoving !== _self) {
otherScrollerActive = true;
}
// Otherwise, check the window scrolling flag to see if anything else has claimed scrolling
else if (_instanceOptions.windowScrollingActiveFlag && window[_instanceOptions.windowScrollingActiveFlag]) {
otherScrollerActive = true;
}
// If another scroller was active, clean up and stop processing.
if (otherScrollerActive) {
_inputIdentifier = false;
_releaseInputCapture();
if (_scrollbarsVisible) {
_cancelAnimation();
if (!_snapScroll(true)) {
_finalizeScroll(true);
}
}
return;
}
}
// If not yet displaying a scroll, determine whether that triggering boundary
// has been exceeded
if (!_isDisplayingScroll) {
// Determine whether to prevent the default scroll event - if the scroll could still
// be triggered, prevent the default to avoid problems (particularly on PlayBook)
if (_instanceOptions.bouncing || scrollInterrupt || (_scrollableAxes.x && gesture.x && distancesBeyondBounds.x < 0) || (_scrollableAxes.y && gesture.y && distancesBeyondBounds.y < 0)) {
rawEvent.preventDefault();
}
// Check scrolled distance against the boundary limit to see if scrolling can be triggered.
// If snapping is active and the scroll has been interrupted, trigger at once
if (!(scrollInterrupt && _instanceOptions.snapping) && (!_scrollableAxes.x || Math.abs(gesture.x) < _instanceOptions.scrollResponseBoundary) && (!_scrollableAxes.y || Math.abs(gesture.y) < _instanceOptions.scrollResponseBoundary)) {
return;
}
// If bouncing is disabled, and already at an edge and scrolling beyond the edge, ignore the scroll for
// now - this allows other scrollers to claim if appropriate, allowing nicer nested scrolls.
if (!_instanceOptions.bouncing && !scrollInterrupt && (!_scrollableAxes.x || !gesture.x || distancesBeyondBounds.x > 0) && (!_scrollableAxes.y || !gesture.y || distancesBeyondBounds.y > 0)) {
// Prevent the original click now that scrolling would be triggered
_preventClick = true;
return;
}
// Trigger the start of visual scrolling
_startAnimation();
_isDisplayingScroll = true;
_hasBeenScrolled = true;
_isAnimating = true;
initialScroll = true;
_scrollbarsVisible = true;
} else {
// Prevent the event default. It is safe to call this in IE10 because the event is never
// a window.event, always a "true" event.
rawEvent.preventDefault();
}
// If not yet locked to a scroll, determine whether to do so
if (!_isScrolling) {
// If the gesture distance has exceeded the scroll lock distance, or snapping is active
// and the scroll has been interrupted, enture exclusive scrolling.
if ((scrollInterrupt && _instanceOptions.snapping)
|| (_scrollableAxes.x && Math.abs(gesture.x) >= _instanceOptions.scrollBoundary)
|| (_scrollableAxes.y && Math.abs(gesture.y) >= _instanceOptions.scrollBoundary)) {
_isScrolling = true;
_ftscrollerMoving = _self;
if (_instanceOptions.windowScrollingActiveFlag) {
window[_instanceOptions.windowScrollingActiveFlag] = _self;
}
_fireEvent('scrollstart', { scrollLeft: -_baseScrollPosition.x, scrollTop: -_baseScrollPosition.y });
}
}
// Cancel text selections while dragging a cursor
if (_canClearSelection) {
window.getSelection().removeAllRanges();
}
// Update axes if appropriate
for (axis in _scrollableAxes) {
if (_scrollableAxes.hasOwnProperty(axis)) {
if (targetPositions[axis] > 0) {
targetPositions[axis] = _modifyDistanceBeyondBounds(targetPositions[axis], axis);
} else if (targetPositions[axis] < _metrics.scrollEnd[axis]) {
targetPositions[axis] = _metrics.scrollEnd[axis] + _modifyDistanceBeyondBounds(targetPositions[axis] - _metrics.scrollEnd[axis], axis);
}
if (_reqAnimationFrame) {
_animationTargetPosition[axis] = targetPositions[axis];
} else {
_setAxisPosition(axis, targetPositions[axis]);
}
}
}
// To aid render/draw coalescing, perform other one-off actions here
if (initialScroll) {
if (_containerNode.className.indexOf('ftscroller_scrolling') === -1) {
_containerNode.className += ' ftscroller_scrolling';
}
}
// If full, locked scrolling has enabled, fire any scroll and segment change events
if (_isScrolling) {
_fireEvent('scroll', { scrollLeft: -targetPositions.x, scrollTop: -targetPositions.y });
_updateSegments(false);
}
// Add an event to the event history, keeping it around twenty events long
_eventHistory.push({ x: inputX, y: inputY, t: inputTime });
if (_eventHistory.length > 30) {
_eventHistory.splice(0, 15);
}
};
/**
* Complete a scroll with a final event time if available (it may
* not be, depending on the input type); this may continue the scroll
* with a fling and/or bounceback depending on options.
*/
_endScroll = function _endScroll(inputTime, rawEvent) {
_inputIdentifier = false;
_releaseInputCapture();
_cancelAnimation();
if (!_isScrolling) {
if (!_snapScroll(true) && _scrollbarsVisible) {
_finalizeScroll(true);
}
return;
}
// Modify the last movement event to include the end event time
_eventHistory[_eventHistory.length - 1].t = inputTime;
// Update flags
_isScrolling = false;
_isDisplayingScroll = false;
_ftscrollerMoving = false;
if (_instanceOptions.windowScrollingActiveFlag) {
window[_instanceOptions.windowScrollingActiveFlag] = false;
}
// Prevent clicks and stop the event default. It is safe to call this in IE10 because
// the event is never a window.event, always a "true" event.
_preventClick = true;
if (rawEvent) {
rawEvent.preventDefault();
}
// Trigger a fling or bounceback if necessary
if (!_flingScroll() && !_snapScroll()) {
_finalizeScroll();
}
};
/**
* Remove the scrolling class, cleaning up display.
*/
_finalizeScroll = function _finalizeScroll(scrollCancelled) {
var i, l, axis;
_isAnimating = false;
_scrollbarsVisible = false;
_isDisplayingScroll = false;
// Remove scrolling class
_containerNode.className = _containerNode.className.replace(/ ?ftscroller_scrolling/g, '');
// Store final position if scrolling occurred
_baseScrollPosition.x = _lastScrollPosition.x;
_baseScrollPosition.y = _lastScrollPosition.y;
if (!scrollCancelled) {
_fireEvent('scroll', { scrollLeft: -_baseScrollPosition.x, scrollTop: -_baseScrollPosition.y });
_updateSegments(true);
_fireEvent('scrollend', { scrollLeft: -_baseScrollPosition.x, scrollTop: -_baseScrollPosition.y });
}
// Restore transitions
for (axis in _scrollableAxes) {
if (_scrollableAxes.hasOwnProperty(axis)) {
_scrollNodes[axis].style[_transitionProperty] = '';
if (_instanceOptions.scrollbars) {
_scrollbarNodes[axis].style[_transitionProperty] = '';
}
}
}
// Clear any remaining timeouts
for (i = 0, l = _timeouts.length; i < l; i = i + 1) {
window.clearTimeout(_timeouts[i]);
}
_timeouts.length = 0;
};
/**
* Interrupt a current scroll, allowing a start scroll during animation to trigger a new scroll
*/
_interruptScroll = function _interruptScroll() {
var axis, i, l;
_isAnimating = false;
// Update the stored base position
_updateElementPosition();
// Ensure the parsed positions are set, also clearing transitions
for (axis in _scrollableAxes) {
if (_scrollableAxes.hasOwnProperty(axis)) {
_setAxisPosition(axis, _baseScrollPosition[axis]);
}
}
// Update segment tracking if snapping is active
_updateSegments(false);
// Clear any remaining timeouts
for (i = 0, l = _timeouts.length; i < l; i = i + 1) {
window.clearTimeout(_timeouts[i]);
}
_timeouts.length = 0;
};
/**
* Determine whether a scroll fling or bounceback is required, and set up the styles and
* timeouts required.
*/
_flingScroll = function _flingScroll() {
var i, axis, movementSpeed, lastPosition, comparisonPosition, flingDuration, flingDistance, flingPosition, bounceDelay, bounceDistance, bounceDuration, bounceTarget, boundsBounce, modifiedDistance, flingBezier, timeProportion, boundsCrossDelay, flingStartSegment, beyondBoundsFlingDistance, baseFlingComponent;
var maxAnimationTime = 0;
var moveRequired = false;
var scrollPositionsToApply = {};
// If we only have the start event available, or are scrolling, no action required.
if (_eventHistory.length === 1 || _inputIdentifier === 'scrollwheel') {
return false;
}
for (axis in _scrollableAxes) {
if (_scrollableAxes.hasOwnProperty(axis)) {
bounceDuration = 350;
bounceDistance = 0;
boundsBounce = false;
bounceTarget = false;
boundsCrossDelay = undefined;
// Re-set a default bezier curve for the animation, with the end lopped off for min speed
flingBezier = _kFlingTruncatedBezier;
// Get the last movement speed, in pixels per millisecond. To do this, look at the events
// in the last 100ms and average out the speed, using a minimum number of two points.
lastPosition = _eventHistory[_eventHistory.length - 1];
comparisonPosition = _eventHistory[_eventHistory.length - 2];
for (i = _eventHistory.length - 3; i >= 0; i = i - 1) {
if (lastPosition.t - _eventHistory[i].t > 100) {
break;
}
comparisonPosition = _eventHistory[i];
}
movementSpeed = (lastPosition[axis] - comparisonPosition[axis]) / (lastPosition.t - comparisonPosition.t);
// If there is little speed, no further action required except for a bounceback, below.
if (Math.abs(movementSpeed) < _kMinimumSpeed) {
flingDuration = 0;
flingDistance = 0;
} else {
/* Calculate the fling duration. As per TouchScroll, the speed at any particular
point in time can be calculated as:
{ speed } = { initial speed } * ({ friction } to the power of { duration })
...assuming all values are in equal pixels/millisecond measurements. As we know the
minimum target speed, this can be altered to:
{ duration } = log( { speed } / { initial speed } ) / log( { friction } )
*/
flingDuration = Math.log(_kMinimumSpeed / Math.abs(movementSpeed)) / Math.log(_kFriction);
/* Calculate the fling distance (before any bouncing or snapping). As per
TouchScroll, the total distance covered can be approximated by summing
the distance per millisecond, per millisecond of duration - a divergent series,
and so rather tricky to model otherwise!
So using values in pixels per millisecond:
{ distance } = { initial speed } * (1 - ({ friction } to the power
of { duration + 1 }) / (1 - { friction })
*/
flingDistance = movementSpeed * (1 - Math.pow(_kFriction, flingDuration + 1)) / (1 - _kFriction);
}
// Determine a target fling position
flingPosition = Math.floor(_lastScrollPosition[axis] + flingDistance);
// If bouncing is disabled, and the last scroll position and fling position are both at a bound,
// reset the fling position to the bound
if (!_instanceOptions.bouncing) {
if (_lastScrollPosition[axis] === 0 && flingPosition > 0) {
flingPosition = 0;
} else if (_lastScrollPosition[axis] === _metrics.scrollEnd[axis] && flingPosition < _lastScrollPosition[axis]) {
flingPosition = _lastScrollPosition[axis];
}
}
// In paginated snapping mode, determine the page to snap to - maximum
// one page in either direction from the current page.
if (_instanceOptions.paginatedSnap && _instanceOptions.snapping) {
flingStartSegment = -_lastScrollPosition[axis] / _snapGridSize[axis];
if (_baseSegment[axis] < flingStartSegment) {
flingStartSegment = Math.floor(flingStartSegment);
} else {
flingStartSegment = Math.ceil(flingStartSegment);
}
// If the target position will end up beyond another page, target that page edge
if (flingPosition > -(flingStartSegment - 1) * _snapGridSize[axis]) {
bounceDistance = flingPosition + (flingStartSegment - 1) * _snapGridSize[axis];
} else if (flingPosition < -(flingStartSegment + 1) * _snapGridSize[axis]) {
bounceDistance = flingPosition + (flingStartSegment + 1) * _snapGridSize[axis];
// Otherwise, if the movement speed was above the minimum velocity, continue
// in the move direction.
} else if (Math.abs(movementSpeed) > _kMinimumSpeed) {
// Determine the target segment
if (movementSpeed < 0) {
flingPosition = Math.floor(_lastScrollPosition[axis] / _snapGridSize[axis]) * _snapGridSize[axis];
} else {
flingPosition = Math.ceil(_lastScrollPosition[axis] / _snapGridSize[axis]) * _snapGridSize[axis];
}
flingDuration = Math.min(_instanceOptions.maxFlingDuration, flingDuration * (flingPosition - _lastScrollPosition[axis]) / flingDistance);
}
// In non-paginated snapping mode, snap to the nearest grid location to the target
} else if (_instanceOptions.snapping) {
bounceDistance = flingPosition - (Math.round(flingPosition / _snapGridSize[axis]) * _snapGridSize[axis]);
}
// Deal with cases where the target is beyond the bounds
if (flingPosition - bounceDistance > 0) {
bounceDistance = flingPosition;
boundsBounce = true;
} else if (flingPosition - bounceDistance < _metrics.scrollEnd[axis]) {
bounceDistance = flingPosition - _metrics.scrollEnd[axis];
boundsBounce = true;
}
// Amend the positions and bezier curve if necessary
if (bounceDistance) {
// If the fling moves the scroller beyond the normal scroll bounds, and
// the bounce is snapping the scroll back after the fling:
if (boundsBounce && _instanceOptions.bouncing && flingDistance) {
flingDistance = Math.floor(flingDistance);
if (flingPosition > 0) {
beyondBoundsFlingDistance = flingPosition - Math.max(0, _lastScrollPosition[axis]);
} else {
beyondBoundsFlingDistance = flingPosition - Math.min(_metrics.scrollEnd[axis], _lastScrollPosition[axis]);
}
baseFlingComponent = flingDistance - beyondBoundsFlingDistance;
// Determine the time proportion the original bound is along the fling curve
if (!flingDistance || !flingDuration) {
timeProportion = 0;
} else {
timeProportion = flingBezier._getCoordinateForT(flingBezier.getTForY((flingDistance - beyondBoundsFlingDistance) / flingDistance, 1 / flingDuration), flingBezier._p1.x, flingBezier._p2.x);
boundsCrossDelay = timeProportion * flingDuration;
}
// Eighth the distance beyonds the bounds
modifiedDistance = Math.ceil(beyondBoundsFlingDistance / 8);
// Further limit the bounce to half the container dimensions
if (Math.abs(modifiedDistance) > _metrics.container[axis] / 2) {
if (modifiedDistance < 0) {
modifiedDistance = -Math.floor(_metrics.container[axis] / 2);
} else {
modifiedDistance = Math.floor(_metrics.container[axis] / 2);
}
}
if (flingPosition > 0) {
bounceTarget = 0;
} else {
bounceTarget = _metrics.scrollEnd[axis];
}
// If the entire fling is a bounce, modify appropriately
if (timeProportion === 0) {
flingDuration = flingDuration / 6;
flingPosition = _lastScrollPosition[axis] + baseFlingComponent + modifiedDistance;
bounceDelay = flingDuration;
// Otherwise, take a new curve and add it to the timeout stack for the bounce
} else {
// The new bounce delay is the pre-boundary fling duration, plus a
// sixth of the post-boundary fling.
bounceDelay = (timeProportion + ((1 - timeProportion) / 6)) * flingDuration;
_scheduleAxisPosition(axis, (_lastScrollPosition[axis] + baseFlingComponent + modifiedDistance), ((1 - timeProportion) * flingDuration / 6), _kDecelerateBezier, boundsCrossDelay);
// Modify the fling to match, clipping to prevent over-fling
flingBezier = flingBezier.divideAtX(bounceDelay / flingDuration, 1 / flingDuration)[0];
flingDuration = bounceDelay;
flingPosition = (_lastScrollPosition[axis] + baseFlingComponent + modifiedDistance);
}
// If the fling requires snapping to a snap location, and the bounce needs to
// reverse the fling direction after the fling completes:
} else if ((flingDistance < 0 && bounceDistance < flingDistance) || (flingDistance > 0 && bounceDistance > flingDistance)) {
// Shorten the original fling duration to reflect the bounce
flingPosition = flingPosition - Math.floor(flingDistance / 2);
bounceDistance = bounceDistance - Math.floor(flingDistance / 2);
bounceDuration = Math.sqrt(Math.abs(bounceDistance)) * 50;
bounceTarget = flingPosition - bounceDistance;
flingDuration = 350;
bounceDelay = flingDuration * 0.97;
// If the bounce is truncating the fling, or continuing the fling on in the same
// direction to hit the next boundary:
} else {
flingPosition = flingPosition - bounceDistance;
// If there was no fling distance originally, use the bounce details
if (!flingDistance) {
flingDuration = bounceDuration;
// If truncating the fling at a snapping edge:
} else if ((flingDistance < 0 && bounceDistance < 0) || (flingDistance > 0 && bounceDistance > 0)) {
timeProportion = flingBezier._getCoordinateForT(flingBezier.getTForY((Math.abs(flingDistance) - Math.abs(bounceDistance)) / Math.abs(flingDistance), 1 / flingDuration), flingBezier._p1.x, flingBezier._p2.x);
flingBezier = flingBezier.divideAtX(timeProportion, 1 / flingDuration)[0];
flingDuration = Math.round(flingDuration * timeProportion);
// If extending the fling to reach the next snapping boundary, no further
// action is required.
}
bounceDistance = 0;
bounceDuration = 0;
}
}
// If no fling or bounce is required, continue
if (flingPosition === _lastScrollPosition[axis] && !bounceDistance) {
continue;
}
moveRequired = true;
// Perform the fling
_setAxisPosition(axis, flingPosition, flingDuration, flingBezier, boundsCrossDelay);
// Schedule a bounce if appropriate
if (bounceDistance && bounceDuration) {
_scheduleAxisPosition(axis, bounceTarget, bounceDuration, _kBounceBezier, bounceDelay);
}
maxAnimationTime = Math.max(maxAnimationTime, bounceDistance ? (bounceDelay + bounceDuration) : flingDuration);
scrollPositionsToApply[axis] = (bounceTarget === false) ? flingPosition : bounceTarget;
}
}
if (moveRequired && maxAnimationTime) {
_timeouts.push(setTimeout(function () {
var axis;
// Update the stored scroll position ready for finalising
for (axis in scrollPositionsToApply) {
if (scrollPositionsToApply.hasOwnProperty(axis)) {
_lastScrollPosition[axis] = scrollPositionsToApply[axis];
}
}
_finalizeScroll();
}, maxAnimationTime));
}
return moveRequired;
};
/**
* Bounce back into bounds if necessary, or snap to a grid location.
*/
_snapScroll = function _snapScroll(scrollCancelled) {
var axis;
var snapDuration = scrollCancelled ? 100 : 350;
// Get the current position and see if a snap is required
var targetPosition = _getSnapPositionForPosition(_lastScrollPosition);
var snapRequired = false;
for (axis in _baseScrollableAxes) {
if (_baseScrollableAxes.hasOwnProperty(axis)) {
if (targetPosition[axis] !== _lastScrollPosition[axis]) {
snapRequired = true;
}
}
}
if (!snapRequired) {
return false;
}
// Perform the snap
for (axis in _baseScrollableAxes) {
if (_baseScrollableAxes.hasOwnProperty(axis)) {
_setAxisPosition(axis, targetPosition[axis], snapDuration);
}
}
_timeouts.push(setTimeout(function () {
// Update the stored scroll position ready for finalizing
_lastScrollPosition = targetPosition;
_finalizeScroll(scrollCancelled);
}, snapDuration));
return true;
};
/**
* Get an appropriate snap point for a supplied point. This will respect the edge of the
* element, and any grid if configured.
*/
_getSnapPositionForPosition = function _getSnapPositionForPosition(coordinates) {
var axis;
var coordinatesToReturn = { x: 0, y: 0 };
for (axis in _scrollableAxes) {
if (_scrollableAxes.hasOwnProperty(axis)) {
// If the coordinate is beyond the edges of the scroller, use the closest edge
if (coordinates[axis] > 0) {
coordinatesToReturn[axis] = 0;
continue;
}
if (coordinates[axis] < _metrics.scrollEnd[axis]) {
coordinatesToReturn[axis] = _metrics.scrollEnd[axis];
continue;
}
// If a grid is present, find the nearest grid delineator.
if (_instanceOptions.snapping && _snapGridSize[axis]) {
coordinatesToReturn[axis] = Math.round(coordinates[axis] / _snapGridSize[axis]) * _snapGridSize[axis];
continue;
}
// Otherwise use the supplied coordinate.
coordinatesToReturn[axis] = coordinates[axis];
}
}
return coordinatesToReturn;
};
/**
* Sets up the DOM around the node to be scrolled.
*/
_initializeDOM = function _initializeDOM() {
var offscreenFragment, offscreenNode, scrollYParent;
// Check whether the DOM is already present and valid - if so, no further action required.
if (_existingDOMValid()) {
return;
}
// Otherwise, the DOM needs to be created inside the originally supplied node. The node
// has a container inserted inside it - which acts as an anchor element with constraints -
// and then the scrollable layers as appropriate.
// Create a new document fragment to temporarily hold the scrollable content
offscreenFragment = _scrollableMasterNode.ownerDocument.createDocumentFragment();
offscreenNode = document.createElement('DIV');
offscreenFragment.appendChild(offscreenNode);
// Drop in the wrapping HTML
offscreenNode.innerHTML = FTScroller.prototype.getPrependedHTML(!_instanceOptions.scrollingX, !_instanceOptions.scrollingY, _instanceOptions.hwAccelerationClass) + FTScroller.prototype.getAppendedHTML(!_instanceOptions.scrollingX, !_instanceOptions.scrollingY, _instanceOptions.hwAccelerationClass, _instanceOptions.scrollbars);
// Update references as appropriate
_containerNode = offscreenNode.firstElementChild;
scrollYParent = _containerNode;
if (_instanceOptions.scrollingX) {
_scrollNodes.x = _containerNode.firstElementChild;
scrollYParent = _scrollNodes.x;
if (_instanceOptions.scrollbars) {
_scrollbarNodes.x = _containerNode.getElementsByClassName('ftscroller_scrollbarx')[0];
}
}
if (_instanceOptions.scrollingY) {
_scrollNodes.y = scrollYParent.firstElementChild;
if (_instanceOptions.scrollbars) {
_scrollbarNodes.y = _containerNode.getElementsByClassName('ftscroller_scrollbary')[0];
}
_contentParentNode = _scrollNodes.y;
} else {
_contentParentNode = _scrollNodes.x;
}
// Take the contents of the scrollable element, and copy them into the new container
while (_scrollableMasterNode.firstChild) {
_contentParentNode.appendChild(_scrollableMasterNode.firstChild);
}
// Move the wrapped elements back into the document
_scrollableMasterNode.appendChild(_containerNode);
};
/**
* Attempts to use any existing DOM scroller nodes if possible, returning true if so;
* updates all internal element references.
*/
_existingDOMValid = function _existingDOMValid() {
var scrollerContainer, layerX, layerY, yParent, scrollerX, scrollerY, candidates, i, l;
// Check that there's an initial child node, and make sure it's the container class
scrollerContainer = _scrollableMasterNode.firstElementChild;
if (!scrollerContainer || scrollerContainer.className.indexOf('ftscroller_container') === -1) {
return;
}
// If x-axis scrolling is enabled, find and verify the x scroller layer
if (_instanceOptions.scrollingX) {
// Find and verify the x scroller layer
layerX = scrollerContainer.firstElementChild;
if (!layerX || layerX.className.indexOf('ftscroller_x') === -1) {
return;
}
yParent = layerX;
// Find and verify the x scrollbar if enabled
if (_instanceOptions.scrollbars) {
candidates = scrollerContainer.getElementsByClassName('ftscroller_scrollbarx');
if (candidates) {
for (i = 0, l = candidates.length; i < l; i = i + 1) {
if (candidates[i].parentNode === scrollerContainer) {
scrollerX = candidates[i];
break;
}
}
}
if (!scrollerX) {
return;
}
}
} else {
yParent = scrollerContainer;
}
// If y-axis scrolling is enabled, find and verify the y scroller layer
if (_instanceOptions.scrollingY) {
// Find and verify the x scroller layer
layerY = yParent.firstElementChild;
if (!layerY || layerY.className.indexOf('ftscroller_y') === -1) {
return;
}
// Find and verify the y scrollbar if enabled
if (_instanceOptions.scrollbars) {
candidates = scrollerContainer.getElementsByClassName('ftscroller_scrollbary');
if (candidates) {
for (i = 0, l = candidates.length; i < l; i = i + 1) {
if (candidates[i].parentNode === scrollerContainer) {
scrollerY = candidates[i];
break;
}
}
}
if (!scrollerY) {
return;
}
}
}
// Elements found and verified - update the references and return success
_containerNode = scrollerContainer;
if (layerX) {
_scrollNodes.x = layerX;
}
if (layerY) {
_scrollNodes.y = layerY;
}
if (scrollerX) {
_scrollbarNodes.x = scrollerX;
}
if (scrollerY) {
_scrollbarNodes.y = scrollerY;
}
if (_instanceOptions.scrollingY) {
_contentParentNode = layerY;
} else {
_contentParentNode = layerX;
}
return true;
};
_domChanged = function _domChanged() {
// If the timer is active, clear it
if (_domChangeDebouncer) {
window.clearTimeout(_domChangeDebouncer);
}
// Set up the DOM changed timer
_domChangeDebouncer = setTimeout(function () {
_updateDimensions();
}, 100);
};
_updateDimensions = function _updateDimensions(ignoreSnapScroll) {
var axis;
// Only update dimensions if the container node exists (DOM elements can go away if
// the scroller instance is not destroyed correctly)
if (!_containerNode || !_contentParentNode) {
return false;
}
if (_domChangeDebouncer) {
window.clearTimeout(_domChangeDebouncer);
_domChangeDebouncer = false;
}
var containerWidth, containerHeight, startAlignments;
// If a manual scroll is in progress, cancel it
_endScroll(Date.now());
// Calculate the starting alignment for comparison later
startAlignments = { x: false, y: false };
for (axis in startAlignments) {
if (startAlignments.hasOwnProperty(axis)) {
if (_lastScrollPosition[axis] === 0) {
startAlignments[axis] = -1;
} else if (_lastScrollPosition[axis] <= _metrics.scrollEnd[axis]) {
startAlignments[axis] = 1;
} else if (_lastScrollPosition[axis] * 2 <= _metrics.scrollEnd[axis] + 5 && _lastScrollPosition[axis] * 2 >= _metrics.scrollEnd[axis] - 5) {
startAlignments[axis] = 0;
}
}
}
containerWidth = _containerNode.offsetWidth;
containerHeight = _containerNode.offsetHeight;
// Grab the dimensions
var rawScrollWidth = options.contentWidth || _contentParentNode.offsetWidth;
var rawScrollHeight = options.contentHeight || _contentParentNode.offsetHeight;
var scrollWidth = rawScrollWidth;
var scrollHeight = rawScrollHeight;
var targetPosition = { x: false, y: false };
// Update snap grid
if (!_snapGridSize.userX) {
_snapGridSize.x = containerWidth;
}
if (!_snapGridSize.userY) {
_snapGridSize.y = containerHeight;
}
// If there is a grid, conform to the grid
if (_instanceOptions.snapping) {
if (_snapGridSize.userX) {
scrollWidth = Math.ceil(scrollWidth / _snapGridSize.userX) * _snapGridSize.userX;
} else {
scrollWidth = Math.ceil(scrollWidth / _snapGridSize.x) * _snapGridSize.x;
}
if (_snapGridSize.userY) {
scrollHeight = Math.ceil(scrollHeight / _snapGridSize.userY) * _snapGridSize.userY;
} else {
scrollHeight = Math.ceil(scrollHeight / _snapGridSize.y) * _snapGridSize.y;
}
}
// If no details have changed, return.
if (_metrics.container.x === containerWidth && _metrics.container.y === containerHeight && _metrics.content.x === scrollWidth && _metrics.content.y === scrollHeight) {
return;
}
// Update the sizes
_metrics.container.x = containerWidth;
_metrics.container.y = containerHeight;
_metrics.content.x = scrollWidth;
_metrics.content.rawX = rawScrollWidth;
_metrics.content.y = scrollHeight;
_metrics.content.rawY = rawScrollHeight;
_metrics.scrollEnd.x = containerWidth - scrollWidth;
_metrics.scrollEnd.y = containerHeight - scrollHeight;
_updateScrollbarDimensions();
// Apply base alignment if appropriate
for (axis in targetPosition) {
if (targetPosition.hasOwnProperty(axis)) {
// If the container is smaller than the content, determine whether to apply the
// alignment. This occurs if a scroll has never taken place, or if the position
// was previously at the correct "end" and can be maintained.
if (_metrics.container[axis] < _metrics.content[axis]) {
if (_hasBeenScrolled && _instanceOptions.baseAlignments[axis] !== startAlignments[axis]) {
continue;
}
}
// Apply the alignment
if (_instanceOptions.baseAlignments[axis] === 1) {
targetPosition[axis] = _metrics.scrollEnd[axis];
} else if (_instanceOptions.baseAlignments[axis] === 0) {
targetPosition[axis] = Math.floor(_metrics.scrollEnd[axis] / 2);
} else if (_instanceOptions.baseAlignments[axis] === -1) {
targetPosition[axis] = 0;
}
}
}
if (_instanceOptions.scrollingX && targetPosition.x !== false) {
_setAxisPosition('x', targetPosition.x, 0);
_baseScrollPosition.x = targetPosition.x;
}
if (_instanceOptions.scrollingY && targetPosition.y !== false) {
_setAxisPosition('y', targetPosition.y, 0);
_baseScrollPosition.y = targetPosition.y;
}
// Ensure bounds are correct
if (!ignoreSnapScroll && _snapScroll()) {
_updateSegments(true);
}
};
_updateScrollbarDimensions = function _updateScrollbarDimensions() {
// Update scrollbar sizes
if (_instanceOptions.scrollbars) {
if (_instanceOptions.scrollingX) {
_scrollbarNodes.x.style.width = Math.max(6, Math.round(_metrics.container.x * (_metrics.container.x / _metrics.content.x) - 4)) + 'px';
}
if (_instanceOptions.scrollingY) {
_scrollbarNodes.y.style.height = Math.max(6, Math.round(_metrics.container.y * (_metrics.container.y / _metrics.content.y) - 4)) + 'px';
}
}
// Update scroll caches
_scrollableAxes = {};
if (_instanceOptions.scrollingX && (_metrics.content.x > _metrics.container.x || _instanceOptions.alwaysScroll)) {
_scrollableAxes.x = true;
}
if (_instanceOptions.scrollingY && (_metrics.content.y > _metrics.container.y || _instanceOptions.alwaysScroll)) {
_scrollableAxes.y = true;
}
};
_updateElementPosition = function _updateElementPosition() {
var axis, computedStyle, splitStyle;
// Retrieve the current position of each active axis.
// Custom parsing is used instead of native matrix support for speed and for
// backwards compatibility.
for (axis in _scrollableAxes) {
if (_scrollableAxes.hasOwnProperty(axis)) {
computedStyle = window.getComputedStyle(_scrollNodes[axis], null)[_vendorTransformLookup];
splitStyle = computedStyle.split(', ');
// For 2d-style transforms, pull out elements four or five
if (splitStyle.length === 6) {
_baseScrollPosition[axis] = parseInt(splitStyle[(axis === 'y') ? 5 : 4], 10);
// For 3d-style transforms, pull out elements twelve or thirteen
} else {
_baseScrollPosition[axis] = parseInt(splitStyle[(axis === 'y') ? 13 : 12], 10);
}
_lastScrollPosition[axis] = _baseScrollPosition[axis];
}
}
};
_updateSegments = function _updateSegments(scrollFinalised) {
var axis;
var newSegment = { x: 0, y: 0 };
// If snapping is disabled, return without any further action required
if (!_instanceOptions.snapping) {
return;
}
// Calculate the new segments
for (axis in _scrollableAxes) {
if (_scrollableAxes.hasOwnProperty(axis)) {
newSegment[axis] = Math.max(0, Math.min(Math.ceil(_metrics.content[axis] / _snapGridSize[axis]) - 1, Math.round(-_lastScrollPosition[axis] / _snapGridSize[axis])));
}
}
// In all cases update the active segment if appropriate
if (newSegment.x !== _activeSegment.x || newSegment.y !== _activeSegment.y) {
_activeSegment.x = newSegment.x;
_activeSegment.y = newSegment.y;
_fireEvent('segmentwillchange', { segmentX: newSegment.x, segmentY: newSegment.y });
}
// If the scroll has been finalised, also update the base segment
if (scrollFinalised) {
if (newSegment.x !== _baseSegment.x || newSegment.y !== _baseSegment.y) {
_baseSegment.x = newSegment.x;
_baseSegment.y = newSegment.y;
_fireEvent('segmentdidchange', { segmentX: newSegment.x, segmentY: newSegment.y });
}
}
};
_setAxisPosition = function _setAxisPosition(axis, position, animationDuration, animationBezier, boundsCrossDelay) {
var transitionCSSString, newPositionAtExtremity = null;
// Only update position if the axis node exists (DOM elements can go away if
// the scroller instance is not destroyed correctly)
if (!_scrollNodes[axis]) {
return false;
}
// Determine the transition property to apply to both the scroll element and the scrollbar
if (animationDuration) {
if (!animationBezier) {
animationBezier = _kFlingTruncatedBezier;
}
transitionCSSString = _vendorCSSPrefix + 'transform ' + animationDuration + 'ms ' + animationBezier.toString();
} else {
transitionCSSString = '';
}
// Apply the transition property to elements
_scrollNodes[axis].style[_transitionProperty] = transitionCSSString;
if (_instanceOptions.scrollbars) {
_scrollbarNodes[axis].style[_transitionProperty] = transitionCSSString;
}
// Update the positions
_scrollNodes[axis].style[_transformProperty] = _translateRulePrefix + _transformPrefixes[axis] + position + 'px' + _transformSuffixes[axis];
if (_instanceOptions.scrollbars) {
_scrollbarNodes[axis].style[_transformProperty] = _translateRulePrefix + _transformPrefixes[axis] + (-position * _metrics.container[axis] / _metrics.content[axis]) + 'px' + _transformSuffixes[axis];
}
// Determine whether the scroll is at an extremity.
if (position >= 0) {
newPositionAtExtremity = 'start';
} else if (position <= _metrics.scrollEnd[axis]) {
newPositionAtExtremity = 'end';
}
// If the extremity status has changed, fire an appropriate event
if (newPositionAtExtremity !== _scrollAtExtremity[axis]) {
if (newPositionAtExtremity !== null) {
if (animationDuration) {
_timeouts.push(setTimeout(function() {
_fireEvent('reached' + newPositionAtExtremity, { axis: axis });
}, boundsCrossDelay || animationDuration));
} else {
_fireEvent('reached' + newPositionAtExtremity, { axis: axis });
}
}
_scrollAtExtremity[axis] = newPositionAtExtremity;
}
// Update the recorded position if there's no duration
if (!animationDuration) {
_lastScrollPosition[axis] = position;
}
};
_scheduleAxisPosition = function _scheduleAxisPosition(axis, position, animationDuration, animationBezier, afterDelay) {
_timeouts.push(setTimeout(function () {
_setAxisPosition(axis, position, animationDuration, animationBezier);
}, afterDelay));
};
_fireEvent = function _fireEvent(eventName, eventObject) {
var i, l;
eventObject.srcObject = _publicSelf;
// Iterate through any listeners
for (i = 0, l = _eventListeners[eventName].length; i < l; i = i + 1) {
// Execute each in a try/catch
try {
_eventListeners[eventName][i](eventObject);
} catch (error) {
if (window.console && window.console.error) {
window.console.error(error.message + ' (' + error.sourceURL + ', line ' + error.line + ')');
}
}
}
};
/**
* Update the scroll position so that the child element is in view.
*/
_childFocused = function _childFocused(event) {
var offset, axis;
var focusedNodeRect = _getBoundingRect(event.target);
var containerRect = _getBoundingRect(_containerNode);
var edgeMap = { x: 'left', y: 'top' };
var dimensionMap = { x: 'width', y: 'height' };
// If an input is currently being tracked, ignore the focus event
if (_inputIdentifier !== false) {
return;
}
for (axis in _scrollableAxes) {
if (_scrollableAxes.hasOwnProperty(axis)) {
// Set the target offset to be in the middle of the container, or as close as bounds permit
offset = -Math.round((focusedNodeRect[dimensionMap[axis]] / 2) - _lastScrollPosition[axis] + focusedNodeRect[edgeMap[axis]] - containerRect[edgeMap[axis]] - (containerRect[dimensionMap[axis]] / 2));
offset = Math.min(0, Math.max(_metrics.scrollEnd[axis], offset));
// Perform the scroll
_setAxisPosition(axis, offset, 0);
_baseScrollPosition[axis] = offset;
}
}
};
/**
* Given a relative distance beyond the element bounds, returns a modified version to
* simulate bouncy/springy edges.
*/
_modifyDistanceBeyondBounds = function _modifyDistanceBeyondBounds(distance, axis) {
if (!_instanceOptions.bouncing) {
return 0;
}
var e = Math.exp(distance / _metrics.container[axis]);
return Math.round(_metrics.container[axis] * 0.6 * (e - 1) / (e + 1));
};
/**
* Given positions for each enabled axis, returns an object showing how far each axis is beyond
* bounds. If within bounds, -1 is returned; if at the bounds, 0 is returned.
*/
_distancesBeyondBounds = function _distancesBeyondBounds(positions) {
var axis, position;
var distances = {};
for (axis in positions) {
if (positions.hasOwnProperty(axis)) {
position = positions[axis];
// If the position is to the left/top, no further modification required
if (position >= 0) {
distances[axis] = position;
// If it's within the bounds, use -1
} else if (position > _metrics.scrollEnd[axis]) {
distances[axis] = -1;
// Otherwise, amend by the distance of the maximum edge
} else {
distances[axis] = _metrics.scrollEnd[axis] - position;
}
}
}
return distances;
};
/**
* On platforms which support it, use RequestAnimationFrame to group
* position updates for speed. Starts the render process.
*/
_startAnimation = function _startAnimation() {
if (_reqAnimationFrame) {
_cancelAnimation();
_animationFrameRequest = _reqAnimationFrame(_scheduleRender);
}
};
/**
* On platforms which support RequestAnimationFrame, provide the rendering loop.
* Takes two arguments; the first is the render/position update function to
* be called, and the second is a string controlling the render type to
* allow previous changes to be cancelled - should be 'pan' or 'scroll'.
*/
_scheduleRender = function _scheduleRender() {
var axis;
// Request the next update at once
_animationFrameRequest = _reqAnimationFrame(_scheduleRender);
// Perform the draw.
for (axis in _scrollableAxes) {
if (_scrollableAxes.hasOwnProperty(axis) && _animationTargetPosition[axis] !== _lastScrollPosition[axis]) {
_setAxisPosition(axis, _animationTargetPosition[axis]);
}
}
};
/**
* Stops the animation process.
*/
_cancelAnimation = function _cancelAnimation() {
if (_animationFrameRequest === false || !_cancelAnimationFrame) {
return;
}
_cancelAnimationFrame(_animationFrameRequest);
_animationFrameRequest = false;
};
/**
* Register or unregister event handlers as appropriate
*/
_toggleEventHandlers = function _toggleEventHandlers(enable) {
var MutationObserver;
// Only remove the event if the node exists (DOM elements can go away)
if (!_containerNode) {
return;
}
if (enable) {
_containerNode._ftscrollerToggle = _containerNode.addEventListener;
} else {
_containerNode._ftscrollerToggle = _containerNode.removeEventListener;
}
if (_trackPointerEvents) {
_containerNode._ftscrollerToggle('MSPointerDown', _onPointerDown, true);
_containerNode._ftscrollerToggle('MSPointerMove', _onPointerMove, true);
_containerNode._ftscrollerToggle('MSPointerUp', _onPointerUp, true);
_containerNode._ftscrollerToggle('MSPointerCancel', _onPointerCancel, true);
} else if (_trackTouchEvents) {
_containerNode._ftscrollerToggle('touchstart', _onTouchStart, true);
_containerNode._ftscrollerToggle('touchmove', _onTouchMove, true);
_containerNode._ftscrollerToggle('touchend', _onTouchEnd, true);
_containerNode._ftscrollerToggle('touchcancel', _onTouchEnd, true);
} else {
_containerNode._ftscrollerToggle('mousedown', _onMouseDown, true);
if (!enable) {
document.removeEventListener('mousemove', _onMouseMove, true);
document.removeEventListener('mouseup', _onMouseUp, true);
}
}
_containerNode._ftscrollerToggle('DOMMouseScroll', _onMouseScroll, false);
_containerNode._ftscrollerToggle('mousewheel', _onMouseScroll, false);
// Add a click listener. On IE, add the listener to the document, to allow
// clicks to be cancelled if a scroll ends outside the bounds of the container; on
// other platforms, add to the container node.
if (_trackPointerEvents) {
if (enable) {
document.addEventListener('click', _onClick, true);
} else {
document.removeEventListener('click', _onClick, true);
}
} else {
_containerNode._ftscrollerToggle('click', _onClick, true);
}
// Watch for changes inside the contained element to update bounds - de-bounced slightly.
if (enable) {
_contentParentNode.addEventListener('focus', _childFocused, true);
if (_instanceOptions.updateOnChanges) {
// Try and reuse the old, disconnected observer instance if available
// Otherwise, check for support before proceeding
if (!_mutationObserver) {
MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window[_vendorStylePropertyPrefix + 'MutationObserver'];
if (MutationObserver) {
_mutationObserver = new MutationObserver(_domChanged);
}
}
if (_mutationObserver) {
_mutationObserver.observe(_contentParentNode, {
childList: true,
characterData: true,
subtree: true
});
} else {
_contentParentNode.addEventListener('DOMSubtreeModified', function (e) {
// Ignore changes to nested FT Scrollers - even updating a transform style
// can trigger a DOMSubtreeModified in IE, causing nested scrollers to always
// favour the deepest scroller as parent scrollers 'resize'/end scrolling.
if (e && (e.srcElement === _contentParentNode || e.srcElement.className.indexOf('ftscroller_') !== -1)) {
return;
}
_domChanged();
}, true);
}
_contentParentNode.addEventListener('load', _domChanged, true);
}
if (_instanceOptions.updateOnWindowResize) {
window.addEventListener('resize', _domChanged, true);
}
} else {
_contentParentNode.removeEventListener('focus', _childFocused, true);
if (_mutationObserver) {
_mutationObserver.disconnect();
} else {
_contentParentNode.removeEventListener('DOMSubtreeModified', _domChanged, true);
}
_contentParentNode.removeEventListener('load', _domChanged, true);
window.removeEventListener('resize', _domChanged, true);
}
delete _containerNode._ftscrollerToggle;
};
/**
* Touch event handlers
*/
_onTouchStart = function _onTouchStart(startEvent) {
var i, l, touchEvent;
// If a touch is already active, ensure that the index
// is mapped to the correct finger, and return.
if (_inputIdentifier) {
for (i = 0, l = startEvent.touches.length; i < l; i = i + 1) {
if (startEvent.touches[i].identifier === _inputIdentifier) {
_inputIndex = i;
}
}
return;
}
// Track the new touch's identifier, reset index, and pass
// the coordinates to the scroll start function.
touchEvent = startEvent.touches[0];
_inputIdentifier = touchEvent.identifier;
_inputIndex = 0;
_startScroll(touchEvent.clientX, touchEvent.clientY, startEvent.timeStamp, startEvent);
};
_onTouchMove = function _onTouchMove(moveEvent) {
if (_inputIdentifier === false) {
return;
}
// Get the coordinates from the appropriate touch event and
// pass them on to the scroll handler
var touchEvent = moveEvent.touches[_inputIndex];
_updateScroll(touchEvent.clientX, touchEvent.clientY, moveEvent.timeStamp, moveEvent);
};
_onTouchEnd = function _onTouchEnd(endEvent) {
var i, l;
// Check whether the original touch event is still active,
// if it is, update the index and return.
if (endEvent.touches) {
for (i = 0, l = endEvent.touches.length; i < l; i = i + 1) {
if (endEvent.touches[i].identifier === _inputIdentifier) {
_inputIndex = i;
return;
}
}
}
// Complete the scroll. Note that touch end events
// don't capture coordinates.
_endScroll(endEvent.timeStamp, endEvent);
};
/**
* Mouse event handlers
*/
_onMouseDown = function _onMouseDown(startEvent) {
// Don't track the right mouse buttons, or a context menu
if ((startEvent.button && startEvent.button === 2) || startEvent.ctrlKey) {
return;
}
// Capture if possible
if (_containerNode.setCapture) {
_containerNode.setCapture();
}
// Add move & up handlers to the *document* to allow handling outside the element
document.addEventListener('mousemove', _onMouseMove, true);
document.addEventListener('mouseup', _onMouseUp, true);
_inputIdentifier = startEvent.button || 1;
_inputIndex = 0;
_startScroll(startEvent.clientX, startEvent.clientY, startEvent.timeStamp, startEvent);
};
_onMouseMove = function _onMouseMove(moveEvent) {
if (!_inputIdentifier) {
return;
}
_updateScroll(moveEvent.clientX, moveEvent.clientY, moveEvent.timeStamp, moveEvent);
};
_onMouseUp = function _onMouseUp(endEvent) {
if (endEvent.button && endEvent.button !== _inputIdentifier) {
return;
}
document.removeEventListener('mousemove', _onMouseMove, true);
document.removeEventListener('mouseup', _onMouseUp, true);
// Release capture if possible
if (_containerNode.releaseCapture) {
_containerNode.releaseCapture();
}
_endScroll(endEvent.timeStamp, endEvent);
};
/**
* Pointer event handlers
*/
_onPointerDown = function _onPointerDown(startEvent) {
// If there is already a pointer event being tracked, ignore subsequent.
if (_inputIdentifier) {
return;
}
_inputIdentifier = startEvent.pointerId;
_captureInput();
_startScroll(startEvent.clientX, startEvent.clientY, startEvent.timeStamp, startEvent);
};
_onPointerMove = function _onPointerMove(moveEvent) {
if (_inputIdentifier !== moveEvent.pointerId) {
return;
}
_updateScroll(moveEvent.clientX, moveEvent.clientY, moveEvent.timeStamp, moveEvent);
};
_onPointerUp = function _onPointerUp(endEvent) {
if (_inputIdentifier !== endEvent.pointerId) {
return;
}
_endScroll(endEvent.timeStamp, endEvent);
};
_onPointerCancel = function _onPointerCancel(endEvent) {
_endScroll(endEvent.timeStamp, endEvent);
};
_onPointerCaptureEnd = function _onPointerCaptureEnd(event) {
_endScroll(event.timeStamp, event);
};
/**
* Prevents click actions if appropriate
*/
_onClick = function _onClick(clickEvent) {
// If a scroll action hasn't resulted in the next scroll being prevented, and a scroll
// isn't currently in progress with a different identifier, allow the click
if (!_preventClick && !_inputIdentifier) {
return true;
}
// Prevent clicks using the preventDefault() and stopPropagation() handlers on the event;
// this is safe even in IE10 as this is always a "true" event, never a window.event.
clickEvent.preventDefault();
clickEvent.stopPropagation();
if (!_inputIdentifier) {
_preventClick = false;
}
return false;
};
/**
* Process scroll wheel/input actions as scroller scrolls
*/
_onMouseScroll = function _onMouseScroll(event) {
var scrollDeltaX, scrollDeltaY;
if (_inputIdentifier !== 'scrollwheel') {
if (_inputIdentifier !== false) {
return true;
}
_inputIdentifier = 'scrollwheel';
_cumulativeScroll.x = 0;
_cumulativeScroll.y = 0;
// Start a scroll event
if (!_startScroll(event.clientX, event.clientY, Date.now(), event)) {
return;
}
}
// Convert the scrollwheel values to a scroll value
if (event.wheelDelta) {
if (event.wheelDeltaX) {
scrollDeltaX = event.wheelDeltaX / 2;
scrollDeltaY = event.wheelDeltaY / 2;
} else {
scrollDeltaX = 0;
scrollDeltaY = event.wheelDelta / 2;
}
} else {
if (event.axis && event.axis === event.HORIZONTAL_AXIS) {
scrollDeltaX = event.detail * -10;
scrollDeltaY = 0;
} else {
scrollDeltaX = 0;
scrollDeltaY = event.detail * -10;
}
}
// If the scroller is constrained to an x axis, convert y scroll to allow single-axis scroll
// wheels to scroll constrained content.
if (!_instanceOptions.scrollingY && !scrollDeltaX) {
scrollDeltaX = scrollDeltaY;
scrollDeltaY = 0;
}
_cumulativeScroll.x = Math.round(_cumulativeScroll.x + scrollDeltaX);
_cumulativeScroll.y = Math.round(_cumulativeScroll.y + scrollDeltaY);
_updateScroll(_gestureStart.x + _cumulativeScroll.x, _gestureStart.y + _cumulativeScroll.y, event.timeStamp, event);
// End scrolling state
if (_scrollWheelEndDebouncer) {
clearTimeout(_scrollWheelEndDebouncer);
}
_scrollWheelEndDebouncer = setTimeout(function () {
_inputIdentifier = false;
_releaseInputCapture();
_isScrolling = false;
_isDisplayingScroll = false;
_ftscrollerMoving = false;
if (_instanceOptions.windowScrollingActiveFlag) {
window[_instanceOptions.windowScrollingActiveFlag] = false;
}
_cancelAnimation();
if (!_snapScroll()) {
_finalizeScroll();
}
}, 300);
};
/**
* Capture and release input support, particularly allowing tracking
* of Metro pointers outside the docked view.
*/
_captureInput = function _captureInput() {
if (_inputCaptured || _inputIdentifier === false || _inputIdentifier === 'scrollwheel') {
return;
}
if (_trackPointerEvents) {
_containerNode.msSetPointerCapture(_inputIdentifier);
_containerNode.addEventListener('MSLostPointerCapture', _onPointerCaptureEnd, false);
}
_inputCaptured = true;
};
_releaseInputCapture = function _releaseInputCapture() {
if (!_inputCaptured) {
return;
}
if (_trackPointerEvents) {
_containerNode.removeEventListener('MSLostPointerCapture', _onPointerCaptureEnd, false);
_containerNode.msReleasePointerCapture(_inputIdentifier);
}
_inputCaptured = false;
};
/**
* Utility function acting as a getBoundingClientRect polyfill.
*/
_getBoundingRect = function _getBoundingRect(anElement) {
if (anElement.getBoundingClientRect) {
return anElement.getBoundingClientRect();
}
var x = 0, y = 0, eachElement = anElement;
while (eachElement) {
x = x + eachElement.offsetLeft - eachElement.scrollLeft;
y = y + eachElement.offsetTop - eachElement.scrollTop;
eachElement = eachElement.offsetParent;
}
return { left: x, top: y, width: anElement.offsetWidth, height: anElement.offsetHeight };
};
/* Instantiation */
// Set up the DOM node if appropriate
_initializeDOM();
// Update sizes
_updateDimensions();
// Set up the event handlers
_toggleEventHandlers(true);
// Define a public API to be returned at the bottom - this is the public-facing interface.
_publicSelf = {
destroy: destroy,
setSnapSize: setSnapSize,
scrollTo: scrollTo,
scrollBy: scrollBy,
updateDimensions: updateDimensions,
addEventListener: addEventListener,
removeEventListener: removeEventListener,
get scrollHeight () { return _metrics.content.y; },
set scrollHeight (value) { throw new SyntaxError('scrollHeight is currently read-only - ignoring ' + value); },
get scrollLeft () { return -_lastScrollPosition.x; },
set scrollLeft (value) { scrollTo(value, false, false); return -_lastScrollPosition.x; },
get scrollTop () { return -_lastScrollPosition.y; },
set scrollTop (value) { scrollTo(false, value, false); return -_lastScrollPosition.y; },
get scrollWidth () { return _metrics.content.x; },
set scrollWidth (value) { throw new SyntaxError('scrollWidth is currently read-only - ignoring ' + value); },
get segmentCount () {
if (!_instanceOptions.snapping) {
return { x: NaN, y: NaN };
}
return {
x: Math.ceil(_metrics.content.x / _snapGridSize.x),
y: Math.ceil(_metrics.content.y / _snapGridSize.y)
};
},
set segmentCount (value) { throw new SyntaxError('segmentCount is currently read-only - ignoring ' + value); },
get currentSegment () { return { x: _activeSegment.x, y: _activeSegment.y }; },
set currentSegment (value) { throw new SyntaxError('currentSegment is currently read-only - ignoring ' + value); },
get contentContainerNode () { return _contentParentNode; },
set contentContainerNode (value) { throw new SyntaxError('contentContainerNode is currently read-only - ignoring ' + value); }
};
// Return the public interface.
return _publicSelf;
};
/* Prototype Functions and Properties */
/**
* The HTML to prepend to the scrollable content to wrap it. Used internally,
* and may be used to pre-wrap scrollable content. Axes can optionally
* be excluded for speed improvements.
*/
FTScroller.prototype.getPrependedHTML = function (excludeXAxis, excludeYAxis, hwAccelerationClass) {
if (!hwAccelerationClass) {
if (typeof FTScrollerOptions === 'object' && FTScrollerOptions.hwAccelerationClass) {
hwAccelerationClass = FTScrollerOptions.hwAccelerationClass;
} else {
hwAccelerationClass = 'ftscroller_hwaccelerated';
}
}
var output = '<div class="ftscroller_container">';
if (!excludeXAxis) {
output += '<div class="ftscroller_x ' + hwAccelerationClass + '">';
}
if (!excludeYAxis) {
output += '<div class="ftscroller_y ' + hwAccelerationClass + '">';
}
return output;
};
/**
* The HTML to append to the scrollable content to wrap it; again, used internally,
* and may be used to pre-wrap scrollable content.
*/
FTScroller.prototype.getAppendedHTML = function (excludeXAxis, excludeYAxis, hwAccelerationClass, scrollbars) {
if (!hwAccelerationClass) {
if (typeof FTScrollerOptions === 'object' && FTScrollerOptions.hwAccelerationClass) {
hwAccelerationClass = FTScrollerOptions.hwAccelerationClass;
} else {
hwAccelerationClass = 'ftscroller_hwaccelerated';
}
}
var output = '';
if (!excludeXAxis) {
output += '</div>';
}
if (!excludeYAxis) {
output += '</div>';
}
if (scrollbars) {
if (!excludeXAxis) {
output += '<div class="ftscroller_scrollbar ftscroller_scrollbarx ' + hwAccelerationClass + '"><div class="ftscroller_scrollbarinner"></div></div>';
}
if (!excludeYAxis) {
output += '<div class="ftscroller_scrollbar ftscroller_scrollbary ' + hwAccelerationClass + '"><div class="ftscroller_scrollbarinner"></div></div>';
}
}
output += '</div>';
return output;
};
}());
(function () {
'use strict';
/**
* Represents a two-dimensional cubic bezier curve with the starting
* point (0, 0) and the end point (1, 1). The two control points p1 and p2
* have x and y coordinates between 0 and 1.
*
* This type of bezier curves can be used as CSS transform timing functions.
*/
CubicBezier = function (p1x, p1y, p2x, p2y) {
if (!(p1x >= 0 && p1x <= 1)) {
throw new RangeError('"p1x" must be a number between 0 and 1. ' + 'Got ' + p1x + 'instead.');
}
if (!(p1y >= 0 && p1y <= 1)) {
throw new RangeError('"p1y" must be a number between 0 and 1. ' + 'Got ' + p1y + 'instead.');
}
if (!(p2x >= 0 && p2x <= 1)) {
throw new RangeError('"p2x" must be a number between 0 and 1. ' + 'Got ' + p2x + 'instead.');
}
if (!(p2y >= 0 && p2y <= 1)) {
throw new RangeError('"p2y" must be a number between 0 and 1. ' + 'Got ' + p2y + 'instead.');
}
// Control points
this._p1 = { x: p1x, y: p1y };
this._p2 = { x: p2x, y: p2y };
};
CubicBezier.prototype._getCoordinateForT = function (t, p1, p2) {
var c = 3 * p1,
b = 3 * (p2 - p1) - c,
a = 1 - c - b;
return ((a * t + b) * t + c) * t;
};
CubicBezier.prototype._getCoordinateDerivateForT = function (t, p1, p2) {
var c = 3 * p1,
b = 3 * (p2 - p1) - c,
a = 1 - c - b;
return (3 * a * t + 2 * b) * t + c;
};
CubicBezier.prototype._getTForCoordinate = function (c, p1, p2, epsilon) {
if (!isFinite(epsilon) || epsilon <= 0) {
throw new RangeError('"epsilon" must be a number greater than 0.');
}
var t2, i, c2, d2;
// First try a few iterations of Newton's method -- normally very fast.
for (t2 = c, i = 0; i < 8; i = i + 1) {
c2 = this._getCoordinateForT(t2, p1, p2) - c;
if (Math.abs(c2) < epsilon) {
return t2;
}
d2 = this._getCoordinateDerivateForT(t2, p1, p2);
if (Math.abs(d2) < 1e-6) {
break;
}
t2 = t2 - c2 / d2;
}
// Fall back to the bisection method for reliability.
t2 = c;
var t0 = 0,
t1 = 1;
if (t2 < t0) {
return t0;
}
if (t2 > t1) {
return t1;
}
while (t0 < t1) {
c2 = this._getCoordinateForT(t2, p1, p2);
if (Math.abs(c2 - c) < epsilon) {
return t2;
}
if (c > c2) {
t0 = t2;
} else {
t1 = t2;
}
t2 = (t1 - t0) * 0.5 + t0;
}
// Failure.
return t2;
};
/**
* Computes the point for a given t value.
*
* @param {number} t
* @returns {Object} Returns an object with x and y properties
*/
CubicBezier.prototype.getPointForT = function (t) {
// Special cases: starting and ending points
if (t === 0 || t === 1) {
return { x: t, y: t };
}
// Check for correct t value (must be between 0 and 1)
if (t < 0 || t > 1) {
throw new RangeError('"t" must be a number between 0 and 1' + 'Got ' + t + ' instead.');
}
return {
x: this._getCoordinateForT(t, this._p1.x, this._p2.x),
y: this._getCoordinateForT(t, this._p1.y, this._p2.y)
};
};
CubicBezier.prototype.getTForX = function (x, epsilon) {
return this._getTForCoordinate(x, this._p1.x, this._p2.x, epsilon);
};
CubicBezier.prototype.getTForY = function (y, epsilon) {
return this._getTForCoordinate(y, this._p1.y, this._p2.y, epsilon);
};
/**
* Computes auxiliary points using De Casteljau's algorithm.
*
* @param {number} t must be greater than 0 and lower than 1.
* @returns {Object} with members i0, i1, i2 (first iteration),
* j1, j2 (second iteration) and k (the exact point for t)
*/
CubicBezier.prototype._getAuxPoints = function (t) {
if (t <= 0 || t >= 1) {
throw new RangeError('"t" must be greater than 0 and lower than 1');
}
/* First series of auxiliary points */
// First control point of the left curve
var i0 = {
x: t * this._p1.x,
y: t * this._p1.y
},
i1 = {
x: this._p1.x + t * (this._p2.x - this._p1.x),
y: this._p1.y + t * (this._p2.y - this._p1.y)
},
// Second control point of the right curve
i2 = {
x: this._p2.x + t * (1 - this._p2.x),
y: this._p2.y + t * (1 - this._p2.y)
};
/* Second series of auxiliary points */
// Second control point of the left curve
var j0 = {
x: i0.x + t * (i1.x - i0.x),
y: i0.y + t * (i1.y - i0.y)
},
// First control point of the right curve
j1 = {
x: i1.x + t * (i2.x - i1.x),
y: i1.y + t * (i2.y - i1.y)
};
// The division point (ending point of left curve, starting point of right curve)
var k = {
x: j0.x + t * (j1.x - j0.x),
y: j0.y + t * (j1.y - j0.y)
};
return {
i0: i0,
i1: i1,
i2: i2,
j0: j0,
j1: j1,
k: k
};
};
/**
* Divides the bezier curve into two bezier functions.
*
* De Casteljau's algorithm is used to compute the new starting, ending, and
* control points.
*
* @param {number} t must be greater than 0 and lower than 1.
* t === 1 or t === 0 are the starting/ending points of the curve, so no
* division is needed.
*
* @returns {CubicBezier[]} Returns an array containing two bezier curves
* to the left and the right of t.
*/
CubicBezier.prototype.divideAtT = function (t) {
if (t < 0 || t > 1) {
throw new RangeError('"t" must be a number between 0 and 1. ' + 'Got ' + t + ' instead.');
}
// Special cases t = 0, t = 1: Curve can be cloned for one side, the other
// side is a linear curve (with duration 0)
if (t === 0 || t === 1) {
var curves = [];
curves[t] = CubicBezier.linear();
curves[1 - t] = this.clone();
return curves;
}
var left = {},
right = {},
points = this._getAuxPoints(t);
var i0 = points.i0,
i2 = points.i2,
j0 = points.j0,
j1 = points.j1,
k = points.k;
// Normalize derived points, so that the new curves starting/ending point
// coordinates are (0, 0) respectively (1, 1)
var factorX = k.x,
factorY = k.y;
left.p1 = {
x: i0.x / factorX,
y: i0.y / factorY
};
left.p2 = {
x: j0.x / factorX,
y: j0.y / factorY
};
right.p1 = {
x: (j1.x - factorX) / (1 - factorX),
y: (j1.y - factorY) / (1 - factorY)
};
right.p2 = {
x: (i2.x - factorX) / (1 - factorX),
y: (i2.y - factorY) / (1 - factorY)
};
return [
new CubicBezier(left.p1.x, left.p1.y, left.p2.x, left.p2.y),
new CubicBezier(right.p1.x, right.p1.y, right.p2.x, right.p2.y)
];
};
CubicBezier.prototype.divideAtX = function (x, epsilon) {
if (x < 0 || x > 1) {
throw new RangeError('"x" must be a number between 0 and 1. ' + 'Got ' + x + ' instead.');
}
var t = this.getTForX(x, epsilon);
return this.divideAtT(t);
};
CubicBezier.prototype.divideAtY = function (y, epsilon) {
if (y < 0 || y > 1) {
throw new RangeError('"y" must be a number between 0 and 1. ' + 'Got ' + y + ' instead.');
}
var t = this.getTForY(y, epsilon);
return this.divideAtT(t);
};
CubicBezier.prototype.clone = function () {
return new CubicBezier(this._p1.x, this._p1.y, this._p2.x, this._p2.y);
};
CubicBezier.prototype.toString = function () {
return "cubic-bezier(" + [
this._p1.x,
this._p1.y,
this._p2.x,
this._p2.y
].join(", ") + ")";
};
CubicBezier.linear = function () {
return new CubicBezier();
};
CubicBezier.ease = function () {
return new CubicBezier(0.25, 0.1, 0.25, 1.0);
};
CubicBezier.linear = function () {
return new CubicBezier(0.0, 0.0, 1.0, 1.0);
};
CubicBezier.easeIn = function () {
return new CubicBezier(0.42, 0, 1.0, 1.0);
};
CubicBezier.easeOut = function () {
return new CubicBezier(0, 0, 0.58, 1.0);
};
CubicBezier.easeInOut = function () {
return new CubicBezier(0.42, 0, 0.58, 1.0);
};
}());
// If a CommonJS environment is present, add our exports; make the check in a jslint-compatible method.
if (typeof module === 'object' && module.exports) {
module.exports = function(domNode, options) {
'use strict';
return new FTScroller(domNode, options);
};
module.exports.FTScroller = FTScroller;
module.exports.CubicBezier = CubicBezier;
} | froala/cdnjs | ajax/libs/ftscroller/0.2.0/ftscroller.js | JavaScript | mit | 91,839 |
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getTableBodyUtilityClass = getTableBodyUtilityClass;
exports.default = void 0;
var _unstyled = require("@material-ui/unstyled");
function getTableBodyUtilityClass(slot) {
return (0, _unstyled.generateUtilityClass)('MuiTableBody', slot);
}
const tableBodyClasses = (0, _unstyled.generateUtilityClasses)('MuiTableBody', ['root']);
var _default = tableBodyClasses;
exports.default = _default; | cdnjs/cdnjs | ajax/libs/material-ui/5.0.0-beta.5/node/TableBody/tableBodyClasses.js | JavaScript | mit | 482 |
/* */
var $def = require("./$.def"),
$entries = require("./$.object-to-array")(true);
$def($def.S, 'Object', {entries: function entries(it) {
return $entries(it);
}});
| jasminZ/sequenceserver | public/vendor/npm/core-js@1.1.2/modules/es7.object.entries.js | JavaScript | agpl-3.0 | 179 |
// META: script=/service-workers/service-worker/resources/test-helpers.sub.js
// META: script=resources/utils.js
'use strict';
// "If parsedURL includes credentials, then throw a TypeError."
// https://fetch.spec.whatwg.org/#dom-request
// (Added by https://github.com/whatwg/fetch/issues/26).
// "A URL includes credentials if its username or password is not the empty
// string."
// https://url.spec.whatwg.org/#include-credentials
backgroundFetchTest((t, bgFetch) => {
return bgFetch.fetch(uniqueTag(), 'https://example.com');
}, 'fetch without credentials in URL should register ok');
backgroundFetchTest((t, bgFetch) => {
return promise_rejects(
t, new TypeError(),
bgFetch.fetch(uniqueTag(), 'https://username:password@example.com'));
}, 'fetch with username and password in URL should reject');
backgroundFetchTest((t, bgFetch) => {
return promise_rejects(
t, new TypeError(),
bgFetch.fetch(uniqueTag(), 'https://username:@example.com'));
}, 'fetch with username and empty password in URL should reject');
backgroundFetchTest((t, bgFetch) => {
return promise_rejects(
t, new TypeError(),
bgFetch.fetch(uniqueTag(), 'https://:password@example.com'));
}, 'fetch with empty username and password in URL should reject');
| anthgur/servo | tests/wpt/web-platform-tests/background-fetch/credentials-in-url.https.window.js | JavaScript | mpl-2.0 | 1,273 |
var assert = require('assert');
var R = require('..');
describe('mapObjIndexed', function() {
var times2 = function(x) {return x * 2;};
var addIndexed = function(x, key) {return x + key;};
var squareVowels = function(x, key) {
var vowels = ['a', 'e', 'i', 'o', 'u'];
return R.contains(key, vowels) ? x * x : x;
};
it('works just like a normal mapObj', function() {
assert.deepEqual(R.mapObjIndexed(times2, {a: 1, b: 2, c: 3, d: 4}), {a: 2, b: 4, c: 6, d: 8});
});
it('passes the index as a second parameter to the callback', function() {
assert.deepEqual(R.mapObjIndexed(addIndexed, {a: 8, b: 6, c: 7, d: 5, e: 3, f: 0, g: 9}),
{a: '8a', b: '6b', c: '7c', d: '5d', e: '3e', f: '0f', g: '9g'});
});
it('passes the entire list as a third parameter to the callback', function() {
assert.deepEqual(R.mapObjIndexed(squareVowels, {a: 8, b: 6, c: 7, d: 5, e: 3, f: 0, g: 9}),
{a: 64, b: 6, c: 7, d: 5, e: 9, f: 0, g: 9});
});
it('is curried', function() {
var makeSquareVowels = R.mapObjIndexed(squareVowels);
assert.deepEqual(makeSquareVowels({a: 8, b: 6, c: 7, d: 5, e: 3, f: 0, g: 9}),
{a: 64, b: 6, c: 7, d: 5, e: 9, f: 0, g: 9});
});
});
| syves/ramda | test/mapObjIndexed.js | JavaScript | mit | 1,258 |
var convert = require('./convert'),
func = convert('wrapperLodash', require('../wrapperLodash'), require('./_falseOptions'));
func.placeholder = require('./placeholder');
module.exports = func;
| Moccine/global-service-plus.com | web/libariries/bootstrap/node_modules/zip-stream/node_modules/lodash/fp/wrapperLodash.js | JavaScript | mit | 204 |
/*
YUI 3.5.1 (build 22)
Copyright 2012 Yahoo! Inc. All rights reserved.
Licensed under the BSD License.
http://yuilibrary.com/license/
*/
YUI.add('sortable', function(Y) {
/**
* The class allows you to create a Drag & Drop reordered list.
* @module sortable
*/
/**
* The class allows you to create a Drag & Drop reordered list.
* @class Sortable
* @extends Base
* @constructor
*/
var Sortable = function(o) {
Sortable.superclass.constructor.apply(this, arguments);
},
CURRENT_NODE = 'currentNode',
OPACITY_NODE = 'opacityNode',
CONT = 'container',
ID = 'id',
ZINDEX = 'zIndex',
OPACITY = 'opacity',
PARENT_NODE = 'parentNode',
NODES = 'nodes',
NODE = 'node';
Y.extend(Sortable, Y.Base, {
/**
* @property delegate
* @type DD.Delegate
* @description A reference to the DD.Delegate instance.
*/
delegate: null,
initializer: function() {
var id = 'sortable-' + Y.guid(), c,
delConfig = {
container: this.get(CONT),
nodes: this.get(NODES),
target: true,
invalid: this.get('invalid'),
dragConfig: {
groups: [ id ]
}
}, del;
if (this.get('handles')) {
delConfig.handles = this.get('handles');
}
del = new Y.DD.Delegate(delConfig);
this.set(ID, id);
del.dd.plug(Y.Plugin.DDProxy, {
moveOnEnd: false,
cloneNode: true
});
c = new Y.DD.Drop({
node: this.get(CONT),
bubbleTarget: del,
groups: del.dd.get('groups')
}).on('drop:over', Y.bind(this._onDropOver, this));
del.on({
'drag:start': Y.bind(this._onDragStart, this),
'drag:end': Y.bind(this._onDragEnd, this),
'drag:over': Y.bind(this._onDragOver, this),
'drag:drag': Y.bind(this._onDrag, this)
});
this.delegate = del;
Sortable.reg(this);
},
_up: null,
_y: null,
_onDrag: function(e) {
if (e.pageY < this._y) {
this._up = true;
} else if (e.pageY > this._y) {
this._up = false;
}
this._y = e.pageY;
},
/**
* @private
* @method _onDropOver
* @param Event e The Event Object
* @description Handles the DropOver event to append a drop node to an empty target
*/
_onDropOver: function(e) {
if (!e.drop.get(NODE).test(this.get(NODES))) {
var nodes = e.drop.get(NODE).all(this.get(NODES));
if (nodes.size() === 0) {
e.drop.get(NODE).append(e.drag.get(NODE));
}
}
},
/**
* @private
* @method _onDragOver
* @param Event e The Event Object
* @description Handles the DragOver event that moves the object in the list or to another list.
*/
_onDragOver: function(e) {
if (!e.drop.get(NODE).test(this.get(NODES))) {
return;
}
if (e.drag.get(NODE) == e.drop.get(NODE)) {
return;
}
// is drop a child of drag?
if (e.drag.get(NODE).contains(e.drop.get(NODE))) {
return;
}
var same = false, dir, oldNode, newNode, dropsort, dropNode,
moveType = this.get('moveType').toLowerCase();
if (e.drag.get(NODE).get(PARENT_NODE).contains(e.drop.get(NODE))) {
same = true;
}
if (same && moveType == 'move') {
moveType = 'insert';
}
switch (moveType) {
case 'insert':
dir = ((this._up) ? 'before' : 'after');
dropNode = e.drop.get(NODE);
if (Y.Sortable._test(dropNode, this.get(CONT))) {
dropNode.append(e.drag.get(NODE));
} else {
dropNode.insert(e.drag.get(NODE), dir);
}
break;
case 'swap':
Y.DD.DDM.swapNode(e.drag, e.drop);
break;
case 'move':
case 'copy':
dropsort = Y.Sortable.getSortable(e.drop.get(NODE).get(PARENT_NODE));
if (!dropsort) {
Y.log('No delegate parent found', 'error', 'sortable');
return;
}
Y.DD.DDM.getDrop(e.drag.get(NODE)).addToGroup(dropsort.get(ID));
//Same List
if (same) {
Y.DD.DDM.swapNode(e.drag, e.drop);
} else {
if (this.get('moveType') == 'copy') {
//New List
oldNode = e.drag.get(NODE);
newNode = oldNode.cloneNode(true);
newNode.set(ID, '');
e.drag.set(NODE, newNode);
dropsort.delegate.createDrop(newNode, [dropsort.get(ID)]);
oldNode.setStyles({
top: '',
left: ''
});
}
e.drop.get(NODE).insert(e.drag.get(NODE), 'before');
}
break;
}
this.fire(moveType, { same: same, drag: e.drag, drop: e.drop });
this.fire('moved', { same: same, drag: e.drag, drop: e.drop });
},
/**
* @private
* @method _onDragStart
* @param Event e The Event Object
* @description Handles the DragStart event and initializes some settings.
*/
_onDragStart: function(e) {
this.delegate.get('lastNode').setStyle(ZINDEX, '');
this.delegate.get(this.get(OPACITY_NODE)).setStyle(OPACITY, this.get(OPACITY));
this.delegate.get(CURRENT_NODE).setStyle(ZINDEX, '999');
},
/**
* @private
* @method _onDragEnd
* @param Event e The Event Object
* @description Handles the DragEnd event that cleans up the settings in the drag:start event.
*/
_onDragEnd: function(e) {
this.delegate.get(this.get(OPACITY_NODE)).setStyle(OPACITY, 1);
this.delegate.get(CURRENT_NODE).setStyles({
top: '',
left: ''
});
this.sync();
},
/**
* @method plug
* @param Class cls The class to plug
* @param Object config The class config
* @description Passthrough to the DD.Delegate.ddplug method
* @chainable
*/
plug: function(cls, config) {
//I don't like this.. Not at all, need to discuss with the team
if (cls && cls.NAME.substring(0, 4).toLowerCase() === 'sort') {
this.constructor.superclass.plug.call(this, cls, config);
} else {
this.delegate.dd.plug(cls, config);
}
return this;
},
/**
* @method sync
* @description Passthrough to the DD.Delegate syncTargets method.
* @chainable
*/
sync: function() {
this.delegate.syncTargets();
return this;
},
destructor: function() {
this.delegate.destroy();
Sortable.unreg(this);
},
/**
* @method join
* @param Sortable sel The Sortable list to join with
* @param String type The type of join to do: full, inner, outer, none. Default: full
* @description Join this Sortable with another Sortable instance.
* <ul>
* <li>full: Exchange nodes with both lists.</li>
* <li>inner: Items can go into this list from the joined list.</li>
* <li>outer: Items can go out of the joined list into this list.</li>
* <li>none: Removes the join.</li>
* </ul>
* @chainable
*/
join: function(sel, type) {
if (!(sel instanceof Y.Sortable)) {
Y.error('Sortable: join needs a Sortable Instance');
return this;
}
if (!type) {
type = 'full';
}
type = type.toLowerCase();
var method = '_join_' + type;
if (this[method]) {
this[method](sel);
}
return this;
},
/**
* @private
* @method _join_none
* @param Sortable sel The Sortable to remove the join from
* @description Removes the join with the passed Sortable.
*/
_join_none: function(sel) {
this.delegate.dd.removeFromGroup(sel.get(ID));
sel.delegate.dd.removeFromGroup(this.get(ID));
},
/**
* @private
* @method _join_full
* @param Sortable sel The Sortable list to join with
* @description Joins both of the Sortables together.
*/
_join_full: function(sel) {
this.delegate.dd.addToGroup(sel.get(ID));
sel.delegate.dd.addToGroup(this.get(ID));
},
/**
* @private
* @method _join_outer
* @param Sortable sel The Sortable list to join with
* @description Allows this Sortable to accept items from the passed Sortable.
*/
_join_outer: function(sel) {
this.delegate.dd.addToGroup(sel.get(ID));
},
/**
* @private
* @method _join_inner
* @param Sortable sel The Sortable list to join with
* @description Allows this Sortable to give items to the passed Sortable.
*/
_join_inner: function(sel) {
sel.delegate.dd.addToGroup(this.get(ID));
},
/**
* A custom callback to allow a user to extract some sort of id or any other data from the node to use in the "ordering list" and then that data should be returned from the callback.
* @method getOrdering
* @param Function callback
* @return Array
*/
getOrdering: function(callback) {
var ordering = [];
if (!Y.Lang.isFunction(callback)) {
callback = function (node) {
return node;
};
}
Y.one(this.get(CONT)).all(this.get(NODES)).each(function(node) {
ordering.push(callback(node));
});
return ordering;
}
}, {
NAME: 'sortable',
ATTRS: {
/**
* @attribute handles
* @description Drag handles to pass on to the internal DD.Delegate instance.
* @type Array
*/
handles: {
value: false
},
/**
* @attribute container
* @description A selector query to get the container to listen for mousedown events on. All "nodes" should be a child of this container.
* @type String
*/
container: {
value: 'body'
},
/**
* @attribute nodes
* @description A selector query to get the children of the "container" to make draggable elements from.
* @type String
*/
nodes: {
value: '.dd-draggable'
},
/**
* @attribute opacity
* @description The opacity to change the proxy item to when dragging.
* @type String
*/
opacity: {
value: '.75'
},
/**
* @attribute opacityNode
* @description The node to set opacity on when dragging (dragNode or currentNode). Default: currentNode.
* @type String
*/
opacityNode: {
value: 'currentNode'
},
/**
* @attribute id
* @description The id of this Sortable, used to get a reference to this Sortable list from another list.
* @type String
*/
id: {
value: null
},
/**
* @attribute moveType
* @description How should an item move to another list: insert, swap, move, copy. Default: insert
* @type String
*/
moveType: {
value: 'insert'
},
/**
* @attribute invalid
* @description A selector string to test if a list item is invalid and not sortable
* @type String
*/
invalid: {
value: ''
}
},
/**
* @static
* @property _sortables
* @private
* @type Array
* @description Hash map of all Sortables on the page.
*/
_sortables: [],
/**
* @static
* @method _test
* @param {Node} node The node instance to test.
* @param {String|Node} test The node instance or selector string to test against.
* @description Test a Node or a selector for the container
*/
_test: function(node, test) {
if (test instanceof Y.Node) {
return (test === node);
} else {
return node.test(test);
}
},
/**
* @static
* @method getSortable
* @param {String|Node} node The node instance or selector string to use to find a Sortable instance.
* @description Get a Sortable instance back from a node reference or a selector string.
*/
getSortable: function(node) {
var s = null;
node = Y.one(node);
Y.each(Y.Sortable._sortables, function(v) {
if (Y.Sortable._test(node, v.get(CONT))) {
s = v;
}
});
return s;
},
/**
* @static
* @method reg
* @param Sortable s A Sortable instance.
* @description Register a Sortable instance with the singleton to allow lookups later.
*/
reg: function(s) {
Y.Sortable._sortables.push(s);
},
/**
* @static
* @method unreg
* @param Sortable s A Sortable instance.
* @description Unregister a Sortable instance with the singleton.
*/
unreg: function(s) {
Y.each(Y.Sortable._sortables, function(v, k) {
if (v === s) {
Y.Sortable._sortables[k] = null;
delete Sortable._sortables[k];
}
});
}
});
Y.Sortable = Sortable;
/**
* @event copy
* @description A Sortable node was moved with a copy.
* @param {Event.Facade} event An Event Facade object
* @param {Boolean} event.same Moved to the same list.
* @param {DD.Drag} event.drag The drag instance.
* @param {DD.Drop} event.drop The drop instance.
* @type {Event.Custom}
*/
/**
* @event move
* @description A Sortable node was moved with a move.
* @param {Event.Facade} event An Event Facade object with the following specific property added:
* @param {Boolean} event.same Moved to the same list.
* @param {DD.Drag} event.drag The drag instance.
* @param {DD.Drop} event.drop The drop instance.
* @type {Event.Custom}
*/
/**
* @event insert
* @description A Sortable node was moved with an insert.
* @param {Event.Facade} event An Event Facade object with the following specific property added:
* @param {Boolean} event.same Moved to the same list.
* @param {DD.Drag} event.drag The drag instance.
* @param {DD.Drop} event.drop The drop instance.
* @type {Event.Custom}
*/
/**
* @event swap
* @description A Sortable node was moved with a swap.
* @param {Event.Facade} event An Event Facade object with the following specific property added:
* @param {Boolean} event.same Moved to the same list.
* @param {DD.Drag} event.drag The drag instance.
* @param {DD.Drop} event.drop The drop instance.
* @type {Event.Custom}
*/
/**
* @event moved
* @description A Sortable node was moved.
* @param {Event.Facade} event An Event Facade object with the following specific property added:
* @param {Boolean} event.same Moved to the same list.
* @param {DD.Drag} event.drag The drag instance.
* @param {DD.Drop} event.drop The drop instance.
* @type {Event.Custom}
*/
}, '3.5.1' ,{requires:['dd-delegate', 'dd-drop-plugin', 'dd-proxy']});
| sergiomt/zesped | src/webapp/js/yui/sortable/sortable-debug.js | JavaScript | agpl-3.0 | 17,368 |
define(
({
nomatchMessage: "Lozinke se ne podudaraju.",
badPasswordMessage: "Neispravna lozinka."
})
);
| avz-cmf/zaboy-middleware | www/js/dojox/form/nls/hr/PasswordValidator.js | JavaScript | gpl-3.0 | 113 |
define("ace/mode/xml_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var XmlHighlightRules = function(normalize) {
var tagRegex = "[_:a-zA-Z\xc0-\uffff][-_:.a-zA-Z0-9\xc0-\uffff]*";
this.$rules = {
start : [
{token : "string.cdata.xml", regex : "<\\!\\[CDATA\\[", next : "cdata"},
{
token : ["punctuation.instruction.xml", "keyword.instruction.xml"],
regex : "(<\\?)(" + tagRegex + ")", next : "processing_instruction"
},
{token : "comment.start.xml", regex : "<\\!--", next : "comment"},
{
token : ["xml-pe.doctype.xml", "xml-pe.doctype.xml"],
regex : "(<\\!)(DOCTYPE)(?=[\\s])", next : "doctype", caseInsensitive: true
},
{include : "tag"},
{token : "text.end-tag-open.xml", regex: "</"},
{token : "text.tag-open.xml", regex: "<"},
{include : "reference"},
{defaultToken : "text.xml"}
],
processing_instruction : [{
token : "entity.other.attribute-name.decl-attribute-name.xml",
regex : tagRegex
}, {
token : "keyword.operator.decl-attribute-equals.xml",
regex : "="
}, {
include: "whitespace"
}, {
include: "string"
}, {
token : "punctuation.xml-decl.xml",
regex : "\\?>",
next : "start"
}],
doctype : [
{include : "whitespace"},
{include : "string"},
{token : "xml-pe.doctype.xml", regex : ">", next : "start"},
{token : "xml-pe.xml", regex : "[-_a-zA-Z0-9:]+"},
{token : "punctuation.int-subset", regex : "\\[", push : "int_subset"}
],
int_subset : [{
token : "text.xml",
regex : "\\s+"
}, {
token: "punctuation.int-subset.xml",
regex: "]",
next: "pop"
}, {
token : ["punctuation.markup-decl.xml", "keyword.markup-decl.xml"],
regex : "(<\\!)(" + tagRegex + ")",
push : [{
token : "text",
regex : "\\s+"
},
{
token : "punctuation.markup-decl.xml",
regex : ">",
next : "pop"
},
{include : "string"}]
}],
cdata : [
{token : "string.cdata.xml", regex : "\\]\\]>", next : "start"},
{token : "text.xml", regex : "\\s+"},
{token : "text.xml", regex : "(?:[^\\]]|\\](?!\\]>))+"}
],
comment : [
{token : "comment.end.xml", regex : "-->", next : "start"},
{defaultToken : "comment.xml"}
],
reference : [{
token : "constant.language.escape.reference.xml",
regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)"
}],
attr_reference : [{
token : "constant.language.escape.reference.attribute-value.xml",
regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)"
}],
tag : [{
token : ["meta.tag.punctuation.tag-open.xml", "meta.tag.punctuation.end-tag-open.xml", "meta.tag.tag-name.xml"],
regex : "(?:(<)|(</))((?:" + tagRegex + ":)?" + tagRegex + ")",
next: [
{include : "attributes"},
{token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next : "start"}
]
}],
tag_whitespace : [
{token : "text.tag-whitespace.xml", regex : "\\s+"}
],
whitespace : [
{token : "text.whitespace.xml", regex : "\\s+"}
],
string: [{
token : "string.xml",
regex : "'",
push : [
{token : "string.xml", regex: "'", next: "pop"},
{defaultToken : "string.xml"}
]
}, {
token : "string.xml",
regex : '"',
push : [
{token : "string.xml", regex: '"', next: "pop"},
{defaultToken : "string.xml"}
]
}],
attributes: [{
token : "entity.other.attribute-name.xml",
regex : tagRegex
}, {
token : "keyword.operator.attribute-equals.xml",
regex : "="
}, {
include: "tag_whitespace"
}, {
include: "attribute_value"
}],
attribute_value: [{
token : "string.attribute-value.xml",
regex : "'",
push : [
{token : "string.attribute-value.xml", regex: "'", next: "pop"},
{include : "attr_reference"},
{defaultToken : "string.attribute-value.xml"}
]
}, {
token : "string.attribute-value.xml",
regex : '"',
push : [
{token : "string.attribute-value.xml", regex: '"', next: "pop"},
{include : "attr_reference"},
{defaultToken : "string.attribute-value.xml"}
]
}]
};
if (this.constructor === XmlHighlightRules)
this.normalizeRules();
};
(function() {
this.embedTagRules = function(HighlightRules, prefix, tag){
this.$rules.tag.unshift({
token : ["meta.tag.punctuation.tag-open.xml", "meta.tag." + tag + ".tag-name.xml"],
regex : "(<)(" + tag + "(?=\\s|>|$))",
next: [
{include : "attributes"},
{token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next : prefix + "start"}
]
});
this.$rules[tag + "-end"] = [
{include : "attributes"},
{token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next: "start",
onMatch : function(value, currentState, stack) {
stack.splice(0);
return this.token;
}}
];
this.embedRules(HighlightRules, prefix, [{
token: ["meta.tag.punctuation.end-tag-open.xml", "meta.tag." + tag + ".tag-name.xml"],
regex : "(</)(" + tag + "(?=\\s|>|$))",
next: tag + "-end"
}, {
token: "string.cdata.xml",
regex : "<\\!\\[CDATA\\["
}, {
token: "string.cdata.xml",
regex : "\\]\\]>"
}]);
};
}).call(TextHighlightRules.prototype);
oop.inherits(XmlHighlightRules, TextHighlightRules);
exports.XmlHighlightRules = XmlHighlightRules;
});
define("ace/mode/behaviour/xml",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/token_iterator","ace/lib/lang"], function(require, exports, module) {
"use strict";
var oop = require("../../lib/oop");
var Behaviour = require("../behaviour").Behaviour;
var TokenIterator = require("../../token_iterator").TokenIterator;
var lang = require("../../lib/lang");
function is(token, type) {
return token && token.type.lastIndexOf(type + ".xml") > -1;
}
var XmlBehaviour = function () {
this.add("string_dquotes", "insertion", function (state, action, editor, session, text) {
if (text == '"' || text == "'") {
var quote = text;
var selected = session.doc.getTextRange(editor.getSelectionRange());
if (selected !== "" && selected !== "'" && selected != '"' && editor.getWrapBehavioursEnabled()) {
return {
text: quote + selected + quote,
selection: false
};
}
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var rightChar = line.substring(cursor.column, cursor.column + 1);
var iterator = new TokenIterator(session, cursor.row, cursor.column);
var token = iterator.getCurrentToken();
if (rightChar == quote && (is(token, "attribute-value") || is(token, "string"))) {
return {
text: "",
selection: [1, 1]
};
}
if (!token)
token = iterator.stepBackward();
if (!token)
return;
while (is(token, "tag-whitespace") || is(token, "whitespace")) {
token = iterator.stepBackward();
}
var rightSpace = !rightChar || rightChar.match(/\s/);
if (is(token, "attribute-equals") && (rightSpace || rightChar == '>') || (is(token, "decl-attribute-equals") && (rightSpace || rightChar == '?'))) {
return {
text: quote + quote,
selection: [1, 1]
};
}
}
});
this.add("string_dquotes", "deletion", function(state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && (selected == '"' || selected == "'")) {
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
if (rightChar == selected) {
range.end.column++;
return range;
}
}
});
this.add("autoclosing", "insertion", function (state, action, editor, session, text) {
if (text == '>') {
var position = editor.getSelectionRange().start;
var iterator = new TokenIterator(session, position.row, position.column);
var token = iterator.getCurrentToken() || iterator.stepBackward();
if (!token || !(is(token, "tag-name") || is(token, "tag-whitespace") || is(token, "attribute-name") || is(token, "attribute-equals") || is(token, "attribute-value")))
return;
if (is(token, "reference.attribute-value"))
return;
if (is(token, "attribute-value")) {
var tokenEndColumn = iterator.getCurrentTokenColumn() + token.value.length;
if (position.column < tokenEndColumn)
return;
if (position.column == tokenEndColumn) {
var nextToken = iterator.stepForward();
// TODO also handle non-closed string at the end of the line
if (nextToken && is(nextToken, "attribute-value"))
return;
iterator.stepBackward();
}
}
if (/^\s*>/.test(session.getLine(position.row).slice(position.column)))
return;
while (!is(token, "tag-name")) {
token = iterator.stepBackward();
if (token.value == "<") {
token = iterator.stepForward();
break;
}
}
var tokenRow = iterator.getCurrentTokenRow();
var tokenColumn = iterator.getCurrentTokenColumn();
if (is(iterator.stepBackward(), "end-tag-open"))
return;
var element = token.value;
if (tokenRow == position.row)
element = element.substring(0, position.column - tokenColumn);
if (this.voidElements.hasOwnProperty(element.toLowerCase()))
return;
return {
text: ">" + "</" + element + ">",
selection: [1, 1]
};
}
});
this.add("autoindent", "insertion", function (state, action, editor, session, text) {
if (text == "\n") {
var cursor = editor.getCursorPosition();
var line = session.getLine(cursor.row);
var iterator = new TokenIterator(session, cursor.row, cursor.column);
var token = iterator.getCurrentToken();
if (token && token.type.indexOf("tag-close") !== -1) {
if (token.value == "/>")
return;
while (token && token.type.indexOf("tag-name") === -1) {
token = iterator.stepBackward();
}
if (!token) {
return;
}
var tag = token.value;
var row = iterator.getCurrentTokenRow();
token = iterator.stepBackward();
if (!token || token.type.indexOf("end-tag") !== -1) {
return;
}
if (this.voidElements && !this.voidElements[tag]) {
var nextToken = session.getTokenAt(cursor.row, cursor.column+1);
var line = session.getLine(row);
var nextIndent = this.$getIndent(line);
var indent = nextIndent + session.getTabString();
if (nextToken && nextToken.value === "</") {
return {
text: "\n" + indent + "\n" + nextIndent,
selection: [1, indent.length, 1, indent.length]
};
} else {
return {
text: "\n" + indent
};
}
}
}
}
});
};
oop.inherits(XmlBehaviour, Behaviour);
exports.XmlBehaviour = XmlBehaviour;
});
define("ace/mode/folding/xml",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/range","ace/mode/folding/fold_mode","ace/token_iterator"], function(require, exports, module) {
"use strict";
var oop = require("../../lib/oop");
var lang = require("../../lib/lang");
var Range = require("../../range").Range;
var BaseFoldMode = require("./fold_mode").FoldMode;
var TokenIterator = require("../../token_iterator").TokenIterator;
var FoldMode = exports.FoldMode = function(voidElements, optionalEndTags) {
BaseFoldMode.call(this);
this.voidElements = voidElements || {};
this.optionalEndTags = oop.mixin({}, this.voidElements);
if (optionalEndTags)
oop.mixin(this.optionalEndTags, optionalEndTags);
};
oop.inherits(FoldMode, BaseFoldMode);
var Tag = function() {
this.tagName = "";
this.closing = false;
this.selfClosing = false;
this.start = {row: 0, column: 0};
this.end = {row: 0, column: 0};
};
function is(token, type) {
return token.type.lastIndexOf(type + ".xml") > -1;
}
(function() {
this.getFoldWidget = function(session, foldStyle, row) {
var tag = this._getFirstTagInLine(session, row);
if (!tag)
return this.getCommentFoldWidget(session, row);
if (tag.closing || (!tag.tagName && tag.selfClosing))
return foldStyle == "markbeginend" ? "end" : "";
if (!tag.tagName || tag.selfClosing || this.voidElements.hasOwnProperty(tag.tagName.toLowerCase()))
return "";
if (this._findEndTagInLine(session, row, tag.tagName, tag.end.column))
return "";
return "start";
};
this.getCommentFoldWidget = function(session, row) {
if (/comment/.test(session.getState(row)) && /<!-/.test(session.getLine(row)))
return "start";
return "";
};
this._getFirstTagInLine = function(session, row) {
var tokens = session.getTokens(row);
var tag = new Tag();
for (var i = 0; i < tokens.length; i++) {
var token = tokens[i];
if (is(token, "tag-open")) {
tag.end.column = tag.start.column + token.value.length;
tag.closing = is(token, "end-tag-open");
token = tokens[++i];
if (!token)
return null;
tag.tagName = token.value;
tag.end.column += token.value.length;
for (i++; i < tokens.length; i++) {
token = tokens[i];
tag.end.column += token.value.length;
if (is(token, "tag-close")) {
tag.selfClosing = token.value == '/>';
break;
}
}
return tag;
} else if (is(token, "tag-close")) {
tag.selfClosing = token.value == '/>';
return tag;
}
tag.start.column += token.value.length;
}
return null;
};
this._findEndTagInLine = function(session, row, tagName, startColumn) {
var tokens = session.getTokens(row);
var column = 0;
for (var i = 0; i < tokens.length; i++) {
var token = tokens[i];
column += token.value.length;
if (column < startColumn)
continue;
if (is(token, "end-tag-open")) {
token = tokens[i + 1];
if (token && token.value == tagName)
return true;
}
}
return false;
};
this._readTagForward = function(iterator) {
var token = iterator.getCurrentToken();
if (!token)
return null;
var tag = new Tag();
do {
if (is(token, "tag-open")) {
tag.closing = is(token, "end-tag-open");
tag.start.row = iterator.getCurrentTokenRow();
tag.start.column = iterator.getCurrentTokenColumn();
} else if (is(token, "tag-name")) {
tag.tagName = token.value;
} else if (is(token, "tag-close")) {
tag.selfClosing = token.value == "/>";
tag.end.row = iterator.getCurrentTokenRow();
tag.end.column = iterator.getCurrentTokenColumn() + token.value.length;
iterator.stepForward();
return tag;
}
} while(token = iterator.stepForward());
return null;
};
this._readTagBackward = function(iterator) {
var token = iterator.getCurrentToken();
if (!token)
return null;
var tag = new Tag();
do {
if (is(token, "tag-open")) {
tag.closing = is(token, "end-tag-open");
tag.start.row = iterator.getCurrentTokenRow();
tag.start.column = iterator.getCurrentTokenColumn();
iterator.stepBackward();
return tag;
} else if (is(token, "tag-name")) {
tag.tagName = token.value;
} else if (is(token, "tag-close")) {
tag.selfClosing = token.value == "/>";
tag.end.row = iterator.getCurrentTokenRow();
tag.end.column = iterator.getCurrentTokenColumn() + token.value.length;
}
} while(token = iterator.stepBackward());
return null;
};
this._pop = function(stack, tag) {
while (stack.length) {
var top = stack[stack.length-1];
if (!tag || top.tagName == tag.tagName) {
return stack.pop();
}
else if (this.optionalEndTags.hasOwnProperty(top.tagName)) {
stack.pop();
continue;
} else {
return null;
}
}
};
this.getFoldWidgetRange = function(session, foldStyle, row) {
var firstTag = this._getFirstTagInLine(session, row);
if (!firstTag) {
return this.getCommentFoldWidget(session, row)
&& session.getCommentFoldRange(row, session.getLine(row).length);
}
var isBackward = firstTag.closing || firstTag.selfClosing;
var stack = [];
var tag;
if (!isBackward) {
var iterator = new TokenIterator(session, row, firstTag.start.column);
var start = {
row: row,
column: firstTag.start.column + firstTag.tagName.length + 2
};
if (firstTag.start.row == firstTag.end.row)
start.column = firstTag.end.column;
while (tag = this._readTagForward(iterator)) {
if (tag.selfClosing) {
if (!stack.length) {
tag.start.column += tag.tagName.length + 2;
tag.end.column -= 2;
return Range.fromPoints(tag.start, tag.end);
} else
continue;
}
if (tag.closing) {
this._pop(stack, tag);
if (stack.length == 0)
return Range.fromPoints(start, tag.start);
}
else {
stack.push(tag);
}
}
}
else {
var iterator = new TokenIterator(session, row, firstTag.end.column);
var end = {
row: row,
column: firstTag.start.column
};
while (tag = this._readTagBackward(iterator)) {
if (tag.selfClosing) {
if (!stack.length) {
tag.start.column += tag.tagName.length + 2;
tag.end.column -= 2;
return Range.fromPoints(tag.start, tag.end);
} else
continue;
}
if (!tag.closing) {
this._pop(stack, tag);
if (stack.length == 0) {
tag.start.column += tag.tagName.length + 2;
if (tag.start.row == tag.end.row && tag.start.column < tag.end.column)
tag.start.column = tag.end.column;
return Range.fromPoints(tag.start, end);
}
}
else {
stack.push(tag);
}
}
}
};
}).call(FoldMode.prototype);
});
define("ace/mode/xml",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text","ace/mode/xml_highlight_rules","ace/mode/behaviour/xml","ace/mode/folding/xml","ace/worker/worker_client"], function(require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var lang = require("../lib/lang");
var TextMode = require("./text").Mode;
var XmlHighlightRules = require("./xml_highlight_rules").XmlHighlightRules;
var XmlBehaviour = require("./behaviour/xml").XmlBehaviour;
var XmlFoldMode = require("./folding/xml").FoldMode;
var WorkerClient = require("../worker/worker_client").WorkerClient;
var Mode = function() {
this.HighlightRules = XmlHighlightRules;
this.$behaviour = new XmlBehaviour();
this.foldingRules = new XmlFoldMode();
};
oop.inherits(Mode, TextMode);
(function() {
this.voidElements = lang.arrayToMap([]);
this.blockComment = {start: "<!--", end: "-->"};
this.createWorker = function(session) {
var worker = new WorkerClient(["ace"], "ace/mode/xml_worker", "Worker");
worker.attachToDocument(session.getDocument());
worker.on("error", function(e) {
session.setAnnotations(e.data);
});
worker.on("terminate", function() {
session.clearAnnotations();
});
return worker;
};
this.$id = "ace/mode/xml";
}).call(Mode.prototype);
exports.Mode = Mode;
});
| ddico/odoo | addons/web/static/lib/ace/mode-xml.js | JavaScript | agpl-3.0 | 23,724 |
loadjs = (function () {
/**
* Global dependencies.
* @global {Object} document - DOM
*/
var devnull = function() {},
bundleIdCache = {},
bundleResultCache = {},
bundleCallbackQueue = {};
/**
* Subscribe to bundle load event.
* @param {string[]} bundleIds - Bundle ids
* @param {Function} callbackFn - The callback function
*/
function subscribe(bundleIds, callbackFn) {
// listify
bundleIds = bundleIds.push ? bundleIds : [bundleIds];
var depsNotFound = [],
i = bundleIds.length,
numWaiting = i,
fn,
bundleId,
r,
q;
// define callback function
fn = function (bundleId, pathsNotFound) {
if (pathsNotFound.length) depsNotFound.push(bundleId);
numWaiting--;
if (!numWaiting) callbackFn(depsNotFound);
};
// register callback
while (i--) {
bundleId = bundleIds[i];
// execute callback if in result cache
r = bundleResultCache[bundleId];
if (r) {
fn(bundleId, r);
continue;
}
// add to callback queue
q = bundleCallbackQueue[bundleId] = bundleCallbackQueue[bundleId] || [];
q.push(fn);
}
}
/**
* Publish bundle load event.
* @param {string} bundleId - Bundle id
* @param {string[]} pathsNotFound - List of files not found
*/
function publish(bundleId, pathsNotFound) {
// exit if id isn't defined
if (!bundleId) return;
var q = bundleCallbackQueue[bundleId];
// cache result
bundleResultCache[bundleId] = pathsNotFound;
// exit if queue is empty
if (!q) return;
// empty callback queue
while (q.length) {
q[0](bundleId, pathsNotFound);
q.splice(0, 1);
}
}
/**
* Load individual file.
* @param {string} path - The file path
* @param {Function} callbackFn - The callback function
*/
function loadFile(path, callbackFn, args, numTries) {
var doc = document,
async = args.async,
maxTries = (args.numRetries || 0) + 1,
beforeCallbackFn = args.before || devnull,
isCss,
e;
numTries = numTries || 0;
if (/\.css$/.test(path)) {
isCss = true;
// css
e = doc.createElement('link');
e.rel = 'stylesheet';
e.href = path;
} else {
// javascript
e = doc.createElement('script');
e.src = path;
e.async = async === undefined ? true : async;
}
e.onload = e.onerror = e.onbeforeload = function (ev) {
var result = ev.type[0];
// Note: The following code isolates IE using `hideFocus` and treats empty
// stylesheets as failures to get around lack of onerror support
if (isCss && 'hideFocus' in e) {
try {
if (!e.sheet.cssText.length) result = 'e';
} catch (x) {
// sheets objects created from load errors don't allow access to
// `cssText`
result = 'e';
}
}
// handle retries in case of load failure
if (result == 'e') {
// increment counter
numTries += 1;
// exit function and try again
if (numTries < maxTries) {
return loadFile(path, callbackFn, args, numTries);
}
}
// execute callback
callbackFn(path, result, ev.defaultPrevented);
};
// execute before callback
beforeCallbackFn(path, e);
// add to document
doc.head.appendChild(e);
}
/**
* Load multiple files.
* @param {string[]} paths - The file paths
* @param {Function} callbackFn - The callback function
*/
function loadFiles(paths, callbackFn, args) {
// listify paths
paths = paths.push ? paths : [paths];
var numWaiting = paths.length,
x = numWaiting,
pathsNotFound = [],
fn,
i;
// define callback function
fn = function(path, result, defaultPrevented) {
// handle error
if (result == 'e') pathsNotFound.push(path);
// handle beforeload event. If defaultPrevented then that means the load
// will be blocked (ex. Ghostery/ABP on Safari)
if (result == 'b') {
if (defaultPrevented) pathsNotFound.push(path);
else return;
}
numWaiting--;
if (!numWaiting) callbackFn(pathsNotFound);
};
// load scripts
for (i=0; i < x; i++) loadFile(paths[i], fn, args);
}
/**
* Initiate script load and register bundle.
* @param {(string|string[])} paths - The file paths
* @param {(string|Function)} [arg1] - The bundleId or success callback
* @param {Function} [arg2] - The success or error callback
* @param {Function} [arg3] - The error callback
*/
function loadjs(paths, arg1, arg2) {
var bundleId,
args;
// bundleId (if string)
if (arg1 && arg1.trim) bundleId = arg1;
// args (default is {})
args = (bundleId ? arg2 : arg1) || {};
// throw error if bundle is already defined
if (bundleId) {
if (bundleId in bundleIdCache) {
throw "LoadJS";
} else {
bundleIdCache[bundleId] = true;
}
}
// load scripts
loadFiles(paths, function (pathsNotFound) {
// success and error callbacks
if (pathsNotFound.length) (args.error || devnull)(pathsNotFound);
else (args.success || devnull)();
// publish bundle load event
publish(bundleId, pathsNotFound);
}, args);
}
/**
* Execute callbacks when dependencies have been satisfied.
* @param {(string|string[])} deps - List of bundle ids
* @param {Object} args - success/error arguments
*/
loadjs.ready = function ready(deps, args) {
// subscribe to bundle load event
subscribe(deps, function (depsNotFound) {
// execute callbacks
if (depsNotFound.length) (args.error || devnull)(depsNotFound);
else (args.success || devnull)();
});
return loadjs;
};
/**
* Manually satisfy bundle dependencies.
* @param {string} bundleId - The bundle id
*/
loadjs.done = function done(bundleId) {
publish(bundleId, []);
};
/**
* Reset loadjs dependencies statuses
*/
loadjs.reset = function reset() {
bundleIdCache = {};
bundleResultCache = {};
bundleCallbackQueue = {};
};
/**
* Determine if bundle has already been defined
* @param String} bundleId - The bundle id
*/
loadjs.isDefined = function isDefined(bundleId) {
return bundleId in bundleIdCache;
};
// export
return loadjs;
})();
| jonobr1/cdnjs | ajax/libs/loadjs/3.4.0/loadjs.js | JavaScript | mit | 6,072 |
(function() {
"use strict";
window.GOVUK = window.GOVUK || {};
// For usage and initialisation see:
// https://github.com/alphagov/govuk_frontend_toolkit/blob/master/docs/analytics.md#create-an-analytics-tracker
var Tracker = function(config) {
this.trackers = [];
if (typeof config.universalId != 'undefined') {
this.trackers.push(new GOVUK.GoogleAnalyticsUniversalTracker(config.universalId, config.cookieDomain));
}
if (typeof config.classicId != 'undefined') {
this.trackers.push(new GOVUK.GoogleAnalyticsClassicTracker(config.classicId, config.cookieDomain));
}
};
Tracker.load = function() {
GOVUK.GoogleAnalyticsClassicTracker.load();
GOVUK.GoogleAnalyticsUniversalTracker.load();
};
Tracker.prototype.trackPageview = function(path, title) {
for (var i=0; i < this.trackers.length; i++) {
this.trackers[i].trackPageview(path, title);
}
};
/*
https://developers.google.com/analytics/devguides/collection/analyticsjs/events
options.label – Useful for categorizing events (eg nav buttons)
options.value – Values must be non-negative. Useful to pass counts
options.nonInteraction – Prevent event from impacting bounce rate
*/
Tracker.prototype.trackEvent = function(category, action, options) {
for (var i=0; i < this.trackers.length; i++) {
this.trackers[i].trackEvent(category, action, options);
}
};
Tracker.prototype.trackShare = function(network) {
var target = location.pathname;
for (var i=0; i < this.trackers.length; i++) {
this.trackers[i].trackSocial(network, 'share', target);
}
};
/*
Assumes that the index of the dimension is the same for both classic and universal.
Check this for your app before using this
*/
Tracker.prototype.setDimension = function(index, value, name, scope) {
for (var i=0; i < this.trackers.length; i++) {
this.trackers[i].setDimension(index, value, name, scope);
}
};
/*
Add a beacon to track a page in another GA account on another domain.
*/
Tracker.prototype.addLinkedTrackerDomain = function(trackerId, name, domain) {
for (var i=0; i < this.trackers.length; i++) {
this.trackers[i].addLinkedTrackerDomain(trackerId, name, domain);
}
};
GOVUK.Tracker = Tracker;
})();
| matt-hammond/baymax | src/baymax/wwwroot/public/javascripts/govuk/analytics/tracker.js | JavaScript | mit | 2,322 |
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("react"));
else if(typeof define === 'function' && define.amd)
define(["react"], factory);
else if(typeof exports === 'object')
exports["ReduxLittleRouter"] = factory(require("react"));
else
root["ReduxLittleRouter"] = factory(root["React"]);
})(this, function(__WEBPACK_EXTERNAL_MODULE_30__) {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.GO_BACK = exports.GO_FORWARD = exports.GO = exports.REPLACE = exports.PUSH = exports.LOCATION_CHANGED = exports.createMatcher = exports.Link = exports.routerReducer = exports.routerMiddleware = exports.createStoreWithRouter = undefined;
var _storeEnhancer = __webpack_require__(1);
var _storeEnhancer2 = _interopRequireDefault(_storeEnhancer);
var _middleware = __webpack_require__(28);
var _middleware2 = _interopRequireDefault(_middleware);
var _reducer = __webpack_require__(26);
var _reducer2 = _interopRequireDefault(_reducer);
var _link = __webpack_require__(29);
var _link2 = _interopRequireDefault(_link);
var _createMatcher = __webpack_require__(16);
var _createMatcher2 = _interopRequireDefault(_createMatcher);
var _actionTypes = __webpack_require__(27);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.createStoreWithRouter = _storeEnhancer2.default;
exports.routerMiddleware = _middleware2.default;
exports.routerReducer = _reducer2.default;
exports.Link = _link2.default;
exports.createMatcher = _createMatcher2.default;
exports.LOCATION_CHANGED = _actionTypes.LOCATION_CHANGED;
exports.PUSH = _actionTypes.PUSH;
exports.REPLACE = _actionTypes.REPLACE;
exports.GO = _actionTypes.GO;
exports.GO_FORWARD = _actionTypes.GO_FORWARD;
exports.GO_BACK = _actionTypes.GO_BACK;
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _redux = __webpack_require__(2);
var _createMatcher = __webpack_require__(16);
var _createMatcher2 = _interopRequireDefault(_createMatcher);
var _reducer = __webpack_require__(26);
var _reducer2 = _interopRequireDefault(_reducer);
var _middleware = __webpack_require__(28);
var _middleware2 = _interopRequireDefault(_middleware);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
exports.default = function (_ref) {
var middleware = _ref.middleware;
var routes = _ref.routes;
var history = _ref.history;
var _ref$createMatcher = _ref.createMatcher;
var createMatcher = _ref$createMatcher === undefined ? _createMatcher2.default : _ref$createMatcher;
return function (createStore) {
return function (reducer, initialState) {
var enhancedReducer = function enhancedReducer(state, action) {
var vanillaState = _extends({}, state);
delete vanillaState.router;
return _extends({}, reducer(vanillaState, action), {
router: (0, _reducer2.default)(routes, createMatcher)(state.router, action)
});
};
return createStore(enhancedReducer, initialState, _redux.applyMiddleware.apply(undefined, [(0, _middleware2.default)(history)].concat(_toConsumableArray(middleware))));
};
};
};
/***/ },
/* 2 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {'use strict';
exports.__esModule = true;
exports.compose = exports.applyMiddleware = exports.bindActionCreators = exports.combineReducers = exports.createStore = undefined;
var _createStore = __webpack_require__(4);
var _createStore2 = _interopRequireDefault(_createStore);
var _combineReducers = __webpack_require__(11);
var _combineReducers2 = _interopRequireDefault(_combineReducers);
var _bindActionCreators = __webpack_require__(13);
var _bindActionCreators2 = _interopRequireDefault(_bindActionCreators);
var _applyMiddleware = __webpack_require__(14);
var _applyMiddleware2 = _interopRequireDefault(_applyMiddleware);
var _compose = __webpack_require__(15);
var _compose2 = _interopRequireDefault(_compose);
var _warning = __webpack_require__(12);
var _warning2 = _interopRequireDefault(_warning);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
/*
* This is a dummy function to check if the function name has been altered by minification.
* If the function has been minified and NODE_ENV !== 'production', warn the user.
*/
function isCrushed() {}
if (process.env.NODE_ENV !== 'production' && typeof isCrushed.name === 'string' && isCrushed.name !== 'isCrushed') {
(0, _warning2["default"])('You are currently using minified code outside of NODE_ENV === \'production\'. ' + 'This means that you are running a slower development build of Redux. ' + 'You can use loose-envify (https://github.com/zertosh/loose-envify) for browserify ' + 'or DefinePlugin for webpack (http://stackoverflow.com/questions/30030031) ' + 'to ensure you have the correct code for your production build.');
}
exports.createStore = _createStore2["default"];
exports.combineReducers = _combineReducers2["default"];
exports.bindActionCreators = _bindActionCreators2["default"];
exports.applyMiddleware = _applyMiddleware2["default"];
exports.compose = _compose2["default"];
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 3 */
/***/ function(module, exports) {
// shim for using process in browser
var process = module.exports = {};
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = setTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
clearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
setTimeout(drainQueue, 0);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports.ActionTypes = undefined;
exports["default"] = createStore;
var _isPlainObject = __webpack_require__(5);
var _isPlainObject2 = _interopRequireDefault(_isPlainObject);
var _symbolObservable = __webpack_require__(9);
var _symbolObservable2 = _interopRequireDefault(_symbolObservable);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
/**
* These are private action types reserved by Redux.
* For any unknown actions, you must return the current state.
* If the current state is undefined, you must return the initial state.
* Do not reference these action types directly in your code.
*/
var ActionTypes = exports.ActionTypes = {
INIT: '@@redux/INIT'
};
/**
* Creates a Redux store that holds the state tree.
* The only way to change the data in the store is to call `dispatch()` on it.
*
* There should only be a single store in your app. To specify how different
* parts of the state tree respond to actions, you may combine several reducers
* into a single reducer function by using `combineReducers`.
*
* @param {Function} reducer A function that returns the next state tree, given
* the current state tree and the action to handle.
*
* @param {any} [initialState] The initial state. You may optionally specify it
* to hydrate the state from the server in universal apps, or to restore a
* previously serialized user session.
* If you use `combineReducers` to produce the root reducer function, this must be
* an object with the same shape as `combineReducers` keys.
*
* @param {Function} enhancer The store enhancer. You may optionally specify it
* to enhance the store with third-party capabilities such as middleware,
* time travel, persistence, etc. The only store enhancer that ships with Redux
* is `applyMiddleware()`.
*
* @returns {Store} A Redux store that lets you read the state, dispatch actions
* and subscribe to changes.
*/
function createStore(reducer, initialState, enhancer) {
var _ref2;
if (typeof initialState === 'function' && typeof enhancer === 'undefined') {
enhancer = initialState;
initialState = undefined;
}
if (typeof enhancer !== 'undefined') {
if (typeof enhancer !== 'function') {
throw new Error('Expected the enhancer to be a function.');
}
return enhancer(createStore)(reducer, initialState);
}
if (typeof reducer !== 'function') {
throw new Error('Expected the reducer to be a function.');
}
var currentReducer = reducer;
var currentState = initialState;
var currentListeners = [];
var nextListeners = currentListeners;
var isDispatching = false;
function ensureCanMutateNextListeners() {
if (nextListeners === currentListeners) {
nextListeners = currentListeners.slice();
}
}
/**
* Reads the state tree managed by the store.
*
* @returns {any} The current state tree of your application.
*/
function getState() {
return currentState;
}
/**
* Adds a change listener. It will be called any time an action is dispatched,
* and some part of the state tree may potentially have changed. You may then
* call `getState()` to read the current state tree inside the callback.
*
* You may call `dispatch()` from a change listener, with the following
* caveats:
*
* 1. The subscriptions are snapshotted just before every `dispatch()` call.
* If you subscribe or unsubscribe while the listeners are being invoked, this
* will not have any effect on the `dispatch()` that is currently in progress.
* However, the next `dispatch()` call, whether nested or not, will use a more
* recent snapshot of the subscription list.
*
* 2. The listener should not expect to see all state changes, as the state
* might have been updated multiple times during a nested `dispatch()` before
* the listener is called. It is, however, guaranteed that all subscribers
* registered before the `dispatch()` started will be called with the latest
* state by the time it exits.
*
* @param {Function} listener A callback to be invoked on every dispatch.
* @returns {Function} A function to remove this change listener.
*/
function subscribe(listener) {
if (typeof listener !== 'function') {
throw new Error('Expected listener to be a function.');
}
var isSubscribed = true;
ensureCanMutateNextListeners();
nextListeners.push(listener);
return function unsubscribe() {
if (!isSubscribed) {
return;
}
isSubscribed = false;
ensureCanMutateNextListeners();
var index = nextListeners.indexOf(listener);
nextListeners.splice(index, 1);
};
}
/**
* Dispatches an action. It is the only way to trigger a state change.
*
* The `reducer` function, used to create the store, will be called with the
* current state tree and the given `action`. Its return value will
* be considered the **next** state of the tree, and the change listeners
* will be notified.
*
* The base implementation only supports plain object actions. If you want to
* dispatch a Promise, an Observable, a thunk, or something else, you need to
* wrap your store creating function into the corresponding middleware. For
* example, see the documentation for the `redux-thunk` package. Even the
* middleware will eventually dispatch plain object actions using this method.
*
* @param {Object} action A plain object representing “what changed”. It is
* a good idea to keep actions serializable so you can record and replay user
* sessions, or use the time travelling `redux-devtools`. An action must have
* a `type` property which may not be `undefined`. It is a good idea to use
* string constants for action types.
*
* @returns {Object} For convenience, the same action object you dispatched.
*
* Note that, if you use a custom middleware, it may wrap `dispatch()` to
* return something else (for example, a Promise you can await).
*/
function dispatch(action) {
if (!(0, _isPlainObject2["default"])(action)) {
throw new Error('Actions must be plain objects. ' + 'Use custom middleware for async actions.');
}
if (typeof action.type === 'undefined') {
throw new Error('Actions may not have an undefined "type" property. ' + 'Have you misspelled a constant?');
}
if (isDispatching) {
throw new Error('Reducers may not dispatch actions.');
}
try {
isDispatching = true;
currentState = currentReducer(currentState, action);
} finally {
isDispatching = false;
}
var listeners = currentListeners = nextListeners;
for (var i = 0; i < listeners.length; i++) {
listeners[i]();
}
return action;
}
/**
* Replaces the reducer currently used by the store to calculate the state.
*
* You might need this if your app implements code splitting and you want to
* load some of the reducers dynamically. You might also need this if you
* implement a hot reloading mechanism for Redux.
*
* @param {Function} nextReducer The reducer for the store to use instead.
* @returns {void}
*/
function replaceReducer(nextReducer) {
if (typeof nextReducer !== 'function') {
throw new Error('Expected the nextReducer to be a function.');
}
currentReducer = nextReducer;
dispatch({ type: ActionTypes.INIT });
}
/**
* Interoperability point for observable/reactive libraries.
* @returns {observable} A minimal observable of state changes.
* For more information, see the observable proposal:
* https://github.com/zenparsing/es-observable
*/
function observable() {
var _ref;
var outerSubscribe = subscribe;
return _ref = {
/**
* The minimal observable subscription method.
* @param {Object} observer Any object that can be used as an observer.
* The observer object should have a `next` method.
* @returns {subscription} An object with an `unsubscribe` method that can
* be used to unsubscribe the observable from the store, and prevent further
* emission of values from the observable.
*/
subscribe: function subscribe(observer) {
if (typeof observer !== 'object') {
throw new TypeError('Expected the observer to be an object.');
}
function observeState() {
if (observer.next) {
observer.next(getState());
}
}
observeState();
var unsubscribe = outerSubscribe(observeState);
return { unsubscribe: unsubscribe };
}
}, _ref[_symbolObservable2["default"]] = function () {
return this;
}, _ref;
}
// When a store is created, an "INIT" action is dispatched so that every
// reducer returns their initial state. This effectively populates
// the initial state tree.
dispatch({ type: ActionTypes.INIT });
return _ref2 = {
dispatch: dispatch,
subscribe: subscribe,
getState: getState,
replaceReducer: replaceReducer
}, _ref2[_symbolObservable2["default"]] = observable, _ref2;
}
/***/ },
/* 5 */
/***/ function(module, exports, __webpack_require__) {
var getPrototype = __webpack_require__(6),
isHostObject = __webpack_require__(7),
isObjectLike = __webpack_require__(8);
/** `Object#toString` result references. */
var objectTag = '[object Object]';
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to resolve the decompiled source of functions. */
var funcToString = Function.prototype.toString;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/** Used to infer the `Object` constructor. */
var objectCtorString = funcToString.call(Object);
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
* of values.
*/
var objectToString = objectProto.toString;
/**
* Checks if `value` is a plain object, that is, an object created by the
* `Object` constructor or one with a `[[Prototype]]` of `null`.
*
* @static
* @memberOf _
* @since 0.8.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a plain object,
* else `false`.
* @example
*
* function Foo() {
* this.a = 1;
* }
*
* _.isPlainObject(new Foo);
* // => false
*
* _.isPlainObject([1, 2, 3]);
* // => false
*
* _.isPlainObject({ 'x': 0, 'y': 0 });
* // => true
*
* _.isPlainObject(Object.create(null));
* // => true
*/
function isPlainObject(value) {
if (!isObjectLike(value) ||
objectToString.call(value) != objectTag || isHostObject(value)) {
return false;
}
var proto = getPrototype(value);
if (proto === null) {
return true;
}
var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;
return (typeof Ctor == 'function' &&
Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString);
}
module.exports = isPlainObject;
/***/ },
/* 6 */
/***/ function(module, exports) {
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeGetPrototype = Object.getPrototypeOf;
/**
* Gets the `[[Prototype]]` of `value`.
*
* @private
* @param {*} value The value to query.
* @returns {null|Object} Returns the `[[Prototype]]`.
*/
function getPrototype(value) {
return nativeGetPrototype(Object(value));
}
module.exports = getPrototype;
/***/ },
/* 7 */
/***/ function(module, exports) {
/**
* Checks if `value` is a host object in IE < 9.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a host object, else `false`.
*/
function isHostObject(value) {
// Many host objects are `Object` objects that can coerce to strings
// despite having improperly defined `toString` methods.
var result = false;
if (value != null && typeof value.toString != 'function') {
try {
result = !!(value + '');
} catch (e) {}
}
return result;
}
module.exports = isHostObject;
/***/ },
/* 8 */
/***/ function(module, exports) {
/**
* Checks if `value` is object-like. A value is object-like if it's not `null`
* and has a `typeof` result of "object".
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
* @example
*
* _.isObjectLike({});
* // => true
*
* _.isObjectLike([1, 2, 3]);
* // => true
*
* _.isObjectLike(_.noop);
* // => false
*
* _.isObjectLike(null);
* // => false
*/
function isObjectLike(value) {
return !!value && typeof value == 'object';
}
module.exports = isObjectLike;
/***/ },
/* 9 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global) {/* global window */
'use strict';
module.exports = __webpack_require__(10)(global || window || this);
/* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
/***/ },
/* 10 */
/***/ function(module, exports) {
'use strict';
module.exports = function symbolObservablePonyfill(root) {
var result;
var Symbol = root.Symbol;
if (typeof Symbol === 'function') {
if (Symbol.observable) {
result = Symbol.observable;
} else {
if (typeof Symbol.for === 'function') {
result = Symbol.for('observable');
} else {
result = Symbol('observable');
}
Symbol.observable = result;
}
} else {
result = '@@observable';
}
return result;
};
/***/ },
/* 11 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {'use strict';
exports.__esModule = true;
exports["default"] = combineReducers;
var _createStore = __webpack_require__(4);
var _isPlainObject = __webpack_require__(5);
var _isPlainObject2 = _interopRequireDefault(_isPlainObject);
var _warning = __webpack_require__(12);
var _warning2 = _interopRequireDefault(_warning);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function getUndefinedStateErrorMessage(key, action) {
var actionType = action && action.type;
var actionName = actionType && '"' + actionType.toString() + '"' || 'an action';
return 'Given action ' + actionName + ', reducer "' + key + '" returned undefined. ' + 'To ignore an action, you must explicitly return the previous state.';
}
function getUnexpectedStateShapeWarningMessage(inputState, reducers, action) {
var reducerKeys = Object.keys(reducers);
var argumentName = action && action.type === _createStore.ActionTypes.INIT ? 'initialState argument passed to createStore' : 'previous state received by the reducer';
if (reducerKeys.length === 0) {
return 'Store does not have a valid reducer. Make sure the argument passed ' + 'to combineReducers is an object whose values are reducers.';
}
if (!(0, _isPlainObject2["default"])(inputState)) {
return 'The ' + argumentName + ' has unexpected type of "' + {}.toString.call(inputState).match(/\s([a-z|A-Z]+)/)[1] + '". Expected argument to be an object with the following ' + ('keys: "' + reducerKeys.join('", "') + '"');
}
var unexpectedKeys = Object.keys(inputState).filter(function (key) {
return !reducers.hasOwnProperty(key);
});
if (unexpectedKeys.length > 0) {
return 'Unexpected ' + (unexpectedKeys.length > 1 ? 'keys' : 'key') + ' ' + ('"' + unexpectedKeys.join('", "') + '" found in ' + argumentName + '. ') + 'Expected to find one of the known reducer keys instead: ' + ('"' + reducerKeys.join('", "') + '". Unexpected keys will be ignored.');
}
}
function assertReducerSanity(reducers) {
Object.keys(reducers).forEach(function (key) {
var reducer = reducers[key];
var initialState = reducer(undefined, { type: _createStore.ActionTypes.INIT });
if (typeof initialState === 'undefined') {
throw new Error('Reducer "' + key + '" returned undefined during initialization. ' + 'If the state passed to the reducer is undefined, you must ' + 'explicitly return the initial state. The initial state may ' + 'not be undefined.');
}
var type = '@@redux/PROBE_UNKNOWN_ACTION_' + Math.random().toString(36).substring(7).split('').join('.');
if (typeof reducer(undefined, { type: type }) === 'undefined') {
throw new Error('Reducer "' + key + '" returned undefined when probed with a random type. ' + ('Don\'t try to handle ' + _createStore.ActionTypes.INIT + ' or other actions in "redux/*" ') + 'namespace. They are considered private. Instead, you must return the ' + 'current state for any unknown actions, unless it is undefined, ' + 'in which case you must return the initial state, regardless of the ' + 'action type. The initial state may not be undefined.');
}
});
}
/**
* Turns an object whose values are different reducer functions, into a single
* reducer function. It will call every child reducer, and gather their results
* into a single state object, whose keys correspond to the keys of the passed
* reducer functions.
*
* @param {Object} reducers An object whose values correspond to different
* reducer functions that need to be combined into one. One handy way to obtain
* it is to use ES6 `import * as reducers` syntax. The reducers may never return
* undefined for any action. Instead, they should return their initial state
* if the state passed to them was undefined, and the current state for any
* unrecognized action.
*
* @returns {Function} A reducer function that invokes every reducer inside the
* passed object, and builds a state object with the same shape.
*/
function combineReducers(reducers) {
var reducerKeys = Object.keys(reducers);
var finalReducers = {};
for (var i = 0; i < reducerKeys.length; i++) {
var key = reducerKeys[i];
if (typeof reducers[key] === 'function') {
finalReducers[key] = reducers[key];
}
}
var finalReducerKeys = Object.keys(finalReducers);
var sanityError;
try {
assertReducerSanity(finalReducers);
} catch (e) {
sanityError = e;
}
return function combination() {
var state = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var action = arguments[1];
if (sanityError) {
throw sanityError;
}
if (process.env.NODE_ENV !== 'production') {
var warningMessage = getUnexpectedStateShapeWarningMessage(state, finalReducers, action);
if (warningMessage) {
(0, _warning2["default"])(warningMessage);
}
}
var hasChanged = false;
var nextState = {};
for (var i = 0; i < finalReducerKeys.length; i++) {
var key = finalReducerKeys[i];
var reducer = finalReducers[key];
var previousStateForKey = state[key];
var nextStateForKey = reducer(previousStateForKey, action);
if (typeof nextStateForKey === 'undefined') {
var errorMessage = getUndefinedStateErrorMessage(key, action);
throw new Error(errorMessage);
}
nextState[key] = nextStateForKey;
hasChanged = hasChanged || nextStateForKey !== previousStateForKey;
}
return hasChanged ? nextState : state;
};
}
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 12 */
/***/ function(module, exports) {
'use strict';
exports.__esModule = true;
exports["default"] = warning;
/**
* Prints a warning in the console if it exists.
*
* @param {String} message The warning message.
* @returns {void}
*/
function warning(message) {
/* eslint-disable no-console */
if (typeof console !== 'undefined' && typeof console.error === 'function') {
console.error(message);
}
/* eslint-enable no-console */
try {
// This error was thrown as a convenience so that you can use this stack
// to find the callsite that caused this warning to fire.
throw new Error(message);
/* eslint-disable no-empty */
} catch (e) {}
/* eslint-enable no-empty */
}
/***/ },
/* 13 */
/***/ function(module, exports) {
'use strict';
exports.__esModule = true;
exports["default"] = bindActionCreators;
function bindActionCreator(actionCreator, dispatch) {
return function () {
return dispatch(actionCreator.apply(undefined, arguments));
};
}
/**
* Turns an object whose values are action creators, into an object with the
* same keys, but with every function wrapped into a `dispatch` call so they
* may be invoked directly. This is just a convenience method, as you can call
* `store.dispatch(MyActionCreators.doSomething())` yourself just fine.
*
* For convenience, you can also pass a single function as the first argument,
* and get a function in return.
*
* @param {Function|Object} actionCreators An object whose values are action
* creator functions. One handy way to obtain it is to use ES6 `import * as`
* syntax. You may also pass a single function.
*
* @param {Function} dispatch The `dispatch` function available on your Redux
* store.
*
* @returns {Function|Object} The object mimicking the original object, but with
* every action creator wrapped into the `dispatch` call. If you passed a
* function as `actionCreators`, the return value will also be a single
* function.
*/
function bindActionCreators(actionCreators, dispatch) {
if (typeof actionCreators === 'function') {
return bindActionCreator(actionCreators, dispatch);
}
if (typeof actionCreators !== 'object' || actionCreators === null) {
throw new Error('bindActionCreators expected an object or a function, instead received ' + (actionCreators === null ? 'null' : typeof actionCreators) + '. ' + 'Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?');
}
var keys = Object.keys(actionCreators);
var boundActionCreators = {};
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var actionCreator = actionCreators[key];
if (typeof actionCreator === 'function') {
boundActionCreators[key] = bindActionCreator(actionCreator, dispatch);
}
}
return boundActionCreators;
}
/***/ },
/* 14 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
exports["default"] = applyMiddleware;
var _compose = __webpack_require__(15);
var _compose2 = _interopRequireDefault(_compose);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
/**
* Creates a store enhancer that applies middleware to the dispatch method
* of the Redux store. This is handy for a variety of tasks, such as expressing
* asynchronous actions in a concise manner, or logging every action payload.
*
* See `redux-thunk` package as an example of the Redux middleware.
*
* Because middleware is potentially asynchronous, this should be the first
* store enhancer in the composition chain.
*
* Note that each middleware will be given the `dispatch` and `getState` functions
* as named arguments.
*
* @param {...Function} middlewares The middleware chain to be applied.
* @returns {Function} A store enhancer applying the middleware.
*/
function applyMiddleware() {
for (var _len = arguments.length, middlewares = Array(_len), _key = 0; _key < _len; _key++) {
middlewares[_key] = arguments[_key];
}
return function (createStore) {
return function (reducer, initialState, enhancer) {
var store = createStore(reducer, initialState, enhancer);
var _dispatch = store.dispatch;
var chain = [];
var middlewareAPI = {
getState: store.getState,
dispatch: function dispatch(action) {
return _dispatch(action);
}
};
chain = middlewares.map(function (middleware) {
return middleware(middlewareAPI);
});
_dispatch = _compose2["default"].apply(undefined, chain)(store.dispatch);
return _extends({}, store, {
dispatch: _dispatch
});
};
};
}
/***/ },
/* 15 */
/***/ function(module, exports) {
"use strict";
exports.__esModule = true;
exports["default"] = compose;
/**
* Composes single-argument functions from right to left. The rightmost
* function can take multiple arguments as it provides the signature for
* the resulting composite function.
*
* @param {...Function} funcs The functions to compose.
* @returns {Function} A function obtained by composing the argument functions
* from right to left. For example, compose(f, g, h) is identical to doing
* (...args) => f(g(h(...args))).
*/
function compose() {
for (var _len = arguments.length, funcs = Array(_len), _key = 0; _key < _len; _key++) {
funcs[_key] = arguments[_key];
}
if (funcs.length === 0) {
return function (arg) {
return arg;
};
} else {
var _ret = function () {
var last = funcs[funcs.length - 1];
var rest = funcs.slice(0, -1);
return {
v: function v() {
return rest.reduceRight(function (composed, f) {
return f(composed);
}, last.apply(undefined, arguments));
}
};
}();
if (typeof _ret === "object") return _ret.v;
}
}
/***/ },
/* 16 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _urlPattern = __webpack_require__(17);
var _urlPattern2 = _interopRequireDefault(_urlPattern);
var _lodash = __webpack_require__(19);
var _lodash2 = _interopRequireDefault(_lodash);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = function (routes) {
var routeCache = Object.keys(routes).map(function (key) {
return {
pattern: new _urlPattern2.default(key),
result: routes[key]
};
});
return function (incomingRoute) {
var match = (0, _lodash2.default)(routeCache, function (route) {
return route.pattern.match(incomingRoute);
}) || null;
return match ? {
params: match.pattern.match(incomingRoute),
result: match.result
} : null;
};
};
/***/ },
/* 17 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// Generated by CoffeeScript 1.10.0
var slice = [].slice;
(function(root, factory) {
if (('function' === "function") && (__webpack_require__(18) != null)) {
return !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else if (typeof exports !== "undefined" && exports !== null) {
return module.exports = factory();
} else {
return root.UrlPattern = factory();
}
})(this, function() {
var P, UrlPattern, astNodeContainsSegmentsForProvidedParams, astNodeToNames, astNodeToRegexString, baseAstNodeToRegexString, concatMap, defaultOptions, escapeForRegex, getParam, keysAndValuesToObject, newParser, regexGroupCount, stringConcatMap, stringify;
escapeForRegex = function(string) {
return string.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
};
concatMap = function(array, f) {
var i, length, results;
results = [];
i = -1;
length = array.length;
while (++i < length) {
results = results.concat(f(array[i]));
}
return results;
};
stringConcatMap = function(array, f) {
var i, length, result;
result = '';
i = -1;
length = array.length;
while (++i < length) {
result += f(array[i]);
}
return result;
};
regexGroupCount = function(regex) {
return (new RegExp(regex.toString() + '|')).exec('').length - 1;
};
keysAndValuesToObject = function(keys, values) {
var i, key, length, object, value;
object = {};
i = -1;
length = keys.length;
while (++i < length) {
key = keys[i];
value = values[i];
if (value == null) {
continue;
}
if (object[key] != null) {
if (!Array.isArray(object[key])) {
object[key] = [object[key]];
}
object[key].push(value);
} else {
object[key] = value;
}
}
return object;
};
P = {};
P.Result = function(value, rest) {
this.value = value;
this.rest = rest;
};
P.Tagged = function(tag, value) {
this.tag = tag;
this.value = value;
};
P.tag = function(tag, parser) {
return function(input) {
var result, tagged;
result = parser(input);
if (result == null) {
return;
}
tagged = new P.Tagged(tag, result.value);
return new P.Result(tagged, result.rest);
};
};
P.regex = function(regex) {
return function(input) {
var matches, result;
matches = regex.exec(input);
if (matches == null) {
return;
}
result = matches[0];
return new P.Result(result, input.slice(result.length));
};
};
P.sequence = function() {
var parsers;
parsers = 1 <= arguments.length ? slice.call(arguments, 0) : [];
return function(input) {
var i, length, parser, rest, result, values;
i = -1;
length = parsers.length;
values = [];
rest = input;
while (++i < length) {
parser = parsers[i];
result = parser(rest);
if (result == null) {
return;
}
values.push(result.value);
rest = result.rest;
}
return new P.Result(values, rest);
};
};
P.pick = function() {
var indexes, parsers;
indexes = arguments[0], parsers = 2 <= arguments.length ? slice.call(arguments, 1) : [];
return function(input) {
var array, result;
result = P.sequence.apply(P, parsers)(input);
if (result == null) {
return;
}
array = result.value;
result.value = array[indexes];
return result;
};
};
P.string = function(string) {
var length;
length = string.length;
return function(input) {
if (input.slice(0, length) === string) {
return new P.Result(string, input.slice(length));
}
};
};
P.lazy = function(fn) {
var cached;
cached = null;
return function(input) {
if (cached == null) {
cached = fn();
}
return cached(input);
};
};
P.baseMany = function(parser, end, stringResult, atLeastOneResultRequired, input) {
var endResult, parserResult, rest, results;
rest = input;
results = stringResult ? '' : [];
while (true) {
if (end != null) {
endResult = end(rest);
if (endResult != null) {
break;
}
}
parserResult = parser(rest);
if (parserResult == null) {
break;
}
if (stringResult) {
results += parserResult.value;
} else {
results.push(parserResult.value);
}
rest = parserResult.rest;
}
if (atLeastOneResultRequired && results.length === 0) {
return;
}
return new P.Result(results, rest);
};
P.many1 = function(parser) {
return function(input) {
return P.baseMany(parser, null, false, true, input);
};
};
P.concatMany1Till = function(parser, end) {
return function(input) {
return P.baseMany(parser, end, true, true, input);
};
};
P.firstChoice = function() {
var parsers;
parsers = 1 <= arguments.length ? slice.call(arguments, 0) : [];
return function(input) {
var i, length, parser, result;
i = -1;
length = parsers.length;
while (++i < length) {
parser = parsers[i];
result = parser(input);
if (result != null) {
return result;
}
}
};
};
newParser = function(options) {
var U;
U = {};
U.wildcard = P.tag('wildcard', P.string(options.wildcardChar));
U.optional = P.tag('optional', P.pick(1, P.string(options.optionalSegmentStartChar), P.lazy(function() {
return U.pattern;
}), P.string(options.optionalSegmentEndChar)));
U.name = P.regex(new RegExp("^[" + options.segmentNameCharset + "]+"));
U.named = P.tag('named', P.pick(1, P.string(options.segmentNameStartChar), P.lazy(function() {
return U.name;
})));
U.escapedChar = P.pick(1, P.string(options.escapeChar), P.regex(/^./));
U["static"] = P.tag('static', P.concatMany1Till(P.firstChoice(P.lazy(function() {
return U.escapedChar;
}), P.regex(/^./)), P.firstChoice(P.string(options.segmentNameStartChar), P.string(options.optionalSegmentStartChar), P.string(options.optionalSegmentEndChar), U.wildcard)));
U.token = P.lazy(function() {
return P.firstChoice(U.wildcard, U.optional, U.named, U["static"]);
});
U.pattern = P.many1(P.lazy(function() {
return U.token;
}));
return U;
};
defaultOptions = {
escapeChar: '\\',
segmentNameStartChar: ':',
segmentValueCharset: 'a-zA-Z0-9-_~ %',
segmentNameCharset: 'a-zA-Z0-9',
optionalSegmentStartChar: '(',
optionalSegmentEndChar: ')',
wildcardChar: '*'
};
baseAstNodeToRegexString = function(astNode, segmentValueCharset) {
if (Array.isArray(astNode)) {
return stringConcatMap(astNode, function(node) {
return baseAstNodeToRegexString(node, segmentValueCharset);
});
}
switch (astNode.tag) {
case 'wildcard':
return '(.*?)';
case 'named':
return "([" + segmentValueCharset + "]+)";
case 'static':
return escapeForRegex(astNode.value);
case 'optional':
return '(?:' + baseAstNodeToRegexString(astNode.value, segmentValueCharset) + ')?';
}
};
astNodeToRegexString = function(astNode, segmentValueCharset) {
if (segmentValueCharset == null) {
segmentValueCharset = defaultOptions.segmentValueCharset;
}
return '^' + baseAstNodeToRegexString(astNode, segmentValueCharset) + '$';
};
astNodeToNames = function(astNode) {
if (Array.isArray(astNode)) {
return concatMap(astNode, astNodeToNames);
}
switch (astNode.tag) {
case 'wildcard':
return ['_'];
case 'named':
return [astNode.value];
case 'static':
return [];
case 'optional':
return astNodeToNames(astNode.value);
}
};
getParam = function(params, key, nextIndexes, sideEffects) {
var index, maxIndex, result, value;
if (sideEffects == null) {
sideEffects = false;
}
value = params[key];
if (value == null) {
if (sideEffects) {
throw new Error("no values provided for key `" + key + "`");
} else {
return;
}
}
index = nextIndexes[key] || 0;
maxIndex = Array.isArray(value) ? value.length - 1 : 0;
if (index > maxIndex) {
if (sideEffects) {
throw new Error("too few values provided for key `" + key + "`");
} else {
return;
}
}
result = Array.isArray(value) ? value[index] : value;
if (sideEffects) {
nextIndexes[key] = index + 1;
}
return result;
};
astNodeContainsSegmentsForProvidedParams = function(astNode, params, nextIndexes) {
var i, length;
if (Array.isArray(astNode)) {
i = -1;
length = astNode.length;
while (++i < length) {
if (astNodeContainsSegmentsForProvidedParams(astNode[i], params, nextIndexes)) {
return true;
}
}
return false;
}
switch (astNode.tag) {
case 'wildcard':
return getParam(params, '_', nextIndexes, false) != null;
case 'named':
return getParam(params, astNode.value, nextIndexes, false) != null;
case 'static':
return false;
case 'optional':
return astNodeContainsSegmentsForProvidedParams(astNode.value, params, nextIndexes);
}
};
stringify = function(astNode, params, nextIndexes) {
if (Array.isArray(astNode)) {
return stringConcatMap(astNode, function(node) {
return stringify(node, params, nextIndexes);
});
}
switch (astNode.tag) {
case 'wildcard':
return getParam(params, '_', nextIndexes, true);
case 'named':
return getParam(params, astNode.value, nextIndexes, true);
case 'static':
return astNode.value;
case 'optional':
if (astNodeContainsSegmentsForProvidedParams(astNode.value, params, nextIndexes)) {
return stringify(astNode.value, params, nextIndexes);
} else {
return '';
}
}
};
UrlPattern = function(arg1, arg2) {
var groupCount, options, parsed, parser, withoutWhitespace;
if (arg1 instanceof UrlPattern) {
this.isRegex = arg1.isRegex;
this.regex = arg1.regex;
this.ast = arg1.ast;
this.names = arg1.names;
return;
}
this.isRegex = arg1 instanceof RegExp;
if (!(('string' === typeof arg1) || this.isRegex)) {
throw new TypeError('argument must be a regex or a string');
}
if (this.isRegex) {
this.regex = arg1;
if (arg2 != null) {
if (!Array.isArray(arg2)) {
throw new Error('if first argument is a regex the second argument may be an array of group names but you provided something else');
}
groupCount = regexGroupCount(this.regex);
if (arg2.length !== groupCount) {
throw new Error("regex contains " + groupCount + " groups but array of group names contains " + arg2.length);
}
this.names = arg2;
}
return;
}
if (arg1 === '') {
throw new Error('argument must not be the empty string');
}
withoutWhitespace = arg1.replace(/\s+/g, '');
if (withoutWhitespace !== arg1) {
throw new Error('argument must not contain whitespace');
}
options = {
escapeChar: (arg2 != null ? arg2.escapeChar : void 0) || defaultOptions.escapeChar,
segmentNameStartChar: (arg2 != null ? arg2.segmentNameStartChar : void 0) || defaultOptions.segmentNameStartChar,
segmentNameCharset: (arg2 != null ? arg2.segmentNameCharset : void 0) || defaultOptions.segmentNameCharset,
segmentValueCharset: (arg2 != null ? arg2.segmentValueCharset : void 0) || defaultOptions.segmentValueCharset,
optionalSegmentStartChar: (arg2 != null ? arg2.optionalSegmentStartChar : void 0) || defaultOptions.optionalSegmentStartChar,
optionalSegmentEndChar: (arg2 != null ? arg2.optionalSegmentEndChar : void 0) || defaultOptions.optionalSegmentEndChar,
wildcardChar: (arg2 != null ? arg2.wildcardChar : void 0) || defaultOptions.wildcardChar
};
parser = newParser(options);
parsed = parser.pattern(arg1);
if (parsed == null) {
throw new Error("couldn't parse pattern");
}
if (parsed.rest !== '') {
throw new Error("could only partially parse pattern");
}
this.ast = parsed.value;
this.regex = new RegExp(astNodeToRegexString(this.ast, options.segmentValueCharset));
this.names = astNodeToNames(this.ast);
};
UrlPattern.prototype.match = function(url) {
var groups, match;
match = this.regex.exec(url);
if (match == null) {
return null;
}
groups = match.slice(1);
if (this.names) {
return keysAndValuesToObject(this.names, groups);
} else {
return groups;
}
};
UrlPattern.prototype.stringify = function(params) {
if (params == null) {
params = {};
}
if (this.isRegex) {
throw new Error("can't stringify patterns generated from a regex");
}
if (params !== Object(params)) {
throw new Error("argument must be an object or undefined");
}
return stringify(this.ast, params, {});
};
UrlPattern.escapeForRegex = escapeForRegex;
UrlPattern.concatMap = concatMap;
UrlPattern.stringConcatMap = stringConcatMap;
UrlPattern.regexGroupCount = regexGroupCount;
UrlPattern.keysAndValuesToObject = keysAndValuesToObject;
UrlPattern.P = P;
UrlPattern.newParser = newParser;
UrlPattern.defaultOptions = defaultOptions;
UrlPattern.astNodeToRegexString = astNodeToRegexString;
UrlPattern.astNodeToNames = astNodeToNames;
UrlPattern.getParam = getParam;
UrlPattern.astNodeContainsSegmentsForProvidedParams = astNodeContainsSegmentsForProvidedParams;
UrlPattern.stringify = stringify;
return UrlPattern;
});
/***/ },
/* 18 */
/***/ function(module, exports) {
/* WEBPACK VAR INJECTION */(function(__webpack_amd_options__) {module.exports = __webpack_amd_options__;
/* WEBPACK VAR INJECTION */}.call(exports, {}))
/***/ },
/* 19 */
/***/ function(module, exports, __webpack_require__) {
/**
* lodash 4.3.0 (Custom Build) <https://lodash.com/>
* Build: `lodash modularize exports="npm" -o ./`
* Copyright jQuery Foundation and other contributors <https://jquery.org/>
* Released under MIT license <https://lodash.com/license>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
*/
var baseEach = __webpack_require__(20),
baseFind = __webpack_require__(21),
baseFindIndex = __webpack_require__(22),
baseIteratee = __webpack_require__(23);
/**
* Iterates over elements of `collection`, returning the first element
* `predicate` returns truthy for. The predicate is invoked with three
* arguments: (value, index|key, collection).
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to search.
* @param {Array|Function|Object|string} [predicate=_.identity]
* The function invoked per iteration.
* @returns {*} Returns the matched element, else `undefined`.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': true },
* { 'user': 'fred', 'age': 40, 'active': false },
* { 'user': 'pebbles', 'age': 1, 'active': true }
* ];
*
* _.find(users, function(o) { return o.age < 40; });
* // => object for 'barney'
*
* // The `_.matches` iteratee shorthand.
* _.find(users, { 'age': 1, 'active': true });
* // => object for 'pebbles'
*
* // The `_.matchesProperty` iteratee shorthand.
* _.find(users, ['active', false]);
* // => object for 'fred'
*
* // The `_.property` iteratee shorthand.
* _.find(users, 'active');
* // => object for 'barney'
*/
function find(collection, predicate) {
predicate = baseIteratee(predicate, 3);
if (isArray(collection)) {
var index = baseFindIndex(collection, predicate);
return index > -1 ? collection[index] : undefined;
}
return baseFind(collection, predicate, baseEach);
}
/**
* Checks if `value` is classified as an `Array` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @type {Function}
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified,
* else `false`.
* @example
*
* _.isArray([1, 2, 3]);
* // => true
*
* _.isArray(document.body.children);
* // => false
*
* _.isArray('abc');
* // => false
*
* _.isArray(_.noop);
* // => false
*/
var isArray = Array.isArray;
module.exports = find;
/***/ },
/* 20 */
/***/ function(module, exports) {
/**
* lodash 4.1.2 (Custom Build) <https://lodash.com/>
* Build: `lodash modularize exports="npm" -o ./`
* Copyright jQuery Foundation and other contributors <https://jquery.org/>
* Released under MIT license <https://lodash.com/license>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
*/
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;
/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
funcTag = '[object Function]',
genTag = '[object GeneratorFunction]',
stringTag = '[object String]';
/** Used to detect unsigned integer values. */
var reIsUint = /^(?:0|[1-9]\d*)$/;
/**
* The base implementation of `_.times` without support for iteratee shorthands
* or max array length checks.
*
* @private
* @param {number} n The number of times to invoke `iteratee`.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the array of results.
*/
function baseTimes(n, iteratee) {
var index = -1,
result = Array(n);
while (++index < n) {
result[index] = iteratee(index);
}
return result;
}
/**
* Checks if `value` is a valid array-like index.
*
* @private
* @param {*} value The value to check.
* @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
* @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
*/
function isIndex(value, length) {
value = (typeof value == 'number' || reIsUint.test(value)) ? +value : -1;
length = length == null ? MAX_SAFE_INTEGER : length;
return value > -1 && value % 1 == 0 && value < length;
}
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
* of values.
*/
var objectToString = objectProto.toString;
/** Built-in value references. */
var propertyIsEnumerable = objectProto.propertyIsEnumerable;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeGetPrototype = Object.getPrototypeOf,
nativeKeys = Object.keys;
/**
* The base implementation of `_.forEach` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array|Object} Returns `collection`.
*/
var baseEach = createBaseEach(baseForOwn);
/**
* The base implementation of `baseForOwn` which iterates over `object`
* properties returned by `keysFunc` invoking `iteratee` for each property.
* Iteratee functions may exit iteration early by explicitly returning `false`.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {Function} keysFunc The function to get the keys of `object`.
* @returns {Object} Returns `object`.
*/
var baseFor = createBaseFor();
/**
* The base implementation of `_.forOwn` without support for iteratee shorthands.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Object} Returns `object`.
*/
function baseForOwn(object, iteratee) {
return object && baseFor(object, iteratee, keys);
}
/**
* The base implementation of `_.has` without support for deep paths.
*
* @private
* @param {Object} object The object to query.
* @param {Array|string} key The key to check.
* @returns {boolean} Returns `true` if `key` exists, else `false`.
*/
function baseHas(object, key) {
// Avoid a bug in IE 10-11 where objects with a [[Prototype]] of `null`,
// that are composed entirely of index properties, return `false` for
// `hasOwnProperty` checks of them.
return hasOwnProperty.call(object, key) ||
(typeof object == 'object' && key in object && getPrototype(object) === null);
}
/**
* The base implementation of `_.keys` which doesn't skip the constructor
* property of prototypes or treat sparse arrays as dense.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function baseKeys(object) {
return nativeKeys(Object(object));
}
/**
* The base implementation of `_.property` without support for deep paths.
*
* @private
* @param {string} key The key of the property to get.
* @returns {Function} Returns the new function.
*/
function baseProperty(key) {
return function(object) {
return object == null ? undefined : object[key];
};
}
/**
* Creates a `baseEach` or `baseEachRight` function.
*
* @private
* @param {Function} eachFunc The function to iterate over a collection.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new base function.
*/
function createBaseEach(eachFunc, fromRight) {
return function(collection, iteratee) {
if (collection == null) {
return collection;
}
if (!isArrayLike(collection)) {
return eachFunc(collection, iteratee);
}
var length = collection.length,
index = fromRight ? length : -1,
iterable = Object(collection);
while ((fromRight ? index-- : ++index < length)) {
if (iteratee(iterable[index], index, iterable) === false) {
break;
}
}
return collection;
};
}
/**
* Creates a base function for methods like `_.forIn` and `_.forOwn`.
*
* @private
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new base function.
*/
function createBaseFor(fromRight) {
return function(object, iteratee, keysFunc) {
var index = -1,
iterable = Object(object),
props = keysFunc(object),
length = props.length;
while (length--) {
var key = props[fromRight ? length : ++index];
if (iteratee(iterable[key], key, iterable) === false) {
break;
}
}
return object;
};
}
/**
* Gets the "length" property value of `object`.
*
* **Note:** This function is used to avoid a
* [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792) that affects
* Safari on at least iOS 8.1-8.3 ARM64.
*
* @private
* @param {Object} object The object to query.
* @returns {*} Returns the "length" value.
*/
var getLength = baseProperty('length');
/**
* Gets the `[[Prototype]]` of `value`.
*
* @private
* @param {*} value The value to query.
* @returns {null|Object} Returns the `[[Prototype]]`.
*/
function getPrototype(value) {
return nativeGetPrototype(Object(value));
}
/**
* Creates an array of index keys for `object` values of arrays,
* `arguments` objects, and strings, otherwise `null` is returned.
*
* @private
* @param {Object} object The object to query.
* @returns {Array|null} Returns index keys, else `null`.
*/
function indexKeys(object) {
var length = object ? object.length : undefined;
if (isLength(length) &&
(isArray(object) || isString(object) || isArguments(object))) {
return baseTimes(length, String);
}
return null;
}
/**
* Checks if `value` is likely a prototype object.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
*/
function isPrototype(value) {
var Ctor = value && value.constructor,
proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;
return value === proto;
}
/**
* Checks if `value` is likely an `arguments` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified,
* else `false`.
* @example
*
* _.isArguments(function() { return arguments; }());
* // => true
*
* _.isArguments([1, 2, 3]);
* // => false
*/
function isArguments(value) {
// Safari 8.1 incorrectly makes `arguments.callee` enumerable in strict mode.
return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') &&
(!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag);
}
/**
* Checks if `value` is classified as an `Array` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @type {Function}
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified,
* else `false`.
* @example
*
* _.isArray([1, 2, 3]);
* // => true
*
* _.isArray(document.body.children);
* // => false
*
* _.isArray('abc');
* // => false
*
* _.isArray(_.noop);
* // => false
*/
var isArray = Array.isArray;
/**
* Checks if `value` is array-like. A value is considered array-like if it's
* not a function and has a `value.length` that's an integer greater than or
* equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is array-like, else `false`.
* @example
*
* _.isArrayLike([1, 2, 3]);
* // => true
*
* _.isArrayLike(document.body.children);
* // => true
*
* _.isArrayLike('abc');
* // => true
*
* _.isArrayLike(_.noop);
* // => false
*/
function isArrayLike(value) {
return value != null && isLength(getLength(value)) && !isFunction(value);
}
/**
* This method is like `_.isArrayLike` except that it also checks if `value`
* is an object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array-like object,
* else `false`.
* @example
*
* _.isArrayLikeObject([1, 2, 3]);
* // => true
*
* _.isArrayLikeObject(document.body.children);
* // => true
*
* _.isArrayLikeObject('abc');
* // => false
*
* _.isArrayLikeObject(_.noop);
* // => false
*/
function isArrayLikeObject(value) {
return isObjectLike(value) && isArrayLike(value);
}
/**
* Checks if `value` is classified as a `Function` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified,
* else `false`.
* @example
*
* _.isFunction(_);
* // => true
*
* _.isFunction(/abc/);
* // => false
*/
function isFunction(value) {
// The use of `Object#toString` avoids issues with the `typeof` operator
// in Safari 8 which returns 'object' for typed array and weak map constructors,
// and PhantomJS 1.9 which returns 'function' for `NodeList` instances.
var tag = isObject(value) ? objectToString.call(value) : '';
return tag == funcTag || tag == genTag;
}
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This function is loosely based on
* [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length,
* else `false`.
* @example
*
* _.isLength(3);
* // => true
*
* _.isLength(Number.MIN_VALUE);
* // => false
*
* _.isLength(Infinity);
* // => false
*
* _.isLength('3');
* // => false
*/
function isLength(value) {
return typeof value == 'number' &&
value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
/**
* Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
* (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(_.noop);
* // => true
*
* _.isObject(null);
* // => false
*/
function isObject(value) {
var type = typeof value;
return !!value && (type == 'object' || type == 'function');
}
/**
* Checks if `value` is object-like. A value is object-like if it's not `null`
* and has a `typeof` result of "object".
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
* @example
*
* _.isObjectLike({});
* // => true
*
* _.isObjectLike([1, 2, 3]);
* // => true
*
* _.isObjectLike(_.noop);
* // => false
*
* _.isObjectLike(null);
* // => false
*/
function isObjectLike(value) {
return !!value && typeof value == 'object';
}
/**
* Checks if `value` is classified as a `String` primitive or object.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified,
* else `false`.
* @example
*
* _.isString('abc');
* // => true
*
* _.isString(1);
* // => false
*/
function isString(value) {
return typeof value == 'string' ||
(!isArray(value) && isObjectLike(value) && objectToString.call(value) == stringTag);
}
/**
* Creates an array of the own enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects. See the
* [ES spec](http://ecma-international.org/ecma-262/6.0/#sec-object.keys)
* for more details.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keys(new Foo);
* // => ['a', 'b'] (iteration order is not guaranteed)
*
* _.keys('hi');
* // => ['0', '1']
*/
function keys(object) {
var isProto = isPrototype(object);
if (!(isProto || isArrayLike(object))) {
return baseKeys(object);
}
var indexes = indexKeys(object),
skipIndexes = !!indexes,
result = indexes || [],
length = result.length;
for (var key in object) {
if (baseHas(object, key) &&
!(skipIndexes && (key == 'length' || isIndex(key, length))) &&
!(isProto && key == 'constructor')) {
result.push(key);
}
}
return result;
}
module.exports = baseEach;
/***/ },
/* 21 */
/***/ function(module, exports) {
/**
* lodash 3.0.0 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.7.0 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
/**
* The base implementation of `_.find`, `_.findLast`, `_.findKey`, and `_.findLastKey`,
* without support for callback shorthands and `this` binding, which iterates
* over `collection` using the provided `eachFunc`.
*
* @private
* @param {Array|Object|string} collection The collection to search.
* @param {Function} predicate The function invoked per iteration.
* @param {Function} eachFunc The function to iterate over `collection`.
* @param {boolean} [retKey] Specify returning the key of the found element
* instead of the element itself.
* @returns {*} Returns the found element or its key, else `undefined`.
*/
function baseFind(collection, predicate, eachFunc, retKey) {
var result;
eachFunc(collection, function(value, key, collection) {
if (predicate(value, key, collection)) {
result = retKey ? key : value;
return false;
}
});
return result;
}
module.exports = baseFind;
/***/ },
/* 22 */
/***/ function(module, exports) {
/**
* lodash 3.6.0 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.2 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
/**
* The base implementation of `_.findIndex` and `_.findLastIndex` without
* support for callback shorthands and `this` binding.
*
* @private
* @param {Array} array The array to search.
* @param {Function} predicate The function invoked per iteration.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function baseFindIndex(array, predicate, fromRight) {
var length = array.length,
index = fromRight ? length : -1;
while ((fromRight ? index-- : ++index < length)) {
if (predicate(array[index], index, array)) {
return index;
}
}
return -1;
}
module.exports = baseFindIndex;
/***/ },
/* 23 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(module, global) {/**
* lodash 4.6.1 (Custom Build) <https://lodash.com/>
* Build: `lodash modularize exports="npm" -o ./`
* Copyright jQuery Foundation and other contributors <https://jquery.org/>
* Released under MIT license <https://lodash.com/license>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
*/
var stringToPath = __webpack_require__(25);
/** Used as the size to enable large array optimizations. */
var LARGE_ARRAY_SIZE = 200;
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';
/** Used to compose bitmasks for comparison styles. */
var UNORDERED_COMPARE_FLAG = 1,
PARTIAL_COMPARE_FLAG = 2;
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;
/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
arrayTag = '[object Array]',
boolTag = '[object Boolean]',
dateTag = '[object Date]',
errorTag = '[object Error]',
funcTag = '[object Function]',
genTag = '[object GeneratorFunction]',
mapTag = '[object Map]',
numberTag = '[object Number]',
objectTag = '[object Object]',
promiseTag = '[object Promise]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
symbolTag = '[object Symbol]',
weakMapTag = '[object WeakMap]';
var arrayBufferTag = '[object ArrayBuffer]',
dataViewTag = '[object DataView]',
float32Tag = '[object Float32Array]',
float64Tag = '[object Float64Array]',
int8Tag = '[object Int8Array]',
int16Tag = '[object Int16Array]',
int32Tag = '[object Int32Array]',
uint8Tag = '[object Uint8Array]',
uint8ClampedTag = '[object Uint8ClampedArray]',
uint16Tag = '[object Uint16Array]',
uint32Tag = '[object Uint32Array]';
/** Used to match property names within property paths. */
var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
reIsPlainProp = /^\w*$/;
/**
* Used to match `RegExp`
* [syntax characters](http://ecma-international.org/ecma-262/6.0/#sec-patterns).
*/
var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
/** Used to detect host constructors (Safari). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;
/** Used to detect unsigned integer values. */
var reIsUint = /^(?:0|[1-9]\d*)$/;
/** Used to identify `toStringTag` values of typed arrays. */
var typedArrayTags = {};
typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
typedArrayTags[uint32Tag] = true;
typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =
typedArrayTags[errorTag] = typedArrayTags[funcTag] =
typedArrayTags[mapTag] = typedArrayTags[numberTag] =
typedArrayTags[objectTag] = typedArrayTags[regexpTag] =
typedArrayTags[setTag] = typedArrayTags[stringTag] =
typedArrayTags[weakMapTag] = false;
/** Used to determine if values are of the language type `Object`. */
var objectTypes = {
'function': true,
'object': true
};
/** Detect free variable `exports`. */
var freeExports = (objectTypes[typeof exports] && exports && !exports.nodeType)
? exports
: undefined;
/** Detect free variable `module`. */
var freeModule = (objectTypes[typeof module] && module && !module.nodeType)
? module
: undefined;
/** Detect free variable `global` from Node.js. */
var freeGlobal = checkGlobal(freeExports && freeModule && typeof global == 'object' && global);
/** Detect free variable `self`. */
var freeSelf = checkGlobal(objectTypes[typeof self] && self);
/** Detect free variable `window`. */
var freeWindow = checkGlobal(objectTypes[typeof window] && window);
/** Detect `this` as the global object. */
var thisGlobal = checkGlobal(objectTypes[typeof this] && this);
/**
* Used as a reference to the global object.
*
* The `this` value is used if it's the global object to avoid Greasemonkey's
* restricted `window` object, otherwise the `window` object is used.
*/
var root = freeGlobal ||
((freeWindow !== (thisGlobal && thisGlobal.window)) && freeWindow) ||
freeSelf || thisGlobal || Function('return this')();
/**
* A specialized version of `_.map` for arrays without support for iteratee
* shorthands.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
*/
function arrayMap(array, iteratee) {
var index = -1,
length = array.length,
result = Array(length);
while (++index < length) {
result[index] = iteratee(array[index], index, array);
}
return result;
}
/**
* A specialized version of `_.some` for arrays without support for iteratee
* shorthands.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {boolean} Returns `true` if any element passes the predicate check,
* else `false`.
*/
function arraySome(array, predicate) {
var index = -1,
length = array.length;
while (++index < length) {
if (predicate(array[index], index, array)) {
return true;
}
}
return false;
}
/**
* The base implementation of `_.times` without support for iteratee shorthands
* or max array length checks.
*
* @private
* @param {number} n The number of times to invoke `iteratee`.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the array of results.
*/
function baseTimes(n, iteratee) {
var index = -1,
result = Array(n);
while (++index < n) {
result[index] = iteratee(index);
}
return result;
}
/**
* The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array
* of key-value pairs for `object` corresponding to the property names of `props`.
*
* @private
* @param {Object} object The object to query.
* @param {Array} props The property names to get values for.
* @returns {Object} Returns the new array of key-value pairs.
*/
function baseToPairs(object, props) {
return arrayMap(props, function(key) {
return [key, object[key]];
});
}
/**
* Checks if `value` is a global object.
*
* @private
* @param {*} value The value to check.
* @returns {null|Object} Returns `value` if it's a global object, else `null`.
*/
function checkGlobal(value) {
return (value && value.Object === Object) ? value : null;
}
/**
* Checks if `value` is a host object in IE < 9.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a host object, else `false`.
*/
function isHostObject(value) {
// Many host objects are `Object` objects that can coerce to strings
// despite having improperly defined `toString` methods.
var result = false;
if (value != null && typeof value.toString != 'function') {
try {
result = !!(value + '');
} catch (e) {}
}
return result;
}
/**
* Checks if `value` is a valid array-like index.
*
* @private
* @param {*} value The value to check.
* @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
* @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
*/
function isIndex(value, length) {
value = (typeof value == 'number' || reIsUint.test(value)) ? +value : -1;
length = length == null ? MAX_SAFE_INTEGER : length;
return value > -1 && value % 1 == 0 && value < length;
}
/**
* Converts `map` to an array.
*
* @private
* @param {Object} map The map to convert.
* @returns {Array} Returns the converted array.
*/
function mapToArray(map) {
var index = -1,
result = Array(map.size);
map.forEach(function(value, key) {
result[++index] = [key, value];
});
return result;
}
/**
* Converts `set` to an array.
*
* @private
* @param {Object} set The set to convert.
* @returns {Array} Returns the converted array.
*/
function setToArray(set) {
var index = -1,
result = Array(set.size);
set.forEach(function(value) {
result[++index] = value;
});
return result;
}
/** Used for built-in method references. */
var arrayProto = Array.prototype,
objectProto = Object.prototype;
/** Used to resolve the decompiled source of functions. */
var funcToString = Function.prototype.toString;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
* of values.
*/
var objectToString = objectProto.toString;
/** Used to detect if a method is native. */
var reIsNative = RegExp('^' +
funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
.replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);
/** Built-in value references. */
var Symbol = root.Symbol,
Uint8Array = root.Uint8Array,
propertyIsEnumerable = objectProto.propertyIsEnumerable,
splice = arrayProto.splice;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeGetPrototype = Object.getPrototypeOf,
nativeKeys = Object.keys;
/* Built-in method references that are verified to be native. */
var DataView = getNative(root, 'DataView'),
Map = getNative(root, 'Map'),
Promise = getNative(root, 'Promise'),
Set = getNative(root, 'Set'),
WeakMap = getNative(root, 'WeakMap'),
nativeCreate = getNative(Object, 'create');
/** Used to detect maps, sets, and weakmaps. */
var dataViewCtorString = toSource(DataView),
mapCtorString = toSource(Map),
promiseCtorString = toSource(Promise),
setCtorString = toSource(Set),
weakMapCtorString = toSource(WeakMap);
/** Used to convert symbols to primitives and strings. */
var symbolProto = Symbol ? Symbol.prototype : undefined,
symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;
/**
* Creates a hash object.
*
* @private
* @constructor
* @returns {Object} Returns the new hash object.
*/
function Hash() {}
/**
* Removes `key` and its value from the hash.
*
* @private
* @param {Object} hash The hash to modify.
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function hashDelete(hash, key) {
return hashHas(hash, key) && delete hash[key];
}
/**
* Gets the hash value for `key`.
*
* @private
* @param {Object} hash The hash to query.
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function hashGet(hash, key) {
if (nativeCreate) {
var result = hash[key];
return result === HASH_UNDEFINED ? undefined : result;
}
return hasOwnProperty.call(hash, key) ? hash[key] : undefined;
}
/**
* Checks if a hash value for `key` exists.
*
* @private
* @param {Object} hash The hash to query.
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function hashHas(hash, key) {
return nativeCreate ? hash[key] !== undefined : hasOwnProperty.call(hash, key);
}
/**
* Sets the hash `key` to `value`.
*
* @private
* @param {Object} hash The hash to modify.
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
*/
function hashSet(hash, key, value) {
hash[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;
}
// Avoid inheriting from `Object.prototype` when possible.
Hash.prototype = nativeCreate ? nativeCreate(null) : objectProto;
/**
* Creates a map cache object to store key-value pairs.
*
* @private
* @constructor
* @param {Array} [values] The values to cache.
*/
function MapCache(values) {
var index = -1,
length = values ? values.length : 0;
this.clear();
while (++index < length) {
var entry = values[index];
this.set(entry[0], entry[1]);
}
}
/**
* Removes all key-value entries from the map.
*
* @private
* @name clear
* @memberOf MapCache
*/
function mapClear() {
this.__data__ = {
'hash': new Hash,
'map': Map ? new Map : [],
'string': new Hash
};
}
/**
* Removes `key` and its value from the map.
*
* @private
* @name delete
* @memberOf MapCache
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function mapDelete(key) {
var data = this.__data__;
if (isKeyable(key)) {
return hashDelete(typeof key == 'string' ? data.string : data.hash, key);
}
return Map ? data.map['delete'](key) : assocDelete(data.map, key);
}
/**
* Gets the map value for `key`.
*
* @private
* @name get
* @memberOf MapCache
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function mapGet(key) {
var data = this.__data__;
if (isKeyable(key)) {
return hashGet(typeof key == 'string' ? data.string : data.hash, key);
}
return Map ? data.map.get(key) : assocGet(data.map, key);
}
/**
* Checks if a map value for `key` exists.
*
* @private
* @name has
* @memberOf MapCache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function mapHas(key) {
var data = this.__data__;
if (isKeyable(key)) {
return hashHas(typeof key == 'string' ? data.string : data.hash, key);
}
return Map ? data.map.has(key) : assocHas(data.map, key);
}
/**
* Sets the map `key` to `value`.
*
* @private
* @name set
* @memberOf MapCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the map cache instance.
*/
function mapSet(key, value) {
var data = this.__data__;
if (isKeyable(key)) {
hashSet(typeof key == 'string' ? data.string : data.hash, key, value);
} else if (Map) {
data.map.set(key, value);
} else {
assocSet(data.map, key, value);
}
return this;
}
// Add methods to `MapCache`.
MapCache.prototype.clear = mapClear;
MapCache.prototype['delete'] = mapDelete;
MapCache.prototype.get = mapGet;
MapCache.prototype.has = mapHas;
MapCache.prototype.set = mapSet;
/**
* Creates a stack cache object to store key-value pairs.
*
* @private
* @constructor
* @param {Array} [values] The values to cache.
*/
function Stack(values) {
var index = -1,
length = values ? values.length : 0;
this.clear();
while (++index < length) {
var entry = values[index];
this.set(entry[0], entry[1]);
}
}
/**
* Removes all key-value entries from the stack.
*
* @private
* @name clear
* @memberOf Stack
*/
function stackClear() {
this.__data__ = { 'array': [], 'map': null };
}
/**
* Removes `key` and its value from the stack.
*
* @private
* @name delete
* @memberOf Stack
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function stackDelete(key) {
var data = this.__data__,
array = data.array;
return array ? assocDelete(array, key) : data.map['delete'](key);
}
/**
* Gets the stack value for `key`.
*
* @private
* @name get
* @memberOf Stack
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function stackGet(key) {
var data = this.__data__,
array = data.array;
return array ? assocGet(array, key) : data.map.get(key);
}
/**
* Checks if a stack value for `key` exists.
*
* @private
* @name has
* @memberOf Stack
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function stackHas(key) {
var data = this.__data__,
array = data.array;
return array ? assocHas(array, key) : data.map.has(key);
}
/**
* Sets the stack `key` to `value`.
*
* @private
* @name set
* @memberOf Stack
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the stack cache instance.
*/
function stackSet(key, value) {
var data = this.__data__,
array = data.array;
if (array) {
if (array.length < (LARGE_ARRAY_SIZE - 1)) {
assocSet(array, key, value);
} else {
data.array = null;
data.map = new MapCache(array);
}
}
var map = data.map;
if (map) {
map.set(key, value);
}
return this;
}
// Add methods to `Stack`.
Stack.prototype.clear = stackClear;
Stack.prototype['delete'] = stackDelete;
Stack.prototype.get = stackGet;
Stack.prototype.has = stackHas;
Stack.prototype.set = stackSet;
/**
* Removes `key` and its value from the associative array.
*
* @private
* @param {Array} array The array to modify.
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function assocDelete(array, key) {
var index = assocIndexOf(array, key);
if (index < 0) {
return false;
}
var lastIndex = array.length - 1;
if (index == lastIndex) {
array.pop();
} else {
splice.call(array, index, 1);
}
return true;
}
/**
* Gets the associative array value for `key`.
*
* @private
* @param {Array} array The array to query.
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function assocGet(array, key) {
var index = assocIndexOf(array, key);
return index < 0 ? undefined : array[index][1];
}
/**
* Checks if an associative array value for `key` exists.
*
* @private
* @param {Array} array The array to query.
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function assocHas(array, key) {
return assocIndexOf(array, key) > -1;
}
/**
* Gets the index at which the `key` is found in `array` of key-value pairs.
*
* @private
* @param {Array} array The array to search.
* @param {*} key The key to search for.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function assocIndexOf(array, key) {
var length = array.length;
while (length--) {
if (eq(array[length][0], key)) {
return length;
}
}
return -1;
}
/**
* Sets the associative array `key` to `value`.
*
* @private
* @param {Array} array The array to modify.
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
*/
function assocSet(array, key, value) {
var index = assocIndexOf(array, key);
if (index < 0) {
array.push([key, value]);
} else {
array[index][1] = value;
}
}
/**
* Casts `value` to a path array if it's not one.
*
* @private
* @param {*} value The value to inspect.
* @returns {Array} Returns the cast property path array.
*/
function baseCastPath(value) {
return isArray(value) ? value : stringToPath(value);
}
/**
* The base implementation of `_.get` without support for default values.
*
* @private
* @param {Object} object The object to query.
* @param {Array|string} path The path of the property to get.
* @returns {*} Returns the resolved value.
*/
function baseGet(object, path) {
path = isKey(path, object) ? [path] : baseCastPath(path);
var index = 0,
length = path.length;
while (object != null && index < length) {
object = object[path[index++]];
}
return (index && index == length) ? object : undefined;
}
/**
* The base implementation of `_.has` without support for deep paths.
*
* @private
* @param {Object} object The object to query.
* @param {Array|string} key The key to check.
* @returns {boolean} Returns `true` if `key` exists, else `false`.
*/
function baseHas(object, key) {
// Avoid a bug in IE 10-11 where objects with a [[Prototype]] of `null`,
// that are composed entirely of index properties, return `false` for
// `hasOwnProperty` checks of them.
return hasOwnProperty.call(object, key) ||
(typeof object == 'object' && key in object && getPrototype(object) === null);
}
/**
* The base implementation of `_.hasIn` without support for deep paths.
*
* @private
* @param {Object} object The object to query.
* @param {Array|string} key The key to check.
* @returns {boolean} Returns `true` if `key` exists, else `false`.
*/
function baseHasIn(object, key) {
return key in Object(object);
}
/**
* The base implementation of `_.isEqual` which supports partial comparisons
* and tracks traversed objects.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @param {Function} [customizer] The function to customize comparisons.
* @param {boolean} [bitmask] The bitmask of comparison flags.
* The bitmask may be composed of the following flags:
* 1 - Unordered comparison
* 2 - Partial comparison
* @param {Object} [stack] Tracks traversed `value` and `other` objects.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
*/
function baseIsEqual(value, other, customizer, bitmask, stack) {
if (value === other) {
return true;
}
if (value == null || other == null || (!isObject(value) && !isObjectLike(other))) {
return value !== value && other !== other;
}
return baseIsEqualDeep(value, other, baseIsEqual, customizer, bitmask, stack);
}
/**
* A specialized version of `baseIsEqual` for arrays and objects which performs
* deep comparisons and tracks traversed objects enabling objects with circular
* references to be compared.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Function} [customizer] The function to customize comparisons.
* @param {number} [bitmask] The bitmask of comparison flags. See `baseIsEqual`
* for more details.
* @param {Object} [stack] Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function baseIsEqualDeep(object, other, equalFunc, customizer, bitmask, stack) {
var objIsArr = isArray(object),
othIsArr = isArray(other),
objTag = arrayTag,
othTag = arrayTag;
if (!objIsArr) {
objTag = getTag(object);
objTag = objTag == argsTag ? objectTag : objTag;
}
if (!othIsArr) {
othTag = getTag(other);
othTag = othTag == argsTag ? objectTag : othTag;
}
var objIsObj = objTag == objectTag && !isHostObject(object),
othIsObj = othTag == objectTag && !isHostObject(other),
isSameTag = objTag == othTag;
if (isSameTag && !objIsObj) {
stack || (stack = new Stack);
return (objIsArr || isTypedArray(object))
? equalArrays(object, other, equalFunc, customizer, bitmask, stack)
: equalByTag(object, other, objTag, equalFunc, customizer, bitmask, stack);
}
if (!(bitmask & PARTIAL_COMPARE_FLAG)) {
var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
if (objIsWrapped || othIsWrapped) {
var objUnwrapped = objIsWrapped ? object.value() : object,
othUnwrapped = othIsWrapped ? other.value() : other;
stack || (stack = new Stack);
return equalFunc(objUnwrapped, othUnwrapped, customizer, bitmask, stack);
}
}
if (!isSameTag) {
return false;
}
stack || (stack = new Stack);
return equalObjects(object, other, equalFunc, customizer, bitmask, stack);
}
/**
* The base implementation of `_.isMatch` without support for iteratee shorthands.
*
* @private
* @param {Object} object The object to inspect.
* @param {Object} source The object of property values to match.
* @param {Array} matchData The property names, values, and compare flags to match.
* @param {Function} [customizer] The function to customize comparisons.
* @returns {boolean} Returns `true` if `object` is a match, else `false`.
*/
function baseIsMatch(object, source, matchData, customizer) {
var index = matchData.length,
length = index,
noCustomizer = !customizer;
if (object == null) {
return !length;
}
object = Object(object);
while (index--) {
var data = matchData[index];
if ((noCustomizer && data[2])
? data[1] !== object[data[0]]
: !(data[0] in object)
) {
return false;
}
}
while (++index < length) {
data = matchData[index];
var key = data[0],
objValue = object[key],
srcValue = data[1];
if (noCustomizer && data[2]) {
if (objValue === undefined && !(key in object)) {
return false;
}
} else {
var stack = new Stack;
if (customizer) {
var result = customizer(objValue, srcValue, key, object, source, stack);
}
if (!(result === undefined
? baseIsEqual(srcValue, objValue, customizer, UNORDERED_COMPARE_FLAG | PARTIAL_COMPARE_FLAG, stack)
: result
)) {
return false;
}
}
}
return true;
}
/**
* The base implementation of `_.iteratee`.
*
* @private
* @param {*} [value=_.identity] The value to convert to an iteratee.
* @returns {Function} Returns the iteratee.
*/
function baseIteratee(value) {
// Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.
// See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.
if (typeof value == 'function') {
return value;
}
if (value == null) {
return identity;
}
if (typeof value == 'object') {
return isArray(value)
? baseMatchesProperty(value[0], value[1])
: baseMatches(value);
}
return property(value);
}
/**
* The base implementation of `_.keys` which doesn't skip the constructor
* property of prototypes or treat sparse arrays as dense.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function baseKeys(object) {
return nativeKeys(Object(object));
}
/**
* The base implementation of `_.matches` which doesn't clone `source`.
*
* @private
* @param {Object} source The object of property values to match.
* @returns {Function} Returns the new function.
*/
function baseMatches(source) {
var matchData = getMatchData(source);
if (matchData.length == 1 && matchData[0][2]) {
return matchesStrictComparable(matchData[0][0], matchData[0][1]);
}
return function(object) {
return object === source || baseIsMatch(object, source, matchData);
};
}
/**
* The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
*
* @private
* @param {string} path The path of the property to get.
* @param {*} srcValue The value to match.
* @returns {Function} Returns the new function.
*/
function baseMatchesProperty(path, srcValue) {
if (isKey(path) && isStrictComparable(srcValue)) {
return matchesStrictComparable(path, srcValue);
}
return function(object) {
var objValue = get(object, path);
return (objValue === undefined && objValue === srcValue)
? hasIn(object, path)
: baseIsEqual(srcValue, objValue, undefined, UNORDERED_COMPARE_FLAG | PARTIAL_COMPARE_FLAG);
};
}
/**
* The base implementation of `_.property` without support for deep paths.
*
* @private
* @param {string} key The key of the property to get.
* @returns {Function} Returns the new function.
*/
function baseProperty(key) {
return function(object) {
return object == null ? undefined : object[key];
};
}
/**
* A specialized version of `baseProperty` which supports deep paths.
*
* @private
* @param {Array|string} path The path of the property to get.
* @returns {Function} Returns the new function.
*/
function basePropertyDeep(path) {
return function(object) {
return baseGet(object, path);
};
}
/**
* A specialized version of `baseIsEqualDeep` for arrays with support for
* partial deep comparisons.
*
* @private
* @param {Array} array The array to compare.
* @param {Array} other The other array to compare.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Function} customizer The function to customize comparisons.
* @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual`
* for more details.
* @param {Object} stack Tracks traversed `array` and `other` objects.
* @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
*/
function equalArrays(array, other, equalFunc, customizer, bitmask, stack) {
var index = -1,
isPartial = bitmask & PARTIAL_COMPARE_FLAG,
isUnordered = bitmask & UNORDERED_COMPARE_FLAG,
arrLength = array.length,
othLength = other.length;
if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
return false;
}
// Assume cyclic values are equal.
var stacked = stack.get(array);
if (stacked) {
return stacked == other;
}
var result = true;
stack.set(array, other);
// Ignore non-index properties.
while (++index < arrLength) {
var arrValue = array[index],
othValue = other[index];
if (customizer) {
var compared = isPartial
? customizer(othValue, arrValue, index, other, array, stack)
: customizer(arrValue, othValue, index, array, other, stack);
}
if (compared !== undefined) {
if (compared) {
continue;
}
result = false;
break;
}
// Recursively compare arrays (susceptible to call stack limits).
if (isUnordered) {
if (!arraySome(other, function(othValue) {
return arrValue === othValue ||
equalFunc(arrValue, othValue, customizer, bitmask, stack);
})) {
result = false;
break;
}
} else if (!(
arrValue === othValue ||
equalFunc(arrValue, othValue, customizer, bitmask, stack)
)) {
result = false;
break;
}
}
stack['delete'](array);
return result;
}
/**
* A specialized version of `baseIsEqualDeep` for comparing objects of
* the same `toStringTag`.
*
* **Note:** This function only supports comparing values with tags of
* `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {string} tag The `toStringTag` of the objects to compare.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Function} customizer The function to customize comparisons.
* @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual`
* for more details.
* @param {Object} stack Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function equalByTag(object, other, tag, equalFunc, customizer, bitmask, stack) {
switch (tag) {
case dataViewTag:
if ((object.byteLength != other.byteLength) ||
(object.byteOffset != other.byteOffset)) {
return false;
}
object = object.buffer;
other = other.buffer;
case arrayBufferTag:
if ((object.byteLength != other.byteLength) ||
!equalFunc(new Uint8Array(object), new Uint8Array(other))) {
return false;
}
return true;
case boolTag:
case dateTag:
// Coerce dates and booleans to numbers, dates to milliseconds and
// booleans to `1` or `0` treating invalid dates coerced to `NaN` as
// not equal.
return +object == +other;
case errorTag:
return object.name == other.name && object.message == other.message;
case numberTag:
// Treat `NaN` vs. `NaN` as equal.
return (object != +object) ? other != +other : object == +other;
case regexpTag:
case stringTag:
// Coerce regexes to strings and treat strings, primitives and objects,
// as equal. See http://www.ecma-international.org/ecma-262/6.0/#sec-regexp.prototype.tostring
// for more details.
return object == (other + '');
case mapTag:
var convert = mapToArray;
case setTag:
var isPartial = bitmask & PARTIAL_COMPARE_FLAG;
convert || (convert = setToArray);
if (object.size != other.size && !isPartial) {
return false;
}
// Assume cyclic values are equal.
var stacked = stack.get(object);
if (stacked) {
return stacked == other;
}
bitmask |= UNORDERED_COMPARE_FLAG;
stack.set(object, other);
// Recursively compare objects (susceptible to call stack limits).
return equalArrays(convert(object), convert(other), equalFunc, customizer, bitmask, stack);
case symbolTag:
if (symbolValueOf) {
return symbolValueOf.call(object) == symbolValueOf.call(other);
}
}
return false;
}
/**
* A specialized version of `baseIsEqualDeep` for objects with support for
* partial deep comparisons.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Function} customizer The function to customize comparisons.
* @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual`
* for more details.
* @param {Object} stack Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function equalObjects(object, other, equalFunc, customizer, bitmask, stack) {
var isPartial = bitmask & PARTIAL_COMPARE_FLAG,
objProps = keys(object),
objLength = objProps.length,
othProps = keys(other),
othLength = othProps.length;
if (objLength != othLength && !isPartial) {
return false;
}
var index = objLength;
while (index--) {
var key = objProps[index];
if (!(isPartial ? key in other : baseHas(other, key))) {
return false;
}
}
// Assume cyclic values are equal.
var stacked = stack.get(object);
if (stacked) {
return stacked == other;
}
var result = true;
stack.set(object, other);
var skipCtor = isPartial;
while (++index < objLength) {
key = objProps[index];
var objValue = object[key],
othValue = other[key];
if (customizer) {
var compared = isPartial
? customizer(othValue, objValue, key, other, object, stack)
: customizer(objValue, othValue, key, object, other, stack);
}
// Recursively compare objects (susceptible to call stack limits).
if (!(compared === undefined
? (objValue === othValue || equalFunc(objValue, othValue, customizer, bitmask, stack))
: compared
)) {
result = false;
break;
}
skipCtor || (skipCtor = key == 'constructor');
}
if (result && !skipCtor) {
var objCtor = object.constructor,
othCtor = other.constructor;
// Non `Object` object instances with different constructors are not equal.
if (objCtor != othCtor &&
('constructor' in object && 'constructor' in other) &&
!(typeof objCtor == 'function' && objCtor instanceof objCtor &&
typeof othCtor == 'function' && othCtor instanceof othCtor)) {
result = false;
}
}
stack['delete'](object);
return result;
}
/**
* Gets the "length" property value of `object`.
*
* **Note:** This function is used to avoid a
* [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792) that affects
* Safari on at least iOS 8.1-8.3 ARM64.
*
* @private
* @param {Object} object The object to query.
* @returns {*} Returns the "length" value.
*/
var getLength = baseProperty('length');
/**
* Gets the property names, values, and compare flags of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the match data of `object`.
*/
function getMatchData(object) {
var result = toPairs(object),
length = result.length;
while (length--) {
result[length][2] = isStrictComparable(result[length][1]);
}
return result;
}
/**
* Gets the native function at `key` of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {string} key The key of the method to get.
* @returns {*} Returns the function if it's native, else `undefined`.
*/
function getNative(object, key) {
var value = object[key];
return isNative(value) ? value : undefined;
}
/**
* Gets the `[[Prototype]]` of `value`.
*
* @private
* @param {*} value The value to query.
* @returns {null|Object} Returns the `[[Prototype]]`.
*/
function getPrototype(value) {
return nativeGetPrototype(Object(value));
}
/**
* Gets the `toStringTag` of `value`.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
*/
function getTag(value) {
return objectToString.call(value);
}
// Fallback for data views, maps, sets, and weak maps in IE 11,
// for data views in Edge, and promises in Node.js.
if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||
(Map && getTag(new Map) != mapTag) ||
(Promise && getTag(Promise.resolve()) != promiseTag) ||
(Set && getTag(new Set) != setTag) ||
(WeakMap && getTag(new WeakMap) != weakMapTag)) {
getTag = function(value) {
var result = objectToString.call(value),
Ctor = result == objectTag ? value.constructor : undefined,
ctorString = Ctor ? toSource(Ctor) : undefined;
if (ctorString) {
switch (ctorString) {
case dataViewCtorString: return dataViewTag;
case mapCtorString: return mapTag;
case promiseCtorString: return promiseTag;
case setCtorString: return setTag;
case weakMapCtorString: return weakMapTag;
}
}
return result;
};
}
/**
* Checks if `path` exists on `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Array|string} path The path to check.
* @param {Function} hasFunc The function to check properties.
* @returns {boolean} Returns `true` if `path` exists, else `false`.
*/
function hasPath(object, path, hasFunc) {
path = isKey(path, object) ? [path] : baseCastPath(path);
var result,
index = -1,
length = path.length;
while (++index < length) {
var key = path[index];
if (!(result = object != null && hasFunc(object, key))) {
break;
}
object = object[key];
}
if (result) {
return result;
}
var length = object ? object.length : 0;
return !!length && isLength(length) && isIndex(key, length) &&
(isArray(object) || isString(object) || isArguments(object));
}
/**
* Creates an array of index keys for `object` values of arrays,
* `arguments` objects, and strings, otherwise `null` is returned.
*
* @private
* @param {Object} object The object to query.
* @returns {Array|null} Returns index keys, else `null`.
*/
function indexKeys(object) {
var length = object ? object.length : undefined;
if (isLength(length) &&
(isArray(object) || isString(object) || isArguments(object))) {
return baseTimes(length, String);
}
return null;
}
/**
* Checks if `value` is a property name and not a property path.
*
* @private
* @param {*} value The value to check.
* @param {Object} [object] The object to query keys on.
* @returns {boolean} Returns `true` if `value` is a property name, else `false`.
*/
function isKey(value, object) {
var type = typeof value;
if (type == 'number' || type == 'symbol') {
return true;
}
return !isArray(value) &&
(isSymbol(value) || reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||
(object != null && value in Object(object)));
}
/**
* Checks if `value` is suitable for use as unique object key.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is suitable, else `false`.
*/
function isKeyable(value) {
var type = typeof value;
return type == 'number' || type == 'boolean' ||
(type == 'string' && value != '__proto__') || value == null;
}
/**
* Checks if `value` is likely a prototype object.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
*/
function isPrototype(value) {
var Ctor = value && value.constructor,
proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;
return value === proto;
}
/**
* Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` if suitable for strict
* equality comparisons, else `false`.
*/
function isStrictComparable(value) {
return value === value && !isObject(value);
}
/**
* A specialized version of `matchesProperty` for source values suitable
* for strict equality comparisons, i.e. `===`.
*
* @private
* @param {string} key The key of the property to get.
* @param {*} srcValue The value to match.
* @returns {Function} Returns the new function.
*/
function matchesStrictComparable(key, srcValue) {
return function(object) {
if (object == null) {
return false;
}
return object[key] === srcValue &&
(srcValue !== undefined || (key in Object(object)));
};
}
/**
* Converts `func` to its source code.
*
* @private
* @param {Function} func The function to process.
* @returns {string} Returns the source code.
*/
function toSource(func) {
if (func != null) {
try {
return funcToString.call(func);
} catch (e) {}
try {
return (func + '');
} catch (e) {}
}
return '';
}
/**
* Performs a
* [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
* comparison between two values to determine if they are equivalent.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'user': 'fred' };
* var other = { 'user': 'fred' };
*
* _.eq(object, object);
* // => true
*
* _.eq(object, other);
* // => false
*
* _.eq('a', 'a');
* // => true
*
* _.eq('a', Object('a'));
* // => false
*
* _.eq(NaN, NaN);
* // => true
*/
function eq(value, other) {
return value === other || (value !== value && other !== other);
}
/**
* Checks if `value` is likely an `arguments` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified,
* else `false`.
* @example
*
* _.isArguments(function() { return arguments; }());
* // => true
*
* _.isArguments([1, 2, 3]);
* // => false
*/
function isArguments(value) {
// Safari 8.1 incorrectly makes `arguments.callee` enumerable in strict mode.
return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') &&
(!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag);
}
/**
* Checks if `value` is classified as an `Array` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @type {Function}
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified,
* else `false`.
* @example
*
* _.isArray([1, 2, 3]);
* // => true
*
* _.isArray(document.body.children);
* // => false
*
* _.isArray('abc');
* // => false
*
* _.isArray(_.noop);
* // => false
*/
var isArray = Array.isArray;
/**
* Checks if `value` is array-like. A value is considered array-like if it's
* not a function and has a `value.length` that's an integer greater than or
* equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is array-like, else `false`.
* @example
*
* _.isArrayLike([1, 2, 3]);
* // => true
*
* _.isArrayLike(document.body.children);
* // => true
*
* _.isArrayLike('abc');
* // => true
*
* _.isArrayLike(_.noop);
* // => false
*/
function isArrayLike(value) {
return value != null && isLength(getLength(value)) && !isFunction(value);
}
/**
* This method is like `_.isArrayLike` except that it also checks if `value`
* is an object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array-like object,
* else `false`.
* @example
*
* _.isArrayLikeObject([1, 2, 3]);
* // => true
*
* _.isArrayLikeObject(document.body.children);
* // => true
*
* _.isArrayLikeObject('abc');
* // => false
*
* _.isArrayLikeObject(_.noop);
* // => false
*/
function isArrayLikeObject(value) {
return isObjectLike(value) && isArrayLike(value);
}
/**
* Checks if `value` is classified as a `Function` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified,
* else `false`.
* @example
*
* _.isFunction(_);
* // => true
*
* _.isFunction(/abc/);
* // => false
*/
function isFunction(value) {
// The use of `Object#toString` avoids issues with the `typeof` operator
// in Safari 8 which returns 'object' for typed array and weak map constructors,
// and PhantomJS 1.9 which returns 'function' for `NodeList` instances.
var tag = isObject(value) ? objectToString.call(value) : '';
return tag == funcTag || tag == genTag;
}
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This function is loosely based on
* [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length,
* else `false`.
* @example
*
* _.isLength(3);
* // => true
*
* _.isLength(Number.MIN_VALUE);
* // => false
*
* _.isLength(Infinity);
* // => false
*
* _.isLength('3');
* // => false
*/
function isLength(value) {
return typeof value == 'number' &&
value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
/**
* Checks if `value` is the
* [language type](http://www.ecma-international.org/ecma-262/6.0/#sec-ecmascript-language-types)
* of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(_.noop);
* // => true
*
* _.isObject(null);
* // => false
*/
function isObject(value) {
var type = typeof value;
return !!value && (type == 'object' || type == 'function');
}
/**
* Checks if `value` is object-like. A value is object-like if it's not `null`
* and has a `typeof` result of "object".
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
* @example
*
* _.isObjectLike({});
* // => true
*
* _.isObjectLike([1, 2, 3]);
* // => true
*
* _.isObjectLike(_.noop);
* // => false
*
* _.isObjectLike(null);
* // => false
*/
function isObjectLike(value) {
return !!value && typeof value == 'object';
}
/**
* Checks if `value` is a native function.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a native function,
* else `false`.
* @example
*
* _.isNative(Array.prototype.push);
* // => true
*
* _.isNative(_);
* // => false
*/
function isNative(value) {
if (!isObject(value)) {
return false;
}
var pattern = (isFunction(value) || isHostObject(value)) ? reIsNative : reIsHostCtor;
return pattern.test(toSource(value));
}
/**
* Checks if `value` is classified as a `String` primitive or object.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified,
* else `false`.
* @example
*
* _.isString('abc');
* // => true
*
* _.isString(1);
* // => false
*/
function isString(value) {
return typeof value == 'string' ||
(!isArray(value) && isObjectLike(value) && objectToString.call(value) == stringTag);
}
/**
* Checks if `value` is classified as a `Symbol` primitive or object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified,
* else `false`.
* @example
*
* _.isSymbol(Symbol.iterator);
* // => true
*
* _.isSymbol('abc');
* // => false
*/
function isSymbol(value) {
return typeof value == 'symbol' ||
(isObjectLike(value) && objectToString.call(value) == symbolTag);
}
/**
* Checks if `value` is classified as a typed array.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified,
* else `false`.
* @example
*
* _.isTypedArray(new Uint8Array);
* // => true
*
* _.isTypedArray([]);
* // => false
*/
function isTypedArray(value) {
return isObjectLike(value) &&
isLength(value.length) && !!typedArrayTags[objectToString.call(value)];
}
/**
* Gets the value at `path` of `object`. If the resolved value is
* `undefined`, the `defaultValue` is used in its place.
*
* @static
* @memberOf _
* @since 3.7.0
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path of the property to get.
* @param {*} [defaultValue] The value returned for `undefined` resolved values.
* @returns {*} Returns the resolved value.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 3 } }] };
*
* _.get(object, 'a[0].b.c');
* // => 3
*
* _.get(object, ['a', '0', 'b', 'c']);
* // => 3
*
* _.get(object, 'a.b.c', 'default');
* // => 'default'
*/
function get(object, path, defaultValue) {
var result = object == null ? undefined : baseGet(object, path);
return result === undefined ? defaultValue : result;
}
/**
* Checks if `path` is a direct or inherited property of `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path to check.
* @returns {boolean} Returns `true` if `path` exists, else `false`.
* @example
*
* var object = _.create({ 'a': _.create({ 'b': 2 }) });
*
* _.hasIn(object, 'a');
* // => true
*
* _.hasIn(object, 'a.b');
* // => true
*
* _.hasIn(object, ['a', 'b']);
* // => true
*
* _.hasIn(object, 'b');
* // => false
*/
function hasIn(object, path) {
return object != null && hasPath(object, path, baseHasIn);
}
/**
* Creates an array of the own enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects. See the
* [ES spec](http://ecma-international.org/ecma-262/6.0/#sec-object.keys)
* for more details.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keys(new Foo);
* // => ['a', 'b'] (iteration order is not guaranteed)
*
* _.keys('hi');
* // => ['0', '1']
*/
function keys(object) {
var isProto = isPrototype(object);
if (!(isProto || isArrayLike(object))) {
return baseKeys(object);
}
var indexes = indexKeys(object),
skipIndexes = !!indexes,
result = indexes || [],
length = result.length;
for (var key in object) {
if (baseHas(object, key) &&
!(skipIndexes && (key == 'length' || isIndex(key, length))) &&
!(isProto && key == 'constructor')) {
result.push(key);
}
}
return result;
}
/**
* Creates an array of own enumerable string keyed-value pairs for `object`
* which can be consumed by `_.fromPairs`.
*
* @static
* @memberOf _
* @since 4.0.0
* @alias entries
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the new array of key-value pairs.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.toPairs(new Foo);
* // => [['a', 1], ['b', 2]] (iteration order is not guaranteed)
*/
function toPairs(object) {
return baseToPairs(object, keys(object));
}
/**
* This method returns the first argument given to it.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {*} value Any value.
* @returns {*} Returns `value`.
* @example
*
* var object = { 'user': 'fred' };
*
* _.identity(object) === object;
* // => true
*/
function identity(value) {
return value;
}
/**
* Creates a function that returns the value at `path` of a given object.
*
* @static
* @memberOf _
* @since 2.4.0
* @category Util
* @param {Array|string} path The path of the property to get.
* @returns {Function} Returns the new function.
* @example
*
* var objects = [
* { 'a': { 'b': 2 } },
* { 'a': { 'b': 1 } }
* ];
*
* _.map(objects, _.property('a.b'));
* // => [2, 1]
*
* _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
* // => [1, 2]
*/
function property(path) {
return isKey(path) ? baseProperty(path) : basePropertyDeep(path);
}
module.exports = baseIteratee;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(24)(module), (function() { return this; }())))
/***/ },
/* 24 */
/***/ function(module, exports) {
module.exports = function(module) {
if(!module.webpackPolyfill) {
module.deprecate = function() {};
module.paths = [];
// module.parent = undefined by default
module.children = [];
module.webpackPolyfill = 1;
}
return module;
}
/***/ },
/* 25 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(module, global) {/**
* lodash 4.7.1 (Custom Build) <https://lodash.com/>
* Build: `lodash modularize exports="npm" -o ./`
* Copyright jQuery Foundation and other contributors <https://jquery.org/>
* Released under MIT license <https://lodash.com/license>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
*/
/** Used as the `TypeError` message for "Functions" methods. */
var FUNC_ERROR_TEXT = 'Expected a function';
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';
/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0;
/** `Object#toString` result references. */
var funcTag = '[object Function]',
genTag = '[object GeneratorFunction]',
symbolTag = '[object Symbol]';
/** Used to match property names within property paths. */
var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]/g;
/**
* Used to match `RegExp`
* [syntax characters](http://ecma-international.org/ecma-262/6.0/#sec-patterns).
*/
var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
/** Used to match backslashes in property paths. */
var reEscapeChar = /\\(\\)?/g;
/** Used to detect host constructors (Safari). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;
/** Used to determine if values are of the language type `Object`. */
var objectTypes = {
'function': true,
'object': true
};
/** Detect free variable `exports`. */
var freeExports = (objectTypes[typeof exports] && exports && !exports.nodeType)
? exports
: undefined;
/** Detect free variable `module`. */
var freeModule = (objectTypes[typeof module] && module && !module.nodeType)
? module
: undefined;
/** Detect free variable `global` from Node.js. */
var freeGlobal = checkGlobal(freeExports && freeModule && typeof global == 'object' && global);
/** Detect free variable `self`. */
var freeSelf = checkGlobal(objectTypes[typeof self] && self);
/** Detect free variable `window`. */
var freeWindow = checkGlobal(objectTypes[typeof window] && window);
/** Detect `this` as the global object. */
var thisGlobal = checkGlobal(objectTypes[typeof this] && this);
/**
* Used as a reference to the global object.
*
* The `this` value is used if it's the global object to avoid Greasemonkey's
* restricted `window` object, otherwise the `window` object is used.
*/
var root = freeGlobal ||
((freeWindow !== (thisGlobal && thisGlobal.window)) && freeWindow) ||
freeSelf || thisGlobal || Function('return this')();
/**
* Checks if `value` is a global object.
*
* @private
* @param {*} value The value to check.
* @returns {null|Object} Returns `value` if it's a global object, else `null`.
*/
function checkGlobal(value) {
return (value && value.Object === Object) ? value : null;
}
/**
* Checks if `value` is a host object in IE < 9.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a host object, else `false`.
*/
function isHostObject(value) {
// Many host objects are `Object` objects that can coerce to strings
// despite having improperly defined `toString` methods.
var result = false;
if (value != null && typeof value.toString != 'function') {
try {
result = !!(value + '');
} catch (e) {}
}
return result;
}
/** Used for built-in method references. */
var arrayProto = Array.prototype,
objectProto = Object.prototype;
/** Used to resolve the decompiled source of functions. */
var funcToString = Function.prototype.toString;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
* of values.
*/
var objectToString = objectProto.toString;
/** Used to detect if a method is native. */
var reIsNative = RegExp('^' +
funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
.replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);
/** Built-in value references. */
var Symbol = root.Symbol,
splice = arrayProto.splice;
/* Built-in method references that are verified to be native. */
var Map = getNative(root, 'Map'),
nativeCreate = getNative(Object, 'create');
/** Used to convert symbols to primitives and strings. */
var symbolProto = Symbol ? Symbol.prototype : undefined,
symbolToString = symbolProto ? symbolProto.toString : undefined;
/**
* Creates a hash object.
*
* @private
* @constructor
* @returns {Object} Returns the new hash object.
*/
function Hash() {}
/**
* Removes `key` and its value from the hash.
*
* @private
* @param {Object} hash The hash to modify.
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function hashDelete(hash, key) {
return hashHas(hash, key) && delete hash[key];
}
/**
* Gets the hash value for `key`.
*
* @private
* @param {Object} hash The hash to query.
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function hashGet(hash, key) {
if (nativeCreate) {
var result = hash[key];
return result === HASH_UNDEFINED ? undefined : result;
}
return hasOwnProperty.call(hash, key) ? hash[key] : undefined;
}
/**
* Checks if a hash value for `key` exists.
*
* @private
* @param {Object} hash The hash to query.
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function hashHas(hash, key) {
return nativeCreate ? hash[key] !== undefined : hasOwnProperty.call(hash, key);
}
/**
* Sets the hash `key` to `value`.
*
* @private
* @param {Object} hash The hash to modify.
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
*/
function hashSet(hash, key, value) {
hash[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;
}
// Avoid inheriting from `Object.prototype` when possible.
Hash.prototype = nativeCreate ? nativeCreate(null) : objectProto;
/**
* Creates a map cache object to store key-value pairs.
*
* @private
* @constructor
* @param {Array} [values] The values to cache.
*/
function MapCache(values) {
var index = -1,
length = values ? values.length : 0;
this.clear();
while (++index < length) {
var entry = values[index];
this.set(entry[0], entry[1]);
}
}
/**
* Removes all key-value entries from the map.
*
* @private
* @name clear
* @memberOf MapCache
*/
function mapClear() {
this.__data__ = {
'hash': new Hash,
'map': Map ? new Map : [],
'string': new Hash
};
}
/**
* Removes `key` and its value from the map.
*
* @private
* @name delete
* @memberOf MapCache
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function mapDelete(key) {
var data = this.__data__;
if (isKeyable(key)) {
return hashDelete(typeof key == 'string' ? data.string : data.hash, key);
}
return Map ? data.map['delete'](key) : assocDelete(data.map, key);
}
/**
* Gets the map value for `key`.
*
* @private
* @name get
* @memberOf MapCache
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function mapGet(key) {
var data = this.__data__;
if (isKeyable(key)) {
return hashGet(typeof key == 'string' ? data.string : data.hash, key);
}
return Map ? data.map.get(key) : assocGet(data.map, key);
}
/**
* Checks if a map value for `key` exists.
*
* @private
* @name has
* @memberOf MapCache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function mapHas(key) {
var data = this.__data__;
if (isKeyable(key)) {
return hashHas(typeof key == 'string' ? data.string : data.hash, key);
}
return Map ? data.map.has(key) : assocHas(data.map, key);
}
/**
* Sets the map `key` to `value`.
*
* @private
* @name set
* @memberOf MapCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the map cache instance.
*/
function mapSet(key, value) {
var data = this.__data__;
if (isKeyable(key)) {
hashSet(typeof key == 'string' ? data.string : data.hash, key, value);
} else if (Map) {
data.map.set(key, value);
} else {
assocSet(data.map, key, value);
}
return this;
}
// Add methods to `MapCache`.
MapCache.prototype.clear = mapClear;
MapCache.prototype['delete'] = mapDelete;
MapCache.prototype.get = mapGet;
MapCache.prototype.has = mapHas;
MapCache.prototype.set = mapSet;
/**
* Removes `key` and its value from the associative array.
*
* @private
* @param {Array} array The array to modify.
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function assocDelete(array, key) {
var index = assocIndexOf(array, key);
if (index < 0) {
return false;
}
var lastIndex = array.length - 1;
if (index == lastIndex) {
array.pop();
} else {
splice.call(array, index, 1);
}
return true;
}
/**
* Gets the associative array value for `key`.
*
* @private
* @param {Array} array The array to query.
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function assocGet(array, key) {
var index = assocIndexOf(array, key);
return index < 0 ? undefined : array[index][1];
}
/**
* Checks if an associative array value for `key` exists.
*
* @private
* @param {Array} array The array to query.
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function assocHas(array, key) {
return assocIndexOf(array, key) > -1;
}
/**
* Gets the index at which the `key` is found in `array` of key-value pairs.
*
* @private
* @param {Array} array The array to search.
* @param {*} key The key to search for.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function assocIndexOf(array, key) {
var length = array.length;
while (length--) {
if (eq(array[length][0], key)) {
return length;
}
}
return -1;
}
/**
* Sets the associative array `key` to `value`.
*
* @private
* @param {Array} array The array to modify.
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
*/
function assocSet(array, key, value) {
var index = assocIndexOf(array, key);
if (index < 0) {
array.push([key, value]);
} else {
array[index][1] = value;
}
}
/**
* Gets the native function at `key` of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {string} key The key of the method to get.
* @returns {*} Returns the function if it's native, else `undefined`.
*/
function getNative(object, key) {
var value = object[key];
return isNative(value) ? value : undefined;
}
/**
* Checks if `value` is suitable for use as unique object key.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is suitable, else `false`.
*/
function isKeyable(value) {
var type = typeof value;
return type == 'number' || type == 'boolean' ||
(type == 'string' && value != '__proto__') || value == null;
}
/**
* Converts `string` to a property path array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the property path array.
*/
var stringToPath = memoize(function(string) {
var result = [];
toString(string).replace(rePropName, function(match, number, quote, string) {
result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match));
});
return result;
});
/**
* Converts `func` to its source code.
*
* @private
* @param {Function} func The function to process.
* @returns {string} Returns the source code.
*/
function toSource(func) {
if (func != null) {
try {
return funcToString.call(func);
} catch (e) {}
try {
return (func + '');
} catch (e) {}
}
return '';
}
/**
* Creates a function that memoizes the result of `func`. If `resolver` is
* provided, it determines the cache key for storing the result based on the
* arguments provided to the memoized function. By default, the first argument
* provided to the memoized function is used as the map cache key. The `func`
* is invoked with the `this` binding of the memoized function.
*
* **Note:** The cache is exposed as the `cache` property on the memoized
* function. Its creation may be customized by replacing the `_.memoize.Cache`
* constructor with one whose instances implement the
* [`Map`](http://ecma-international.org/ecma-262/6.0/#sec-properties-of-the-map-prototype-object)
* method interface of `delete`, `get`, `has`, and `set`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to have its output memoized.
* @param {Function} [resolver] The function to resolve the cache key.
* @returns {Function} Returns the new memoizing function.
* @example
*
* var object = { 'a': 1, 'b': 2 };
* var other = { 'c': 3, 'd': 4 };
*
* var values = _.memoize(_.values);
* values(object);
* // => [1, 2]
*
* values(other);
* // => [3, 4]
*
* object.a = 2;
* values(object);
* // => [1, 2]
*
* // Modify the result cache.
* values.cache.set(object, ['a', 'b']);
* values(object);
* // => ['a', 'b']
*
* // Replace `_.memoize.Cache`.
* _.memoize.Cache = WeakMap;
*/
function memoize(func, resolver) {
if (typeof func != 'function' || (resolver && typeof resolver != 'function')) {
throw new TypeError(FUNC_ERROR_TEXT);
}
var memoized = function() {
var args = arguments,
key = resolver ? resolver.apply(this, args) : args[0],
cache = memoized.cache;
if (cache.has(key)) {
return cache.get(key);
}
var result = func.apply(this, args);
memoized.cache = cache.set(key, result);
return result;
};
memoized.cache = new (memoize.Cache || MapCache);
return memoized;
}
// Assign cache to `_.memoize`.
memoize.Cache = MapCache;
/**
* Performs a
* [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
* comparison between two values to determine if they are equivalent.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'user': 'fred' };
* var other = { 'user': 'fred' };
*
* _.eq(object, object);
* // => true
*
* _.eq(object, other);
* // => false
*
* _.eq('a', 'a');
* // => true
*
* _.eq('a', Object('a'));
* // => false
*
* _.eq(NaN, NaN);
* // => true
*/
function eq(value, other) {
return value === other || (value !== value && other !== other);
}
/**
* Checks if `value` is classified as a `Function` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified,
* else `false`.
* @example
*
* _.isFunction(_);
* // => true
*
* _.isFunction(/abc/);
* // => false
*/
function isFunction(value) {
// The use of `Object#toString` avoids issues with the `typeof` operator
// in Safari 8 which returns 'object' for typed array and weak map constructors,
// and PhantomJS 1.9 which returns 'function' for `NodeList` instances.
var tag = isObject(value) ? objectToString.call(value) : '';
return tag == funcTag || tag == genTag;
}
/**
* Checks if `value` is the
* [language type](http://www.ecma-international.org/ecma-262/6.0/#sec-ecmascript-language-types)
* of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(_.noop);
* // => true
*
* _.isObject(null);
* // => false
*/
function isObject(value) {
var type = typeof value;
return !!value && (type == 'object' || type == 'function');
}
/**
* Checks if `value` is object-like. A value is object-like if it's not `null`
* and has a `typeof` result of "object".
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
* @example
*
* _.isObjectLike({});
* // => true
*
* _.isObjectLike([1, 2, 3]);
* // => true
*
* _.isObjectLike(_.noop);
* // => false
*
* _.isObjectLike(null);
* // => false
*/
function isObjectLike(value) {
return !!value && typeof value == 'object';
}
/**
* Checks if `value` is a native function.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a native function,
* else `false`.
* @example
*
* _.isNative(Array.prototype.push);
* // => true
*
* _.isNative(_);
* // => false
*/
function isNative(value) {
if (!isObject(value)) {
return false;
}
var pattern = (isFunction(value) || isHostObject(value)) ? reIsNative : reIsHostCtor;
return pattern.test(toSource(value));
}
/**
* Checks if `value` is classified as a `Symbol` primitive or object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified,
* else `false`.
* @example
*
* _.isSymbol(Symbol.iterator);
* // => true
*
* _.isSymbol('abc');
* // => false
*/
function isSymbol(value) {
return typeof value == 'symbol' ||
(isObjectLike(value) && objectToString.call(value) == symbolTag);
}
/**
* Converts `value` to a string if it's not one. An empty string is returned
* for `null` and `undefined` values. The sign of `-0` is preserved.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to process.
* @returns {string} Returns the string.
* @example
*
* _.toString(null);
* // => ''
*
* _.toString(-0);
* // => '-0'
*
* _.toString([1, 2, 3]);
* // => '1,2,3'
*/
function toString(value) {
// Exit early for strings to avoid a performance hit in some environments.
if (typeof value == 'string') {
return value;
}
if (value == null) {
return '';
}
if (isSymbol(value)) {
return symbolToString ? symbolToString.call(value) : '';
}
var result = (value + '');
return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
}
module.exports = stringToPath;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(24)(module), (function() { return this; }())))
/***/ },
/* 26 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _actionTypes = __webpack_require__(27);
var _createMatcher = __webpack_require__(16);
var _createMatcher2 = _interopRequireDefault(_createMatcher);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = function (routes) {
var createMatcher = arguments.length <= 1 || arguments[1] === undefined ? _createMatcher2.default : arguments[1];
var matchRoute = createMatcher(routes);
return function () {
var state = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var action = arguments[1];
if (action.type === _actionTypes.LOCATION_CHANGED) {
return {
current: _extends({}, matchRoute(action.payload.url), action.payload),
previous: state.current
};
}
return state;
};
};
/***/ },
/* 27 */
/***/ function(module, exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var LOCATION_CHANGED = exports.LOCATION_CHANGED = 'ROUTER_LOCATION_CHANGED';
var PUSH = exports.PUSH = 'ROUTER_PUSH';
var REPLACE = exports.REPLACE = 'ROUTER_REPLACE';
var GO = exports.GO = 'ROUTER_GO';
var GO_BACK = exports.GO_BACK = 'ROUTER_GO_BACK';
var GO_FORWARD = exports.GO_FORWARD = 'ROUTER_GO_FORWARD';
/***/ },
/* 28 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _actionTypes = __webpack_require__(27);
var locationDidChange = function locationDidChange(location) {
var basename = location.basename;
var pathname = location.pathname;
var action = location.action;
var state = location.state;
return {
type: _actionTypes.LOCATION_CHANGED,
payload: {
action: action,
state: state,
url: ('' + (basename || '') + pathname).replace(/\/$/, '') // remove trailing slash
}
};
};
var locationListener = void 0;
exports.default = function (history) {
return function () {
return function (next) {
return function (action) {
if (!locationListener) {
locationListener = history.listen(function (location) {
if (location) {
next(locationDidChange(location));
}
});
}
switch (action.type) {
case _actionTypes.PUSH:
history.push(action.payload);
break;
case _actionTypes.REPLACE:
history.replace(action.payload);
break;
case _actionTypes.GO:
history.go(action.payload);
break;
case _actionTypes.GO_BACK:
history.goBack();
break;
case _actionTypes.GO_FORWARD:
history.goForward();
break;
case _actionTypes.LOCATION_CHANGED:
break;
default:
next(action);
}
};
};
};
};
/***/ },
/* 29 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(30);
var _react2 = _interopRequireDefault(_react);
var _actionTypes = __webpack_require__(27);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Link = function (_Component) {
_inherits(Link, _Component);
function Link() {
_classCallCheck(this, Link);
return _possibleConstructorReturn(this, Object.getPrototypeOf(Link).apply(this, arguments));
}
_createClass(Link, [{
key: 'onClick',
value: function onClick(event) {
event.preventDefault();
var _props = this.props;
var replaceState = _props.replaceState;
var dispatch = _props.dispatch;
dispatch({
type: replaceState ? _actionTypes.REPLACE : _actionTypes.PUSH,
payload: {
pathname: this.props.href
}
});
}
}, {
key: 'render',
value: function render() {
var _props2 = this.props;
var href = _props2.href;
var history = _props2.history;
var children = _props2.children;
return _react2.default.createElement(
'a',
_extends({}, this.props, {
href: history ? history.createHref(href) : href,
onClick: this.onClick.bind(this)
}),
children
);
}
}]);
return Link;
}(_react.Component);
exports.default = Link;
Link.propTypes = {
href: _react.PropTypes.string,
children: _react.PropTypes.node,
dispatch: _react.PropTypes.func,
history: _react.PropTypes.object,
replaceState: _react.PropTypes.bool
};
/***/ },
/* 30 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_30__;
/***/ }
/******/ ])
});
;
//# sourceMappingURL=redux-little-router.js.map | maruilian11/cdnjs | ajax/libs/redux-little-router/3.0.0/redux-little-router.js | JavaScript | mit | 156,293 |
/**
* @copyright Copyright (C) 2005 - 2012 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
Object.append(Browser.Features, {
inputemail: (function() {
var i = document.createElement("input");
i.setAttribute("type", "email");
return i.type !== "text";
})()
});
/**
* Unobtrusive Form Validation library
*
* Inspired by: Chris Campbell <www.particletree.com>
*
* @package Joomla.Framework
* @subpackage Forms
* @since 1.5
*/
var JFormValidator = new Class({
initialize: function()
{
// Initialize variables
this.handlers = Object();
this.custom = Object();
// Default handlers
this.setHandler('username',
function (value) {
regex = new RegExp("[\<|\>|\"|\'|\%|\;|\(|\)|\&]", "i");
return !regex.test(value);
}
);
this.setHandler('password',
function (value) {
regex=/^\S[\S ]{2,98}\S$/;
return regex.test(value);
}
);
this.setHandler('numeric',
function (value) {
regex=/^(\d|-)?(\d|,)*\.?\d*$/;
return regex.test(value);
}
);
this.setHandler('email',
function (value) {
regex=/^[a-zA-Z0-9._-]+(\+[a-zA-Z0-9._-]+)*@([a-zA-Z0-9.-]+\.)+[a-zA-Z0-9.-]{2,4}$/;
return regex.test(value);
}
);
// Attach to forms with class 'form-validate'
var forms = $$('form.form-validate');
forms.each(function(form){ this.attachToForm(form); }, this);
},
setHandler: function(name, fn, en)
{
en = (en == '') ? true : en;
this.handlers[name] = { enabled: en, exec: fn };
},
attachToForm: function(form)
{
// Iterate through the form object and attach the validate method to all input fields.
form.getElements('input,textarea,select,button').each(function(el){
if (el.hasClass('required')) {
el.set('aria-required', 'true');
el.set('required', 'required');
}
if ((document.id(el).get('tag') == 'input' || document.id(el).get('tag') == 'button') && document.id(el).get('type') == 'submit') {
if (el.hasClass('validate')) {
el.onclick = function(){return document.formvalidator.isValid(this.form);};
}
} else {
el.addEvent('blur', function(){return document.formvalidator.validate(this);});
if (el.hasClass('validate-email') && Browser.Features.inputemail) {
el.type = 'email';
}
}
});
},
validate: function(el)
{
el = document.id(el);
// Ignore the element if its currently disabled, because are not submitted for the http-request. For those case return always true.
if(el.get('disabled')) {
this.handleResponse(true, el);
return true;
}
// If the field is required make sure it has a value
if (el.hasClass('required')) {
if (el.get('tag')=='fieldset' && (el.hasClass('radio') || el.hasClass('checkboxes'))) {
for(var i=0;;i++) {
if (document.id(el.get('id')+i)) {
if (document.id(el.get('id')+i).checked) {
break;
}
}
else {
this.handleResponse(false, el);
return false;
}
}
}
else if (!(el.get('value'))) {
this.handleResponse(false, el);
return false;
}
}
// Only validate the field if the validate class is set
var handler = (el.className && el.className.search(/validate-([a-zA-Z0-9\_\-]+)/) != -1) ? el.className.match(/validate-([a-zA-Z0-9\_\-]+)/)[1] : "";
if (handler == '') {
this.handleResponse(true, el);
return true;
}
// Check the additional validation types
if ((handler) && (handler != 'none') && (this.handlers[handler]) && el.get('value')) {
// Execute the validation handler and return result
if (this.handlers[handler].exec(el.get('value')) != true) {
this.handleResponse(false, el);
return false;
}
}
// Return validation state
this.handleResponse(true, el);
return true;
},
isValid: function(form)
{
var valid = true;
// Validate form fields
var elements = form.getElements('fieldset').concat(Array.from(form.elements));
for (var i=0;i < elements.length; i++) {
if (this.validate(elements[i]) == false) {
valid = false;
}
}
// Run custom form validators if present
new Hash(this.custom).each(function(validator){
if (validator.exec() != true) {
valid = false;
}
});
return valid;
},
handleResponse: function(state, el)
{
// Find the label object for the given field if it exists
if (!(el.labelref)) {
var labels = $$('label');
labels.each(function(label){
if (label.get('for') == el.get('id')) {
el.labelref = label;
}
});
}
// Set the element and its label (if exists) invalid state
if (state == false) {
el.addClass('invalid');
el.set('aria-invalid', 'true');
if (el.labelref) {
document.id(el.labelref).addClass('invalid');
document.id(el.labelref).set('aria-invalid', 'true');
}
} else {
el.removeClass('invalid');
el.set('aria-invalid', 'false');
if (el.labelref) {
document.id(el.labelref).removeClass('invalid');
document.id(el.labelref).set('aria-invalid', 'false');
}
}
}
});
document.formvalidator = null;
window.addEvent('domready', function(){
document.formvalidator = new JFormValidator();
}); | SuperFamousGuy/AdLib | tmp/install_4f31d69ae5bd9/media/system/js/validate-uncompressed.js | JavaScript | gpl-2.0 | 4,702 |
CKEDITOR.plugins.setLang("iframe","es",{border:"Mostrar borde del marco",noUrl:"Por favor, escriba la dirección del iframe",scrolling:"Activar barras de desplazamiento",title:"Propiedades de iframe",toolbar:"IFrame",tabindex:"Remove from tabindex"}); | stweil/TYPO3.CMS | typo3/sysext/rte_ckeditor/Resources/Public/JavaScript/Contrib/plugins/iframe/lang/es.js | JavaScript | gpl-2.0 | 254 |
"use strict";
/**
* @license
* Copyright 2017 Palantir Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var utils = require("tsutils");
var ts = require("typescript");
var Lint = require("../index");
var Rule = (function (_super) {
tslib_1.__extends(Rule, _super);
function Rule() {
return _super !== null && _super.apply(this, arguments) || this;
}
/* tslint:enable:object-literal-sort-keys */
Rule.FAILURE_STRING = function (name) {
return "Qualifier is unnecessary since '" + name + "' is in scope.";
};
Rule.prototype.applyWithProgram = function (sourceFile, program) {
return this.applyWithFunction(sourceFile, function (ctx) { return walk(ctx, program.getTypeChecker()); });
};
return Rule;
}(Lint.Rules.TypedRule));
/* tslint:disable:object-literal-sort-keys */
Rule.metadata = {
ruleName: "no-unnecessary-qualifier",
description: "Warns when a namespace qualifier (`A.x`) is unnecessary.",
hasFix: true,
optionsDescription: "Not configurable.",
options: null,
optionExamples: [true],
type: "style",
typescriptOnly: true,
requiresTypeInfo: true,
};
exports.Rule = Rule;
function walk(ctx, checker) {
var namespacesInScope = [];
ts.forEachChild(ctx.sourceFile, cb);
function cb(node) {
switch (node.kind) {
case ts.SyntaxKind.ModuleDeclaration:
case ts.SyntaxKind.EnumDeclaration:
namespacesInScope.push(node);
ts.forEachChild(node, cb);
namespacesInScope.pop();
break;
case ts.SyntaxKind.QualifiedName:
var _a = node, left = _a.left, right = _a.right;
visitNamespaceAccess(node, left, right);
break;
case ts.SyntaxKind.PropertyAccessExpression:
var _b = node, expression = _b.expression, name = _b.name;
if (utils.isEntityNameExpression(expression)) {
visitNamespaceAccess(node, expression, name);
break;
}
// falls through
default:
ts.forEachChild(node, cb);
}
}
function visitNamespaceAccess(node, qualifier, name) {
if (qualifierIsUnnecessary(qualifier, name)) {
var fix = Lint.Replacement.deleteFromTo(qualifier.getStart(), name.getStart());
ctx.addFailureAtNode(qualifier, Rule.FAILURE_STRING(qualifier.getText()), fix);
}
else {
// Only look for nested qualifier errors if we didn't already fail on the outer qualifier.
ts.forEachChild(node, cb);
}
}
function qualifierIsUnnecessary(qualifier, name) {
var namespaceSymbol = checker.getSymbolAtLocation(qualifier);
if (namespaceSymbol === undefined || !symbolIsNamespaceInScope(namespaceSymbol)) {
return false;
}
var accessedSymbol = checker.getSymbolAtLocation(name);
if (accessedSymbol === undefined) {
return false;
}
// If the symbol in scope is different, the qualifier is necessary.
var fromScope = getSymbolInScope(qualifier, accessedSymbol.flags, name.text);
return fromScope === undefined || fromScope === accessedSymbol;
}
function getSymbolInScope(node, flags, name) {
// TODO:PERF `getSymbolsInScope` gets a long list. Is there a better way?
var scope = checker.getSymbolsInScope(node, flags);
return scope.find(function (scopeSymbol) { return scopeSymbol.name === name; });
}
function symbolIsNamespaceInScope(symbol) {
var symbolDeclarations = symbol.getDeclarations();
if (symbolDeclarations == null) {
return false;
}
else if (symbolDeclarations.some(function (decl) { return namespacesInScope.some(function (ns) { return ns === decl; }); })) {
return true;
}
var alias = tryGetAliasedSymbol(symbol, checker);
return alias !== undefined && symbolIsNamespaceInScope(alias);
}
}
function tryGetAliasedSymbol(symbol, checker) {
return Lint.isSymbolFlagSet(symbol, ts.SymbolFlags.Alias) ? checker.getAliasedSymbol(symbol) : undefined;
}
| rootulp/exercism | typescript/space-age/node_modules/tslint/lib/rules/noUnnecessaryQualifierRule.js | JavaScript | mit | 4,873 |
'use strict';
var SAX = require('sax'),
JSAPI = require('./jsAPI');
var config = {
strict: true,
trim: false,
normalize: true,
lowercase: true,
xmlns: true,
position: false
};
/**
* Convert SVG (XML) string to SVG-as-JS object.
*
* @param {String} data input data
* @param {Function} callback
*/
module.exports = function(data, callback) {
var sax = SAX.parser(config.strict, config),
root = new JSAPI({ elem: '#document' }),
current = root,
stack = [root],
textContext = null;
function pushToContent(content) {
content = new JSAPI(content, current);
(current.content = current.content || []).push(content);
return content;
}
sax.ondoctype = function(doctype) {
pushToContent({
doctype: doctype
});
};
sax.onprocessinginstruction = function(data) {
pushToContent({
processinginstruction: data
});
};
sax.oncomment = function(comment) {
pushToContent({
comment: comment.trim()
});
};
sax.oncdata = function(cdata) {
pushToContent({
cdata: cdata
});
};
sax.onopentag = function(data) {
var elem = {
elem: data.name,
prefix: data.prefix,
local: data.local
};
if (Object.keys(data.attributes).length) {
elem.attrs = {};
for (var name in data.attributes) {
elem.attrs[name] = {
name: name,
value: data.attributes[name].value,
prefix: data.attributes[name].prefix,
local: data.attributes[name].local
};
}
}
elem = pushToContent(elem);
current = elem;
// Save info about <text> tag to prevent trimming of meaningful whitespace
if (data.name == 'text' && !data.prefix) {
textContext = current;
}
stack.push(elem);
};
sax.ontext = function(text) {
if (/\S/.test(text) || textContext) {
if (!textContext)
text = text.trim();
pushToContent({
text: text
});
}
};
sax.onclosetag = function() {
var last = stack.pop();
// Trim text inside <text> tag.
if (last == textContext) {
trim(textContext);
textContext = null;
}
current = stack[stack.length - 1];
};
sax.onerror = function(e) {
callback({ error: 'Error in parsing: ' + e.message });
};
sax.onend = function() {
callback(root);
};
sax.write(data).close();
function trim(elem) {
if (!elem.content) return elem;
var start = elem.content[0],
end = elem.content[elem.content.length - 1];
while (start && !start.text) start = start.content[0];
if (start) start.text = start.text.replace(/^\s+/, '');
while (end && !end.text) end = end.content[end.content.length - 1];
if (end) end.text = end.text.replace(/\s+$/, '');
return elem;
}
};
| shanginn/newsaity74.ru | templates/blank_j3/node_modules/gulp-imagemin/node_modules/imagemin/node_modules/imagemin-svgo/node_modules/svgo/lib/svgo/svg2js.js | JavaScript | gpl-2.0 | 3,231 |
/* Copyright 2014 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*jshint globalstrict: false */
/* globals PDFJS, PDFViewer, PDFPageView, TextLayerBuilder, PDFLinkService,
DefaultTextLayerFactory, AnnotationLayerBuilder, PDFHistory,
DefaultAnnotationLayerFactory, DownloadManager, ProgressBar */
// Initializing PDFJS global object (if still undefined)
if (typeof PDFJS === 'undefined') {
(typeof window !== 'undefined' ? window : this).PDFJS = {};
}
(function pdfViewerWrapper() {
'use strict';
var CSS_UNITS = 96.0 / 72.0;
var DEFAULT_SCALE_VALUE = 'auto';
var DEFAULT_SCALE = 1.0;
var UNKNOWN_SCALE = 0;
var MAX_AUTO_SCALE = 1.25;
var SCROLLBAR_PADDING = 40;
var VERTICAL_PADDING = 5;
/**
* Returns scale factor for the canvas. It makes sense for the HiDPI displays.
* @return {Object} The object with horizontal (sx) and vertical (sy)
scales. The scaled property is set to false if scaling is
not required, true otherwise.
*/
function getOutputScale(ctx) {
var devicePixelRatio = window.devicePixelRatio || 1;
var backingStoreRatio = ctx.webkitBackingStorePixelRatio ||
ctx.mozBackingStorePixelRatio ||
ctx.msBackingStorePixelRatio ||
ctx.oBackingStorePixelRatio ||
ctx.backingStorePixelRatio || 1;
var pixelRatio = devicePixelRatio / backingStoreRatio;
return {
sx: pixelRatio,
sy: pixelRatio,
scaled: pixelRatio !== 1
};
}
/**
* Scrolls specified element into view of its parent.
* @param {Object} element - The element to be visible.
* @param {Object} spot - An object with optional top and left properties,
* specifying the offset from the top left edge.
* @param {boolean} skipOverflowHiddenElements - Ignore elements that have
* the CSS rule `overflow: hidden;` set. The default is false.
*/
function scrollIntoView(element, spot, skipOverflowHiddenElements) {
// Assuming offsetParent is available (it's not available when viewer is in
// hidden iframe or object). We have to scroll: if the offsetParent is not set
// producing the error. See also animationStartedClosure.
var parent = element.offsetParent;
if (!parent) {
console.error('offsetParent is not set -- cannot scroll');
return;
}
var checkOverflow = skipOverflowHiddenElements || false;
var offsetY = element.offsetTop + element.clientTop;
var offsetX = element.offsetLeft + element.clientLeft;
while (parent.clientHeight === parent.scrollHeight ||
(checkOverflow && getComputedStyle(parent).overflow === 'hidden')) {
if (parent.dataset._scaleY) {
offsetY /= parent.dataset._scaleY;
offsetX /= parent.dataset._scaleX;
}
offsetY += parent.offsetTop;
offsetX += parent.offsetLeft;
parent = parent.offsetParent;
if (!parent) {
return; // no need to scroll
}
}
if (spot) {
if (spot.top !== undefined) {
offsetY += spot.top;
}
if (spot.left !== undefined) {
offsetX += spot.left;
parent.scrollLeft = offsetX;
}
}
parent.scrollTop = offsetY;
}
/**
* Helper function to start monitoring the scroll event and converting them into
* PDF.js friendly one: with scroll debounce and scroll direction.
*/
function watchScroll(viewAreaElement, callback) {
var debounceScroll = function debounceScroll(evt) {
if (rAF) {
return;
}
// schedule an invocation of scroll for next animation frame.
rAF = window.requestAnimationFrame(function viewAreaElementScrolled() {
rAF = null;
var currentY = viewAreaElement.scrollTop;
var lastY = state.lastY;
if (currentY !== lastY) {
state.down = currentY > lastY;
}
state.lastY = currentY;
callback(state);
});
};
var state = {
down: true,
lastY: viewAreaElement.scrollTop,
_eventHandler: debounceScroll
};
var rAF = null;
viewAreaElement.addEventListener('scroll', debounceScroll, true);
return state;
}
/**
* Helper function to parse query string (e.g. ?param1=value&parm2=...).
*/
function parseQueryString(query) {
var parts = query.split('&');
var params = {};
for (var i = 0, ii = parts.length; i < ii; ++i) {
var param = parts[i].split('=');
var key = param[0].toLowerCase();
var value = param.length > 1 ? param[1] : null;
params[decodeURIComponent(key)] = decodeURIComponent(value);
}
return params;
}
/**
* Use binary search to find the index of the first item in a given array which
* passes a given condition. The items are expected to be sorted in the sense
* that if the condition is true for one item in the array, then it is also true
* for all following items.
*
* @returns {Number} Index of the first array element to pass the test,
* or |items.length| if no such element exists.
*/
function binarySearchFirstItem(items, condition) {
var minIndex = 0;
var maxIndex = items.length - 1;
if (items.length === 0 || !condition(items[maxIndex])) {
return items.length;
}
if (condition(items[minIndex])) {
return minIndex;
}
while (minIndex < maxIndex) {
var currentIndex = (minIndex + maxIndex) >> 1;
var currentItem = items[currentIndex];
if (condition(currentItem)) {
maxIndex = currentIndex;
} else {
minIndex = currentIndex + 1;
}
}
return minIndex; /* === maxIndex */
}
/**
* Approximates float number as a fraction using Farey sequence (max order
* of 8).
* @param {number} x - Positive float number.
* @returns {Array} Estimated fraction: the first array item is a numerator,
* the second one is a denominator.
*/
function approximateFraction(x) {
// Fast paths for int numbers or their inversions.
if (Math.floor(x) === x) {
return [x, 1];
}
var xinv = 1 / x;
var limit = 8;
if (xinv > limit) {
return [1, limit];
} else if (Math.floor(xinv) === xinv) {
return [1, xinv];
}
var x_ = x > 1 ? xinv : x;
// a/b and c/d are neighbours in Farey sequence.
var a = 0, b = 1, c = 1, d = 1;
// Limiting search to order 8.
while (true) {
// Generating next term in sequence (order of q).
var p = a + c, q = b + d;
if (q > limit) {
break;
}
if (x_ <= p / q) {
c = p; d = q;
} else {
a = p; b = q;
}
}
// Select closest of the neighbours to x.
if (x_ - a / b < c / d - x_) {
return x_ === x ? [a, b] : [b, a];
} else {
return x_ === x ? [c, d] : [d, c];
}
}
function roundToDivide(x, div) {
var r = x % div;
return r === 0 ? x : Math.round(x - r + div);
}
/**
* Generic helper to find out what elements are visible within a scroll pane.
*/
function getVisibleElements(scrollEl, views, sortByVisibility) {
var top = scrollEl.scrollTop, bottom = top + scrollEl.clientHeight;
var left = scrollEl.scrollLeft, right = left + scrollEl.clientWidth;
function isElementBottomBelowViewTop(view) {
var element = view.div;
var elementBottom =
element.offsetTop + element.clientTop + element.clientHeight;
return elementBottom > top;
}
var visible = [], view, element;
var currentHeight, viewHeight, hiddenHeight, percentHeight;
var currentWidth, viewWidth;
var firstVisibleElementInd = (views.length === 0) ? 0 :
binarySearchFirstItem(views, isElementBottomBelowViewTop);
for (var i = firstVisibleElementInd, ii = views.length; i < ii; i++) {
view = views[i];
element = view.div;
currentHeight = element.offsetTop + element.clientTop;
viewHeight = element.clientHeight;
if (currentHeight > bottom) {
break;
}
currentWidth = element.offsetLeft + element.clientLeft;
viewWidth = element.clientWidth;
if (currentWidth + viewWidth < left || currentWidth > right) {
continue;
}
hiddenHeight = Math.max(0, top - currentHeight) +
Math.max(0, currentHeight + viewHeight - bottom);
percentHeight = ((viewHeight - hiddenHeight) * 100 / viewHeight) | 0;
visible.push({
id: view.id,
x: currentWidth,
y: currentHeight,
view: view,
percent: percentHeight
});
}
var first = visible[0];
var last = visible[visible.length - 1];
if (sortByVisibility) {
visible.sort(function(a, b) {
var pc = a.percent - b.percent;
if (Math.abs(pc) > 0.001) {
return -pc;
}
return a.id - b.id; // ensure stability
});
}
return {first: first, last: last, views: visible};
}
/**
* Event handler to suppress context menu.
*/
function noContextMenuHandler(e) {
e.preventDefault();
}
/**
* Returns the filename or guessed filename from the url (see issue 3455).
* url {String} The original PDF location.
* @return {String} Guessed PDF file name.
*/
function getPDFFileNameFromURL(url) {
var reURI = /^(?:([^:]+:)?\/\/[^\/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/;
// SCHEME HOST 1.PATH 2.QUERY 3.REF
// Pattern to get last matching NAME.pdf
var reFilename = /[^\/?#=]+\.pdf\b(?!.*\.pdf\b)/i;
var splitURI = reURI.exec(url);
var suggestedFilename = reFilename.exec(splitURI[1]) ||
reFilename.exec(splitURI[2]) ||
reFilename.exec(splitURI[3]);
if (suggestedFilename) {
suggestedFilename = suggestedFilename[0];
if (suggestedFilename.indexOf('%') !== -1) {
// URL-encoded %2Fpath%2Fto%2Ffile.pdf should be file.pdf
try {
suggestedFilename =
reFilename.exec(decodeURIComponent(suggestedFilename))[0];
} catch(e) { // Possible (extremely rare) errors:
// URIError "Malformed URI", e.g. for "%AA.pdf"
// TypeError "null has no properties", e.g. for "%2F.pdf"
}
}
}
return suggestedFilename || 'document.pdf';
}
var ProgressBar = (function ProgressBarClosure() {
function clamp(v, min, max) {
return Math.min(Math.max(v, min), max);
}
function ProgressBar(id, opts) {
this.visible = true;
// Fetch the sub-elements for later.
this.div = document.querySelector(id + ' .progress');
// Get the loading bar element, so it can be resized to fit the viewer.
this.bar = this.div.parentNode;
// Get options, with sensible defaults.
this.height = opts.height || 100;
this.width = opts.width || 100;
this.units = opts.units || '%';
// Initialize heights.
this.div.style.height = this.height + this.units;
this.percent = 0;
}
ProgressBar.prototype = {
updateBar: function ProgressBar_updateBar() {
if (this._indeterminate) {
this.div.classList.add('indeterminate');
this.div.style.width = this.width + this.units;
return;
}
this.div.classList.remove('indeterminate');
var progressSize = this.width * this._percent / 100;
this.div.style.width = progressSize + this.units;
},
get percent() {
return this._percent;
},
set percent(val) {
this._indeterminate = isNaN(val);
this._percent = clamp(val, 0, 100);
this.updateBar();
},
setWidth: function ProgressBar_setWidth(viewer) {
if (viewer) {
var container = viewer.parentNode;
var scrollbarWidth = container.offsetWidth - viewer.offsetWidth;
if (scrollbarWidth > 0) {
this.bar.setAttribute('style', 'width: calc(100% - ' +
scrollbarWidth + 'px);');
}
}
},
hide: function ProgressBar_hide() {
if (!this.visible) {
return;
}
this.visible = false;
this.bar.classList.add('hidden');
document.body.classList.remove('loadingInProgress');
},
show: function ProgressBar_show() {
if (this.visible) {
return;
}
this.visible = true;
document.body.classList.add('loadingInProgress');
this.bar.classList.remove('hidden');
}
};
return ProgressBar;
})();
/**
* Performs navigation functions inside PDF, such as opening specified page,
* or destination.
* @class
* @implements {IPDFLinkService}
*/
var PDFLinkService = (function () {
/**
* @constructs PDFLinkService
*/
function PDFLinkService() {
this.baseUrl = null;
this.pdfDocument = null;
this.pdfViewer = null;
this.pdfHistory = null;
this._pagesRefCache = null;
}
PDFLinkService.prototype = {
setDocument: function PDFLinkService_setDocument(pdfDocument, baseUrl) {
this.baseUrl = baseUrl;
this.pdfDocument = pdfDocument;
this._pagesRefCache = Object.create(null);
},
setViewer: function PDFLinkService_setViewer(pdfViewer) {
this.pdfViewer = pdfViewer;
},
setHistory: function PDFLinkService_setHistory(pdfHistory) {
this.pdfHistory = pdfHistory;
},
/**
* @returns {number}
*/
get pagesCount() {
return this.pdfDocument.numPages;
},
/**
* @returns {number}
*/
get page() {
return this.pdfViewer.currentPageNumber;
},
/**
* @param {number} value
*/
set page(value) {
this.pdfViewer.currentPageNumber = value;
},
/**
* @param dest - The PDF destination object.
*/
navigateTo: function PDFLinkService_navigateTo(dest) {
var destString = '';
var self = this;
var goToDestination = function(destRef) {
// dest array looks like that: <page-ref> </XYZ|FitXXX> <args..>
var pageNumber = destRef instanceof Object ?
self._pagesRefCache[destRef.num + ' ' + destRef.gen + ' R'] :
(destRef + 1);
if (pageNumber) {
if (pageNumber > self.pagesCount) {
pageNumber = self.pagesCount;
}
self.pdfViewer.scrollPageIntoView(pageNumber, dest);
if (self.pdfHistory) {
// Update the browsing history.
self.pdfHistory.push({
dest: dest,
hash: destString,
page: pageNumber
});
}
} else {
self.pdfDocument.getPageIndex(destRef).then(function (pageIndex) {
var pageNum = pageIndex + 1;
var cacheKey = destRef.num + ' ' + destRef.gen + ' R';
self._pagesRefCache[cacheKey] = pageNum;
goToDestination(destRef);
});
}
};
var destinationPromise;
if (typeof dest === 'string') {
destString = dest;
destinationPromise = this.pdfDocument.getDestination(dest);
} else {
destinationPromise = Promise.resolve(dest);
}
destinationPromise.then(function(destination) {
dest = destination;
if (!(destination instanceof Array)) {
return; // invalid destination
}
goToDestination(destination[0]);
});
},
/**
* @param dest - The PDF destination object.
* @returns {string} The hyperlink to the PDF object.
*/
getDestinationHash: function PDFLinkService_getDestinationHash(dest) {
if (typeof dest === 'string') {
return this.getAnchorUrl('#' + escape(dest));
}
if (dest instanceof Array) {
var destRef = dest[0]; // see navigateTo method for dest format
var pageNumber = destRef instanceof Object ?
this._pagesRefCache[destRef.num + ' ' + destRef.gen + ' R'] :
(destRef + 1);
if (pageNumber) {
var pdfOpenParams = this.getAnchorUrl('#page=' + pageNumber);
var destKind = dest[1];
if (typeof destKind === 'object' && 'name' in destKind &&
destKind.name === 'XYZ') {
var scale = (dest[4] || this.pdfViewer.currentScaleValue);
var scaleNumber = parseFloat(scale);
if (scaleNumber) {
scale = scaleNumber * 100;
}
pdfOpenParams += '&zoom=' + scale;
if (dest[2] || dest[3]) {
pdfOpenParams += ',' + (dest[2] || 0) + ',' + (dest[3] || 0);
}
}
return pdfOpenParams;
}
}
return this.getAnchorUrl('');
},
/**
* Prefix the full url on anchor links to make sure that links are resolved
* relative to the current URL instead of the one defined in <base href>.
* @param {String} anchor The anchor hash, including the #.
* @returns {string} The hyperlink to the PDF object.
*/
getAnchorUrl: function PDFLinkService_getAnchorUrl(anchor) {
return (this.baseUrl || '') + anchor;
},
/**
* @param {string} hash
*/
setHash: function PDFLinkService_setHash(hash) {
if (hash.indexOf('=') >= 0) {
var params = parseQueryString(hash);
// borrowing syntax from "Parameters for Opening PDF Files"
if ('nameddest' in params) {
if (this.pdfHistory) {
this.pdfHistory.updateNextHashParam(params.nameddest);
}
this.navigateTo(params.nameddest);
return;
}
var pageNumber, dest;
if ('page' in params) {
pageNumber = (params.page | 0) || 1;
}
if ('zoom' in params) {
// Build the destination array.
var zoomArgs = params.zoom.split(','); // scale,left,top
var zoomArg = zoomArgs[0];
var zoomArgNumber = parseFloat(zoomArg);
if (zoomArg.indexOf('Fit') === -1) {
// If the zoomArg is a number, it has to get divided by 100. If it's
// a string, it should stay as it is.
dest = [null, { name: 'XYZ' },
zoomArgs.length > 1 ? (zoomArgs[1] | 0) : null,
zoomArgs.length > 2 ? (zoomArgs[2] | 0) : null,
(zoomArgNumber ? zoomArgNumber / 100 : zoomArg)];
} else {
if (zoomArg === 'Fit' || zoomArg === 'FitB') {
dest = [null, { name: zoomArg }];
} else if ((zoomArg === 'FitH' || zoomArg === 'FitBH') ||
(zoomArg === 'FitV' || zoomArg === 'FitBV')) {
dest = [null, { name: zoomArg },
zoomArgs.length > 1 ? (zoomArgs[1] | 0) : null];
} else if (zoomArg === 'FitR') {
if (zoomArgs.length !== 5) {
console.error('PDFLinkService_setHash: ' +
'Not enough parameters for \'FitR\'.');
} else {
dest = [null, { name: zoomArg },
(zoomArgs[1] | 0), (zoomArgs[2] | 0),
(zoomArgs[3] | 0), (zoomArgs[4] | 0)];
}
} else {
console.error('PDFLinkService_setHash: \'' + zoomArg +
'\' is not a valid zoom value.');
}
}
}
if (dest) {
this.pdfViewer.scrollPageIntoView(pageNumber || this.page, dest);
} else if (pageNumber) {
this.page = pageNumber; // simple page
}
if ('pagemode' in params) {
var event = document.createEvent('CustomEvent');
event.initCustomEvent('pagemode', true, true, {
mode: params.pagemode,
});
this.pdfViewer.container.dispatchEvent(event);
}
} else if (/^\d+$/.test(hash)) { // page number
this.page = hash;
} else { // named destination
if (this.pdfHistory) {
this.pdfHistory.updateNextHashParam(unescape(hash));
}
this.navigateTo(unescape(hash));
}
},
/**
* @param {string} action
*/
executeNamedAction: function PDFLinkService_executeNamedAction(action) {
// See PDF reference, table 8.45 - Named action
switch (action) {
case 'GoBack':
if (this.pdfHistory) {
this.pdfHistory.back();
}
break;
case 'GoForward':
if (this.pdfHistory) {
this.pdfHistory.forward();
}
break;
case 'NextPage':
this.page++;
break;
case 'PrevPage':
this.page--;
break;
case 'LastPage':
this.page = this.pagesCount;
break;
case 'FirstPage':
this.page = 1;
break;
default:
break; // No action according to spec
}
var event = document.createEvent('CustomEvent');
event.initCustomEvent('namedaction', true, true, {
action: action
});
this.pdfViewer.container.dispatchEvent(event);
},
/**
* @param {number} pageNum - page number.
* @param {Object} pageRef - reference to the page.
*/
cachePageRef: function PDFLinkService_cachePageRef(pageNum, pageRef) {
var refStr = pageRef.num + ' ' + pageRef.gen + ' R';
this._pagesRefCache[refStr] = pageNum;
}
};
return PDFLinkService;
})();
var PresentationModeState = {
UNKNOWN: 0,
NORMAL: 1,
CHANGING: 2,
FULLSCREEN: 3,
};
var IGNORE_CURRENT_POSITION_ON_ZOOM = false;
var DEFAULT_CACHE_SIZE = 10;
var CLEANUP_TIMEOUT = 30000;
var RenderingStates = {
INITIAL: 0,
RUNNING: 1,
PAUSED: 2,
FINISHED: 3
};
/**
* Controls rendering of the views for pages and thumbnails.
* @class
*/
var PDFRenderingQueue = (function PDFRenderingQueueClosure() {
/**
* @constructs
*/
function PDFRenderingQueue() {
this.pdfViewer = null;
this.pdfThumbnailViewer = null;
this.onIdle = null;
this.highestPriorityPage = null;
this.idleTimeout = null;
this.printing = false;
this.isThumbnailViewEnabled = false;
}
PDFRenderingQueue.prototype = /** @lends PDFRenderingQueue.prototype */ {
/**
* @param {PDFViewer} pdfViewer
*/
setViewer: function PDFRenderingQueue_setViewer(pdfViewer) {
this.pdfViewer = pdfViewer;
},
/**
* @param {PDFThumbnailViewer} pdfThumbnailViewer
*/
setThumbnailViewer:
function PDFRenderingQueue_setThumbnailViewer(pdfThumbnailViewer) {
this.pdfThumbnailViewer = pdfThumbnailViewer;
},
/**
* @param {IRenderableView} view
* @returns {boolean}
*/
isHighestPriority: function PDFRenderingQueue_isHighestPriority(view) {
return this.highestPriorityPage === view.renderingId;
},
renderHighestPriority: function
PDFRenderingQueue_renderHighestPriority(currentlyVisiblePages) {
if (this.idleTimeout) {
clearTimeout(this.idleTimeout);
this.idleTimeout = null;
}
// Pages have a higher priority than thumbnails, so check them first.
if (this.pdfViewer.forceRendering(currentlyVisiblePages)) {
return;
}
// No pages needed rendering so check thumbnails.
if (this.pdfThumbnailViewer && this.isThumbnailViewEnabled) {
if (this.pdfThumbnailViewer.forceRendering()) {
return;
}
}
if (this.printing) {
// If printing is currently ongoing do not reschedule cleanup.
return;
}
if (this.onIdle) {
this.idleTimeout = setTimeout(this.onIdle.bind(this), CLEANUP_TIMEOUT);
}
},
getHighestPriority: function
PDFRenderingQueue_getHighestPriority(visible, views, scrolledDown) {
// The state has changed figure out which page has the highest priority to
// render next (if any).
// Priority:
// 1 visible pages
// 2 if last scrolled down page after the visible pages
// 2 if last scrolled up page before the visible pages
var visibleViews = visible.views;
var numVisible = visibleViews.length;
if (numVisible === 0) {
return false;
}
for (var i = 0; i < numVisible; ++i) {
var view = visibleViews[i].view;
if (!this.isViewFinished(view)) {
return view;
}
}
// All the visible views have rendered, try to render next/previous pages.
if (scrolledDown) {
var nextPageIndex = visible.last.id;
// ID's start at 1 so no need to add 1.
if (views[nextPageIndex] &&
!this.isViewFinished(views[nextPageIndex])) {
return views[nextPageIndex];
}
} else {
var previousPageIndex = visible.first.id - 2;
if (views[previousPageIndex] &&
!this.isViewFinished(views[previousPageIndex])) {
return views[previousPageIndex];
}
}
// Everything that needs to be rendered has been.
return null;
},
/**
* @param {IRenderableView} view
* @returns {boolean}
*/
isViewFinished: function PDFRenderingQueue_isViewFinished(view) {
return view.renderingState === RenderingStates.FINISHED;
},
/**
* Render a page or thumbnail view. This calls the appropriate function
* based on the views state. If the view is already rendered it will return
* false.
* @param {IRenderableView} view
*/
renderView: function PDFRenderingQueue_renderView(view) {
var state = view.renderingState;
switch (state) {
case RenderingStates.FINISHED:
return false;
case RenderingStates.PAUSED:
this.highestPriorityPage = view.renderingId;
view.resume();
break;
case RenderingStates.RUNNING:
this.highestPriorityPage = view.renderingId;
break;
case RenderingStates.INITIAL:
this.highestPriorityPage = view.renderingId;
var continueRendering = function () {
this.renderHighestPriority();
}.bind(this);
view.draw().then(continueRendering, continueRendering);
break;
}
return true;
},
};
return PDFRenderingQueue;
})();
var TEXT_LAYER_RENDER_DELAY = 200; // ms
/**
* @typedef {Object} PDFPageViewOptions
* @property {HTMLDivElement} container - The viewer element.
* @property {number} id - The page unique ID (normally its number).
* @property {number} scale - The page scale display.
* @property {PageViewport} defaultViewport - The page viewport.
* @property {PDFRenderingQueue} renderingQueue - The rendering queue object.
* @property {IPDFTextLayerFactory} textLayerFactory
* @property {IPDFAnnotationLayerFactory} annotationLayerFactory
*/
/**
* @class
* @implements {IRenderableView}
*/
var PDFPageView = (function PDFPageViewClosure() {
/**
* @constructs PDFPageView
* @param {PDFPageViewOptions} options
*/
function PDFPageView(options) {
var container = options.container;
var id = options.id;
var scale = options.scale;
var defaultViewport = options.defaultViewport;
var renderingQueue = options.renderingQueue;
var textLayerFactory = options.textLayerFactory;
var annotationLayerFactory = options.annotationLayerFactory;
this.id = id;
this.renderingId = 'page' + id;
this.rotation = 0;
this.scale = scale || DEFAULT_SCALE;
this.viewport = defaultViewport;
this.pdfPageRotate = defaultViewport.rotation;
this.hasRestrictedScaling = false;
this.renderingQueue = renderingQueue;
this.textLayerFactory = textLayerFactory;
this.annotationLayerFactory = annotationLayerFactory;
this.renderingState = RenderingStates.INITIAL;
this.resume = null;
this.onBeforeDraw = null;
this.onAfterDraw = null;
this.textLayer = null;
this.zoomLayer = null;
this.annotationLayer = null;
var div = document.createElement('div');
div.id = 'pageContainer' + this.id;
div.className = 'page';
div.style.width = Math.floor(this.viewport.width) + 'px';
div.style.height = Math.floor(this.viewport.height) + 'px';
div.setAttribute('data-page-number', this.id);
this.div = div;
container.appendChild(div);
}
PDFPageView.prototype = {
setPdfPage: function PDFPageView_setPdfPage(pdfPage) {
this.pdfPage = pdfPage;
this.pdfPageRotate = pdfPage.rotate;
var totalRotation = (this.rotation + this.pdfPageRotate) % 360;
this.viewport = pdfPage.getViewport(this.scale * CSS_UNITS,
totalRotation);
this.stats = pdfPage.stats;
this.reset();
},
destroy: function PDFPageView_destroy() {
this.zoomLayer = null;
this.reset();
if (this.pdfPage) {
this.pdfPage.cleanup();
}
},
reset: function PDFPageView_reset(keepZoomLayer, keepAnnotations) {
if (this.renderTask) {
this.renderTask.cancel();
}
this.resume = null;
this.renderingState = RenderingStates.INITIAL;
var div = this.div;
div.style.width = Math.floor(this.viewport.width) + 'px';
div.style.height = Math.floor(this.viewport.height) + 'px';
var childNodes = div.childNodes;
var currentZoomLayerNode = (keepZoomLayer && this.zoomLayer) || null;
var currentAnnotationNode = (keepAnnotations && this.annotationLayer &&
this.annotationLayer.div) || null;
for (var i = childNodes.length - 1; i >= 0; i--) {
var node = childNodes[i];
if (currentZoomLayerNode === node || currentAnnotationNode === node) {
continue;
}
div.removeChild(node);
}
div.removeAttribute('data-loaded');
if (currentAnnotationNode) {
// Hide annotationLayer until all elements are resized
// so they are not displayed on the already-resized page
this.annotationLayer.hide();
} else {
this.annotationLayer = null;
}
if (this.canvas && !currentZoomLayerNode) {
// Zeroing the width and height causes Firefox to release graphics
// resources immediately, which can greatly reduce memory consumption.
this.canvas.width = 0;
this.canvas.height = 0;
delete this.canvas;
}
this.loadingIconDiv = document.createElement('div');
this.loadingIconDiv.className = 'loadingIcon';
div.appendChild(this.loadingIconDiv);
},
update: function PDFPageView_update(scale, rotation) {
this.scale = scale || this.scale;
if (typeof rotation !== 'undefined') {
this.rotation = rotation;
}
var totalRotation = (this.rotation + this.pdfPageRotate) % 360;
this.viewport = this.viewport.clone({
scale: this.scale * CSS_UNITS,
rotation: totalRotation
});
var isScalingRestricted = false;
if (this.canvas && PDFJS.maxCanvasPixels > 0) {
var outputScale = this.outputScale;
var pixelsInViewport = this.viewport.width * this.viewport.height;
var maxScale = Math.sqrt(PDFJS.maxCanvasPixels / pixelsInViewport);
if (((Math.floor(this.viewport.width) * outputScale.sx) | 0) *
((Math.floor(this.viewport.height) * outputScale.sy) | 0) >
PDFJS.maxCanvasPixels) {
isScalingRestricted = true;
}
}
if (this.canvas) {
if (PDFJS.useOnlyCssZoom ||
(this.hasRestrictedScaling && isScalingRestricted)) {
this.cssTransform(this.canvas, true);
var event = document.createEvent('CustomEvent');
event.initCustomEvent('pagerendered', true, true, {
pageNumber: this.id,
cssTransform: true,
});
this.div.dispatchEvent(event);
return;
}
if (!this.zoomLayer) {
this.zoomLayer = this.canvas.parentNode;
this.zoomLayer.style.position = 'absolute';
}
}
if (this.zoomLayer) {
this.cssTransform(this.zoomLayer.firstChild);
}
this.reset(/* keepZoomLayer = */ true, /* keepAnnotations = */ true);
},
/**
* Called when moved in the parent's container.
*/
updatePosition: function PDFPageView_updatePosition() {
if (this.textLayer) {
this.textLayer.render(TEXT_LAYER_RENDER_DELAY);
}
},
cssTransform: function PDFPageView_transform(canvas, redrawAnnotations) {
var CustomStyle = PDFJS.CustomStyle;
// Scale canvas, canvas wrapper, and page container.
var width = this.viewport.width;
var height = this.viewport.height;
var div = this.div;
canvas.style.width = canvas.parentNode.style.width = div.style.width =
Math.floor(width) + 'px';
canvas.style.height = canvas.parentNode.style.height = div.style.height =
Math.floor(height) + 'px';
// The canvas may have been originally rotated, rotate relative to that.
var relativeRotation = this.viewport.rotation - canvas._viewport.rotation;
var absRotation = Math.abs(relativeRotation);
var scaleX = 1, scaleY = 1;
if (absRotation === 90 || absRotation === 270) {
// Scale x and y because of the rotation.
scaleX = height / width;
scaleY = width / height;
}
var cssTransform = 'rotate(' + relativeRotation + 'deg) ' +
'scale(' + scaleX + ',' + scaleY + ')';
CustomStyle.setProp('transform', canvas, cssTransform);
if (this.textLayer) {
// Rotating the text layer is more complicated since the divs inside the
// the text layer are rotated.
// TODO: This could probably be simplified by drawing the text layer in
// one orientation then rotating overall.
var textLayerViewport = this.textLayer.viewport;
var textRelativeRotation = this.viewport.rotation -
textLayerViewport.rotation;
var textAbsRotation = Math.abs(textRelativeRotation);
var scale = width / textLayerViewport.width;
if (textAbsRotation === 90 || textAbsRotation === 270) {
scale = width / textLayerViewport.height;
}
var textLayerDiv = this.textLayer.textLayerDiv;
var transX, transY;
switch (textAbsRotation) {
case 0:
transX = transY = 0;
break;
case 90:
transX = 0;
transY = '-' + textLayerDiv.style.height;
break;
case 180:
transX = '-' + textLayerDiv.style.width;
transY = '-' + textLayerDiv.style.height;
break;
case 270:
transX = '-' + textLayerDiv.style.width;
transY = 0;
break;
default:
console.error('Bad rotation value.');
break;
}
CustomStyle.setProp('transform', textLayerDiv,
'rotate(' + textAbsRotation + 'deg) ' +
'scale(' + scale + ', ' + scale + ') ' +
'translate(' + transX + ', ' + transY + ')');
CustomStyle.setProp('transformOrigin', textLayerDiv, '0% 0%');
}
if (redrawAnnotations && this.annotationLayer) {
this.annotationLayer.render(this.viewport, 'display');
}
},
get width() {
return this.viewport.width;
},
get height() {
return this.viewport.height;
},
getPagePoint: function PDFPageView_getPagePoint(x, y) {
return this.viewport.convertToPdfPoint(x, y);
},
draw: function PDFPageView_draw() {
if (this.renderingState !== RenderingStates.INITIAL) {
console.error('Must be in new state before drawing');
}
this.renderingState = RenderingStates.RUNNING;
var pdfPage = this.pdfPage;
var viewport = this.viewport;
var div = this.div;
// Wrap the canvas so if it has a css transform for highdpi the overflow
// will be hidden in FF.
var canvasWrapper = document.createElement('div');
canvasWrapper.style.width = div.style.width;
canvasWrapper.style.height = div.style.height;
canvasWrapper.classList.add('canvasWrapper');
var canvas = document.createElement('canvas');
canvas.id = 'page' + this.id;
// Keep the canvas hidden until the first draw callback, or until drawing
// is complete when `!this.renderingQueue`, to prevent black flickering.
canvas.setAttribute('hidden', 'hidden');
var isCanvasHidden = true;
canvasWrapper.appendChild(canvas);
if (this.annotationLayer && this.annotationLayer.div) {
// annotationLayer needs to stay on top
div.insertBefore(canvasWrapper, this.annotationLayer.div);
} else {
div.appendChild(canvasWrapper);
}
this.canvas = canvas;
var ctx = canvas.getContext('2d', {alpha: false});
var outputScale = getOutputScale(ctx);
this.outputScale = outputScale;
if (PDFJS.useOnlyCssZoom) {
var actualSizeViewport = viewport.clone({scale: CSS_UNITS});
// Use a scale that will make the canvas be the original intended size
// of the page.
outputScale.sx *= actualSizeViewport.width / viewport.width;
outputScale.sy *= actualSizeViewport.height / viewport.height;
outputScale.scaled = true;
}
if (PDFJS.maxCanvasPixels > 0) {
var pixelsInViewport = viewport.width * viewport.height;
var maxScale = Math.sqrt(PDFJS.maxCanvasPixels / pixelsInViewport);
if (outputScale.sx > maxScale || outputScale.sy > maxScale) {
outputScale.sx = maxScale;
outputScale.sy = maxScale;
outputScale.scaled = true;
this.hasRestrictedScaling = true;
} else {
this.hasRestrictedScaling = false;
}
}
var sfx = approximateFraction(outputScale.sx);
var sfy = approximateFraction(outputScale.sy);
canvas.width = roundToDivide(viewport.width * outputScale.sx, sfx[0]);
canvas.height = roundToDivide(viewport.height * outputScale.sy, sfy[0]);
canvas.style.width = roundToDivide(viewport.width, sfx[1]) + 'px';
canvas.style.height = roundToDivide(viewport.height, sfy[1]) + 'px';
// Add the viewport so it's known what it was originally drawn with.
canvas._viewport = viewport;
var textLayerDiv = null;
var textLayer = null;
if (this.textLayerFactory) {
textLayerDiv = document.createElement('div');
textLayerDiv.className = 'textLayer';
textLayerDiv.style.width = canvasWrapper.style.width;
textLayerDiv.style.height = canvasWrapper.style.height;
if (this.annotationLayer && this.annotationLayer.div) {
// annotationLayer needs to stay on top
div.insertBefore(textLayerDiv, this.annotationLayer.div);
} else {
div.appendChild(textLayerDiv);
}
textLayer = this.textLayerFactory.createTextLayerBuilder(textLayerDiv,
this.id - 1,
this.viewport);
}
this.textLayer = textLayer;
var resolveRenderPromise, rejectRenderPromise;
var promise = new Promise(function (resolve, reject) {
resolveRenderPromise = resolve;
rejectRenderPromise = reject;
});
// Rendering area
var self = this;
function pageViewDrawCallback(error) {
// The renderTask may have been replaced by a new one, so only remove
// the reference to the renderTask if it matches the one that is
// triggering this callback.
if (renderTask === self.renderTask) {
self.renderTask = null;
}
if (error === 'cancelled') {
rejectRenderPromise(error);
return;
}
self.renderingState = RenderingStates.FINISHED;
if (isCanvasHidden) {
self.canvas.removeAttribute('hidden');
isCanvasHidden = false;
}
if (self.loadingIconDiv) {
div.removeChild(self.loadingIconDiv);
delete self.loadingIconDiv;
}
if (self.zoomLayer) {
// Zeroing the width and height causes Firefox to release graphics
// resources immediately, which can greatly reduce memory consumption.
var zoomLayerCanvas = self.zoomLayer.firstChild;
zoomLayerCanvas.width = 0;
zoomLayerCanvas.height = 0;
div.removeChild(self.zoomLayer);
self.zoomLayer = null;
}
self.error = error;
self.stats = pdfPage.stats;
if (self.onAfterDraw) {
self.onAfterDraw();
}
var event = document.createEvent('CustomEvent');
event.initCustomEvent('pagerendered', true, true, {
pageNumber: self.id,
cssTransform: false,
});
div.dispatchEvent(event);
if (!error) {
resolveRenderPromise(undefined);
} else {
rejectRenderPromise(error);
}
}
var renderContinueCallback = null;
if (this.renderingQueue) {
renderContinueCallback = function renderContinueCallback(cont) {
if (!self.renderingQueue.isHighestPriority(self)) {
self.renderingState = RenderingStates.PAUSED;
self.resume = function resumeCallback() {
self.renderingState = RenderingStates.RUNNING;
cont();
};
return;
}
if (isCanvasHidden) {
self.canvas.removeAttribute('hidden');
isCanvasHidden = false;
}
cont();
};
}
var transform = !outputScale.scaled ? null :
[outputScale.sx, 0, 0, outputScale.sy, 0, 0];
var renderContext = {
canvasContext: ctx,
transform: transform,
viewport: this.viewport,
// intent: 'default', // === 'display'
};
var renderTask = this.renderTask = this.pdfPage.render(renderContext);
renderTask.onContinue = renderContinueCallback;
this.renderTask.promise.then(
function pdfPageRenderCallback() {
pageViewDrawCallback(null);
if (textLayer) {
self.pdfPage.getTextContent({ normalizeWhitespace: true }).then(
function textContentResolved(textContent) {
textLayer.setTextContent(textContent);
textLayer.render(TEXT_LAYER_RENDER_DELAY);
}
);
}
},
function pdfPageRenderError(error) {
pageViewDrawCallback(error);
}
);
if (this.annotationLayerFactory) {
if (!this.annotationLayer) {
this.annotationLayer = this.annotationLayerFactory.
createAnnotationLayerBuilder(div, this.pdfPage);
}
this.annotationLayer.render(this.viewport, 'display');
}
div.setAttribute('data-loaded', true);
if (self.onBeforeDraw) {
self.onBeforeDraw();
}
return promise;
},
beforePrint: function PDFPageView_beforePrint() {
var CustomStyle = PDFJS.CustomStyle;
var pdfPage = this.pdfPage;
var viewport = pdfPage.getViewport(1);
// Use the same hack we use for high dpi displays for printing to get
// better output until bug 811002 is fixed in FF.
var PRINT_OUTPUT_SCALE = 2;
var canvas = document.createElement('canvas');
// The logical size of the canvas.
canvas.width = Math.floor(viewport.width) * PRINT_OUTPUT_SCALE;
canvas.height = Math.floor(viewport.height) * PRINT_OUTPUT_SCALE;
// The rendered size of the canvas, relative to the size of canvasWrapper.
canvas.style.width = (PRINT_OUTPUT_SCALE * 100) + '%';
canvas.style.height = (PRINT_OUTPUT_SCALE * 100) + '%';
var cssScale = 'scale(' + (1 / PRINT_OUTPUT_SCALE) + ', ' +
(1 / PRINT_OUTPUT_SCALE) + ')';
CustomStyle.setProp('transform' , canvas, cssScale);
CustomStyle.setProp('transformOrigin' , canvas, '0% 0%');
var printContainer = document.getElementById('printContainer');
var canvasWrapper = document.createElement('div');
canvasWrapper.style.width = viewport.width + 'pt';
canvasWrapper.style.height = viewport.height + 'pt';
canvasWrapper.appendChild(canvas);
printContainer.appendChild(canvasWrapper);
canvas.mozPrintCallback = function(obj) {
var ctx = obj.context;
ctx.save();
ctx.fillStyle = 'rgb(255, 255, 255)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.restore();
// Used by the mozCurrentTransform polyfill in src/display/canvas.js.
ctx._transformMatrix =
[PRINT_OUTPUT_SCALE, 0, 0, PRINT_OUTPUT_SCALE, 0, 0];
ctx.scale(PRINT_OUTPUT_SCALE, PRINT_OUTPUT_SCALE);
var renderContext = {
canvasContext: ctx,
viewport: viewport,
intent: 'print'
};
pdfPage.render(renderContext).promise.then(function() {
// Tell the printEngine that rendering this canvas/page has finished.
obj.done();
}, function(error) {
console.error(error);
// Tell the printEngine that rendering this canvas/page has failed.
// This will make the print proces stop.
if ('abort' in obj) {
obj.abort();
} else {
obj.done();
}
});
};
},
};
return PDFPageView;
})();
/**
* @typedef {Object} TextLayerBuilderOptions
* @property {HTMLDivElement} textLayerDiv - The text layer container.
* @property {number} pageIndex - The page index.
* @property {PageViewport} viewport - The viewport of the text layer.
* @property {PDFFindController} findController
*/
/**
* TextLayerBuilder provides text-selection functionality for the PDF.
* It does this by creating overlay divs over the PDF text. These divs
* contain text that matches the PDF text they are overlaying. This object
* also provides a way to highlight text that is being searched for.
* @class
*/
var TextLayerBuilder = (function TextLayerBuilderClosure() {
function TextLayerBuilder(options) {
this.textLayerDiv = options.textLayerDiv;
this.renderingDone = false;
this.divContentDone = false;
this.pageIdx = options.pageIndex;
this.pageNumber = this.pageIdx + 1;
this.matches = [];
this.viewport = options.viewport;
this.textDivs = [];
this.findController = options.findController || null;
this.textLayerRenderTask = null;
this._bindMouse();
}
TextLayerBuilder.prototype = {
_finishRendering: function TextLayerBuilder_finishRendering() {
this.renderingDone = true;
var endOfContent = document.createElement('div');
endOfContent.className = 'endOfContent';
this.textLayerDiv.appendChild(endOfContent);
var event = document.createEvent('CustomEvent');
event.initCustomEvent('textlayerrendered', true, true, {
pageNumber: this.pageNumber
});
this.textLayerDiv.dispatchEvent(event);
},
/**
* Renders the text layer.
* @param {number} timeout (optional) if specified, the rendering waits
* for specified amount of ms.
*/
render: function TextLayerBuilder_render(timeout) {
if (!this.divContentDone || this.renderingDone) {
return;
}
if (this.textLayerRenderTask) {
this.textLayerRenderTask.cancel();
this.textLayerRenderTask = null;
}
this.textDivs = [];
var textLayerFrag = document.createDocumentFragment();
this.textLayerRenderTask = PDFJS.renderTextLayer({
textContent: this.textContent,
container: textLayerFrag,
viewport: this.viewport,
textDivs: this.textDivs,
timeout: timeout
});
this.textLayerRenderTask.promise.then(function () {
this.textLayerDiv.appendChild(textLayerFrag);
this._finishRendering();
this.updateMatches();
}.bind(this), function (reason) {
// canceled or failed to render text layer -- skipping errors
});
},
setTextContent: function TextLayerBuilder_setTextContent(textContent) {
if (this.textLayerRenderTask) {
this.textLayerRenderTask.cancel();
this.textLayerRenderTask = null;
}
this.textContent = textContent;
this.divContentDone = true;
},
convertMatches: function TextLayerBuilder_convertMatches(matches) {
var i = 0;
var iIndex = 0;
var bidiTexts = this.textContent.items;
var end = bidiTexts.length - 1;
var queryLen = (this.findController === null ?
0 : this.findController.state.query.length);
var ret = [];
for (var m = 0, len = matches.length; m < len; m++) {
// Calculate the start position.
var matchIdx = matches[m];
// Loop over the divIdxs.
while (i !== end && matchIdx >= (iIndex + bidiTexts[i].str.length)) {
iIndex += bidiTexts[i].str.length;
i++;
}
if (i === bidiTexts.length) {
console.error('Could not find a matching mapping');
}
var match = {
begin: {
divIdx: i,
offset: matchIdx - iIndex
}
};
// Calculate the end position.
matchIdx += queryLen;
// Somewhat the same array as above, but use > instead of >= to get
// the end position right.
while (i !== end && matchIdx > (iIndex + bidiTexts[i].str.length)) {
iIndex += bidiTexts[i].str.length;
i++;
}
match.end = {
divIdx: i,
offset: matchIdx - iIndex
};
ret.push(match);
}
return ret;
},
renderMatches: function TextLayerBuilder_renderMatches(matches) {
// Early exit if there is nothing to render.
if (matches.length === 0) {
return;
}
var bidiTexts = this.textContent.items;
var textDivs = this.textDivs;
var prevEnd = null;
var pageIdx = this.pageIdx;
var isSelectedPage = (this.findController === null ?
false : (pageIdx === this.findController.selected.pageIdx));
var selectedMatchIdx = (this.findController === null ?
-1 : this.findController.selected.matchIdx);
var highlightAll = (this.findController === null ?
false : this.findController.state.highlightAll);
var infinity = {
divIdx: -1,
offset: undefined
};
function beginText(begin, className) {
var divIdx = begin.divIdx;
textDivs[divIdx].textContent = '';
appendTextToDiv(divIdx, 0, begin.offset, className);
}
function appendTextToDiv(divIdx, fromOffset, toOffset, className) {
var div = textDivs[divIdx];
var content = bidiTexts[divIdx].str.substring(fromOffset, toOffset);
var node = document.createTextNode(content);
if (className) {
var span = document.createElement('span');
span.className = className;
span.appendChild(node);
div.appendChild(span);
return;
}
div.appendChild(node);
}
var i0 = selectedMatchIdx, i1 = i0 + 1;
if (highlightAll) {
i0 = 0;
i1 = matches.length;
} else if (!isSelectedPage) {
// Not highlighting all and this isn't the selected page, so do nothing.
return;
}
for (var i = i0; i < i1; i++) {
var match = matches[i];
var begin = match.begin;
var end = match.end;
var isSelected = (isSelectedPage && i === selectedMatchIdx);
var highlightSuffix = (isSelected ? ' selected' : '');
if (this.findController) {
this.findController.updateMatchPosition(pageIdx, i, textDivs,
begin.divIdx, end.divIdx);
}
// Match inside new div.
if (!prevEnd || begin.divIdx !== prevEnd.divIdx) {
// If there was a previous div, then add the text at the end.
if (prevEnd !== null) {
appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset);
}
// Clear the divs and set the content until the starting point.
beginText(begin);
} else {
appendTextToDiv(prevEnd.divIdx, prevEnd.offset, begin.offset);
}
if (begin.divIdx === end.divIdx) {
appendTextToDiv(begin.divIdx, begin.offset, end.offset,
'highlight' + highlightSuffix);
} else {
appendTextToDiv(begin.divIdx, begin.offset, infinity.offset,
'highlight begin' + highlightSuffix);
for (var n0 = begin.divIdx + 1, n1 = end.divIdx; n0 < n1; n0++) {
textDivs[n0].className = 'highlight middle' + highlightSuffix;
}
beginText(end, 'highlight end' + highlightSuffix);
}
prevEnd = end;
}
if (prevEnd) {
appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset);
}
},
updateMatches: function TextLayerBuilder_updateMatches() {
// Only show matches when all rendering is done.
if (!this.renderingDone) {
return;
}
// Clear all matches.
var matches = this.matches;
var textDivs = this.textDivs;
var bidiTexts = this.textContent.items;
var clearedUntilDivIdx = -1;
// Clear all current matches.
for (var i = 0, len = matches.length; i < len; i++) {
var match = matches[i];
var begin = Math.max(clearedUntilDivIdx, match.begin.divIdx);
for (var n = begin, end = match.end.divIdx; n <= end; n++) {
var div = textDivs[n];
div.textContent = bidiTexts[n].str;
div.className = '';
}
clearedUntilDivIdx = match.end.divIdx + 1;
}
if (this.findController === null || !this.findController.active) {
return;
}
// Convert the matches on the page controller into the match format
// used for the textLayer.
this.matches = this.convertMatches(this.findController === null ?
[] : (this.findController.pageMatches[this.pageIdx] || []));
this.renderMatches(this.matches);
},
/**
* Fixes text selection: adds additional div where mouse was clicked.
* This reduces flickering of the content if mouse slowly dragged down/up.
* @private
*/
_bindMouse: function TextLayerBuilder_bindMouse() {
var div = this.textLayerDiv;
div.addEventListener('mousedown', function (e) {
var end = div.querySelector('.endOfContent');
if (!end) {
return;
}
// On non-Firefox browsers, the selection will feel better if the height
// of the endOfContent div will be adjusted to start at mouse click
// location -- this will avoid flickering when selections moves up.
// However it does not work when selection started on empty space.
var adjustTop = e.target !== div;
if (adjustTop) {
var divBounds = div.getBoundingClientRect();
var r = Math.max(0, (e.pageY - divBounds.top) / divBounds.height);
end.style.top = (r * 100).toFixed(2) + '%';
}
end.classList.add('active');
});
div.addEventListener('mouseup', function (e) {
var end = div.querySelector('.endOfContent');
if (!end) {
return;
}
end.style.top = '';
end.classList.remove('active');
});
},
};
return TextLayerBuilder;
})();
/**
* @constructor
* @implements IPDFTextLayerFactory
*/
function DefaultTextLayerFactory() {}
DefaultTextLayerFactory.prototype = {
/**
* @param {HTMLDivElement} textLayerDiv
* @param {number} pageIndex
* @param {PageViewport} viewport
* @returns {TextLayerBuilder}
*/
createTextLayerBuilder: function (textLayerDiv, pageIndex, viewport) {
return new TextLayerBuilder({
textLayerDiv: textLayerDiv,
pageIndex: pageIndex,
viewport: viewport
});
}
};
/**
* @typedef {Object} AnnotationLayerBuilderOptions
* @property {HTMLDivElement} pageDiv
* @property {PDFPage} pdfPage
* @property {IPDFLinkService} linkService
* @property {DownloadManager} downloadManager
*/
/**
* @class
*/
var AnnotationLayerBuilder = (function AnnotationLayerBuilderClosure() {
/**
* @param {AnnotationLayerBuilderOptions} options
* @constructs AnnotationLayerBuilder
*/
function AnnotationLayerBuilder(options) {
this.pageDiv = options.pageDiv;
this.pdfPage = options.pdfPage;
this.linkService = options.linkService;
this.downloadManager = options.downloadManager;
this.div = null;
}
AnnotationLayerBuilder.prototype =
/** @lends AnnotationLayerBuilder.prototype */ {
/**
* @param {PageViewport} viewport
* @param {string} intent (default value is 'display')
*/
render: function AnnotationLayerBuilder_render(viewport, intent) {
var self = this;
var parameters = {
intent: (intent === undefined ? 'display' : intent),
};
this.pdfPage.getAnnotations(parameters).then(function (annotations) {
viewport = viewport.clone({ dontFlip: true });
parameters = {
viewport: viewport,
div: self.div,
annotations: annotations,
page: self.pdfPage,
linkService: self.linkService,
downloadManager: self.downloadManager
};
if (self.div) {
// If an annotationLayer already exists, refresh its children's
// transformation matrices.
PDFJS.AnnotationLayer.update(parameters);
} else {
// Create an annotation layer div and render the annotations
// if there is at least one annotation.
if (annotations.length === 0) {
return;
}
self.div = document.createElement('div');
self.div.className = 'annotationLayer';
self.pageDiv.appendChild(self.div);
parameters.div = self.div;
PDFJS.AnnotationLayer.render(parameters);
if (typeof mozL10n !== 'undefined') {
mozL10n.translate(self.div);
}
}
});
},
hide: function AnnotationLayerBuilder_hide() {
if (!this.div) {
return;
}
this.div.setAttribute('hidden', 'true');
}
};
return AnnotationLayerBuilder;
})();
/**
* @constructor
* @implements IPDFAnnotationLayerFactory
*/
function DefaultAnnotationLayerFactory() {}
DefaultAnnotationLayerFactory.prototype = {
/**
* @param {HTMLDivElement} pageDiv
* @param {PDFPage} pdfPage
* @returns {AnnotationLayerBuilder}
*/
createAnnotationLayerBuilder: function (pageDiv, pdfPage) {
return new AnnotationLayerBuilder({
pageDiv: pageDiv,
pdfPage: pdfPage,
linkService: new SimpleLinkService(),
});
}
};
/**
* @typedef {Object} PDFViewerOptions
* @property {HTMLDivElement} container - The container for the viewer element.
* @property {HTMLDivElement} viewer - (optional) The viewer element.
* @property {IPDFLinkService} linkService - The navigation/linking service.
* @property {DownloadManager} downloadManager - (optional) The download
* manager component.
* @property {PDFRenderingQueue} renderingQueue - (optional) The rendering
* queue object.
* @property {boolean} removePageBorders - (optional) Removes the border shadow
* around the pages. The default is false.
*/
/**
* Simple viewer control to display PDF content/pages.
* @class
* @implements {IRenderableView}
*/
var PDFViewer = (function pdfViewer() {
function PDFPageViewBuffer(size) {
var data = [];
this.push = function cachePush(view) {
var i = data.indexOf(view);
if (i >= 0) {
data.splice(i, 1);
}
data.push(view);
if (data.length > size) {
data.shift().destroy();
}
};
this.resize = function (newSize) {
size = newSize;
while (data.length > size) {
data.shift().destroy();
}
};
}
function isSameScale(oldScale, newScale) {
if (newScale === oldScale) {
return true;
}
if (Math.abs(newScale - oldScale) < 1e-15) {
// Prevent unnecessary re-rendering of all pages when the scale
// changes only because of limited numerical precision.
return true;
}
return false;
}
/**
* @constructs PDFViewer
* @param {PDFViewerOptions} options
*/
function PDFViewer(options) {
this.container = options.container;
this.viewer = options.viewer || options.container.firstElementChild;
this.linkService = options.linkService || new SimpleLinkService();
this.downloadManager = options.downloadManager || null;
this.removePageBorders = options.removePageBorders || false;
this.defaultRenderingQueue = !options.renderingQueue;
if (this.defaultRenderingQueue) {
// Custom rendering queue is not specified, using default one
this.renderingQueue = new PDFRenderingQueue();
this.renderingQueue.setViewer(this);
} else {
this.renderingQueue = options.renderingQueue;
}
this.scroll = watchScroll(this.container, this._scrollUpdate.bind(this));
this.updateInProgress = false;
this.presentationModeState = PresentationModeState.UNKNOWN;
this._resetView();
if (this.removePageBorders) {
this.viewer.classList.add('removePageBorders');
}
}
PDFViewer.prototype = /** @lends PDFViewer.prototype */{
get pagesCount() {
return this._pages.length;
},
getPageView: function (index) {
return this._pages[index];
},
get currentPageNumber() {
return this._currentPageNumber;
},
set currentPageNumber(val) {
if (!this.pdfDocument) {
this._currentPageNumber = val;
return;
}
var event = document.createEvent('UIEvents');
event.initUIEvent('pagechange', true, true, window, 0);
event.updateInProgress = this.updateInProgress;
if (!(0 < val && val <= this.pagesCount)) {
event.pageNumber = this._currentPageNumber;
event.previousPageNumber = val;
this.container.dispatchEvent(event);
return;
}
event.previousPageNumber = this._currentPageNumber;
this._currentPageNumber = val;
event.pageNumber = val;
this.container.dispatchEvent(event);
// Check if the caller is `PDFViewer_update`, to avoid breaking scrolling.
if (this.updateInProgress) {
return;
}
this.scrollPageIntoView(val);
},
/**
* @returns {number}
*/
get currentScale() {
return this._currentScale !== UNKNOWN_SCALE ? this._currentScale :
DEFAULT_SCALE;
},
/**
* @param {number} val - Scale of the pages in percents.
*/
set currentScale(val) {
if (isNaN(val)) {
throw new Error('Invalid numeric scale');
}
if (!this.pdfDocument) {
this._currentScale = val;
this._currentScaleValue = val !== UNKNOWN_SCALE ? val.toString() : null;
return;
}
this._setScale(val, false);
},
/**
* @returns {string}
*/
get currentScaleValue() {
return this._currentScaleValue;
},
/**
* @param val - The scale of the pages (in percent or predefined value).
*/
set currentScaleValue(val) {
if (!this.pdfDocument) {
this._currentScale = isNaN(val) ? UNKNOWN_SCALE : val;
this._currentScaleValue = val;
return;
}
this._setScale(val, false);
},
/**
* @returns {number}
*/
get pagesRotation() {
return this._pagesRotation;
},
/**
* @param {number} rotation - The rotation of the pages (0, 90, 180, 270).
*/
set pagesRotation(rotation) {
this._pagesRotation = rotation;
for (var i = 0, l = this._pages.length; i < l; i++) {
var pageView = this._pages[i];
pageView.update(pageView.scale, rotation);
}
this._setScale(this._currentScaleValue, true);
if (this.defaultRenderingQueue) {
this.update();
}
},
/**
* @param pdfDocument {PDFDocument}
*/
setDocument: function (pdfDocument) {
if (this.pdfDocument) {
this._resetView();
}
this.pdfDocument = pdfDocument;
if (!pdfDocument) {
return;
}
var pagesCount = pdfDocument.numPages;
var self = this;
var resolvePagesPromise;
var pagesPromise = new Promise(function (resolve) {
resolvePagesPromise = resolve;
});
this.pagesPromise = pagesPromise;
pagesPromise.then(function () {
var event = document.createEvent('CustomEvent');
event.initCustomEvent('pagesloaded', true, true, {
pagesCount: pagesCount
});
self.container.dispatchEvent(event);
});
var isOnePageRenderedResolved = false;
var resolveOnePageRendered = null;
var onePageRendered = new Promise(function (resolve) {
resolveOnePageRendered = resolve;
});
this.onePageRendered = onePageRendered;
var bindOnAfterAndBeforeDraw = function (pageView) {
pageView.onBeforeDraw = function pdfViewLoadOnBeforeDraw() {
// Add the page to the buffer at the start of drawing. That way it can
// be evicted from the buffer and destroyed even if we pause its
// rendering.
self._buffer.push(this);
};
// when page is painted, using the image as thumbnail base
pageView.onAfterDraw = function pdfViewLoadOnAfterDraw() {
if (!isOnePageRenderedResolved) {
isOnePageRenderedResolved = true;
resolveOnePageRendered();
}
};
};
var firstPagePromise = pdfDocument.getPage(1);
this.firstPagePromise = firstPagePromise;
// Fetch a single page so we can get a viewport that will be the default
// viewport for all pages
return firstPagePromise.then(function(pdfPage) {
var scale = this.currentScale;
var viewport = pdfPage.getViewport(scale * CSS_UNITS);
for (var pageNum = 1; pageNum <= pagesCount; ++pageNum) {
var textLayerFactory = null;
if (!PDFJS.disableTextLayer) {
textLayerFactory = this;
}
var pageView = new PDFPageView({
container: this.viewer,
id: pageNum,
scale: scale,
defaultViewport: viewport.clone(),
renderingQueue: this.renderingQueue,
textLayerFactory: textLayerFactory,
annotationLayerFactory: this
});
bindOnAfterAndBeforeDraw(pageView);
this._pages.push(pageView);
}
var linkService = this.linkService;
// Fetch all the pages since the viewport is needed before printing
// starts to create the correct size canvas. Wait until one page is
// rendered so we don't tie up too many resources early on.
onePageRendered.then(function () {
if (!PDFJS.disableAutoFetch) {
var getPagesLeft = pagesCount;
for (var pageNum = 1; pageNum <= pagesCount; ++pageNum) {
pdfDocument.getPage(pageNum).then(function (pageNum, pdfPage) {
var pageView = self._pages[pageNum - 1];
if (!pageView.pdfPage) {
pageView.setPdfPage(pdfPage);
}
linkService.cachePageRef(pageNum, pdfPage.ref);
getPagesLeft--;
if (!getPagesLeft) {
resolvePagesPromise();
}
}.bind(null, pageNum));
}
} else {
// XXX: Printing is semi-broken with auto fetch disabled.
resolvePagesPromise();
}
});
var event = document.createEvent('CustomEvent');
event.initCustomEvent('pagesinit', true, true, null);
self.container.dispatchEvent(event);
if (this.defaultRenderingQueue) {
this.update();
}
if (this.findController) {
this.findController.resolveFirstPage();
}
}.bind(this));
},
_resetView: function () {
this._pages = [];
this._currentPageNumber = 1;
this._currentScale = UNKNOWN_SCALE;
this._currentScaleValue = null;
this._buffer = new PDFPageViewBuffer(DEFAULT_CACHE_SIZE);
this._location = null;
this._pagesRotation = 0;
this._pagesRequests = [];
var container = this.viewer;
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
},
_scrollUpdate: function PDFViewer_scrollUpdate() {
if (this.pagesCount === 0) {
return;
}
this.update();
for (var i = 0, ii = this._pages.length; i < ii; i++) {
this._pages[i].updatePosition();
}
},
_setScaleDispatchEvent: function pdfViewer_setScaleDispatchEvent(
newScale, newValue, preset) {
var event = document.createEvent('UIEvents');
event.initUIEvent('scalechange', true, true, window, 0);
event.scale = newScale;
if (preset) {
event.presetValue = newValue;
}
this.container.dispatchEvent(event);
},
_setScaleUpdatePages: function pdfViewer_setScaleUpdatePages(
newScale, newValue, noScroll, preset) {
this._currentScaleValue = newValue;
if (isSameScale(this._currentScale, newScale)) {
if (preset) {
this._setScaleDispatchEvent(newScale, newValue, true);
}
return;
}
for (var i = 0, ii = this._pages.length; i < ii; i++) {
this._pages[i].update(newScale);
}
this._currentScale = newScale;
if (!noScroll) {
var page = this._currentPageNumber, dest;
if (this._location && !IGNORE_CURRENT_POSITION_ON_ZOOM &&
!(this.isInPresentationMode || this.isChangingPresentationMode)) {
page = this._location.pageNumber;
dest = [null, { name: 'XYZ' }, this._location.left,
this._location.top, null];
}
this.scrollPageIntoView(page, dest);
}
this._setScaleDispatchEvent(newScale, newValue, preset);
if (this.defaultRenderingQueue) {
this.update();
}
},
_setScale: function pdfViewer_setScale(value, noScroll) {
var scale = parseFloat(value);
if (scale > 0) {
this._setScaleUpdatePages(scale, value, noScroll, false);
} else {
var currentPage = this._pages[this._currentPageNumber - 1];
if (!currentPage) {
return;
}
var hPadding = (this.isInPresentationMode || this.removePageBorders) ?
0 : SCROLLBAR_PADDING;
var vPadding = (this.isInPresentationMode || this.removePageBorders) ?
0 : VERTICAL_PADDING;
var pageWidthScale = (this.container.clientWidth - hPadding) /
currentPage.width * currentPage.scale;
var pageHeightScale = (this.container.clientHeight - vPadding) /
currentPage.height * currentPage.scale;
switch (value) {
case 'page-actual':
scale = 1;
break;
case 'page-width':
scale = pageWidthScale;
break;
case 'page-height':
scale = pageHeightScale;
break;
case 'page-fit':
scale = Math.min(pageWidthScale, pageHeightScale);
break;
case 'auto':
var isLandscape = (currentPage.width > currentPage.height);
// For pages in landscape mode, fit the page height to the viewer
// *unless* the page would thus become too wide to fit horizontally.
var horizontalScale = isLandscape ?
Math.min(pageHeightScale, pageWidthScale) : pageWidthScale;
scale = Math.min(MAX_AUTO_SCALE, horizontalScale);
break;
default:
console.error('pdfViewSetScale: \'' + value +
'\' is an unknown zoom value.');
return;
}
this._setScaleUpdatePages(scale, value, noScroll, true);
}
},
/**
* Scrolls page into view.
* @param {number} pageNumber
* @param {Array} dest - (optional) original PDF destination array:
* <page-ref> </XYZ|FitXXX> <args..>
*/
scrollPageIntoView: function PDFViewer_scrollPageIntoView(pageNumber,
dest) {
if (!this.pdfDocument) {
return;
}
var pageView = this._pages[pageNumber - 1];
if (this.isInPresentationMode) {
if (this._currentPageNumber !== pageView.id) {
// Avoid breaking getVisiblePages in presentation mode.
this.currentPageNumber = pageView.id;
return;
}
dest = null;
// Fixes the case when PDF has different page sizes.
this._setScale(this._currentScaleValue, true);
}
if (!dest) {
scrollIntoView(pageView.div);
return;
}
var x = 0, y = 0;
var width = 0, height = 0, widthScale, heightScale;
var changeOrientation = (pageView.rotation % 180 === 0 ? false : true);
var pageWidth = (changeOrientation ? pageView.height : pageView.width) /
pageView.scale / CSS_UNITS;
var pageHeight = (changeOrientation ? pageView.width : pageView.height) /
pageView.scale / CSS_UNITS;
var scale = 0;
switch (dest[1].name) {
case 'XYZ':
x = dest[2];
y = dest[3];
scale = dest[4];
// If x and/or y coordinates are not supplied, default to
// _top_ left of the page (not the obvious bottom left,
// since aligning the bottom of the intended page with the
// top of the window is rarely helpful).
x = x !== null ? x : 0;
y = y !== null ? y : pageHeight;
break;
case 'Fit':
case 'FitB':
scale = 'page-fit';
break;
case 'FitH':
case 'FitBH':
y = dest[2];
scale = 'page-width';
// According to the PDF spec, section 12.3.2.2, a `null` value in the
// parameter should maintain the position relative to the new page.
if (y === null && this._location) {
x = this._location.left;
y = this._location.top;
}
break;
case 'FitV':
case 'FitBV':
x = dest[2];
width = pageWidth;
height = pageHeight;
scale = 'page-height';
break;
case 'FitR':
x = dest[2];
y = dest[3];
width = dest[4] - x;
height = dest[5] - y;
var hPadding = this.removePageBorders ? 0 : SCROLLBAR_PADDING;
var vPadding = this.removePageBorders ? 0 : VERTICAL_PADDING;
widthScale = (this.container.clientWidth - hPadding) /
width / CSS_UNITS;
heightScale = (this.container.clientHeight - vPadding) /
height / CSS_UNITS;
scale = Math.min(Math.abs(widthScale), Math.abs(heightScale));
break;
default:
return;
}
if (scale && scale !== this._currentScale) {
this.currentScaleValue = scale;
} else if (this._currentScale === UNKNOWN_SCALE) {
this.currentScaleValue = DEFAULT_SCALE_VALUE;
}
if (scale === 'page-fit' && !dest[4]) {
scrollIntoView(pageView.div);
return;
}
var boundingRect = [
pageView.viewport.convertToViewportPoint(x, y),
pageView.viewport.convertToViewportPoint(x + width, y + height)
];
var left = Math.min(boundingRect[0][0], boundingRect[1][0]);
var top = Math.min(boundingRect[0][1], boundingRect[1][1]);
scrollIntoView(pageView.div, { left: left, top: top });
},
_updateLocation: function (firstPage) {
var currentScale = this._currentScale;
var currentScaleValue = this._currentScaleValue;
var normalizedScaleValue =
parseFloat(currentScaleValue) === currentScale ?
Math.round(currentScale * 10000) / 100 : currentScaleValue;
var pageNumber = firstPage.id;
var pdfOpenParams = '#page=' + pageNumber;
pdfOpenParams += '&zoom=' + normalizedScaleValue;
var currentPageView = this._pages[pageNumber - 1];
var container = this.container;
var topLeft = currentPageView.getPagePoint(
(container.scrollLeft - firstPage.x),
(container.scrollTop - firstPage.y));
var intLeft = Math.round(topLeft[0]);
var intTop = Math.round(topLeft[1]);
pdfOpenParams += ',' + intLeft + ',' + intTop;
this._location = {
pageNumber: pageNumber,
scale: normalizedScaleValue,
top: intTop,
left: intLeft,
pdfOpenParams: pdfOpenParams
};
},
update: function PDFViewer_update() {
var visible = this._getVisiblePages();
var visiblePages = visible.views;
if (visiblePages.length === 0) {
return;
}
this.updateInProgress = true;
var suggestedCacheSize = Math.max(DEFAULT_CACHE_SIZE,
2 * visiblePages.length + 1);
this._buffer.resize(suggestedCacheSize);
this.renderingQueue.renderHighestPriority(visible);
var currentId = this._currentPageNumber;
var firstPage = visible.first;
for (var i = 0, ii = visiblePages.length, stillFullyVisible = false;
i < ii; ++i) {
var page = visiblePages[i];
if (page.percent < 100) {
break;
}
if (page.id === currentId) {
stillFullyVisible = true;
break;
}
}
if (!stillFullyVisible) {
currentId = visiblePages[0].id;
}
if (!this.isInPresentationMode) {
this.currentPageNumber = currentId;
}
this._updateLocation(firstPage);
this.updateInProgress = false;
var event = document.createEvent('UIEvents');
event.initUIEvent('updateviewarea', true, true, window, 0);
event.location = this._location;
this.container.dispatchEvent(event);
},
containsElement: function (element) {
return this.container.contains(element);
},
focus: function () {
this.container.focus();
},
get isInPresentationMode() {
return this.presentationModeState === PresentationModeState.FULLSCREEN;
},
get isChangingPresentationMode() {
return this.presentationModeState === PresentationModeState.CHANGING;
},
get isHorizontalScrollbarEnabled() {
return (this.isInPresentationMode ?
false : (this.container.scrollWidth > this.container.clientWidth));
},
_getVisiblePages: function () {
if (!this.isInPresentationMode) {
return getVisibleElements(this.container, this._pages, true);
} else {
// The algorithm in getVisibleElements doesn't work in all browsers and
// configurations when presentation mode is active.
var visible = [];
var currentPage = this._pages[this._currentPageNumber - 1];
visible.push({ id: currentPage.id, view: currentPage });
return { first: currentPage, last: currentPage, views: visible };
}
},
cleanup: function () {
for (var i = 0, ii = this._pages.length; i < ii; i++) {
if (this._pages[i] &&
this._pages[i].renderingState !== RenderingStates.FINISHED) {
this._pages[i].reset();
}
}
},
/**
* @param {PDFPageView} pageView
* @returns {PDFPage}
* @private
*/
_ensurePdfPageLoaded: function (pageView) {
if (pageView.pdfPage) {
return Promise.resolve(pageView.pdfPage);
}
var pageNumber = pageView.id;
if (this._pagesRequests[pageNumber]) {
return this._pagesRequests[pageNumber];
}
var promise = this.pdfDocument.getPage(pageNumber).then(
function (pdfPage) {
pageView.setPdfPage(pdfPage);
this._pagesRequests[pageNumber] = null;
return pdfPage;
}.bind(this));
this._pagesRequests[pageNumber] = promise;
return promise;
},
forceRendering: function (currentlyVisiblePages) {
var visiblePages = currentlyVisiblePages || this._getVisiblePages();
var pageView = this.renderingQueue.getHighestPriority(visiblePages,
this._pages,
this.scroll.down);
if (pageView) {
this._ensurePdfPageLoaded(pageView).then(function () {
this.renderingQueue.renderView(pageView);
}.bind(this));
return true;
}
return false;
},
getPageTextContent: function (pageIndex) {
return this.pdfDocument.getPage(pageIndex + 1).then(function (page) {
return page.getTextContent({ normalizeWhitespace: true });
});
},
/**
* @param {HTMLDivElement} textLayerDiv
* @param {number} pageIndex
* @param {PageViewport} viewport
* @returns {TextLayerBuilder}
*/
createTextLayerBuilder: function (textLayerDiv, pageIndex, viewport) {
return new TextLayerBuilder({
textLayerDiv: textLayerDiv,
pageIndex: pageIndex,
viewport: viewport,
findController: this.isInPresentationMode ? null : this.findController
});
},
/**
* @param {HTMLDivElement} pageDiv
* @param {PDFPage} pdfPage
* @returns {AnnotationLayerBuilder}
*/
createAnnotationLayerBuilder: function (pageDiv, pdfPage) {
return new AnnotationLayerBuilder({
pageDiv: pageDiv,
pdfPage: pdfPage,
linkService: this.linkService,
downloadManager: this.downloadManager
});
},
setFindController: function (findController) {
this.findController = findController;
},
};
return PDFViewer;
})();
var SimpleLinkService = (function SimpleLinkServiceClosure() {
function SimpleLinkService() {}
SimpleLinkService.prototype = {
/**
* @returns {number}
*/
get page() {
return 0;
},
/**
* @param {number} value
*/
set page(value) {},
/**
* @param dest - The PDF destination object.
*/
navigateTo: function (dest) {},
/**
* @param dest - The PDF destination object.
* @returns {string} The hyperlink to the PDF object.
*/
getDestinationHash: function (dest) {
return '#';
},
/**
* @param hash - The PDF parameters/hash.
* @returns {string} The hyperlink to the PDF object.
*/
getAnchorUrl: function (hash) {
return '#';
},
/**
* @param {string} hash
*/
setHash: function (hash) {},
/**
* @param {string} action
*/
executeNamedAction: function (action) {},
/**
* @param {number} pageNum - page number.
* @param {Object} pageRef - reference to the page.
*/
cachePageRef: function (pageNum, pageRef) {}
};
return SimpleLinkService;
})();
var PDFHistory = (function () {
function PDFHistory(options) {
this.linkService = options.linkService;
this.initialized = false;
this.initialDestination = null;
this.initialBookmark = null;
}
PDFHistory.prototype = {
/**
* @param {string} fingerprint
* @param {IPDFLinkService} linkService
*/
initialize: function pdfHistoryInitialize(fingerprint) {
this.initialized = true;
this.reInitialized = false;
this.allowHashChange = true;
this.historyUnlocked = true;
this.isViewerInPresentationMode = false;
this.previousHash = window.location.hash.substring(1);
this.currentBookmark = '';
this.currentPage = 0;
this.updatePreviousBookmark = false;
this.previousBookmark = '';
this.previousPage = 0;
this.nextHashParam = '';
this.fingerprint = fingerprint;
this.currentUid = this.uid = 0;
this.current = {};
var state = window.history.state;
if (this._isStateObjectDefined(state)) {
// This corresponds to navigating back to the document
// from another page in the browser history.
if (state.target.dest) {
this.initialDestination = state.target.dest;
} else {
this.initialBookmark = state.target.hash;
}
this.currentUid = state.uid;
this.uid = state.uid + 1;
this.current = state.target;
} else {
// This corresponds to the loading of a new document.
if (state && state.fingerprint &&
this.fingerprint !== state.fingerprint) {
// Reinitialize the browsing history when a new document
// is opened in the web viewer.
this.reInitialized = true;
}
this._pushOrReplaceState({fingerprint: this.fingerprint}, true);
}
var self = this;
window.addEventListener('popstate', function pdfHistoryPopstate(evt) {
if (!self.historyUnlocked) {
return;
}
if (evt.state) {
// Move back/forward in the history.
self._goTo(evt.state);
return;
}
// If the state is not set, then the user tried to navigate to a
// different hash by manually editing the URL and pressing Enter, or by
// clicking on an in-page link (e.g. the "current view" link).
// Save the current view state to the browser history.
// Note: In Firefox, history.null could also be null after an in-page
// navigation to the same URL, and without dispatching the popstate
// event: https://bugzilla.mozilla.org/show_bug.cgi?id=1183881
if (self.uid === 0) {
// Replace the previous state if it was not explicitly set.
var previousParams = (self.previousHash && self.currentBookmark &&
self.previousHash !== self.currentBookmark) ?
{hash: self.currentBookmark, page: self.currentPage} :
{page: 1};
replacePreviousHistoryState(previousParams, function() {
updateHistoryWithCurrentHash();
});
} else {
updateHistoryWithCurrentHash();
}
}, false);
function updateHistoryWithCurrentHash() {
self.previousHash = window.location.hash.slice(1);
self._pushToHistory({hash: self.previousHash}, false, true);
self._updatePreviousBookmark();
}
function replacePreviousHistoryState(params, callback) {
// To modify the previous history entry, the following happens:
// 1. history.back()
// 2. _pushToHistory, which calls history.replaceState( ... )
// 3. history.forward()
// Because a navigation via the history API does not immediately update
// the history state, the popstate event is used for synchronization.
self.historyUnlocked = false;
// Suppress the hashchange event to avoid side effects caused by
// navigating back and forward.
self.allowHashChange = false;
window.addEventListener('popstate', rewriteHistoryAfterBack);
history.back();
function rewriteHistoryAfterBack() {
window.removeEventListener('popstate', rewriteHistoryAfterBack);
window.addEventListener('popstate', rewriteHistoryAfterForward);
self._pushToHistory(params, false, true);
history.forward();
}
function rewriteHistoryAfterForward() {
window.removeEventListener('popstate', rewriteHistoryAfterForward);
self.allowHashChange = true;
self.historyUnlocked = true;
callback();
}
}
function pdfHistoryBeforeUnload() {
var previousParams = self._getPreviousParams(null, true);
if (previousParams) {
var replacePrevious = (!self.current.dest &&
self.current.hash !== self.previousHash);
self._pushToHistory(previousParams, false, replacePrevious);
self._updatePreviousBookmark();
}
// Remove the event listener when navigating away from the document,
// since 'beforeunload' prevents Firefox from caching the document.
window.removeEventListener('beforeunload', pdfHistoryBeforeUnload,
false);
}
window.addEventListener('beforeunload', pdfHistoryBeforeUnload, false);
window.addEventListener('pageshow', function pdfHistoryPageShow(evt) {
// If the entire viewer (including the PDF file) is cached in
// the browser, we need to reattach the 'beforeunload' event listener
// since the 'DOMContentLoaded' event is not fired on 'pageshow'.
window.addEventListener('beforeunload', pdfHistoryBeforeUnload, false);
}, false);
window.addEventListener('presentationmodechanged', function(e) {
self.isViewerInPresentationMode = !!e.detail.active;
});
},
clearHistoryState: function pdfHistory_clearHistoryState() {
this._pushOrReplaceState(null, true);
},
_isStateObjectDefined: function pdfHistory_isStateObjectDefined(state) {
return (state && state.uid >= 0 &&
state.fingerprint && this.fingerprint === state.fingerprint &&
state.target && state.target.hash) ? true : false;
},
_pushOrReplaceState: function pdfHistory_pushOrReplaceState(stateObj,
replace) {
if (replace) {
window.history.replaceState(stateObj, '');
} else {
window.history.pushState(stateObj, '');
}
},
get isHashChangeUnlocked() {
if (!this.initialized) {
return true;
}
return this.allowHashChange;
},
_updatePreviousBookmark: function pdfHistory_updatePreviousBookmark() {
if (this.updatePreviousBookmark &&
this.currentBookmark && this.currentPage) {
this.previousBookmark = this.currentBookmark;
this.previousPage = this.currentPage;
this.updatePreviousBookmark = false;
}
},
updateCurrentBookmark: function pdfHistoryUpdateCurrentBookmark(bookmark,
pageNum) {
if (this.initialized) {
this.currentBookmark = bookmark.substring(1);
this.currentPage = pageNum | 0;
this._updatePreviousBookmark();
}
},
updateNextHashParam: function pdfHistoryUpdateNextHashParam(param) {
if (this.initialized) {
this.nextHashParam = param;
}
},
push: function pdfHistoryPush(params, isInitialBookmark) {
if (!(this.initialized && this.historyUnlocked)) {
return;
}
if (params.dest && !params.hash) {
params.hash = (this.current.hash && this.current.dest &&
this.current.dest === params.dest) ?
this.current.hash :
this.linkService.getDestinationHash(params.dest).split('#')[1];
}
if (params.page) {
params.page |= 0;
}
if (isInitialBookmark) {
var target = window.history.state.target;
if (!target) {
// Invoked when the user specifies an initial bookmark,
// thus setting initialBookmark, when the document is loaded.
this._pushToHistory(params, false);
this.previousHash = window.location.hash.substring(1);
}
this.updatePreviousBookmark = this.nextHashParam ? false : true;
if (target) {
// If the current document is reloaded,
// avoid creating duplicate entries in the history.
this._updatePreviousBookmark();
}
return;
}
if (this.nextHashParam) {
if (this.nextHashParam === params.hash) {
this.nextHashParam = null;
this.updatePreviousBookmark = true;
return;
} else {
this.nextHashParam = null;
}
}
if (params.hash) {
if (this.current.hash) {
if (this.current.hash !== params.hash) {
this._pushToHistory(params, true);
} else {
if (!this.current.page && params.page) {
this._pushToHistory(params, false, true);
}
this.updatePreviousBookmark = true;
}
} else {
this._pushToHistory(params, true);
}
} else if (this.current.page && params.page &&
this.current.page !== params.page) {
this._pushToHistory(params, true);
}
},
_getPreviousParams: function pdfHistory_getPreviousParams(onlyCheckPage,
beforeUnload) {
if (!(this.currentBookmark && this.currentPage)) {
return null;
} else if (this.updatePreviousBookmark) {
this.updatePreviousBookmark = false;
}
if (this.uid > 0 && !(this.previousBookmark && this.previousPage)) {
// Prevent the history from getting stuck in the current state,
// effectively preventing the user from going back/forward in
// the history.
//
// This happens if the current position in the document didn't change
// when the history was previously updated. The reasons for this are
// either:
// 1. The current zoom value is such that the document does not need to,
// or cannot, be scrolled to display the destination.
// 2. The previous destination is broken, and doesn't actally point to a
// position within the document.
// (This is either due to a bad PDF generator, or the user making a
// mistake when entering a destination in the hash parameters.)
return null;
}
if ((!this.current.dest && !onlyCheckPage) || beforeUnload) {
if (this.previousBookmark === this.currentBookmark) {
return null;
}
} else if (this.current.page || onlyCheckPage) {
if (this.previousPage === this.currentPage) {
return null;
}
} else {
return null;
}
var params = {hash: this.currentBookmark, page: this.currentPage};
if (this.isViewerInPresentationMode) {
params.hash = null;
}
return params;
},
_stateObj: function pdfHistory_stateObj(params) {
return {fingerprint: this.fingerprint, uid: this.uid, target: params};
},
_pushToHistory: function pdfHistory_pushToHistory(params,
addPrevious, overwrite) {
if (!this.initialized) {
return;
}
if (!params.hash && params.page) {
params.hash = ('page=' + params.page);
}
if (addPrevious && !overwrite) {
var previousParams = this._getPreviousParams();
if (previousParams) {
var replacePrevious = (!this.current.dest &&
this.current.hash !== this.previousHash);
this._pushToHistory(previousParams, false, replacePrevious);
}
}
this._pushOrReplaceState(this._stateObj(params),
(overwrite || this.uid === 0));
this.currentUid = this.uid++;
this.current = params;
this.updatePreviousBookmark = true;
},
_goTo: function pdfHistory_goTo(state) {
if (!(this.initialized && this.historyUnlocked &&
this._isStateObjectDefined(state))) {
return;
}
if (!this.reInitialized && state.uid < this.currentUid) {
var previousParams = this._getPreviousParams(true);
if (previousParams) {
this._pushToHistory(this.current, false);
this._pushToHistory(previousParams, false);
this.currentUid = state.uid;
window.history.back();
return;
}
}
this.historyUnlocked = false;
if (state.target.dest) {
this.linkService.navigateTo(state.target.dest);
} else {
this.linkService.setHash(state.target.hash);
}
this.currentUid = state.uid;
if (state.uid > this.uid) {
this.uid = state.uid;
}
this.current = state.target;
this.updatePreviousBookmark = true;
var currentHash = window.location.hash.substring(1);
if (this.previousHash !== currentHash) {
this.allowHashChange = false;
}
this.previousHash = currentHash;
this.historyUnlocked = true;
},
back: function pdfHistoryBack() {
this.go(-1);
},
forward: function pdfHistoryForward() {
this.go(1);
},
go: function pdfHistoryGo(direction) {
if (this.initialized && this.historyUnlocked) {
var state = window.history.state;
if (direction === -1 && state && state.uid > 0) {
window.history.back();
} else if (direction === 1 && state && state.uid < (this.uid - 1)) {
window.history.forward();
}
}
}
};
return PDFHistory;
})();
var DownloadManager = (function DownloadManagerClosure() {
function download(blobUrl, filename) {
var a = document.createElement('a');
if (a.click) {
// Use a.click() if available. Otherwise, Chrome might show
// "Unsafe JavaScript attempt to initiate a navigation change
// for frame with URL" and not open the PDF at all.
// Supported by (not mentioned = untested):
// - Firefox 6 - 19 (4- does not support a.click, 5 ignores a.click)
// - Chrome 19 - 26 (18- does not support a.click)
// - Opera 9 - 12.15
// - Internet Explorer 6 - 10
// - Safari 6 (5.1- does not support a.click)
a.href = blobUrl;
a.target = '_parent';
// Use a.download if available. This increases the likelihood that
// the file is downloaded instead of opened by another PDF plugin.
if ('download' in a) {
a.download = filename;
}
// <a> must be in the document for IE and recent Firefox versions.
// (otherwise .click() is ignored)
(document.body || document.documentElement).appendChild(a);
a.click();
a.parentNode.removeChild(a);
} else {
if (window.top === window &&
blobUrl.split('#')[0] === window.location.href.split('#')[0]) {
// If _parent == self, then opening an identical URL with different
// location hash will only cause a navigation, not a download.
var padCharacter = blobUrl.indexOf('?') === -1 ? '?' : '&';
blobUrl = blobUrl.replace(/#|$/, padCharacter + '$&');
}
window.open(blobUrl, '_parent');
}
}
function DownloadManager() {}
DownloadManager.prototype = {
downloadUrl: function DownloadManager_downloadUrl(url, filename) {
if (!PDFJS.isValidUrl(url, true)) {
return; // restricted/invalid URL
}
download(url + '#pdfjs.action=download', filename);
},
downloadData: function DownloadManager_downloadData(data, filename,
contentType) {
if (navigator.msSaveBlob) { // IE10 and above
return navigator.msSaveBlob(new Blob([data], { type: contentType }),
filename);
}
var blobUrl = PDFJS.createObjectURL(data, contentType);
download(blobUrl, filename);
},
download: function DownloadManager_download(blob, url, filename) {
if (!URL) {
// URL.createObjectURL is not supported
this.downloadUrl(url, filename);
return;
}
if (navigator.msSaveBlob) {
// IE10 / IE11
if (!navigator.msSaveBlob(blob, filename)) {
this.downloadUrl(url, filename);
}
return;
}
var blobUrl = URL.createObjectURL(blob);
download(blobUrl, filename);
}
};
return DownloadManager;
})();
PDFJS.PDFViewer = PDFViewer;
PDFJS.PDFPageView = PDFPageView;
PDFJS.PDFLinkService = PDFLinkService;
PDFJS.TextLayerBuilder = TextLayerBuilder;
PDFJS.DefaultTextLayerFactory = DefaultTextLayerFactory;
PDFJS.AnnotationLayerBuilder = AnnotationLayerBuilder;
PDFJS.DefaultAnnotationLayerFactory = DefaultAnnotationLayerFactory;
PDFJS.PDFHistory = PDFHistory;
PDFJS.DownloadManager = DownloadManager;
PDFJS.ProgressBar = ProgressBar;
}).call((typeof window === 'undefined') ? this : window);
| sajochiu/cdnjs | ajax/libs/pdf.js/1.4.99/pdf_viewer.js | JavaScript | mit | 101,003 |
YUI.add('anim-base', function(Y) {
/**
* The Animation Utility provides an API for creating advanced transitions.
* @module anim
*/
/**
* Provides the base Anim class, for animating numeric properties.
*
* @module anim
* @submodule anim-base
*/
/**
* A class for constructing animation instances.
* @class Anim
* @for Anim
* @constructor
* @extends Base
*/
var RUNNING = 'running',
START_TIME = 'startTime',
ELAPSED_TIME = 'elapsedTime',
/**
* @for Anim
* @event start
* @description fires when an animation begins.
* @param {Event} ev The start event.
* @type Event.Custom
*/
START = 'start',
/**
* @event tween
* @description fires every frame of the animation.
* @param {Event} ev The tween event.
* @type Event.Custom
*/
TWEEN = 'tween',
/**
* @event end
* @description fires after the animation completes.
* @param {Event} ev The end event.
* @type Event.Custom
*/
END = 'end',
NODE = 'node',
PAUSED = 'paused',
REVERSE = 'reverse', // TODO: cleanup
ITERATION_COUNT = 'iterationCount',
NUM = Number;
var _running = {},
_instances = {},
_timer;
Y.Anim = function() {
Y.Anim.superclass.constructor.apply(this, arguments);
_instances[Y.stamp(this)] = this;
};
Y.Anim.NAME = 'anim';
/**
* Regex of properties that should use the default unit.
*
* @property RE_DEFAULT_UNIT
* @static
*/
Y.Anim.RE_DEFAULT_UNIT = /^width|height|top|right|bottom|left|margin.*|padding.*|border.*$/i;
/**
* The default unit to use with properties that pass the RE_DEFAULT_UNIT test.
*
* @property DEFAULT_UNIT
* @static
*/
Y.Anim.DEFAULT_UNIT = 'px';
Y.Anim.DEFAULT_EASING = function (t, b, c, d) {
return c * t / d + b; // linear easing
};
/**
* Time in milliseconds passed to setInterval for frame processing
*
* @property intervalTime
* @default 20
* @static
*/
Y.Anim._intervalTime = 20;
/**
* Bucket for custom getters and setters
*
* @property behaviors
* @static
*/
Y.Anim.behaviors = {
left: {
get: function(anim, attr) {
return anim._getOffset(attr);
}
}
};
Y.Anim.behaviors.top = Y.Anim.behaviors.left;
/**
* The default setter to use when setting object properties.
*
* @property DEFAULT_SETTER
* @static
*/
Y.Anim.DEFAULT_SETTER = function(anim, att, from, to, elapsed, duration, fn, unit) {
unit = unit || '';
anim._node.setStyle(att, fn(elapsed, NUM(from), NUM(to) - NUM(from), duration) + unit);
};
/**
* The default getter to use when getting object properties.
*
* @property DEFAULT_GETTER
* @static
*/
Y.Anim.DEFAULT_GETTER = function(anim, prop) {
return anim._node.getComputedStyle(prop);
};
Y.Anim.ATTRS = {
/**
* The object to be animated.
* @attribute node
* @type Node
*/
node: {
setter: function(node) {
node = Y.one(node);
this._node = node;
if (!node) {
Y.log(node + ' is not a valid node', 'warn', 'Anim');
}
return node;
}
},
/**
* The length of the animation. Defaults to "1" (second).
* @attribute duration
* @type NUM
*/
duration: {
value: 1
},
/**
* The method that will provide values to the attribute(s) during the animation.
* Defaults to "Easing.easeNone".
* @attribute easing
* @type Function
*/
easing: {
value: Y.Anim.DEFAULT_EASING,
setter: function(val) {
if (typeof val === 'string' && Y.Easing) {
return Y.Easing[val];
}
}
},
/**
* The starting values for the animated properties.
* Fields may be strings, numbers, or functions.
* If a function is used, the return value becomes the from value.
* If no from value is specified, the DEFAULT_GETTER will be used.
* @attribute from
* @type Object
*/
from: {},
/**
* The ending values for the animated properties.
* Fields may be strings, numbers, or functions.
* @attribute to
* @type Object
*/
to: {},
/**
* Date stamp for the first frame of the animation.
* @attribute startTime
* @type Int
* @default 0
* @readOnly
*/
startTime: {
value: 0,
readOnly: true
},
/**
* Current time the animation has been running.
* @attribute elapsedTime
* @type Int
* @default 0
* @readOnly
*/
elapsedTime: {
value: 0,
readOnly: true
},
/**
* Whether or not the animation is currently running.
* @attribute running
* @type Boolean
* @default false
* @readOnly
*/
running: {
getter: function() {
return !!_running[Y.stamp(this)];
},
value: false,
readOnly: true
},
/**
* The number of times the animation should run
* @attribute iterations
* @type Int
* @default 1
*/
iterations: {
value: 1
},
/**
* The number of iterations that have occurred.
* Resets when an animation ends (reaches iteration count or stop() called).
* @attribute iterationCount
* @type Int
* @default 0
* @readOnly
*/
iterationCount: {
value: 0,
readOnly: true
},
/**
* How iterations of the animation should behave.
* Possible values are "normal" and "alternate".
* Normal will repeat the animation, alternate will reverse on every other pass.
*
* @attribute direction
* @type String
* @default "normal"
*/
direction: {
value: 'normal' // | alternate (fwd on odd, rev on even per spec)
},
/**
* Whether or not the animation is currently paused.
* @attribute paused
* @type Boolean
* @default false
* @readOnly
*/
paused: {
readOnly: true,
value: false
},
/**
* If true, animation begins from last frame
* @attribute reverse
* @type Boolean
* @default false
*/
reverse: {
value: false
}
};
/**
* Runs all animation instances.
* @method run
* @static
*/
Y.Anim.run = function() {
for (var i in _instances) {
if (_instances[i].run) {
_instances[i].run();
}
}
};
/**
* Pauses all animation instances.
* @method pause
* @static
*/
Y.Anim.pause = function() {
for (var i in _running) { // stop timer if nothing running
if (_running[i].pause) {
_running[i].pause();
}
}
Y.Anim._stopTimer();
};
/**
* Stops all animation instances.
* @method stop
* @static
*/
Y.Anim.stop = function() {
for (var i in _running) { // stop timer if nothing running
if (_running[i].stop) {
_running[i].stop();
}
}
Y.Anim._stopTimer();
};
Y.Anim._startTimer = function() {
if (!_timer) {
_timer = setInterval(Y.Anim._runFrame, Y.Anim._intervalTime);
}
};
Y.Anim._stopTimer = function() {
clearInterval(_timer);
_timer = 0;
};
/**
* Called per Interval to handle each animation frame.
* @method _runFrame
* @private
* @static
*/
Y.Anim._runFrame = function() {
var done = true;
for (var anim in _running) {
if (_running[anim]._runFrame) {
done = false;
_running[anim]._runFrame();
}
}
if (done) {
Y.Anim._stopTimer();
}
};
Y.Anim.RE_UNITS = /^(-?\d*\.?\d*){1}(em|ex|px|in|cm|mm|pt|pc|%)*$/;
var proto = {
/**
* Starts or resumes an animation.
* @method run
* @chainable
*/
run: function() {
if (this.get(PAUSED)) {
this._resume();
} else if (!this.get(RUNNING)) {
this._start();
}
return this;
},
/**
* Pauses the animation and
* freezes it in its current state and time.
* Calling run() will continue where it left off.
* @method pause
* @chainable
*/
pause: function() {
if (this.get(RUNNING)) {
this._pause();
}
return this;
},
/**
* Stops the animation and resets its time.
* @method stop
* @chainable
*/
stop: function(finish) {
if (this.get(RUNNING) || this.get(PAUSED)) {
this._end(finish);
}
return this;
},
_added: false,
_start: function() {
this._set(START_TIME, new Date() - this.get(ELAPSED_TIME));
this._actualFrames = 0;
if (!this.get(PAUSED)) {
this._initAnimAttr();
}
_running[Y.stamp(this)] = this;
Y.Anim._startTimer();
this.fire(START);
},
_pause: function() {
this._set(START_TIME, null);
this._set(PAUSED, true);
delete _running[Y.stamp(this)];
/**
* @event pause
* @description fires when an animation is paused.
* @param {Event} ev The pause event.
* @type Event.Custom
*/
this.fire('pause');
},
_resume: function() {
this._set(PAUSED, false);
_running[Y.stamp(this)] = this;
/**
* @event resume
* @description fires when an animation is resumed (run from pause).
* @param {Event} ev The pause event.
* @type Event.Custom
*/
this.fire('resume');
},
_end: function(finish) {
var duration = this.get('duration') * 1000;
if (finish) { // jump to last frame
this._runAttrs(duration, duration, this.get(REVERSE));
}
this._set(START_TIME, null);
this._set(ELAPSED_TIME, 0);
this._set(PAUSED, false);
delete _running[Y.stamp(this)];
this.fire(END, {elapsed: this.get(ELAPSED_TIME)});
},
_runFrame: function() {
var d = this._runtimeAttr.duration,
t = new Date() - this.get(START_TIME),
reverse = this.get(REVERSE),
done = (t >= d),
attribute,
setter;
this._runAttrs(t, d, reverse);
this._actualFrames += 1;
this._set(ELAPSED_TIME, t);
this.fire(TWEEN);
if (done) {
this._lastFrame();
}
},
_runAttrs: function(t, d, reverse) {
var attr = this._runtimeAttr,
customAttr = Y.Anim.behaviors,
easing = attr.easing,
lastFrame = d,
attribute,
setter,
i;
if (reverse) {
t = d - t;
lastFrame = 0;
}
for (i in attr) {
if (attr[i].to) {
attribute = attr[i];
setter = (i in customAttr && 'set' in customAttr[i]) ?
customAttr[i].set : Y.Anim.DEFAULT_SETTER;
if (t < d) {
setter(this, i, attribute.from, attribute.to, t, d, easing, attribute.unit);
} else {
setter(this, i, attribute.from, attribute.to, lastFrame, d, easing, attribute.unit);
}
}
}
},
_lastFrame: function() {
var iter = this.get('iterations'),
iterCount = this.get(ITERATION_COUNT);
iterCount += 1;
if (iter === 'infinite' || iterCount < iter) {
if (this.get('direction') === 'alternate') {
this.set(REVERSE, !this.get(REVERSE)); // flip it
}
/**
* @event iteration
* @description fires when an animation begins an iteration.
* @param {Event} ev The iteration event.
* @type Event.Custom
*/
this.fire('iteration');
} else {
iterCount = 0;
this._end();
}
this._set(START_TIME, new Date());
this._set(ITERATION_COUNT, iterCount);
},
_initAnimAttr: function() {
var from = this.get('from') || {},
to = this.get('to') || {},
attr = {
duration: this.get('duration') * 1000,
easing: this.get('easing')
},
customAttr = Y.Anim.behaviors,
node = this.get(NODE), // implicit attr init
unit, begin, end;
Y.each(to, function(val, name) {
if (typeof val === 'function') {
val = val.call(this, node);
}
begin = from[name];
if (begin === undefined) {
begin = (name in customAttr && 'get' in customAttr[name]) ?
customAttr[name].get(this, name) : Y.Anim.DEFAULT_GETTER(this, name);
} else if (typeof begin === 'function') {
begin = begin.call(this, node);
}
var mFrom = Y.Anim.RE_UNITS.exec(begin);
var mTo = Y.Anim.RE_UNITS.exec(val);
begin = mFrom ? mFrom[1] : begin;
end = mTo ? mTo[1] : val;
unit = mTo ? mTo[2] : mFrom ? mFrom[2] : ''; // one might be zero TODO: mixed units
if (!unit && Y.Anim.RE_DEFAULT_UNIT.test(name)) {
unit = Y.Anim.DEFAULT_UNIT;
}
if (!begin || !end) {
Y.error('invalid "from" or "to" for "' + name + '"', 'Anim');
return;
}
attr[name] = {
from: begin,
to: end,
unit: unit
};
}, this);
this._runtimeAttr = attr;
},
// TODO: move to computedStyle? (browsers dont agree on default computed offsets)
_getOffset: function(attr) {
var node = this._node,
val = node.getComputedStyle(attr),
get = (attr === 'left') ? 'getX': 'getY',
set = (attr === 'left') ? 'setX': 'setY';
if (val === 'auto') {
var position = node.getStyle('position');
if (position === 'absolute' || position === 'fixed') {
val = node[get]();
node[set](val);
} else {
val = 0;
}
}
return val;
}
};
Y.extend(Y.Anim, Y.Base, proto);
}, '@VERSION@' ,{requires:['base-base', 'node-style']});
YUI.add('anim-color', function(Y) {
/**
* Adds support for color properties in <code>to</code>
* and <code>from</code> attributes.
* @module anim
* @submodule anim-color
*/
var NUM = Number;
Y.Anim.behaviors.color = {
set: function(anim, att, from, to, elapsed, duration, fn) {
from = Y.Color.re_RGB.exec(Y.Color.toRGB(from));
to = Y.Color.re_RGB.exec(Y.Color.toRGB(to));
if (!from || from.length < 3 || !to || to.length < 3) {
Y.error('invalid from or to passed to color behavior');
}
anim._node.setStyle(att, 'rgb(' + [
Math.floor(fn(elapsed, NUM(from[1]), NUM(to[1]) - NUM(from[1]), duration)),
Math.floor(fn(elapsed, NUM(from[2]), NUM(to[2]) - NUM(from[2]), duration)),
Math.floor(fn(elapsed, NUM(from[3]), NUM(to[3]) - NUM(from[3]), duration))
].join(', ') + ')');
},
// TODO: default bgcolor const
get: function(anim, att) {
var val = anim._node.getComputedStyle(att);
val = (val === 'transparent') ? 'rgb(255, 255, 255)' : val;
return val;
}
};
Y.each(['backgroundColor',
'borderColor',
'borderTopColor',
'borderRightColor',
'borderBottomColor',
'borderLeftColor'],
function(v, i) {
Y.Anim.behaviors[v] = Y.Anim.behaviors.color;
}
);
}, '@VERSION@' ,{requires:['anim-base']});
YUI.add('anim-curve', function(Y) {
/**
* Adds support for the <code>curve</code> property for the <code>to</code>
* attribute. A curve is zero or more control points and an end point.
* @module anim
* @submodule anim-curve
*/
Y.Anim.behaviors.curve = {
set: function(anim, att, from, to, elapsed, duration, fn) {
from = from.slice.call(from);
to = to.slice.call(to);
var t = fn(elapsed, 0, 100, duration) / 100;
to.unshift(from);
anim._node.setXY(Y.Anim.getBezier(to, t));
},
get: function(anim, att) {
return anim._node.getXY();
}
};
/**
* Get the current position of the animated element based on t.
* Each point is an array of "x" and "y" values (0 = x, 1 = y)
* At least 2 points are required (start and end).
* First point is start. Last point is end.
* Additional control points are optional.
* @for Anim
* @method getBezier
* @static
* @param {Array} points An array containing Bezier points
* @param {Number} t A number between 0 and 1 which is the basis for determining current position
* @return {Array} An array containing int x and y member data
*/
Y.Anim.getBezier = function(points, t) {
var n = points.length;
var tmp = [];
for (var i = 0; i < n; ++i){
tmp[i] = [points[i][0], points[i][1]]; // save input
}
for (var j = 1; j < n; ++j) {
for (i = 0; i < n - j; ++i) {
tmp[i][0] = (1 - t) * tmp[i][0] + t * tmp[parseInt(i + 1, 10)][0];
tmp[i][1] = (1 - t) * tmp[i][1] + t * tmp[parseInt(i + 1, 10)][1];
}
}
return [ tmp[0][0], tmp[0][1] ];
};
}, '@VERSION@' ,{requires:['anim-xy']});
YUI.add('anim-easing', function(Y) {
/*
TERMS OF USE - EASING EQUATIONS
Open source under the BSD License.
Copyright 2001 Robert Penner All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* The easing module provides methods for customizing
* how an animation behaves during each run.
* @class Easing
* @module anim
* @submodule anim-easing
*/
Y.Easing = {
/**
* Uniform speed between points.
* @for Easing
* @method easeNone
* @param {Number} t Time value used to compute current value
* @param {Number} b Starting value
* @param {Number} c Delta between start and end values
* @param {Number} d Total length of animation
* @return {Number} The computed value for the current animation frame
*/
easeNone: function (t, b, c, d) {
return c*t/d + b;
},
/**
* Begins slowly and accelerates towards end. (quadratic)
* @method easeIn
* @param {Number} t Time value used to compute current value
* @param {Number} b Starting value
* @param {Number} c Delta between start and end values
* @param {Number} d Total length of animation
* @return {Number} The computed value for the current animation frame
*/
easeIn: function (t, b, c, d) {
return c*(t/=d)*t + b;
},
/**
* Begins quickly and decelerates towards end. (quadratic)
* @method easeOut
* @param {Number} t Time value used to compute current value
* @param {Number} b Starting value
* @param {Number} c Delta between start and end values
* @param {Number} d Total length of animation
* @return {Number} The computed value for the current animation frame
*/
easeOut: function (t, b, c, d) {
return -c *(t/=d)*(t-2) + b;
},
/**
* Begins slowly and decelerates towards end. (quadratic)
* @method easeBoth
* @param {Number} t Time value used to compute current value
* @param {Number} b Starting value
* @param {Number} c Delta between start and end values
* @param {Number} d Total length of animation
* @return {Number} The computed value for the current animation frame
*/
easeBoth: function (t, b, c, d) {
if ((t/=d/2) < 1) {
return c/2*t*t + b;
}
return -c/2 * ((--t)*(t-2) - 1) + b;
},
/**
* Begins slowly and accelerates towards end. (quartic)
* @method easeInStrong
* @param {Number} t Time value used to compute current value
* @param {Number} b Starting value
* @param {Number} c Delta between start and end values
* @param {Number} d Total length of animation
* @return {Number} The computed value for the current animation frame
*/
easeInStrong: function (t, b, c, d) {
return c*(t/=d)*t*t*t + b;
},
/**
* Begins quickly and decelerates towards end. (quartic)
* @method easeOutStrong
* @param {Number} t Time value used to compute current value
* @param {Number} b Starting value
* @param {Number} c Delta between start and end values
* @param {Number} d Total length of animation
* @return {Number} The computed value for the current animation frame
*/
easeOutStrong: function (t, b, c, d) {
return -c * ((t=t/d-1)*t*t*t - 1) + b;
},
/**
* Begins slowly and decelerates towards end. (quartic)
* @method easeBothStrong
* @param {Number} t Time value used to compute current value
* @param {Number} b Starting value
* @param {Number} c Delta between start and end values
* @param {Number} d Total length of animation
* @return {Number} The computed value for the current animation frame
*/
easeBothStrong: function (t, b, c, d) {
if ((t/=d/2) < 1) {
return c/2*t*t*t*t + b;
}
return -c/2 * ((t-=2)*t*t*t - 2) + b;
},
/**
* Snap in elastic effect.
* @method elasticIn
* @param {Number} t Time value used to compute current value
* @param {Number} b Starting value
* @param {Number} c Delta between start and end values
* @param {Number} d Total length of animation
* @param {Number} a Amplitude (optional)
* @param {Number} p Period (optional)
* @return {Number} The computed value for the current animation frame
*/
elasticIn: function (t, b, c, d, a, p) {
var s;
if (t === 0) {
return b;
}
if ( (t /= d) === 1 ) {
return b+c;
}
if (!p) {
p = d* 0.3;
}
if (!a || a < Math.abs(c)) {
a = c;
s = p/4;
}
else {
s = p/(2*Math.PI) * Math.asin (c/a);
}
return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
},
/**
* Snap out elastic effect.
* @method elasticOut
* @param {Number} t Time value used to compute current value
* @param {Number} b Starting value
* @param {Number} c Delta between start and end values
* @param {Number} d Total length of animation
* @param {Number} a Amplitude (optional)
* @param {Number} p Period (optional)
* @return {Number} The computed value for the current animation frame
*/
elasticOut: function (t, b, c, d, a, p) {
var s;
if (t === 0) {
return b;
}
if ( (t /= d) === 1 ) {
return b+c;
}
if (!p) {
p=d * 0.3;
}
if (!a || a < Math.abs(c)) {
a = c;
s = p / 4;
}
else {
s = p/(2*Math.PI) * Math.asin (c/a);
}
return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
},
/**
* Snap both elastic effect.
* @method elasticBoth
* @param {Number} t Time value used to compute current value
* @param {Number} b Starting value
* @param {Number} c Delta between start and end values
* @param {Number} d Total length of animation
* @param {Number} a Amplitude (optional)
* @param {Number} p Period (optional)
* @return {Number} The computed value for the current animation frame
*/
elasticBoth: function (t, b, c, d, a, p) {
var s;
if (t === 0) {
return b;
}
if ( (t /= d/2) === 2 ) {
return b+c;
}
if (!p) {
p = d*(0.3*1.5);
}
if ( !a || a < Math.abs(c) ) {
a = c;
s = p/4;
}
else {
s = p/(2*Math.PI) * Math.asin (c/a);
}
if (t < 1) {
return -0.5*(a*Math.pow(2,10*(t-=1)) *
Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
}
return a*Math.pow(2,-10*(t-=1)) *
Math.sin( (t*d-s)*(2*Math.PI)/p )*0.5 + c + b;
},
/**
* Backtracks slightly, then reverses direction and moves to end.
* @method backIn
* @param {Number} t Time value used to compute current value
* @param {Number} b Starting value
* @param {Number} c Delta between start and end values
* @param {Number} d Total length of animation
* @param {Number} s Overshoot (optional)
* @return {Number} The computed value for the current animation frame
*/
backIn: function (t, b, c, d, s) {
if (s === undefined) {
s = 1.70158;
}
if (t === d) {
t -= 0.001;
}
return c*(t/=d)*t*((s+1)*t - s) + b;
},
/**
* Overshoots end, then reverses and comes back to end.
* @method backOut
* @param {Number} t Time value used to compute current value
* @param {Number} b Starting value
* @param {Number} c Delta between start and end values
* @param {Number} d Total length of animation
* @param {Number} s Overshoot (optional)
* @return {Number} The computed value for the current animation frame
*/
backOut: function (t, b, c, d, s) {
if (typeof s === 'undefined') {
s = 1.70158;
}
return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
},
/**
* Backtracks slightly, then reverses direction, overshoots end,
* then reverses and comes back to end.
* @method backBoth
* @param {Number} t Time value used to compute current value
* @param {Number} b Starting value
* @param {Number} c Delta between start and end values
* @param {Number} d Total length of animation
* @param {Number} s Overshoot (optional)
* @return {Number} The computed value for the current animation frame
*/
backBoth: function (t, b, c, d, s) {
if (typeof s === 'undefined') {
s = 1.70158;
}
if ((t /= d/2 ) < 1) {
return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
}
return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
},
/**
* Bounce off of start.
* @method bounceIn
* @param {Number} t Time value used to compute current value
* @param {Number} b Starting value
* @param {Number} c Delta between start and end values
* @param {Number} d Total length of animation
* @return {Number} The computed value for the current animation frame
*/
bounceIn: function (t, b, c, d) {
return c - Y.Easing.bounceOut(d-t, 0, c, d) + b;
},
/**
* Bounces off end.
* @method bounceOut
* @param {Number} t Time value used to compute current value
* @param {Number} b Starting value
* @param {Number} c Delta between start and end values
* @param {Number} d Total length of animation
* @return {Number} The computed value for the current animation frame
*/
bounceOut: function (t, b, c, d) {
if ((t/=d) < (1/2.75)) {
return c*(7.5625*t*t) + b;
} else if (t < (2/2.75)) {
return c*(7.5625*(t-=(1.5/2.75))*t + 0.75) + b;
} else if (t < (2.5/2.75)) {
return c*(7.5625*(t-=(2.25/2.75))*t + 0.9375) + b;
}
return c*(7.5625*(t-=(2.625/2.75))*t + 0.984375) + b;
},
/**
* Bounces off start and end.
* @method bounceBoth
* @param {Number} t Time value used to compute current value
* @param {Number} b Starting value
* @param {Number} c Delta between start and end values
* @param {Number} d Total length of animation
* @return {Number} The computed value for the current animation frame
*/
bounceBoth: function (t, b, c, d) {
if (t < d/2) {
return Y.Easing.bounceIn(t * 2, 0, c, d) * 0.5 + b;
}
return Y.Easing.bounceOut(t * 2 - d, 0, c, d) * 0.5 + c * 0.5 + b;
}
};
}, '@VERSION@' ,{requires:['anim-base']});
YUI.add('anim-node-plugin', function(Y) {
/**
* Binds an Anim instance to a Node instance
* @module anim
* @class Plugin.NodeFX
* @extends Base
* @submodule anim-node-plugin
*/
var NodeFX = function(config) {
config = (config) ? Y.merge(config) : {};
config.node = config.host;
NodeFX.superclass.constructor.apply(this, arguments);
};
NodeFX.NAME = "nodefx";
NodeFX.NS = "fx";
Y.extend(NodeFX, Y.Anim);
Y.namespace('Plugin');
Y.Plugin.NodeFX = NodeFX;
}, '@VERSION@' ,{requires:['node-pluginhost', 'anim-base']});
YUI.add('anim-scroll', function(Y) {
/**
* Adds support for the <code>scroll</code> property in <code>to</code>
* and <code>from</code> attributes.
* @module anim
* @submodule anim-scroll
*/
var NUM = Number;
//TODO: deprecate for scrollTop/Left properties?
Y.Anim.behaviors.scroll = {
set: function(anim, att, from, to, elapsed, duration, fn) {
var
node = anim._node,
val = ([
fn(elapsed, NUM(from[0]), NUM(to[0]) - NUM(from[0]), duration),
fn(elapsed, NUM(from[1]), NUM(to[1]) - NUM(from[1]), duration)
]);
if (val[0]) {
node.set('scrollLeft', val[0]);
}
if (val[1]) {
node.set('scrollTop', val[1]);
}
},
get: function(anim) {
var node = anim._node;
return [node.get('scrollLeft'), node.get('scrollTop')];
}
};
}, '@VERSION@' ,{requires:['anim-base']});
YUI.add('anim-xy', function(Y) {
/**
* Adds support for the <code>xy</code> property in <code>from</code> and
* <code>to</code> attributes.
* @module anim
* @submodule anim-xy
*/
var NUM = Number;
Y.Anim.behaviors.xy = {
set: function(anim, att, from, to, elapsed, duration, fn) {
anim._node.setXY([
fn(elapsed, NUM(from[0]), NUM(to[0]) - NUM(from[0]), duration),
fn(elapsed, NUM(from[1]), NUM(to[1]) - NUM(from[1]), duration)
]);
},
get: function(anim) {
return anim._node.getXY();
}
};
}, '@VERSION@' ,{requires:['anim-base', 'node-screen']});
YUI.add('anim', function(Y){}, '@VERSION@' ,{use:['anim-base', 'anim-color', 'anim-curve', 'anim-easing', 'anim-node-plugin', 'anim-scroll', 'anim-xy'], skinnable:false});
| Showfom/cdnjs | ajax/libs/yui/3.1.0pr2/anim/anim-debug.js | JavaScript | mit | 34,102 |
(function(h,t,z,q){function g(b,a){try{return t.hasOwnProperty?b.hasOwnProperty(a.toString()):Object.prototype.hasOwnProperty.call(b,a.toString())}catch(d){console.dir(d)}}function p(b,a){var d=[],c=/^[+-]?\d+(\.\d+)?$/,f={lat:"",lng:""};if("string"===typeof b||h.isArray(b))if(d="string"===typeof b?b.replace(/\s+/,"").split(","):b,2===d.length)c.test(d[0])&&c.test(d[1])&&(f.lat=d[0],f.lng=d[1]);else return b;else if("object"===typeof b){if("function"===typeof b.lat||"function"===typeof b.lng)return b;
g(b,"x")&&g(b,"y")?(f.lat=b.x,f.lng=b.y):g(b,"lat")&&g(b,"lng")&&(f.lat=b.lat,f.lng=b.lng)}return q!==a&&!0===a?new google.maps.LatLng(f.lat,f.lng):f}function r(b){var a=b.css||"";this.setValues(b);this.span=h("<span/>").css({position:"relative",left:"-50%",top:"0","white-space":"nowrap"}).addClass(a);this.div=h("<div/>").css({position:"absolute",display:"none"});this.span.appendTo(this.div)}function u(b,a){var d=h.extend({},y,a),c={},f="";if(g(t,"google")){this.map=null;this._markers=[];this._labels=
[];this.container=b;this.options=d;this.googleMapOptions={};this.interval=parseInt(this.options.interval,10)||200;for(f in this.options)g(this.options,f)&&(c=this.options[f],/ControlOptions/g.test(f)&&g(c,"position")&&"string"===typeof c.position&&(this.options[f].position=google.maps.ControlPosition[c.position.toUpperCase()]));this.googleMapOptions=this.options;g(d,"streetView")&&(this.googleMapOptions.streetViewObj=d.streetView,delete this.googleMapOptions.streetView);this.googleMapOptions.center=
p(d.center,!0);g(d,"styles")&&("string"===typeof d.styles?g(v,d.styles)&&(this.googleMapOptions.styles=v[d.styles]):h.isArray(d.styles)&&(this.googleMapOptions.styles=d.styles));h(this.container).html(d.loading);this.init()}}var y={autoLocation:!1,center:[24,121],event:null,infoWindowAutoClose:!0,interval:200,kml:[],loading:"\u8b80\u53d6\u4e2d…",marker:[],markerCluster:!1,markerFitBounds:!1,notfound:"\u627e\u4e0d\u5230\u67e5\u8a62\u7684\u5730\u9ede",polyline:[],zoom:8},w=0,x=0,v={},v={greyscale:[{featureType:"all",
stylers:[{saturation:-100},{gamma:.5}]}]};r.prototype=new google.maps.OverlayView;r.prototype.onAdd=function(){this.div.appendTo(h(this.getPanes().overlayLayer));this.listeners=[google.maps.event.addListener(this,"visible_changed",this.onRemove)]};r.prototype.draw=function(){var b=this.getProjection(),a={};try{a=b.fromLatLngToDivPixel(this.get("position")),this.div.css({left:a.x+"px",top:a.y+"px",display:"block"}),this.text&&this.span.html(this.text.toString())}catch(d){}};r.prototype.onRemove=function(){h(this.div).remove()};
u.prototype={VERSION:"2.9.8",_polylines:[],_polygons:[],_circles:[],_kmls:[],_directions:[],_directionsMarkers:[],bounds:new google.maps.LatLngBounds,kml:function(b,a){var d={},c={preserveViewport:!1,suppressInfoWindows:!1},f=0;if(g(a,"kml"))if("string"===typeof a.kml)d=new google.maps.KmlLayer(a.kml,c),d.setMap(b),this._kmls.push(d);else if(h.isArray(a.kml))for(f=0;f<a.kml.length;f+=1)"string"===typeof a.kml[f]&&(d=new google.maps.KmlLayer(a.kml[f],c),d.setMap(b),this._kmls.push(d))},direction:function(b,
a){if(g(a,"direction")&&h.isArray(a.direction))for(var d=0;d<a.direction.length;d+=1)this.directionService(a.direction[d])},markers:function(b,a,d){var c={},f=0,e=0,k=c=0,l=[],m=[];x=w=0;l=this._markers;if(!d||0===l.length&&h.isArray(a.marker))for(e=0,f=a.marker.length;e<f;e+=1)c=a.marker[e],g(c,"addr")&&(c.parseAddr=p(c.addr,!0),"string"===typeof c.parseAddr?this.markerByGeocoder(b,c,a):this.markerDirect(b,c,a));if("modify"===d)for(m=this._labels,e=0,f=a.marker.length;e<f;e+=1)if(g(a.marker[e],"id")){for(c=
0;c<l.length;c+=1)a.marker[e].id===l[c].id&&g(a.marker[e],"addr")&&(l[c].setPosition(new google.maps.LatLng(a.marker[e].addr[0],a.marker[e].addr[1])),g(a.marker[e],"text")&&(g(l[c],"infoWindow")?"function"===typeof l[c].infoWindow.setContent&&l[c].infoWindow.setContent(a.marker[e].text):(l[c].infoWindow=new google.maps.InfoWindow({content:a.marker[e].text}),this.bindEvents(l[c],a.marker[e].event))),g(a.marker[e],"icon")&&l[c].setIcon(a.marker[e].icon));c=0;for(k=m.length;c<k;c+=1)a.marker[e].id===
m[c].id&&(g(a.marker[e],"label")&&(m[c].text=a.marker[e].label),m[c].draw())}else g(a.marker[e],"addr")&&(a.marker[e].parseAddr=p(a.marker[e].addr,!0),"string"===typeof a.marker[e].parseAddr?this.markerByGeocoder(b,a.marker[e]):this.markerDirect(b,a.marker[e]));if(g(a,"markerCluster")&&!0===a.markerCluster&&"function"===typeof MarkerClusterer)return new MarkerClusterer(b,this._markers)},drawPolyline:function(b,a){var d={},c=0,f={},f={},e=0,k=new google.maps.MVCArray,f={},l=[],f={},m=[],s={};if(g(a,
"polyline")&&g(a.polyline,"coords")&&h.isArray(a.polyline.coords)){for(c=0;c<a.polyline.coords.length;c+=1)f=a.polyline.coords[c],f=p(f,!0),"function"===typeof f.lat&&k.push(f);f=h.extend({},{strokeColor:a.polyline.color||"#FF0000",strokeOpacity:1,strokeWeight:a.polyline.width||2},a.polyline);d=new google.maps.Polyline(f);this._polylines.push(d);if(2<k.getLength())for(c=0;c<k.length;c+=1)0<c&&k.length-1>c&&m.push({location:k.getAt(c),stopover:!1});g(a.polyline,"event")&&self.bindEvents(d,a.polyline.event);
g(a.polyline,"snap")&&!0===a.polyline.snap?(f=new google.maps.DirectionsService,f.route({origin:k.getAt(0),waypoints:m,destination:k.getAt(k.length-1),travelMode:google.maps.DirectionsTravelMode.DRIVING},function(b,f){if(f===google.maps.DirectionsStatus.OK){c=0;for(e=b.routes[0].overview_path;c<e.length;c+=1)l.push(e[c]);d.setPath(l);"function"===typeof a.polyline.getDistance&&(s=b.routes[0].legs[0].distance,a.polyline.getDistance.call(this,s))}})):(d.setPath(k),g(google.maps,"geometry")&&g(google.maps.geometry,
"spherical")&&"function"===typeof google.maps.geometry.spherical.computeDistanceBetween&&(s=google.maps.geometry.spherical.computeDistanceBetween(k.getAt(0),k.getAt(k.length-1)),"function"===typeof a.polyline.getDistance&&a.polyline.getDistance.call(this,s)));d.setMap(b)}},drawPolygon:function(b,a){var d={},d=0,c={},c={},d={},f=[];if(g(a,"polygon")&&g(a.polygon,"coords")&&h.isArray(a.polygon.coords)){for(d=0;d<a.polygon.coords.length;d+=1)c=a.polygon.coords[d],c=p(c,!0),"function"===typeof c.lat&&
f.push(c);d=h.extend({},{path:f,strokeColor:a.polygon.color||"#FF0000",strokeOpacity:1,strokeWeight:a.polygon.width||2,fillColor:a.polygon.fillcolor||"#CC0000",fillOpacity:.35},a.polygon);d=new google.maps.Polygon(d);g(a.polygon,"event")&&this.bindEvents(d,a.polygon.event);this._polygons.push(d);d.setMap(b)}},drawCircle:function(b,a){var d=0,c={},f={},e={},f={};if(g(a,"circle")&&h.isArray(a.circle))for(d=a.circle.length-1;0<=d;d-=1)e=a.circle[d],f=h.extend({},{map:b,strokeColor:e.color||"#FF0000",
strokeOpacity:e.opacity||.8,strokeWeight:e.width||2,fillColor:e.fillcolor||"#FF0000",fillOpacity:e.fillopacity||.35,radius:e.radius||10,zIndex:100,id:g(e,"id")?e.id:""},e),g(e,"center")&&(c=p(e.center,!0),f.center=c),"function"===typeof c.lat&&(f=new google.maps.Circle(f),this._circles.push(f),g(e,"event")&&this.bindEvents(f,e.event))},overlay:function(){var b=this.map,a=this.options;try{this.kml(b,a),this.direction(b,a),this.markers(b,a),this.drawPolyline(b,a),this.drawPolygon(b,a),this.drawCircle(b,
a),this.streetView(b,a),this.geoLocation(b,a)}catch(d){console.dir(d)}},markerIcon:function(b){var a=h.extend({},a,b.icon);if(g(b,"icon")){if("string"===typeof b.icon)return b.icon;g(b.icon,"url")&&(a.url=b.icon.url);g(b.icon,"size")&&h.isArray(b.icon.size)&&2===b.icon.size.length&&(a.size=new google.maps.Size(b.icon.size[0],b.icon.size[1]));g(b.icon,"scaledSize")&&h.isArray(b.icon.scaledSize)&&2===b.icon.scaledSize.length&&(a.scaledSize=new google.maps.Size(b.icon.scaledSize[0],b.icon.scaledSize[1]));
g(b.icon,"anchor")&&h.isArray(b.icon.anchor)&&2===b.icon.anchor.length&&(a.anchor=new google.maps.Point(b.icon.anchor[0],b.icon.anchor[1]))}return a},markerDirect:function(b,a){var d={},c={},c={},c=g(a,"id")?a.id:"",d=g(a,"title")?a.title.toString().replace(/<([^>]+)>/g,""):!1,f=g(a,"text")?a.text.toString():!1,e=h.extend({},{map:b,position:a.parseAddr,animation:null,id:c},a),k=this.markerIcon(a);d&&(e.title=d);f&&(e.text=f,e.infoWindow=new google.maps.InfoWindow({content:f}));h.isEmptyObject(k)||
(e.icon=k);g(a,"animation")&&"string"===typeof a.animation&&(e.animation=google.maps.Animation[a.animation.toUpperCase()]);d=new google.maps.Marker(e);this._markers.push(d);g(d,"position")&&("function"===typeof d.getPosition&&this.bounds.extend(d.position),!0===this.options.markerFitBounds&&this._markers.length===this.options.marker.length&&b.fitBounds(this.bounds));if(!0===this.options.markerCluster&&"function"===typeof MarkerClusterer&&w===this.options.marker.length)return new MarkerClusterer(b,
this._markers);c={map:b,css:g(a,"css")?a.css.toString():"",id:c};"string"===typeof a.label&&0!==a.label.length&&(c.text=a.label,c=new r(c),c.bindTo("position",d,"position"),c.bindTo("text",d,"position"),c.bindTo("visible",d),this._labels.push(c));this.bindEvents(d,a.event)},markerByGeocoder:function(b,a){var d=this;(new google.maps.Geocoder).geocode({address:a.parseAddr},function(c,f){if(f===google.maps.GeocoderStatus.OVER_QUERY_LIMIT)t.setTimeout(function(){d.markerByGeocoder(b,a)},d.interval);else if(f===
google.maps.GeocoderStatus.OK){var e={},k={},k={},l=g(a,"id")?a.id:"",e=g(a,"title")?a.title.toString().replace(/<([^>]+)>/g,""):!1,k=g(a,"text")?a.text.toString():!1,l={map:b,position:c[0].geometry.location,animation:null,id:l},m=d.markerIcon(a);e&&(l.title=e);k&&(l.text=k,l.infoWindow=new google.maps.InfoWindow({content:k}));h.isEmptyObject(m)||(l.icon=m);g(a,"animation")&&"string"===typeof a.animation&&(l.animation=google.maps.Animation[a.animation.toUpperCase()]);l=h.extend({},l,a);e=new google.maps.Marker(l);
d._markers.push(e);g(e,"position")&&("function"===typeof e.getPosition&&d.bounds.extend(e.position),!0===d.options.markerFitBounds&&d._markers.length===d.options.marker.length&&b.fitBounds(d.bounds));if(g(d.options,"markerCluster")&&"function"===typeof MarkerClusterer&&x===d.options.marker.length)return new MarkerClusterer(b,d._markers);k={map:d.map,css:g(a,"css")?a.css.toString():""};"string"===typeof a.label&&0!==a.label.length&&(k.text=a.label,k=new r(k),k.bindTo("position",e,"position"),k.bindTo("text",
e,"position"),k.bindTo("visible",e),d._labels.push(k));d.bindEvents(e,a.event)}})},directionService:function(b){if(g(b,"from")&&g(b,"to")){var a=this,d=new google.maps.DirectionsService,c=new google.maps.DirectionsRenderer,f={travelMode:google.maps.DirectionsTravelMode.DRIVING,optimizeWaypoints:g(b,"optimize")?b.optimize:!1},e={},k={},l=[],m={},s=[],q={},r="",n=0,t=0;f.origin=p(b.from,!0);f.destination=p(b.to,!0);g(b,"travel")&&google.maps.TravelMode[b.travel.toString().toUpperCase()]&&(f.travelMode=
google.maps.TravelMode[b.travel.toString().toUpperCase()]);g(b,"panel")&&(e=h(b.panel));if(g(b,"waypoint")&&h.isArray(b.waypoint)){n=0;for(t=b.waypoint.length;n<t;n+=1)m={},"string"===typeof b.waypoint[n]||h.isArray(b.waypoint[n])?m={location:p(b.waypoint[n],!0),stopover:!0}:(g(b.waypoint[n],"location")&&(m.location=p(b.waypoint[n].location,!0)),m.stopover=g(b.waypoint[n],"stopover")?b.waypoint[n].stopover:!0),s.push(b.waypoint[n].text||b.waypoint[n].toString()),l.push(m);f.waypoints=l}d.route(f,
function(d,f){var e=0,h=0;if(f===google.maps.DirectionsStatus.OK){e=d.routes[0].legs;g(b,"autoViewport")&&(k.preserveViewport=!1===b.autoViewport?!0:!1);try{for(g(b,"fromText")&&(e[0].start_address=b.fromText),g(b,"toText")&&(1===e.length?e[0].end_address=b.toText:e[e.length-1].end_address=b.toText),1===e.length?(q=e[0].end_location,r=e[0].end_address):(q=e[e.length-1].end_location,r=e[e.length-1].end_address),g(b,"icon")&&(k.suppressMarkers=!0,g(b.icon,"from")&&"string"===typeof b.icon.from&&a.directionServiceMarker(e[0].start_location,
{icon:b.icon.from,text:e[0].start_address}),g(b.icon,"to")&&"string"===typeof b.icon.to&&a.directionServiceMarker(q,{icon:b.icon.to,text:r})),h=0;h<e.length-1;h+=1)e[h].end_address=s[h],g(b,"icon")&&g(b.icon,"waypoint")&&a.directionServiceMarker(e[h].start_location,{icon:b.icon.waypoint,text:e[h].start_address})}catch(l){}a.bindEvents(c,b.event);c.setOptions(k);c.setDirections(d)}});c.setMap(a.map);e.length&&c.setPanel(e.get(0));a._directions.push(c)}},directionServiceMarker:function(b,a){var d=h.extend({},
{position:b,map:this.map},a),c={};g(d,"text")&&(d.infoWindow=new google.maps.InfoWindow({content:d.text}));c=new google.maps.Marker(d);this._directionsMarkers.push(c);this.bindEvents(c)},bindEvents:function(b,a){var d=this,c={};switch(typeof a){case "function":google.maps.event.addListener(b,"click",a);break;case "object":for(c in a)"function"===typeof a[c]?google.maps.event.addListener(b,c,a[c]):g(a[c],"func")&&"function"===typeof a[c].func?g(a[c],"once")&&!0===a[c].once?google.maps.event.addListenerOnce(b,
c,a[c].func):google.maps.event.addListener(b,c,a[c].func):"function"===typeof a[c]&&google.maps.event.addListener(b,c,a[c])}g(b,"infoWindow")&&google.maps.event.addListener(b,"click",function(){var a=0,c={};if(g(d.options,"infoWindowAutoClose")&&!0===d.options.infoWindowAutoClose)for(a=0;a<d._markers.length;a+=1)c=d._markers[a],g(c,"infoWindow")&&"function"===typeof c.infoWindow.close&&c.infoWindow.close();b.infoWindow.open(d.map,b)})},streetView:function(b,a){var d={},c=g(a,"streetViewObj")?a.streetViewObj:
{},f={heading:0,pitch:0,zoom:1},e={};"function"===typeof b.getStreetView&&g(a,"streetViewObj")&&(d=b.getStreetView(),g(c,"position")?(e=p(c.position,!0),c.position="object"!==typeof e?b.getCenter():e):c.position=b.getCenter(),g(c,"pov")&&(c.pov=h.extend({},f,c.pov)),g(c,"visible")&&d.setVisible(c.visible),d.setOptions(c),g(c,"event")&&this.bindEvents(d,c.event))},panto:function(b){var a={},d={},c=this.map;null!==c&&q!==c&&(a=p(b,!0),"string"===typeof a?(d=new google.maps.Geocoder,d.geocode({address:a},
function(a,b){b===google.maps.GeocoderStatus.OK?"function"===typeof c.panTo&&a.length&&c.panTo(a[0].geometry.location):console.error(b)})):"function"===typeof c.panTo&&c.panTo(a))},clear:function(b){for(var a="marker,circle,polygon,polyline,direction,kml",d="",c=0,f=0,a="string"===typeof b?b.split(","):h.isArray(b)?b:a.split(","),c=0;c<a.length;c+=1){d="_"+h.trim(a[c].toString().toLowerCase())+"s";if(q!==this[d]&&this[d].length){for(f=0;f<this[d].length;f+=1)this.map===this[d][f].getMap()&&(this[d][f].set("visible",
!1),this[d][f].set("directions",null),this[d][f].setMap(null));this[d].length=0}if("direction"===a[c])for(f=0;f<this._directionsMarkers.length;f+=1)this._directionsMarkers[f].setMap(null)}},modify:function(b){var a=[],d=[["kml","kml"],["marker","markers"],["direction","direction"],["polyline","drawPolyline"],["polygon","drawPolygon"],["circle","drawCircle"],["streetView","streetView"]],c=0,f=this.map;if(q!==b){for(c=0;c<d.length;c+=1)g(b,d[c][0])&&a.push(d[c][1]);if(null!==f){if(a.length)for(c=0;c<
a.length;c+=1)"function"===typeof this[a[c]]&&("streetView"===a[c]&&(b.streetViewObj=b.streetView,delete b.streetView),this[a[c]](f,b,"modify"));else f.setOptions(b);g(b,"event")&&this.bindEvents(f,b.event)}}},destroy:function(){var b=h(this.container);h.data(b.get(0),"tinyMap",null)},geoLocation:function(b,a){var d=navigator.geolocation;d&&!0===a.autoLocation&&d.getCurrentPosition(function(a){a&&g(a,"coords")&&b.panTo(new google.maps.LatLng(a.coords.latitude,a.coords.longitude))},function(a){console.error(a)},
{maximumAge:6E5,timeout:3E3,enableHighAccuracy:!1})},init:function(){var b=this,a={};"string"===typeof b.options.center?(a=new google.maps.Geocoder,a.geocode({address:b.options.center},function(a,c){try{c===google.maps.GeocoderStatus.OVER_QUERY_LIMIT?b.init():c===google.maps.GeocoderStatus.OK&&0!==a.length?q!==a[0]&&g(a[0],"geometry")&&(b.googleMapOptions.center=a[0].geometry.location,b.map=new google.maps.Map(b.container,b.googleMapOptions),google.maps.event.addListenerOnce(b.map,"idle",function(){b.overlay()}),
b.bindEvents(b.map,b.options.event)):console.error(c)}catch(f){console.error(f)}})):(b.map=new google.maps.Map(b.container,b.googleMapOptions),google.maps.event.addListenerOnce(b.map,"idle",function(){b.overlay()}),b.bindEvents(b.map,b.options.event))}};h.fn.tinyMap=function(b){var a=arguments,d=[],c={};return"string"===typeof b?(this.each(function(){c=h.data(this,"tinyMap");c instanceof u&&"function"===typeof c[b]&&(d=c[b].apply(c,Array.prototype.slice.call(a,1)))}),q!==d?d:this):this.each(function(){h.data(this,
"tinyMap")||h.data(this,"tinyMap",new u(this,b))})}})(jQuery,window,document);
| DKMonster/Shoper | Lesson39/assets/js/plugin/jquery.tinyMap.min.js | JavaScript | mit | 16,478 |
/*
* Copyright (c) 2013 Adobe Systems Incorporated. All rights reserved.
*
* 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.
*
*/
/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4,
maxerr: 50, browser: true */
/*global $, define, brackets, WebSocket, ArrayBuffer, Uint32Array */
define(function (require, exports, module) {
"use strict";
var EventDispatcher = require("utils/EventDispatcher");
/**
* Connection attempts to make before failing
* @type {number}
*/
var CONNECTION_ATTEMPTS = 10;
/**
* Milliseconds to wait before a particular connection attempt is considered failed.
* NOTE: It's okay for the connection timeout to be long because the
* expected behavior of WebSockets is to send a "close" event as soon
* as they realize they can't connect. So, we should rarely hit the
* connection timeout even if we try to connect to a port that isn't open.
* @type {number}
*/
var CONNECTION_TIMEOUT = 10000; // 10 seconds
/**
* Milliseconds to wait before retrying connecting
* @type {number}
*/
var RETRY_DELAY = 500; // 1/2 second
/**
* Maximum value of the command ID counter
* @type {number}
*/
var MAX_COUNTER_VALUE = 4294967295; // 2^32 - 1
/**
* @private
* Helper function to auto-reject a deferred after a given amount of time.
* If the deferred is resolved/rejected manually, then the timeout is
* automatically cleared.
*/
function setDeferredTimeout(deferred, delay) {
var timer = setTimeout(function () {
deferred.reject("timeout");
}, delay);
deferred.always(function () { clearTimeout(timer); });
}
/**
* @private
* Helper function to attempt a single connection to the node server
*/
function attemptSingleConnect() {
var deferred = $.Deferred();
var port = null;
var ws = null;
setDeferredTimeout(deferred, CONNECTION_TIMEOUT);
brackets.app.getNodeState(function (err, nodePort) {
if (!err && nodePort && deferred.state() !== "rejected") {
port = nodePort;
ws = new WebSocket("ws://localhost:" + port);
// Expect ArrayBuffer objects from Node when receiving binary
// data instead of DOM Blobs, which are the default.
ws.binaryType = "arraybuffer";
// If the server port isn't open, we get a close event
// at some point in the future (and will not get an onopen
// event)
ws.onclose = function () {
deferred.reject("WebSocket closed");
};
ws.onopen = function () {
// If we successfully opened, remove the old onclose
// handler (which was present to detect failure to
// connect at all).
ws.onclose = null;
deferred.resolveWith(null, [ws, port]);
};
} else {
deferred.reject("brackets.app.getNodeState error: " + err);
}
});
return deferred.promise();
}
/**
* Provides an interface for interacting with the node server.
* @constructor
*/
function NodeConnection() {
this.domains = {};
this._registeredModules = [];
this._pendingInterfaceRefreshDeferreds = [];
this._pendingCommandDeferreds = [];
}
EventDispatcher.makeEventDispatcher(NodeConnection.prototype);
/**
* @type {Object}
* Exposes the domains registered with the server. This object will
* have a property for each registered domain. Each of those properties
* will be an object containing properties for all the commands in that
* domain. So, myConnection.base.enableDebugger would point to the function
* to call to enable the debugger.
*
* This object is automatically replaced every time the API changes (based
* on the base:newDomains event from the server). Therefore, code that
* uses this object should not keep their own pointer to the domain property.
*/
NodeConnection.prototype.domains = null;
/**
* @private
* @type {Array.<string>}
* List of module pathnames that should be re-registered if there is
* a disconnection/connection (i.e. if the server died).
*/
NodeConnection.prototype._registeredModules = null;
/**
* @private
* @type {WebSocket}
* The connection to the server
*/
NodeConnection.prototype._ws = null;
/**
* @private
* @type {?number}
* The port the WebSocket is currently connected to
*/
NodeConnection.prototype._port = null;
/**
* @private
* @type {number}
* Unique ID for commands
*/
NodeConnection.prototype._commandCount = 1;
/**
* @private
* @type {boolean}
* Whether to attempt reconnection if connection fails
*/
NodeConnection.prototype._autoReconnect = false;
/**
* @private
* @type {Array.<jQuery.Deferred>}
* List of deferred objects that should be resolved pending
* a successful refresh of the API
*/
NodeConnection.prototype._pendingInterfaceRefreshDeferreds = null;
/**
* @private
* @type {Array.<jQuery.Deferred>}
* Array (indexed on command ID) of deferred objects that should be
* resolved/rejected with the response of commands.
*/
NodeConnection.prototype._pendingCommandDeferreds = null;
/**
* @private
* @return {number} The next command ID to use. Always representable as an
* unsigned 32-bit integer.
*/
NodeConnection.prototype._getNextCommandID = function () {
var nextID;
if (this._commandCount > MAX_COUNTER_VALUE) {
nextID = this._commandCount = 0;
} else {
nextID = this._commandCount++;
}
return nextID;
};
/**
* @private
* Helper function to do cleanup work when a connection fails
*/
NodeConnection.prototype._cleanup = function () {
// clear out the domains, since we may get different ones
// on the next connection
this.domains = {};
// shut down the old connection if there is one
if (this._ws && this._ws.readyState !== WebSocket.CLOSED) {
try {
this._ws.close();
} catch (e) { }
}
var failedDeferreds = this._pendingInterfaceRefreshDeferreds
.concat(this._pendingCommandDeferreds);
failedDeferreds.forEach(function (d) {
d.reject("cleanup");
});
this._pendingInterfaceRefreshDeferreds = [];
this._pendingCommandDeferreds = [];
this._ws = null;
this._port = null;
};
/**
* Connect to the node server. After connecting, the NodeConnection
* object will trigger a "close" event when the underlying socket
* is closed. If the connection is set to autoReconnect, then the
* event will also include a jQuery promise for the connection.
*
* @param {boolean} autoReconnect Whether to automatically try to
* reconnect to the server if the connection succeeds and then
* later disconnects. Note if this connection fails initially, the
* autoReconnect flag is set to false. Future calls to connect()
* can reset it to true
* @return {jQuery.Promise} Promise that resolves/rejects when the
* connection succeeds/fails
*/
NodeConnection.prototype.connect = function (autoReconnect) {
var self = this;
self._autoReconnect = autoReconnect;
var deferred = $.Deferred();
var attemptCount = 0;
var attemptTimestamp = null;
// Called after a successful connection to do final setup steps
function registerHandlersAndDomains(ws, port) {
// Called if we succeed at the final setup
function success() {
self._ws.onclose = function () {
if (self._autoReconnect) {
var $promise = self.connect(true);
self.trigger("close", $promise);
} else {
self._cleanup();
self.trigger("close");
}
};
deferred.resolve();
}
// Called if we fail at the final setup
function fail(err) {
self._cleanup();
deferred.reject(err);
}
self._ws = ws;
self._port = port;
self._ws.onmessage = self._receive.bind(self);
// refresh the current domains, then re-register any
// "autoregister" modules
self._refreshInterface().then(
function () {
if (self._registeredModules.length > 0) {
self.loadDomains(self._registeredModules, false).then(
success,
fail
);
} else {
success();
}
},
fail
);
}
// Repeatedly tries to connect until we succeed or until we've
// failed CONNECTION_ATTEMPT times. After each attempt, waits
// at least RETRY_DELAY before trying again.
function doConnect() {
attemptCount++;
attemptTimestamp = new Date();
attemptSingleConnect().then(
registerHandlersAndDomains, // succeded
function () { // failed this attempt, possibly try again
if (attemptCount < CONNECTION_ATTEMPTS) { //try again
// Calculate how long we should wait before trying again
var now = new Date();
var delay = Math.max(
RETRY_DELAY - (now - attemptTimestamp),
1
);
setTimeout(doConnect, delay);
} else { // too many attempts, give up
deferred.reject("Max connection attempts reached");
}
}
);
}
// Start the connection process
self._cleanup();
doConnect();
return deferred.promise();
};
/**
* Determines whether the NodeConnection is currently connected
* @return {boolean} Whether the NodeConnection is connected.
*/
NodeConnection.prototype.connected = function () {
return !!(this._ws && this._ws.readyState === WebSocket.OPEN);
};
/**
* Explicitly disconnects from the server. Note that even if
* autoReconnect was set to true at connection time, the connection
* will not reconnect after this call. Reconnection can be manually done
* by calling connect() again.
*/
NodeConnection.prototype.disconnect = function () {
this._autoReconnect = false;
this._cleanup();
};
/**
* Load domains into the server by path
* @param {Array.<string>} List of absolute paths to load
* @param {boolean} autoReload Whether to auto-reload the domains if the server
* fails and restarts. Note that the reload is initiated by the
* client, so it will only happen after the client reconnects.
* @return {jQuery.Promise} Promise that resolves after the load has
* succeeded and the new API is availale at NodeConnection.domains,
* or that rejects on failure.
*/
NodeConnection.prototype.loadDomains = function (paths, autoReload) {
var deferred = $.Deferred();
setDeferredTimeout(deferred, CONNECTION_TIMEOUT);
var pathArray = paths;
if (!Array.isArray(paths)) {
pathArray = [paths];
}
if (autoReload) {
Array.prototype.push.apply(this._registeredModules, pathArray);
}
if (this.domains.base && this.domains.base.loadDomainModulesFromPaths) {
this.domains.base.loadDomainModulesFromPaths(pathArray).then(
function (success) { // command call succeeded
if (!success) {
// response from commmand call was "false" so we know
// the actual load failed.
deferred.reject("loadDomainModulesFromPaths failed");
}
// if the load succeeded, we wait for the API refresh to
// resolve the deferred.
},
function (reason) { // command call failed
deferred.reject("Unable to load one of the modules: " + pathArray + (reason ? ", reason: " + reason : ""));
}
);
this._pendingInterfaceRefreshDeferreds.push(deferred);
} else {
deferred.reject("this.domains.base is undefined");
}
return deferred.promise();
};
/**
* @private
* Sends a message over the WebSocket. Automatically JSON.stringifys
* the message if necessary.
* @param {Object|string} m Object to send. Must be JSON.stringify-able.
*/
NodeConnection.prototype._send = function (m) {
if (this.connected()) {
// Convert the message to a string
var messageString = null;
if (typeof m === "string") {
messageString = m;
} else {
try {
messageString = JSON.stringify(m);
} catch (stringifyError) {
console.error("[NodeConnection] Unable to stringify message in order to send: " + stringifyError.message);
}
}
// If we succeded in making a string, try to send it
if (messageString) {
try {
this._ws.send(messageString);
} catch (sendError) {
console.error("[NodeConnection] Error sending message: " + sendError.message);
}
}
} else {
console.error("[NodeConnection] Not connected to node, unable to send.");
}
};
/**
* @private
* Handler for receiving events on the WebSocket. Parses the message
* and dispatches it appropriately.
* @param {WebSocket.Message} message Message object from WebSocket
*/
NodeConnection.prototype._receive = function (message) {
var responseDeferred = null;
var data = message.data;
var m;
if (message.data instanceof ArrayBuffer) {
// The first four bytes encode the command ID as an unsigned 32-bit integer
if (data.byteLength < 4) {
console.error("[NodeConnection] received malformed binary message");
return;
}
var header = data.slice(0, 4),
body = data.slice(4),
headerView = new Uint32Array(header),
id = headerView[0];
// Unpack the binary message into a commandResponse
m = {
type: "commandResponse",
message: {
id: id,
response: body
}
};
} else {
try {
m = JSON.parse(data);
} catch (e) {
console.error("[NodeConnection] received malformed message", message, e.message);
return;
}
}
switch (m.type) {
case "event":
if (m.message.domain === "base" && m.message.event === "newDomains") {
this._refreshInterface();
}
// Event type "domain:event"
EventDispatcher.triggerWithArray(this, m.message.domain + ":" + m.message.event,
m.message.parameters);
break;
case "commandResponse":
responseDeferred = this._pendingCommandDeferreds[m.message.id];
if (responseDeferred) {
responseDeferred.resolveWith(this, [m.message.response]);
delete this._pendingCommandDeferreds[m.message.id];
}
break;
case "commandError":
responseDeferred = this._pendingCommandDeferreds[m.message.id];
if (responseDeferred) {
responseDeferred.rejectWith(
this,
[m.message.message, m.message.stack]
);
delete this._pendingCommandDeferreds[m.message.id];
}
break;
case "error":
console.error("[NodeConnection] received error: " +
m.message.message);
break;
default:
console.error("[NodeConnection] unknown event type: " + m.type);
}
};
/**
* @private
* Helper function for refreshing the interface in the "domain" property.
* Automatically called when the connection receives a base:newDomains
* event from the server, and also called at connection time.
*/
NodeConnection.prototype._refreshInterface = function () {
var deferred = $.Deferred();
var self = this;
var pendingDeferreds = this._pendingInterfaceRefreshDeferreds;
this._pendingInterfaceRefreshDeferreds = [];
deferred.then(
function () {
pendingDeferreds.forEach(function (d) { d.resolve(); });
},
function (err) {
pendingDeferreds.forEach(function (d) { d.reject(err); });
}
);
function refreshInterfaceCallback(spec) {
function makeCommandFunction(domainName, commandSpec) {
return function () {
var deferred = $.Deferred();
var parameters = Array.prototype.slice.call(arguments, 0);
var id = self._getNextCommandID();
self._pendingCommandDeferreds[id] = deferred;
self._send({id: id,
domain: domainName,
command: commandSpec.name,
parameters: parameters
});
return deferred;
};
}
// TODO: Don't replace the domain object every time. Instead, merge.
self.domains = {};
self.domainEvents = {};
spec.forEach(function (domainSpec) {
self.domains[domainSpec.domain] = {};
domainSpec.commands.forEach(function (commandSpec) {
self.domains[domainSpec.domain][commandSpec.name] =
makeCommandFunction(domainSpec.domain, commandSpec);
});
self.domainEvents[domainSpec.domain] = {};
domainSpec.events.forEach(function (eventSpec) {
var parameters = eventSpec.parameters;
self.domainEvents[domainSpec.domain][eventSpec.name] = parameters;
});
});
deferred.resolve();
}
if (this.connected()) {
$.getJSON("http://localhost:" + this._port + "/api")
.done(refreshInterfaceCallback)
.fail(function (err) { deferred.reject(err); });
} else {
deferred.reject("Attempted to call _refreshInterface when not connected.");
}
return deferred.promise();
};
/**
* @private
* Get the default timeout value
* @return {number} Timeout value in milliseconds
*/
NodeConnection._getConnectionTimeout = function () {
return CONNECTION_TIMEOUT;
};
module.exports = NodeConnection;
});
| mat-mcloughlin/brackets | src/utils/NodeConnection.js | JavaScript | mit | 21,552 |
/*
YUI 3.7.3 (build 5687)
Copyright 2012 Yahoo! Inc. All rights reserved.
Licensed under the BSD License.
http://yuilibrary.com/license/
*/
YUI.add("anim-xy",function(e,t){var n=Number;e.Anim.behaviors.xy={set:function(e,t,r,i,s,o,u){e._node.setXY([u(s,n(r[0]),n(i[0])-n(r[0]),o),u(s,n(r[1]),n(i[1])-n(r[1]),o)])},get:function(e){return e._node.getXY()}}},"3.7.3",{requires:["anim-base","node-screen"]});
| pulipulichen/kals-moodle | moodle/lib/yuilib/3.7.3/build/anim-xy/anim-xy-min.js | JavaScript | bsd-3-clause | 405 |
/*
* jQuery Autocomplete plugin 1.1
*
* Copyright (c) 2009 Jörn Zaefferer
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
* Revision: $Id: jquery.autocomplete.js 15 2009-08-22 10:30:27Z joern.zaefferer $
*/
;(function($) {
$.fn.extend({
autocomplete: function(urlOrData, options) {
var isUrl = typeof urlOrData == "string";
options = $.extend({}, $.Autocompleter.defaults, {
url: isUrl ? urlOrData : null,
data: isUrl ? null : urlOrData,
delay: isUrl ? $.Autocompleter.defaults.delay : 10,
max: options && !options.scroll ? 10 : 150
}, options);
// if highlight is set to false, replace it with a do-nothing function
options.highlight = options.highlight || function(value) { return value; };
// if the formatMatch option is not specified, then use formatItem for backwards compatibility
options.formatMatch = options.formatMatch || options.formatItem;
return this.each(function() {
new $.Autocompleter(this, options);
});
},
result: function(handler) {
return this.bind("result", handler);
},
search: function(handler) {
return this.trigger("search", [handler]);
},
flushCache: function() {
return this.trigger("flushCache");
},
setOptions: function(options){
return this.trigger("setOptions", [options]);
},
unautocomplete: function() {
return this.trigger("unautocomplete");
}
});
$.Autocompleter = function(input, options) {
var KEY = {
UP: 38,
DOWN: 40,
DEL: 46,
TAB: 9,
RETURN: 13,
ESC: 27,
COMMA: 188,
PAGEUP: 33,
PAGEDOWN: 34,
BACKSPACE: 8
};
// Create $ object for input element
var $input = $(input).attr("autocomplete", "off").addClass(options.inputClass);
var timeout;
var previousValue = "";
var cache = $.Autocompleter.Cache(options);
var hasFocus = 0;
var lastKeyPressCode;
var config = {
mouseDownOnSelect: false
};
var select = $.Autocompleter.Select(options, input, selectCurrent, config);
var blockSubmit;
// prevent form submit in opera when selecting with return key
$.browser.opera && $(input.form).bind("submit.autocomplete", function() {
if (blockSubmit) {
blockSubmit = false;
return false;
}
});
// only opera doesn't trigger keydown multiple times while pressed, others don't work with keypress at all
$input.bind(($.browser.opera ? "keypress" : "keydown") + ".autocomplete", function(event) {
// a keypress means the input has focus
// avoids issue where input had focus before the autocomplete was applied
hasFocus = 1;
// track last key pressed
lastKeyPressCode = event.keyCode;
switch(event.keyCode) {
case KEY.UP:
event.preventDefault();
if ( select.visible() ) {
select.prev();
} else {
onChange(0, true);
}
break;
case KEY.DOWN:
event.preventDefault();
if ( select.visible() ) {
select.next();
} else {
onChange(0, true);
}
break;
case KEY.PAGEUP:
event.preventDefault();
if ( select.visible() ) {
select.pageUp();
} else {
onChange(0, true);
}
break;
case KEY.PAGEDOWN:
event.preventDefault();
if ( select.visible() ) {
select.pageDown();
} else {
onChange(0, true);
}
break;
// matches also semicolon
case options.multiple && $.trim(options.multipleSeparator) == "," && KEY.COMMA:
case KEY.TAB:
case KEY.RETURN:
if( selectCurrent() ) {
// stop default to prevent a form submit, Opera needs special handling
event.preventDefault();
blockSubmit = true;
return false;
}
break;
case KEY.ESC:
select.hide();
break;
default:
clearTimeout(timeout);
timeout = setTimeout(onChange, options.delay);
break;
}
}).focus(function(){
// track whether the field has focus, we shouldn't process any
// results if the field no longer has focus
hasFocus++;
}).blur(function() {
hasFocus = 0;
if (!config.mouseDownOnSelect) {
hideResults();
}
}).click(function() {
// show select when clicking in a focused field
if ( hasFocus++ > 1 && !select.visible() ) {
onChange(0, true);
}
}).bind("search", function() {
// TODO why not just specifying both arguments?
var fn = (arguments.length > 1) ? arguments[1] : null;
function findValueCallback(q, data) {
var result;
if( data && data.length ) {
for (var i=0; i < data.length; i++) {
if( data[i].result.toLowerCase() == q.toLowerCase() ) {
result = data[i];
break;
}
}
}
if( typeof fn == "function" ) fn(result);
else $input.trigger("result", result && [result.data, result.value]);
}
$.each(trimWords($input.val()), function(i, value) {
request(value, findValueCallback, findValueCallback);
});
}).bind("flushCache", function() {
cache.flush();
}).bind("setOptions", function() {
$.extend(options, arguments[1]);
// if we've updated the data, repopulate
if ( "data" in arguments[1] )
cache.populate();
}).bind("unautocomplete", function() {
select.unbind();
$input.unbind();
$(input.form).unbind(".autocomplete");
});
function selectCurrent() {
var selected = select.selected();
if( !selected )
return false;
var v = selected.result;
previousValue = v;
if ( options.multiple ) {
var words = trimWords($input.val());
if ( words.length > 1 ) {
var seperator = options.multipleSeparator.length;
var cursorAt = $(input).selection().start;
var wordAt, progress = 0;
$.each(words, function(i, word) {
progress += word.length;
if (cursorAt <= progress) {
wordAt = i;
return false;
}
progress += seperator;
});
words[wordAt] = v;
// TODO this should set the cursor to the right position, but it gets overriden somewhere
//$.Autocompleter.Selection(input, progress + seperator, progress + seperator);
v = words.join( options.multipleSeparator );
}
v += options.multipleSeparator;
}
$input.val(v);
hideResultsNow();
$input.trigger("result", [selected.data, selected.value]);
return true;
}
function onChange(crap, skipPrevCheck) {
if( lastKeyPressCode == KEY.DEL ) {
select.hide();
return;
}
var currentValue = $input.val();
if ( !skipPrevCheck && currentValue == previousValue )
return;
previousValue = currentValue;
currentValue = lastWord(currentValue);
if ( currentValue.length >= options.minChars) {
$input.addClass(options.loadingClass);
if (!options.matchCase)
currentValue = currentValue.toLowerCase();
request(currentValue, receiveData, hideResultsNow);
} else {
stopLoading();
select.hide();
}
};
function trimWords(value) {
if (!value)
return [""];
if (!options.multiple)
return [$.trim(value)];
return $.map(value.split(options.multipleSeparator), function(word) {
return $.trim(value).length ? $.trim(word) : null;
});
}
function lastWord(value) {
if ( !options.multiple )
return value;
var words = trimWords(value);
if (words.length == 1)
return words[0];
var cursorAt = $(input).selection().start;
if (cursorAt == value.length) {
words = trimWords(value)
} else {
words = trimWords(value.replace(value.substring(cursorAt), ""));
}
return words[words.length - 1];
}
// fills in the input box w/the first match (assumed to be the best match)
// q: the term entered
// sValue: the first matching result
function autoFill(q, sValue){
// autofill in the complete box w/the first match as long as the user hasn't entered in more data
// if the last user key pressed was backspace, don't autofill
if( options.autoFill && (lastWord($input.val()).toLowerCase() == q.toLowerCase()) && lastKeyPressCode != KEY.BACKSPACE ) {
// fill in the value (keep the case the user has typed)
$input.val($input.val() + sValue.substring(lastWord(previousValue).length));
// select the portion of the value not typed by the user (so the next character will erase)
$(input).selection(previousValue.length, previousValue.length + sValue.length);
}
};
function hideResults() {
clearTimeout(timeout);
timeout = setTimeout(hideResultsNow, 200);
};
function hideResultsNow() {
var wasVisible = select.visible();
select.hide();
clearTimeout(timeout);
stopLoading();
if (options.mustMatch) {
// call search and run callback
$input.search(
function (result){
// if no value found, clear the input box
if( !result ) {
if (options.multiple) {
var words = trimWords($input.val()).slice(0, -1);
$input.val( words.join(options.multipleSeparator) + (words.length ? options.multipleSeparator : "") );
}
else {
$input.val( "" );
$input.trigger("result", null);
}
}
}
);
}
};
function receiveData(q, data) {
if ( data && data.length && hasFocus ) {
stopLoading();
select.display(data, q);
autoFill(q, data[0].value);
select.show();
} else {
hideResultsNow();
}
};
function request(term, success, failure) {
if (!options.matchCase)
term = term.toLowerCase();
var data = cache.load(term);
// recieve the cached data
if (data && data.length) {
success(term, data);
// if an AJAX url has been supplied, try loading the data now
} else if( (typeof options.url == "string") && (options.url.length > 0) ){
var extraParams = {
timestamp: +new Date()
};
$.each(options.extraParams, function(key, param) {
extraParams[key] = typeof param == "function" ? param() : param;
});
$.ajax({
// try to leverage ajaxQueue plugin to abort previous requests
mode: "abort",
// limit abortion to this input
port: "autocomplete" + input.name,
dataType: options.dataType,
url: options.url,
data: $.extend({
q: lastWord(term),
limit: options.max
}, extraParams),
success: function(data) {
var parsed = options.parse && options.parse(data) || parse(data);
cache.add(term, parsed);
success(term, parsed);
}
});
} else {
// if we have a failure, we need to empty the list -- this prevents the the [TAB] key from selecting the last successful match
select.emptyList();
failure(term);
}
};
function parse(data) {
var parsed = [];
var rows = data.split("\n");
for (var i=0; i < rows.length; i++) {
var row = $.trim(rows[i]);
if (row) {
row = row.split("|");
parsed[parsed.length] = {
data: row,
value: row[0],
result: options.formatResult && options.formatResult(row, row[0]) || row[0]
};
}
}
return parsed;
};
function stopLoading() {
$input.removeClass(options.loadingClass);
};
};
$.Autocompleter.defaults = {
inputClass: "ac_input",
resultsClass: "ac_results",
loadingClass: "ac_loading",
minChars: 1,
delay: 400,
matchCase: false,
matchSubset: true,
matchContains: false,
cacheLength: 10,
max: 100,
mustMatch: false,
extraParams: {},
selectFirst: true,
formatItem: function(row) { return row[0]; },
formatMatch: null,
autoFill: false,
width: 0,
multiple: false,
multipleSeparator: ", ",
highlight: function(value, term) {
return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
},
scroll: true,
scrollHeight: 180
};
$.Autocompleter.Cache = function(options) {
var data = {};
var length = 0;
function matchSubset(s, sub) {
if (!options.matchCase)
s = s.toLowerCase();
var i = s.indexOf(sub);
if (options.matchContains == "word"){
i = s.toLowerCase().search("\\b" + sub.toLowerCase());
}
if (i == -1) return false;
return i == 0 || options.matchContains;
};
function add(q, value) {
if (length > options.cacheLength){
flush();
}
if (!data[q]){
length++;
}
data[q] = value;
}
function populate(){
if( !options.data ) return false;
// track the matches
var stMatchSets = {},
nullData = 0;
// no url was specified, we need to adjust the cache length to make sure it fits the local data store
if( !options.url ) options.cacheLength = 1;
// track all options for minChars = 0
stMatchSets[""] = [];
// loop through the array and create a lookup structure
for ( var i = 0, ol = options.data.length; i < ol; i++ ) {
var rawValue = options.data[i];
// if rawValue is a string, make an array otherwise just reference the array
rawValue = (typeof rawValue == "string") ? [rawValue] : rawValue;
var value = options.formatMatch(rawValue, i+1, options.data.length);
if ( value === false )
continue;
var firstChar = value.charAt(0).toLowerCase();
// if no lookup array for this character exists, look it up now
if( !stMatchSets[firstChar] )
stMatchSets[firstChar] = [];
// if the match is a string
var row = {
value: value,
data: rawValue,
result: options.formatResult && options.formatResult(rawValue) || value
};
// push the current match into the set list
stMatchSets[firstChar].push(row);
// keep track of minChars zero items
if ( nullData++ < options.max ) {
stMatchSets[""].push(row);
}
};
// add the data items to the cache
$.each(stMatchSets, function(i, value) {
// increase the cache size
options.cacheLength++;
// add to the cache
add(i, value);
});
}
// populate any existing data
setTimeout(populate, 25);
function flush(){
data = {};
length = 0;
}
return {
flush: flush,
add: add,
populate: populate,
load: function(q) {
if (!options.cacheLength || !length)
return null;
/*
* if dealing w/local data and matchContains than we must make sure
* to loop through all the data collections looking for matches
*/
if( !options.url && options.matchContains ){
// track all matches
var csub = [];
// loop through all the data grids for matches
for( var k in data ){
// don't search through the stMatchSets[""] (minChars: 0) cache
// this prevents duplicates
if( k.length > 0 ){
var c = data[k];
$.each(c, function(i, x) {
// if we've got a match, add it to the array
if (matchSubset(x.value, q)) {
csub.push(x);
}
});
}
}
return csub;
} else
// if the exact item exists, use it
if (data[q]){
return data[q];
} else
if (options.matchSubset) {
for (var i = q.length - 1; i >= options.minChars; i--) {
var c = data[q.substr(0, i)];
if (c) {
var csub = [];
$.each(c, function(i, x) {
if (matchSubset(x.value, q)) {
csub[csub.length] = x;
}
});
return csub;
}
}
}
return null;
}
};
};
$.Autocompleter.Select = function (options, input, select, config) {
var CLASSES = {
ACTIVE: "ac_over"
};
var listItems,
active = -1,
data,
term = "",
needsInit = true,
element,
list;
// Create results
function init() {
if (!needsInit)
return;
element = $("<div/>")
.hide()
.addClass(options.resultsClass)
.css("position", "absolute")
.appendTo(document.body);
list = $("<ul/>").appendTo(element).mouseover( function(event) {
if(target(event).nodeName && target(event).nodeName.toUpperCase() == 'LI') {
active = $("li", list).removeClass(CLASSES.ACTIVE).index(target(event));
$(target(event)).addClass(CLASSES.ACTIVE);
}
}).click(function(event) {
$(target(event)).addClass(CLASSES.ACTIVE);
select();
// TODO provide option to avoid setting focus again after selection? useful for cleanup-on-focus
input.focus();
return false;
}).mousedown(function() {
config.mouseDownOnSelect = true;
}).mouseup(function() {
config.mouseDownOnSelect = false;
});
if( options.width > 0 )
element.css("width", options.width);
needsInit = false;
}
function target(event) {
var element = event.target;
while(element && element.tagName != "LI")
element = element.parentNode;
// more fun with IE, sometimes event.target is empty, just ignore it then
if(!element)
return [];
return element;
}
function moveSelect(step) {
listItems.slice(active, active + 1).removeClass(CLASSES.ACTIVE);
movePosition(step);
var activeItem = listItems.slice(active, active + 1).addClass(CLASSES.ACTIVE);
if(options.scroll) {
var offset = 0;
listItems.slice(0, active).each(function() {
offset += this.offsetHeight;
});
if((offset + activeItem[0].offsetHeight - list.scrollTop()) > list[0].clientHeight) {
list.scrollTop(offset + activeItem[0].offsetHeight - list.innerHeight());
} else if(offset < list.scrollTop()) {
list.scrollTop(offset);
}
}
};
function movePosition(step) {
active += step;
if (active < 0) {
active = listItems.size() - 1;
} else if (active >= listItems.size()) {
active = 0;
}
}
function limitNumberOfItems(available) {
return options.max && options.max < available
? options.max
: available;
}
function fillList() {
list.empty();
var max = limitNumberOfItems(data.length);
for (var i=0; i < max; i++) {
if (!data[i])
continue;
var formatted = options.formatItem(data[i].data, i+1, max, data[i].value, term);
if ( formatted === false )
continue;
var li = $("<li/>").html( options.highlight(formatted, term) ).addClass(i%2 == 0 ? "ac_even" : "ac_odd").appendTo(list)[0];
$.data(li, "ac_data", data[i]);
}
listItems = list.find("li");
if ( options.selectFirst ) {
listItems.slice(0, 1).addClass(CLASSES.ACTIVE);
active = 0;
}
// apply bgiframe if available
if ( $.fn.bgiframe )
list.bgiframe();
}
return {
display: function(d, q) {
init();
data = d;
term = q;
fillList();
},
next: function() {
moveSelect(1);
},
prev: function() {
moveSelect(-1);
},
pageUp: function() {
if (active != 0 && active - 8 < 0) {
moveSelect( -active );
} else {
moveSelect(-8);
}
},
pageDown: function() {
if (active != listItems.size() - 1 && active + 8 > listItems.size()) {
moveSelect( listItems.size() - 1 - active );
} else {
moveSelect(8);
}
},
hide: function() {
element && element.hide();
listItems && listItems.removeClass(CLASSES.ACTIVE);
active = -1;
},
visible : function() {
return element && element.is(":visible");
},
current: function() {
return this.visible() && (listItems.filter("." + CLASSES.ACTIVE)[0] || options.selectFirst && listItems[0]);
},
show: function() {
var offset = $(input).offset();
element.css({
width: typeof options.width == "string" || options.width > 0 ? options.width : $(input).width(),
top: offset.top + input.offsetHeight,
left: offset.left
}).show();
if(options.scroll) {
list.scrollTop(0);
list.css({
maxHeight: options.scrollHeight,
overflow: 'auto'
});
if($.browser.msie && typeof document.body.style.maxHeight === "undefined") {
var listHeight = 0;
listItems.each(function() {
listHeight += this.offsetHeight;
});
var scrollbarsVisible = listHeight > options.scrollHeight;
list.css('height', scrollbarsVisible ? options.scrollHeight : listHeight );
if (!scrollbarsVisible) {
// IE doesn't recalculate width when scrollbar disappears
listItems.width( list.width() - parseInt(listItems.css("padding-left")) - parseInt(listItems.css("padding-right")) );
}
}
}
},
selected: function() {
var selected = listItems && listItems.filter("." + CLASSES.ACTIVE).removeClass(CLASSES.ACTIVE);
return selected && selected.length && $.data(selected[0], "ac_data");
},
emptyList: function (){
list && list.empty();
},
unbind: function() {
element && element.remove();
}
};
};
$.fn.selection = function(start, end) {
if (start !== undefined) {
return this.each(function() {
if( this.createTextRange ){
var selRange = this.createTextRange();
if (end === undefined || start == end) {
selRange.move("character", start);
selRange.select();
} else {
selRange.collapse(true);
selRange.moveStart("character", start);
selRange.moveEnd("character", end);
selRange.select();
}
} else if( this.setSelectionRange ){
this.setSelectionRange(start, end);
} else if( this.selectionStart ){
this.selectionStart = start;
this.selectionEnd = end;
}
});
}
var field = this[0];
if ( field.createTextRange ) {
var range = document.selection.createRange(),
orig = field.value,
teststring = "<->",
textLength = range.text.length;
range.text = teststring;
var caretAt = field.value.indexOf(teststring);
field.value = orig;
this.selection(caretAt, caretAt + textLength);
return {
start: caretAt,
end: caretAt + textLength
}
} else if( field.selectionStart !== undefined ){
return {
start: field.selectionStart,
end: field.selectionEnd
}
}
};
})(jQuery); | zorna/zorna | zorna/media/javascript/jquery.autocomplete.js | JavaScript | bsd-3-clause | 21,271 |
module.exports = function(grunt) {
/**
* Initialize development environment for Testacular
*
* - register git hooks (commit-msg)
*/
grunt.registerTask('init-dev-env', 'Initialize dev environment.', function() {
var fs = require('fs');
var done = this.async();
fs.symlink('../../tasks/lib/validate-commit-msg.js', '.git/hooks/commit-msg', function(e) {
if (!e) {
grunt.log.ok('Hook "validate-commit-msg" installed.');
}
done();
});
});
};
| risingspiral/testacular | tasks/init-dev-env.js | JavaScript | mit | 500 |
var test = require("tap").test
var npm = require.resolve("../../bin/npm-cli.js")
var spawn = require("child_process").spawn
var node = process.execPath
// ignore-scripts/package.json has scripts that always exit with non-zero error
// codes. The "install" script is omitted so that npm tries to run node-gyp,
// which should also fail.
var pkg = __dirname + "/ignore-scripts"
test("ignore-scripts: install using the option", function(t) {
createChild([npm, "install", "--ignore-scripts"]).on("close", function(code) {
t.equal(code, 0)
t.end()
})
})
test("ignore-scripts: install NOT using the option", function(t) {
createChild([npm, "install"]).on("close", function(code) {
t.notEqual(code, 0)
t.end()
})
})
var scripts = [
"prepublish", "publish", "postpublish",
"preinstall", "install", "postinstall",
"preuninstall", "uninstall", "postuninstall",
"preupdate", "update", "postupdate",
"pretest", "test", "posttest",
"prestop", "stop", "poststop",
"prestart", "start", "poststart",
"prerestart", "restart", "postrestart"
]
scripts.forEach(function(script) {
test("ignore-scripts: run-script"+script+" using the option", function(t) {
createChild([npm, "--ignore-scripts", "run-script", script])
.on("close", function(code) {
t.equal(code, 0)
t.end()
})
})
})
scripts.forEach(function(script) {
test("ignore-scripts: run-script "+script+" NOT using the option", function(t) {
createChild([npm, "run-script", script]).on("close", function(code) {
t.notEqual(code, 0)
t.end()
})
})
})
function createChild (args) {
var env = {
HOME: process.env.HOME,
Path: process.env.PATH,
PATH: process.env.PATH
}
if (process.platform === "win32")
env.npm_config_cache = "%APPDATA%\\npm-cache"
return spawn(node, args, {
cwd: pkg,
stdio: "inherit",
env: env
})
}
| teeple/pns_server | work/install/node-v0.10.25/deps/npm/test/tap/ignore-scripts.js | JavaScript | gpl-2.0 | 1,896 |
tinyMCE.addI18n('ta.advhr_dlg',{size:"\u0b89\u0baf\u0bb0\u0bae\u0bcd",noshade:"\u0ba8\u0bbf\u0bb4\u0bb2\u0bcd \u0b87\u0bb2\u0bcd\u0bb2\u0bc8",width:"\u0b85\u0b95\u0bb2\u0bae\u0bcd",normal:"Normal",widthunits:"Units"}); | ciudadanointeligente/votainteligente-portal-electoral | votai_general_theme/static/js/tiny_mce/plugins/advhr/langs/ta_dlg.js | JavaScript | gpl-3.0 | 218 |
// @flow
let tests = [
// setting a property
function(x: $Tainted<string>, y: string) {
let obj: Object = {};
obj.foo = x; // error, taint ~> any
obj[y] = x; // error, taint ~> any
},
// getting a property
function() {
let obj: Object = { foo: 'foo' };
(obj.foo: $Tainted<string>); // ok
},
// calling a method
function(x: $Tainted<string>) {
let obj: Object = {};
obj.foo(x); // error, taint ~> any
let foo = obj.foo;
foo(x); // error, taint ~> any
},
];
| MichaelDeBoey/flow | tests/taint/any_object.js | JavaScript | mit | 514 |
/**
* @author TristanVALCKE / https://github.com/Itee
* @author moraxy / https://github.com/moraxy
*/
/* global QUnit */
import { runStdLightTests } from '../../qunit-utils';
import { DirectionalLight } from '../../../../src/lights/DirectionalLight';
export default QUnit.module( 'Lights', () => {
QUnit.module( 'DirectionalLight', ( hooks ) => {
var lights = undefined;
hooks.beforeEach( function () {
const parameters = {
color: 0xaaaaaa,
intensity: 0.8
};
lights = [
new DirectionalLight(),
new DirectionalLight( parameters.color ),
new DirectionalLight( parameters.color, parameters.intensity )
];
} );
// INHERITANCE
QUnit.todo( "Extending", ( assert ) => {
assert.ok( false, "everything's gonna be alright" );
} );
// INSTANCING
QUnit.todo( "Instancing", ( assert ) => {
assert.ok( false, "everything's gonna be alright" );
} );
// PUBLIC STUFF
QUnit.todo( "isDirectionalLight", ( assert ) => {
assert.ok( false, "everything's gonna be alright" );
} );
QUnit.todo( "copy", ( assert ) => {
assert.ok( false, "everything's gonna be alright" );
} );
// OTHERS
QUnit.test( 'Standard light tests', ( assert ) => {
runStdLightTests( assert, lights );
} );
} );
} );
| SpinVR/three.js | test/unit/src/lights/DirectionalLight.tests.js | JavaScript | mit | 1,276 |
/**
* Shopware 5
* Copyright (c) shopware AG
*
* According to our dual licensing model, this program can be used either
* under the terms of the GNU Affero General Public License, version 3,
* or under a proprietary license.
*
* The texts of the GNU Affero General Public License with an additional
* permission and of our proprietary license can be found at and
* in the LICENSE file you have received along with this program.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* "Shopware" is a registered trademark of shopware AG.
* The licensing of the program under the AGPLv3 does not imply a
* trademark license. Therefore any rights, title and interest in
* our trademarks remain entirely with us.
*
* @category Shopware
* @package Base
* @subpackage Model
* @version $Id$
* @author shopware AG
*/
/**
* Shopware Model - Global Stores and Models
*
* The shop model represents a data row of the s_core_tax or the
* Shopware\Models\Article\Tax doctrine model.
*/
//{block name="backend/base/model/tax"}
Ext.define('Shopware.apps.Base.model.Tax', {
/**
* Defines an alternate name for this class.
*/
alternateClassName:'Shopware.model.Tax',
/**
* Extends the standard ExtJS Model
* @string
*/
extend : 'Shopware.data.Model',
/**
* unique id
* @int
*/
idProperty:'id',
/**
* The fields used for this model
* @array
*/
fields : [
//{block name="backend/base/model/tax/fields"}{/block}
{ name : 'id', type: 'integer' },
{ name : 'tax',type: 'float' },
{ name : 'name',type: 'string' }
]
});
//{/block}
| Goucher/shopware | themes/Backend/ExtJs/backend/base/model/tax.js | JavaScript | agpl-3.0 | 1,867 |
/* Copyright (c) 2011 by The Authors.
* Published under the LGPL 2.1 license.
* See /license-notice.txt for the full text of the license notice.
* See /license.txt for the full text of the license.
*/
describe('jsts.algorithm.InteriorPointArea', function() {
var ipa;
it('can be constructed', function() {
var shell = new jsts.geom.LinearRing([
new jsts.geom.Coordinate(2, 2),
new jsts.geom.Coordinate(6, 2),
new jsts.geom.Coordinate(6, 6),
new jsts.geom.Coordinate(2, 6),
new jsts.geom.Coordinate(2, 2)
]);
var polygon = new jsts.geom.Polygon(shell);
ipa = new jsts.algorithm.InteriorPointArea(polygon);
expect(ipa).toBeDefined();
});
it('interior point of simple square', function() {
var validCoord = new jsts.geom.Coordinate(4, 4);
expect(ipa.getInteriorPoint().distance(validCoord)).toEqual(0);
});
it('interior point of square with hole', function() {
var shell = new jsts.geom.LinearRing([
new jsts.geom.Coordinate(2, 2),
new jsts.geom.Coordinate(8, 2),
new jsts.geom.Coordinate(8, 6),
new jsts.geom.Coordinate(2, 6),
new jsts.geom.Coordinate(2, 2)
]);
var hole = new jsts.geom.LinearRing([
new jsts.geom.Coordinate(3, 3),
new jsts.geom.Coordinate(3, 5),
new jsts.geom.Coordinate(6, 5),
new jsts.geom.Coordinate(6, 3),
new jsts.geom.Coordinate(3, 3)
]);
var polygon = new jsts.geom.Polygon(shell, [hole]);
ipa = new jsts.algorithm.InteriorPointArea(polygon);
var validCoord = new jsts.geom.Coordinate(7, 4);
expect(ipa.getInteriorPoint().distance(validCoord)).toEqual(0);
});
it('interior point of the widest horizontal intersection in geometry collection', function() {
var shell1 = new jsts.geom.LinearRing([
new jsts.geom.Coordinate(2, 2),
new jsts.geom.Coordinate(4, 2),
new jsts.geom.Coordinate(4, 4),
new jsts.geom.Coordinate(2, 4),
new jsts.geom.Coordinate(2, 2)
]);
var polygon1 = new jsts.geom.Polygon(shell1);
var shell2 = new jsts.geom.LinearRing([
new jsts.geom.Coordinate(5, 5),
new jsts.geom.Coordinate(11, 5),
new jsts.geom.Coordinate(11, 7),
new jsts.geom.Coordinate(5, 7),
new jsts.geom.Coordinate(5, 5)
]);
var polygon2 = new jsts.geom.Polygon(shell2);
var shell3 = new jsts.geom.LinearRing([
new jsts.geom.Coordinate(12, 12),
new jsts.geom.Coordinate(15, 12),
new jsts.geom.Coordinate(15, 25),
new jsts.geom.Coordinate(12, 25),
new jsts.geom.Coordinate(12, 12)
]);
var polygon3 = new jsts.geom.Polygon(shell3);
var gc = new jsts.geom.GeometryCollection([polygon1, polygon2, polygon3]);
ipa = new jsts.algorithm.InteriorPointArea(gc);
var validCoord = new jsts.geom.Coordinate(8, 6);
expect(ipa.getInteriorPoint().distance(validCoord)).toEqual(0);
});
});
| mileswwatkins/ABiteBetweenUs | utilities/scripts/jsts/test/spec/jsts/algorithm/InteriorPointArea.js | JavaScript | apache-2.0 | 3,213 |
/*
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("language","es",{button:"Fijar lenguaje",remove:"Quitar lenguaje"}); | Laravel-Backpack/crud | src/public/packages/ckeditor/plugins/language/lang/es.js | JavaScript | mit | 261 |
// Copyright 2008 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Similiar functionality of {@link goog.ui.ButtonRenderer},
* but uses a <div> element instead of a <button> or <input> element.
*
*/
goog.provide('goog.ui.FlatButtonRenderer');
goog.require('goog.a11y.aria');
goog.require('goog.a11y.aria.Role');
goog.require('goog.dom.classes');
goog.require('goog.ui.Button');
goog.require('goog.ui.ButtonRenderer');
goog.require('goog.ui.INLINE_BLOCK_CLASSNAME');
goog.require('goog.ui.registry');
/**
* Flat renderer for {@link goog.ui.Button}s. Flat buttons can contain
* almost arbitrary HTML content, will flow like inline elements, but can be
* styled like block-level elements.
* @constructor
* @extends {goog.ui.ButtonRenderer}
*/
goog.ui.FlatButtonRenderer = function() {
goog.ui.ButtonRenderer.call(this);
};
goog.inherits(goog.ui.FlatButtonRenderer, goog.ui.ButtonRenderer);
goog.addSingletonGetter(goog.ui.FlatButtonRenderer);
/**
* Default CSS class to be applied to the root element of components rendered
* by this renderer.
* @type {string}
*/
goog.ui.FlatButtonRenderer.CSS_CLASS = goog.getCssName('goog-flat-button');
/**
* Returns the control's contents wrapped in a div element, with
* the renderer's own CSS class and additional state-specific classes applied
* to it, and the button's disabled attribute set or cleared as needed.
* Overrides {@link goog.ui.ButtonRenderer#createDom}.
* @param {goog.ui.Control} button Button to render.
* @return {Element} Root element for the button.
* @override
*/
goog.ui.FlatButtonRenderer.prototype.createDom = function(button) {
var classNames = this.getClassNames(button);
var attributes = {
'class': goog.ui.INLINE_BLOCK_CLASSNAME + ' ' + classNames.join(' '),
'title': button.getTooltip() || ''
};
return button.getDomHelper().createDom(
'div', attributes, button.getContent());
};
/**
* Returns the ARIA role to be applied to flat buttons.
* @return {goog.a11y.aria.Role|undefined} ARIA role.
* @override
*/
goog.ui.FlatButtonRenderer.prototype.getAriaRole = function() {
return goog.a11y.aria.Role.BUTTON;
};
/**
* Returns true if this renderer can decorate the element. Overrides
* {@link goog.ui.ButtonRenderer#canDecorate} by returning true if the
* element is a DIV, false otherwise.
* @param {Element} element Element to decorate.
* @return {boolean} Whether the renderer can decorate the element.
* @override
*/
goog.ui.FlatButtonRenderer.prototype.canDecorate = function(element) {
return element.tagName == 'DIV';
};
/**
* Takes an existing element and decorates it with the flat button control.
* Initializes the control's ID, content, tooltip, value, and state based
* on the ID of the element, its child nodes, and its CSS classes, respectively.
* Returns the element. Overrides {@link goog.ui.ButtonRenderer#decorate}.
* @param {goog.ui.Control} button Button instance to decorate the element.
* @param {Element} element Element to decorate.
* @return {Element} Decorated element.
* @override
*/
goog.ui.FlatButtonRenderer.prototype.decorate = function(button, element) {
goog.dom.classes.add(element, goog.ui.INLINE_BLOCK_CLASSNAME);
return goog.ui.FlatButtonRenderer.superClass_.decorate.call(this, button,
element);
};
/**
* Flat buttons can't use the value attribute since they are div elements.
* Overrides {@link goog.ui.ButtonRenderer#getValue} to prevent trying to
* access the element's value.
* @param {Element} element The button control's root element.
* @return {string} Value not valid for flat buttons.
* @override
*/
goog.ui.FlatButtonRenderer.prototype.getValue = function(element) {
// Flat buttons don't store their value in the DOM.
return '';
};
/**
* Returns the CSS class to be applied to the root element of components
* rendered using this renderer.
* @return {string} Renderer-specific CSS class.
* @override
*/
goog.ui.FlatButtonRenderer.prototype.getCssClass = function() {
return goog.ui.FlatButtonRenderer.CSS_CLASS;
};
// Register a decorator factory function for Flat Buttons.
goog.ui.registry.setDecoratorByClassName(goog.ui.FlatButtonRenderer.CSS_CLASS,
function() {
// Uses goog.ui.Button, but with FlatButtonRenderer.
return new goog.ui.Button(null, goog.ui.FlatButtonRenderer.getInstance());
});
| elsigh/browserscope | third_party/closure/goog/ui/flatbuttonrenderer.js | JavaScript | apache-2.0 | 4,935 |
function load(/*String*/fileName){
//summary: opens the file at fileName and evals the contents as JavaScript.
//Read the file
var fileContents = readFile(fileName);
//Eval the contents.
var Context = Packages.org.mozilla.javascript.Context;
var context = Context.enter();
try{
return context.evaluateString(this, fileContents, fileName, 1, null);
}finally{
Context.exit();
}
}
function readFile(/*String*/path, /*String?*/encoding){
//summary: reads a file and returns a string
encoding = encoding || "utf-8";
var file = new java.io.File(path);
var lineSeparator = "\n";
var input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(file), encoding));
try {
var stringBuffer = new java.lang.StringBuffer();
var line = "";
while((line = input.readLine()) !== null){
stringBuffer.append(line);
stringBuffer.append(lineSeparator);
}
//Make sure we return a JavaScript string and not a Java string.
return new String(stringBuffer.toString()); //String
} finally {
input.close();
}
}
//TODO: inlining this function since the new shrinksafe.jar is used, and older
//versions of Dojo's buildscripts are not compatible.
function optimizeJs(/*String fileName*/fileName, /*String*/fileContents, /*String*/copyright, /*String*/optimizeType, /*String*/stripConsole){
//summary: either strips comments from string or compresses it.
copyright = copyright || "";
//Use rhino to help do minifying/compressing.
var context = Packages.org.mozilla.javascript.Context.enter();
try{
// Use the interpreter for interactive input (copied this from Main rhino class).
context.setOptimizationLevel(-1);
// the "packer" type is now just a synonym for shrinksafe
if(optimizeType.indexOf("shrinksafe") == 0 || optimizeType == "packer"){
//Apply compression using custom compression call in Dojo-modified rhino.
fileContents = new String(Packages.org.dojotoolkit.shrinksafe.Compressor.compressScript(fileContents, 0, 1, stripConsole));
if(optimizeType.indexOf(".keepLines") == -1){
fileContents = fileContents.replace(/[\r\n]/g, "");
}
}else if(optimizeType == "comments"){
//Strip comments
var script = context.compileString(fileContents, fileName, 1, null);
fileContents = new String(context.decompileScript(script, 0));
//Replace the spaces with tabs.
//Ideally do this in the pretty printer rhino code.
fileContents = fileContents.replace(/ /g, "\t");
//If this is an nls bundle, make sure it does not end in a ;
//Otherwise, bad things happen.
if(fileName.match(/\/nls\//)){
fileContents = fileContents.replace(/;\s*$/, "");
}
}
}finally{
Packages.org.mozilla.javascript.Context.exit();
}
return copyright + fileContents;
}
build = {
make: function(
//The path to this file. Assumes dojo builds under it.
/*String*/builderPath,
//"1.1.1" or "1.3.2": used to choose directory of dojo to use.
/*String*/version,
//"google" or "aol"
/*String*/cdnType,
//comma-separated list of resource names. No double-quotes or quotes around values.
/*String*/dependencies,
//comments, shrinksafe, none
/*String*/optimizeType){
//Validate.
if(version != "1.3.2"){
return "invalid version";
}
if(cdnType != "google" && cdnType != "aol"){
return "invalide CDN type";
}
if(optimizeType != "comments" && optimizeType != "shrinksafe"
&& optimizeType != "none" && optimizeType != "shrinksafe.keepLines"){
return "invalid optimize type";
}
if(!dependencies.match(/^[\w\-\,\s\.]+$/)){
return "invalid dependency list";
}
//Set up full CDN path.
var xdDojoPath = "http://ajax.googleapis.com/ajax/libs/dojo/";
if(cdnType == "aol"){
xdDojoPath = "http://o.aolcdn.com/dojo/";
}
xdDojoPath += version;
//Directory that holds dojo source distro. Direct child under the helma dir
var dojoDir = builderPath + version + "/";
//Normalize the dependencies so that have double-quotes
//around each dependency.
var normalizedDependencies = dependencies || "";
if(normalizedDependencies){
normalizedDependencies = '"' + normalizedDependencies.split(",").join('","') + '"';
}
var buildscriptDir = dojoDir + "util/buildscripts/";
//Load the libraries to help in the build.
load(dojoDir + "util/buildscripts/jslib/logger.js");
load(dojoDir + "util/buildscripts/jslib/fileUtil.js");
load(dojoDir + "util/buildscripts/jslib/buildUtil.js");
load(dojoDir + "util/buildscripts/jslib/buildUtilXd.js");
load(dojoDir + "util/buildscripts/jslib/i18nUtil.js");
//Set up the build args.
var kwArgs = buildUtil.makeBuildOptions([
"loader=xdomain",
"version=" + version,
"xdDojoPath=" + xdDojoPath,
"layerOptimize=" + optimizeType
]);
//Specify the basic profile for build.
var profileText = 'dependencies = {'
+ 'layers: ['
+ ' {'
+ ' name: "dojo.js",'
+ ' dependencies: ['
+ normalizedDependencies
+ ' ]'
+ ' }'
+ '],'
+ 'prefixes: ['
+ ' [ "dojo", "' + dojoDir + 'dojo" ],'
+ ' [ "dijit", "' + dojoDir + 'dijit" ],'
+ ' [ "dojox", "' + dojoDir + 'dojox" ]'
+ ']'
+ '}';
//Bring the profile into existence
var profileProperties = buildUtil.evalProfile(profileText, true);
kwArgs.profileProperties = profileProperties;
//Set up some helper variables.
dependencies = kwArgs.profileProperties.dependencies;
var prefixes = dependencies.prefixes;
var lineSeparator = fileUtil.getLineSeparator();
var layerLegalText = fileUtil.readFile(buildscriptDir + "copyright.txt")
+ lineSeparator
+ fileUtil.readFile(buildscriptDir + "build_notice.txt");
//Manually set the loader on the dependencies object. Ideally the buildUtil.loadDependencyList() function
//and subfunctions would take kwArgs directly.
dependencies.loader = kwArgs.loader;
//Build the layer contents.
var depResult = buildUtil.makeDojoJs(buildUtil.loadDependencyList(kwArgs.profileProperties, null, buildscriptDir), kwArgs.version, kwArgs);
//Grab the content from the "dojo.xd.js" layer.
var layerName = depResult[1].layerName;
var layerContents = depResult[1].contents;
//Burn in xd path for dojo if requested, and only do this in dojo.xd.js.
if(layerName.match(/dojo\.xd\.js/) && kwArgs.xdDojoPath){
layerContents = buildUtilXd.setXdDojoConfig(layerContents, kwArgs.xdDojoPath);
}
//Intern strings
if(kwArgs.internStrings){
prefixes = dependencies["prefixes"] || [];
var skiplist = dependencies["internSkipList"] || [];
layerContents = buildUtil.interningRegexpMagic(layerName, layerContents, dojoDir, prefixes, skiplist);
}
//Minify the contents
return optimizeJs(layerName, layerContents, layerLegalText, kwArgs.layerOptimize, "");
}
};
| ozoneplatform/owf-framework | web-app/js-lib/dojo-release-1.5.0-src/util/buildscripts/webbuild/server/js/build.js | JavaScript | apache-2.0 | 6,787 |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* pschwartau@netscape.com
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
/*
* Date: 17 September 2001
*
* SUMMARY: Regression test for Bugzilla bug 100199
* See http://bugzilla.mozilla.org/show_bug.cgi?id=100199
*
* The empty character class [] is a valid RegExp construct: the condition
* that a given character belong to a set containing no characters. As such,
* it can never be met and is always FALSE. Similarly, [^] is a condition
* that matches any given character and is always TRUE.
*
* Neither one of these conditions should cause syntax errors in a RegExp.
*/
//-----------------------------------------------------------------------------
var gTestfile = 'regress-100199.js';
var i = 0;
var BUGNUMBER = 100199;
var summary = '[], [^] are valid RegExp conditions. Should not cause errors -';
var status = '';
var statusmessages = new Array();
var pattern = '';
var patterns = new Array();
var string = '';
var strings = new Array();
var actualmatch = '';
var actualmatches = new Array();
var expectedmatch = '';
var expectedmatches = new Array();
pattern = /[]/;
string = 'abc';
status = inSection(1);
actualmatch = string.match(pattern);
expectedmatch = null;
addThis();
string = '';
status = inSection(2);
actualmatch = string.match(pattern);
expectedmatch = null;
addThis();
string = '[';
status = inSection(3);
actualmatch = string.match(pattern);
expectedmatch = null;
addThis();
string = '/';
status = inSection(4);
actualmatch = string.match(pattern);
expectedmatch = null;
addThis();
string = '[';
status = inSection(5);
actualmatch = string.match(pattern);
expectedmatch = null;
addThis();
string = ']';
status = inSection(6);
actualmatch = string.match(pattern);
expectedmatch = null;
addThis();
string = '[]';
status = inSection(7);
actualmatch = string.match(pattern);
expectedmatch = null;
addThis();
string = '[ ]';
status = inSection(8);
actualmatch = string.match(pattern);
expectedmatch = null;
addThis();
string = '][';
status = inSection(9);
actualmatch = string.match(pattern);
expectedmatch = null;
addThis();
pattern = /a[]/;
string = 'abc';
status = inSection(10);
actualmatch = string.match(pattern);
expectedmatch = null;
addThis();
string = '';
status = inSection(11);
actualmatch = string.match(pattern);
expectedmatch = null;
addThis();
string = 'a[';
status = inSection(12);
actualmatch = string.match(pattern);
expectedmatch = null;
addThis();
string = 'a[]';
status = inSection(13);
actualmatch = string.match(pattern);
expectedmatch = null;
addThis();
string = '[';
status = inSection(14);
actualmatch = string.match(pattern);
expectedmatch = null;
addThis();
string = ']';
status = inSection(15);
actualmatch = string.match(pattern);
expectedmatch = null;
addThis();
string = '[]';
status = inSection(16);
actualmatch = string.match(pattern);
expectedmatch = null;
addThis();
string = '[ ]';
status = inSection(17);
actualmatch = string.match(pattern);
expectedmatch = null;
addThis();
string = '][';
status = inSection(18);
actualmatch = string.match(pattern);
expectedmatch = null;
addThis();
pattern = /[^]/;
string = 'abc';
status = inSection(19);
actualmatch = string.match(pattern);
expectedmatch = Array('a');
addThis();
string = '';
status = inSection(20);
actualmatch = string.match(pattern);
expectedmatch = null; //there are no characters to test against the condition
addThis();
string = '\/';
status = inSection(21);
actualmatch = string.match(pattern);
expectedmatch = Array('/');
addThis();
string = '\[';
status = inSection(22);
actualmatch = string.match(pattern);
expectedmatch = Array('[');
addThis();
string = '[';
status = inSection(23);
actualmatch = string.match(pattern);
expectedmatch = Array('[');
addThis();
string = ']';
status = inSection(24);
actualmatch = string.match(pattern);
expectedmatch = Array(']');
addThis();
string = '[]';
status = inSection(25);
actualmatch = string.match(pattern);
expectedmatch = Array('[');
addThis();
string = '[ ]';
status = inSection(26);
actualmatch = string.match(pattern);
expectedmatch = Array('[');
addThis();
string = '][';
status = inSection(27);
actualmatch = string.match(pattern);
expectedmatch = Array(']');
addThis();
pattern = /a[^]/;
string = 'abc';
status = inSection(28);
actualmatch = string.match(pattern);
expectedmatch = Array('ab');
addThis();
string = '';
status = inSection(29);
actualmatch = string.match(pattern);
expectedmatch = null; //there are no characters to test against the condition
addThis();
string = 'a[';
status = inSection(30);
actualmatch = string.match(pattern);
expectedmatch = Array('a[');
addThis();
string = 'a]';
status = inSection(31);
actualmatch = string.match(pattern);
expectedmatch = Array('a]');
addThis();
string = 'a[]';
status = inSection(32);
actualmatch = string.match(pattern);
expectedmatch = Array('a[');
addThis();
string = 'a[ ]';
status = inSection(33);
actualmatch = string.match(pattern);
expectedmatch = Array('a[');
addThis();
string = 'a][';
status = inSection(34);
actualmatch = string.match(pattern);
expectedmatch = Array('a]');
addThis();
//-----------------------------------------------------------------------------
test();
//-----------------------------------------------------------------------------
function addThis()
{
statusmessages[i] = status;
patterns[i] = pattern;
strings[i] = string;
actualmatches[i] = actualmatch;
expectedmatches[i] = expectedmatch;
i++;
}
function test()
{
enterFunc ('test');
printBugNumber(BUGNUMBER);
printStatus (summary);
testRegExp(statusmessages, patterns, strings, actualmatches, expectedmatches);
exitFunc ('test');
}
| igor-sfdc/qt-wk | tests/auto/qscriptjstestsuite/tests/ecma_3/RegExp/regress-100199.js | JavaScript | lgpl-2.1 | 7,363 |
//=require rich/base | Nimdis/rich | test/dummy/app/assets/javascripts/rich.js | JavaScript | mit | 20 |
var Notify = require('../');
var notifier = new Notify();
notifier.notify({
"title": "Phil Coulson",
"subtitle": "Agent of S.H.I.E.L.D.",
"message": "If I come out, will you shoot me? 'Cause then I won't come out.",
"sound": "Funk", // case sensitive
"appIcon": __dirname + "/coulson.jpg",
"contentImage": __dirname + "/coulson.jpg",
"open": "file://" + __dirname + "/coulson.jpg"
});
setTimeout(function() {
console.log("Done");
}, 5000); | digisavvy/pureallex | wp-content/themes/pureallax/node_modules/gulp-notify/node_modules/node-notifier/example/advanced.js | JavaScript | gpl-2.0 | 457 |
var numLimitInput = element(by.model('numLimit'));
var letterLimitInput = element(by.model('letterLimit'));
var longNumberLimitInput = element(by.model('longNumberLimit'));
var limitedNumbers = element(by.binding('numbers | limitTo:numLimit'));
var limitedLetters = element(by.binding('letters | limitTo:letterLimit'));
var limitedLongNumber = element(by.binding('longNumber | limitTo:longNumberLimit'));
it('should limit the number array to first three items', function() {
expect(numLimitInput.getAttribute('value')).toBe('3');
expect(letterLimitInput.getAttribute('value')).toBe('3');
expect(longNumberLimitInput.getAttribute('value')).toBe('3');
expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]');
expect(limitedLetters.getText()).toEqual('Output letters: abc');
expect(limitedLongNumber.getText()).toEqual('Output long number: 234');
});
// There is a bug in safari and protractor that doesn't like the minus key
// it('should update the output when -3 is entered', function() {
// numLimitInput.clear();
// numLimitInput.sendKeys('-3');
// letterLimitInput.clear();
// letterLimitInput.sendKeys('-3');
// longNumberLimitInput.clear();
// longNumberLimitInput.sendKeys('-3');
// expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]');
// expect(limitedLetters.getText()).toEqual('Output letters: ghi');
// expect(limitedLongNumber.getText()).toEqual('Output long number: 342');
// });
it('should not exceed the maximum size of input array', function() {
numLimitInput.clear();
numLimitInput.sendKeys('100');
letterLimitInput.clear();
letterLimitInput.sendKeys('100');
longNumberLimitInput.clear();
longNumberLimitInput.sendKeys('100');
expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]');
expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi');
expect(limitedLongNumber.getText()).toEqual('Output long number: 2345432342');
}); | viral810/ngSimpleCMS | web/bundles/sunraangular/js/angular/angular-1.3.3/docs/examples/example-example102/protractor.js | JavaScript | mit | 2,030 |
/**
* @license AngularJS v1.6.10
* (c) 2010-2018 Google, Inc. http://angularjs.org
* License: MIT
*/
(function(window, angular) {'use strict';
var $resourceMinErr = angular.$$minErr('$resource');
// Helper functions and regex to lookup a dotted path on an object
// stopping at undefined/null. The path must be composed of ASCII
// identifiers (just like $parse)
var MEMBER_NAME_REGEX = /^(\.[a-zA-Z_$@][0-9a-zA-Z_$@]*)+$/;
function isValidDottedPath(path) {
return (path != null && path !== '' && path !== 'hasOwnProperty' &&
MEMBER_NAME_REGEX.test('.' + path));
}
function lookupDottedPath(obj, path) {
if (!isValidDottedPath(path)) {
throw $resourceMinErr('badmember', 'Dotted member path "@{0}" is invalid.', path);
}
var keys = path.split('.');
for (var i = 0, ii = keys.length; i < ii && angular.isDefined(obj); i++) {
var key = keys[i];
obj = (obj !== null) ? obj[key] : undefined;
}
return obj;
}
/**
* Create a shallow copy of an object and clear other fields from the destination
*/
function shallowClearAndCopy(src, dst) {
dst = dst || {};
angular.forEach(dst, function(value, key) {
delete dst[key];
});
for (var key in src) {
if (src.hasOwnProperty(key) && !(key.charAt(0) === '$' && key.charAt(1) === '$')) {
dst[key] = src[key];
}
}
return dst;
}
/**
* @ngdoc module
* @name ngResource
* @description
*
* The `ngResource` module provides interaction support with RESTful services
* via the $resource service.
*
* See {@link ngResource.$resourceProvider} and {@link ngResource.$resource} for usage.
*/
/**
* @ngdoc provider
* @name $resourceProvider
*
* @description
*
* Use `$resourceProvider` to change the default behavior of the {@link ngResource.$resource}
* service.
*
* ## Dependencies
* Requires the {@link ngResource } module to be installed.
*
*/
/**
* @ngdoc service
* @name $resource
* @requires $http
* @requires ng.$log
* @requires $q
* @requires ng.$timeout
*
* @description
* A factory which creates a resource object that lets you interact with
* [RESTful](http://en.wikipedia.org/wiki/Representational_State_Transfer) server-side data sources.
*
* The returned resource object has action methods which provide high-level behaviors without
* the need to interact with the low level {@link ng.$http $http} service.
*
* Requires the {@link ngResource `ngResource`} module to be installed.
*
* By default, trailing slashes will be stripped from the calculated URLs,
* which can pose problems with server backends that do not expect that
* behavior. This can be disabled by configuring the `$resourceProvider` like
* this:
*
* ```js
app.config(['$resourceProvider', function($resourceProvider) {
// Don't strip trailing slashes from calculated URLs
$resourceProvider.defaults.stripTrailingSlashes = false;
}]);
* ```
*
* @param {string} url A parameterized URL template with parameters prefixed by `:` as in
* `/user/:username`. If you are using a URL with a port number (e.g.
* `http://example.com:8080/api`), it will be respected.
*
* If you are using a url with a suffix, just add the suffix, like this:
* `$resource('http://example.com/resource.json')` or `$resource('http://example.com/:id.json')`
* or even `$resource('http://example.com/resource/:resource_id.:format')`
* If the parameter before the suffix is empty, :resource_id in this case, then the `/.` will be
* collapsed down to a single `.`. If you need this sequence to appear and not collapse then you
* can escape it with `/\.`.
*
* @param {Object=} paramDefaults Default values for `url` parameters. These can be overridden in
* `actions` methods. If a parameter value is a function, it will be called every time
* a param value needs to be obtained for a request (unless the param was overridden). The function
* will be passed the current data value as an argument.
*
* Each key value in the parameter object is first bound to url template if present and then any
* excess keys are appended to the url search query after the `?`.
*
* Given a template `/path/:verb` and parameter `{verb:'greet', salutation:'Hello'}` results in
* URL `/path/greet?salutation=Hello`.
*
* If the parameter value is prefixed with `@`, then the value for that parameter will be
* extracted from the corresponding property on the `data` object (provided when calling actions
* with a request body).
* For example, if the `defaultParam` object is `{someParam: '@someProp'}` then the value of
* `someParam` will be `data.someProp`.
* Note that the parameter will be ignored, when calling a "GET" action method (i.e. an action
* method that does not accept a request body)
*
* @param {Object.<Object>=} actions Hash with declaration of custom actions that will be available
* in addition to the default set of resource actions (see below). If a custom action has the same
* key as a default action (e.g. `save`), then the default action will be *overwritten*, and not
* extended.
*
* The declaration should be created in the format of {@link ng.$http#usage $http.config}:
*
* {action1: {method:?, params:?, isArray:?, headers:?, ...},
* action2: {method:?, params:?, isArray:?, headers:?, ...},
* ...}
*
* Where:
*
* - **`action`** – {string} – The name of action. This name becomes the name of the method on
* your resource object.
* - **`method`** – {string} – Case insensitive HTTP method (e.g. `GET`, `POST`, `PUT`,
* `DELETE`, `JSONP`, etc).
* - **`params`** – {Object=} – Optional set of pre-bound parameters for this action. If any of
* the parameter value is a function, it will be called every time when a param value needs to
* be obtained for a request (unless the param was overridden). The function will be passed the
* current data value as an argument.
* - **`url`** – {string} – action specific `url` override. The url templating is supported just
* like for the resource-level urls.
* - **`isArray`** – {boolean=} – If true then the returned object for this action is an array,
* see `returns` section.
* - **`transformRequest`** –
* `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
* transform function or an array of such functions. The transform function takes the http
* request body and headers and returns its transformed (typically serialized) version.
* By default, transformRequest will contain one function that checks if the request data is
* an object and serializes it using `angular.toJson`. To prevent this behavior, set
* `transformRequest` to an empty array: `transformRequest: []`
* - **`transformResponse`** –
* `{function(data, headersGetter, status)|Array.<function(data, headersGetter, status)>}` –
* transform function or an array of such functions. The transform function takes the http
* response body, headers and status and returns its transformed (typically deserialized)
* version.
* By default, transformResponse will contain one function that checks if the response looks
* like a JSON string and deserializes it using `angular.fromJson`. To prevent this behavior,
* set `transformResponse` to an empty array: `transformResponse: []`
* - **`cache`** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the
* GET request, otherwise if a cache instance built with
* {@link ng.$cacheFactory $cacheFactory} is supplied, this cache will be used for
* caching.
* - **`timeout`** – `{number}` – timeout in milliseconds.<br />
* **Note:** In contrast to {@link ng.$http#usage $http.config}, {@link ng.$q promises} are
* **not** supported in $resource, because the same value would be used for multiple requests.
* If you are looking for a way to cancel requests, you should use the `cancellable` option.
* - **`cancellable`** – `{boolean}` – if set to true, the request made by a "non-instance" call
* will be cancelled (if not already completed) by calling `$cancelRequest()` on the call's
* return value. Calling `$cancelRequest()` for a non-cancellable or an already
* completed/cancelled request will have no effect.<br />
* - **`withCredentials`** - `{boolean}` - whether to set the `withCredentials` flag on the
* XHR object. See
* [requests with credentials](https://developer.mozilla.org/en/http_access_control#section_5)
* for more information.
* - **`responseType`** - `{string}` - see
* [requestType](https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType).
* - **`interceptor`** - `{Object=}` - The interceptor object has two optional methods -
* `response` and `responseError`. Both `response` and `responseError` interceptors get called
* with `http response` object. See {@link ng.$http $http interceptors}. In addition, the
* resource instance or array object is accessible by the `resource` property of the
* `http response` object.
* Keep in mind that the associated promise will be resolved with the value returned by the
* response interceptor, if one is specified. The default response interceptor returns
* `response.resource` (i.e. the resource instance or array).
* - **`hasBody`** - `{boolean}` - allows to specify if a request body should be included or not.
* If not specified only POST, PUT and PATCH requests will have a body.
*
* @param {Object} options Hash with custom settings that should extend the
* default `$resourceProvider` behavior. The supported options are:
*
* - **`stripTrailingSlashes`** – {boolean} – If true then the trailing
* slashes from any calculated URL will be stripped. (Defaults to true.)
* - **`cancellable`** – {boolean} – If true, the request made by a "non-instance" call will be
* cancelled (if not already completed) by calling `$cancelRequest()` on the call's return value.
* This can be overwritten per action. (Defaults to false.)
*
* @returns {Object} A resource "class" object with methods for the default set of resource actions
* optionally extended with custom `actions`. The default set contains these actions:
* ```js
* { 'get': {method:'GET'},
* 'save': {method:'POST'},
* 'query': {method:'GET', isArray:true},
* 'remove': {method:'DELETE'},
* 'delete': {method:'DELETE'} };
* ```
*
* Calling these methods invoke an {@link ng.$http} with the specified http method,
* destination and parameters. When the data is returned from the server then the object is an
* instance of the resource class. The actions `save`, `remove` and `delete` are available on it
* as methods with the `$` prefix. This allows you to easily perform CRUD operations (create,
* read, update, delete) on server-side data like this:
* ```js
* var User = $resource('/user/:userId', {userId:'@id'});
* var user = User.get({userId:123}, function() {
* user.abc = true;
* user.$save();
* });
* ```
*
* It is important to realize that invoking a $resource object method immediately returns an
* empty reference (object or array depending on `isArray`). Once the data is returned from the
* server the existing reference is populated with the actual data. This is a useful trick since
* usually the resource is assigned to a model which is then rendered by the view. Having an empty
* object results in no rendering, once the data arrives from the server then the object is
* populated with the data and the view automatically re-renders itself showing the new data. This
* means that in most cases one never has to write a callback function for the action methods.
*
* The action methods on the class object or instance object can be invoked with the following
* parameters:
*
* - "class" actions without a body: `Resource.action([parameters], [success], [error])`
* - "class" actions with a body: `Resource.action([parameters], postData, [success], [error])`
* - instance actions: `instance.$action([parameters], [success], [error])`
*
*
* When calling instance methods, the instance itself is used as the request body (if the action
* should have a body). By default, only actions using `POST`, `PUT` or `PATCH` have request
* bodies, but you can use the `hasBody` configuration option to specify whether an action
* should have a body or not (regardless of its HTTP method).
*
*
* Success callback is called with (value (Object|Array), responseHeaders (Function),
* status (number), statusText (string)) arguments, where the value is the populated resource
* instance or collection object. The error callback is called with (httpResponse) argument.
*
* Class actions return empty instance (with additional properties below).
* Instance actions return promise of the action.
*
* The Resource instances and collections have these additional properties:
*
* - `$promise`: the {@link ng.$q promise} of the original server interaction that created this
* instance or collection.
*
* On success, the promise is resolved with the same resource instance or collection object,
* updated with data from server. This makes it easy to use in
* {@link ngRoute.$routeProvider resolve section of $routeProvider.when()} to defer view
* rendering until the resource(s) are loaded.
*
* On failure, the promise is rejected with the {@link ng.$http http response} object.
*
* If an interceptor object was provided, the promise will instead be resolved with the value
* returned by the interceptor.
*
* - `$resolved`: `true` after first server interaction is completed (either with success or
* rejection), `false` before that. Knowing if the Resource has been resolved is useful in
* data-binding.
*
* The Resource instances and collections have these additional methods:
*
* - `$cancelRequest`: If there is a cancellable, pending request related to the instance or
* collection, calling this method will abort the request.
*
* The Resource instances have these additional methods:
*
* - `toJSON`: It returns a simple object without any of the extra properties added as part of
* the Resource API. This object can be serialized through {@link angular.toJson} safely
* without attaching AngularJS-specific fields. Notice that `JSON.stringify` (and
* `angular.toJson`) automatically use this method when serializing a Resource instance
* (see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#toJSON%28%29_behavior)).
*
* @example
*
* ### Credit card resource
*
* ```js
// Define CreditCard class
var CreditCard = $resource('/user/:userId/card/:cardId',
{userId:123, cardId:'@id'}, {
charge: {method:'POST', params:{charge:true}}
});
// We can retrieve a collection from the server
var cards = CreditCard.query(function() {
// GET: /user/123/card
// server returns: [ {id:456, number:'1234', name:'Smith'} ];
var card = cards[0];
// each item is an instance of CreditCard
expect(card instanceof CreditCard).toEqual(true);
card.name = "J. Smith";
// non GET methods are mapped onto the instances
card.$save();
// POST: /user/123/card/456 {id:456, number:'1234', name:'J. Smith'}
// server returns: {id:456, number:'1234', name: 'J. Smith'};
// our custom method is mapped as well.
card.$charge({amount:9.99});
// POST: /user/123/card/456?amount=9.99&charge=true {id:456, number:'1234', name:'J. Smith'}
});
// we can create an instance as well
var newCard = new CreditCard({number:'0123'});
newCard.name = "Mike Smith";
newCard.$save();
// POST: /user/123/card {number:'0123', name:'Mike Smith'}
// server returns: {id:789, number:'0123', name: 'Mike Smith'};
expect(newCard.id).toEqual(789);
* ```
*
* The object returned from this function execution is a resource "class" which has "static" method
* for each action in the definition.
*
* Calling these methods invoke `$http` on the `url` template with the given `method`, `params` and
* `headers`.
*
* @example
*
* ### User resource
*
* When the data is returned from the server then the object is an instance of the resource type and
* all of the non-GET methods are available with `$` prefix. This allows you to easily support CRUD
* operations (create, read, update, delete) on server-side data.
```js
var User = $resource('/user/:userId', {userId:'@id'});
User.get({userId:123}, function(user) {
user.abc = true;
user.$save();
});
```
*
* It's worth noting that the success callback for `get`, `query` and other methods gets passed
* in the response that came from the server as well as $http header getter function, so one
* could rewrite the above example and get access to http headers as:
*
```js
var User = $resource('/user/:userId', {userId:'@id'});
User.get({userId:123}, function(user, getResponseHeaders){
user.abc = true;
user.$save(function(user, putResponseHeaders) {
//user => saved user object
//putResponseHeaders => $http header getter
});
});
```
*
* You can also access the raw `$http` promise via the `$promise` property on the object returned
*
```
var User = $resource('/user/:userId', {userId:'@id'});
User.get({userId:123})
.$promise.then(function(user) {
$scope.user = user;
});
```
*
* @example
*
* ### Creating a custom 'PUT' request
*
* In this example we create a custom method on our resource to make a PUT request
* ```js
* var app = angular.module('app', ['ngResource', 'ngRoute']);
*
* // Some APIs expect a PUT request in the format URL/object/ID
* // Here we are creating an 'update' method
* app.factory('Notes', ['$resource', function($resource) {
* return $resource('/notes/:id', null,
* {
* 'update': { method:'PUT' }
* });
* }]);
*
* // In our controller we get the ID from the URL using ngRoute and $routeParams
* // We pass in $routeParams and our Notes factory along with $scope
* app.controller('NotesCtrl', ['$scope', '$routeParams', 'Notes',
function($scope, $routeParams, Notes) {
* // First get a note object from the factory
* var note = Notes.get({ id:$routeParams.id });
* $id = note.id;
*
* // Now call update passing in the ID first then the object you are updating
* Notes.update({ id:$id }, note);
*
* // This will PUT /notes/ID with the note object in the request payload
* }]);
* ```
*
* @example
*
* ### Cancelling requests
*
* If an action's configuration specifies that it is cancellable, you can cancel the request related
* to an instance or collection (as long as it is a result of a "non-instance" call):
*
```js
// ...defining the `Hotel` resource...
var Hotel = $resource('/api/hotel/:id', {id: '@id'}, {
// Let's make the `query()` method cancellable
query: {method: 'get', isArray: true, cancellable: true}
});
// ...somewhere in the PlanVacationController...
...
this.onDestinationChanged = function onDestinationChanged(destination) {
// We don't care about any pending request for hotels
// in a different destination any more
this.availableHotels.$cancelRequest();
// Let's query for hotels in '<destination>'
// (calls: /api/hotel?location=<destination>)
this.availableHotels = Hotel.query({location: destination});
};
```
*
*/
angular.module('ngResource', ['ng']).
info({ angularVersion: '1.6.10' }).
provider('$resource', function ResourceProvider() {
var PROTOCOL_AND_IPV6_REGEX = /^https?:\/\/\[[^\]]*][^/]*/;
var provider = this;
/**
* @ngdoc property
* @name $resourceProvider#defaults
* @description
* Object containing default options used when creating `$resource` instances.
*
* The default values satisfy a wide range of usecases, but you may choose to overwrite any of
* them to further customize your instances. The available properties are:
*
* - **stripTrailingSlashes** – `{boolean}` – If true, then the trailing slashes from any
* calculated URL will be stripped.<br />
* (Defaults to true.)
* - **cancellable** – `{boolean}` – If true, the request made by a "non-instance" call will be
* cancelled (if not already completed) by calling `$cancelRequest()` on the call's return
* value. For more details, see {@link ngResource.$resource}. This can be overwritten per
* resource class or action.<br />
* (Defaults to false.)
* - **actions** - `{Object.<Object>}` - A hash with default actions declarations. Actions are
* high-level methods corresponding to RESTful actions/methods on resources. An action may
* specify what HTTP method to use, what URL to hit, if the return value will be a single
* object or a collection (array) of objects etc. For more details, see
* {@link ngResource.$resource}. The actions can also be enhanced or overwritten per resource
* class.<br />
* The default actions are:
* ```js
* {
* get: {method: 'GET'},
* save: {method: 'POST'},
* query: {method: 'GET', isArray: true},
* remove: {method: 'DELETE'},
* delete: {method: 'DELETE'}
* }
* ```
*
* #### Example
*
* For example, you can specify a new `update` action that uses the `PUT` HTTP verb:
*
* ```js
* angular.
* module('myApp').
* config(['$resourceProvider', function ($resourceProvider) {
* $resourceProvider.defaults.actions.update = {
* method: 'PUT'
* };
* }]);
* ```
*
* Or you can even overwrite the whole `actions` list and specify your own:
*
* ```js
* angular.
* module('myApp').
* config(['$resourceProvider', function ($resourceProvider) {
* $resourceProvider.defaults.actions = {
* create: {method: 'POST'},
* get: {method: 'GET'},
* getAll: {method: 'GET', isArray:true},
* update: {method: 'PUT'},
* delete: {method: 'DELETE'}
* };
* });
* ```
*
*/
this.defaults = {
// Strip slashes by default
stripTrailingSlashes: true,
// Make non-instance requests cancellable (via `$cancelRequest()`)
cancellable: false,
// Default actions configuration
actions: {
'get': {method: 'GET'},
'save': {method: 'POST'},
'query': {method: 'GET', isArray: true},
'remove': {method: 'DELETE'},
'delete': {method: 'DELETE'}
}
};
this.$get = ['$http', '$log', '$q', '$timeout', function($http, $log, $q, $timeout) {
var noop = angular.noop,
forEach = angular.forEach,
extend = angular.extend,
copy = angular.copy,
isArray = angular.isArray,
isDefined = angular.isDefined,
isFunction = angular.isFunction,
isNumber = angular.isNumber,
encodeUriQuery = angular.$$encodeUriQuery,
encodeUriSegment = angular.$$encodeUriSegment;
function Route(template, defaults) {
this.template = template;
this.defaults = extend({}, provider.defaults, defaults);
this.urlParams = {};
}
Route.prototype = {
setUrlParams: function(config, params, actionUrl) {
var self = this,
url = actionUrl || self.template,
val,
encodedVal,
protocolAndIpv6 = '';
var urlParams = self.urlParams = Object.create(null);
forEach(url.split(/\W/), function(param) {
if (param === 'hasOwnProperty') {
throw $resourceMinErr('badname', 'hasOwnProperty is not a valid parameter name.');
}
if (!(new RegExp('^\\d+$').test(param)) && param &&
(new RegExp('(^|[^\\\\]):' + param + '(\\W|$)').test(url))) {
urlParams[param] = {
isQueryParamValue: (new RegExp('\\?.*=:' + param + '(?:\\W|$)')).test(url)
};
}
});
url = url.replace(/\\:/g, ':');
url = url.replace(PROTOCOL_AND_IPV6_REGEX, function(match) {
protocolAndIpv6 = match;
return '';
});
params = params || {};
forEach(self.urlParams, function(paramInfo, urlParam) {
val = params.hasOwnProperty(urlParam) ? params[urlParam] : self.defaults[urlParam];
if (isDefined(val) && val !== null) {
if (paramInfo.isQueryParamValue) {
encodedVal = encodeUriQuery(val, true);
} else {
encodedVal = encodeUriSegment(val);
}
url = url.replace(new RegExp(':' + urlParam + '(\\W|$)', 'g'), function(match, p1) {
return encodedVal + p1;
});
} else {
url = url.replace(new RegExp('(/?):' + urlParam + '(\\W|$)', 'g'), function(match,
leadingSlashes, tail) {
if (tail.charAt(0) === '/') {
return tail;
} else {
return leadingSlashes + tail;
}
});
}
});
// strip trailing slashes and set the url (unless this behavior is specifically disabled)
if (self.defaults.stripTrailingSlashes) {
url = url.replace(/\/+$/, '') || '/';
}
// Collapse `/.` if found in the last URL path segment before the query.
// E.g. `http://url.com/id/.format?q=x` becomes `http://url.com/id.format?q=x`.
url = url.replace(/\/\.(?=\w+($|\?))/, '.');
// Replace escaped `/\.` with `/.`.
// (If `\.` comes from a param value, it will be encoded as `%5C.`.)
config.url = protocolAndIpv6 + url.replace(/\/(\\|%5C)\./, '/.');
// set params - delegate param encoding to $http
forEach(params, function(value, key) {
if (!self.urlParams[key]) {
config.params = config.params || {};
config.params[key] = value;
}
});
}
};
function resourceFactory(url, paramDefaults, actions, options) {
var route = new Route(url, options);
actions = extend({}, provider.defaults.actions, actions);
function extractParams(data, actionParams) {
var ids = {};
actionParams = extend({}, paramDefaults, actionParams);
forEach(actionParams, function(value, key) {
if (isFunction(value)) { value = value(data); }
ids[key] = value && value.charAt && value.charAt(0) === '@' ?
lookupDottedPath(data, value.substr(1)) : value;
});
return ids;
}
function defaultResponseInterceptor(response) {
return response.resource;
}
function Resource(value) {
shallowClearAndCopy(value || {}, this);
}
Resource.prototype.toJSON = function() {
var data = extend({}, this);
delete data.$promise;
delete data.$resolved;
delete data.$cancelRequest;
return data;
};
forEach(actions, function(action, name) {
var hasBody = action.hasBody === true || (action.hasBody !== false && /^(POST|PUT|PATCH)$/i.test(action.method));
var numericTimeout = action.timeout;
var cancellable = isDefined(action.cancellable) ?
action.cancellable : route.defaults.cancellable;
if (numericTimeout && !isNumber(numericTimeout)) {
$log.debug('ngResource:\n' +
' Only numeric values are allowed as `timeout`.\n' +
' Promises are not supported in $resource, because the same value would ' +
'be used for multiple requests. If you are looking for a way to cancel ' +
'requests, you should use the `cancellable` option.');
delete action.timeout;
numericTimeout = null;
}
Resource[name] = function(a1, a2, a3, a4) {
var params = {}, data, success, error;
switch (arguments.length) {
case 4:
error = a4;
success = a3;
// falls through
case 3:
case 2:
if (isFunction(a2)) {
if (isFunction(a1)) {
success = a1;
error = a2;
break;
}
success = a2;
error = a3;
// falls through
} else {
params = a1;
data = a2;
success = a3;
break;
}
// falls through
case 1:
if (isFunction(a1)) success = a1;
else if (hasBody) data = a1;
else params = a1;
break;
case 0: break;
default:
throw $resourceMinErr('badargs',
'Expected up to 4 arguments [params, data, success, error], got {0} arguments',
arguments.length);
}
var isInstanceCall = this instanceof Resource;
var value = isInstanceCall ? data : (action.isArray ? [] : new Resource(data));
var httpConfig = {};
var responseInterceptor = action.interceptor && action.interceptor.response ||
defaultResponseInterceptor;
var responseErrorInterceptor = action.interceptor && action.interceptor.responseError ||
undefined;
var hasError = !!error;
var hasResponseErrorInterceptor = !!responseErrorInterceptor;
var timeoutDeferred;
var numericTimeoutPromise;
forEach(action, function(value, key) {
switch (key) {
default:
httpConfig[key] = copy(value);
break;
case 'params':
case 'isArray':
case 'interceptor':
case 'cancellable':
break;
}
});
if (!isInstanceCall && cancellable) {
timeoutDeferred = $q.defer();
httpConfig.timeout = timeoutDeferred.promise;
if (numericTimeout) {
numericTimeoutPromise = $timeout(timeoutDeferred.resolve, numericTimeout);
}
}
if (hasBody) httpConfig.data = data;
route.setUrlParams(httpConfig,
extend({}, extractParams(data, action.params || {}), params),
action.url);
var promise = $http(httpConfig).then(function(response) {
var data = response.data;
if (data) {
// Need to convert action.isArray to boolean in case it is undefined
if (isArray(data) !== (!!action.isArray)) {
throw $resourceMinErr('badcfg',
'Error in resource configuration for action `{0}`. Expected response to ' +
'contain an {1} but got an {2} (Request: {3} {4})', name, action.isArray ? 'array' : 'object',
isArray(data) ? 'array' : 'object', httpConfig.method, httpConfig.url);
}
if (action.isArray) {
value.length = 0;
forEach(data, function(item) {
if (typeof item === 'object') {
value.push(new Resource(item));
} else {
// Valid JSON values may be string literals, and these should not be converted
// into objects. These items will not have access to the Resource prototype
// methods, but unfortunately there
value.push(item);
}
});
} else {
var promise = value.$promise; // Save the promise
shallowClearAndCopy(data, value);
value.$promise = promise; // Restore the promise
}
}
response.resource = value;
return response;
}, function(response) {
response.resource = value;
return $q.reject(response);
});
promise = promise['finally'](function() {
value.$resolved = true;
if (!isInstanceCall && cancellable) {
value.$cancelRequest = noop;
$timeout.cancel(numericTimeoutPromise);
timeoutDeferred = numericTimeoutPromise = httpConfig.timeout = null;
}
});
promise = promise.then(
function(response) {
var value = responseInterceptor(response);
(success || noop)(value, response.headers, response.status, response.statusText);
return value;
},
(hasError || hasResponseErrorInterceptor) ?
function(response) {
if (hasError && !hasResponseErrorInterceptor) {
// Avoid `Possibly Unhandled Rejection` error,
// but still fulfill the returned promise with a rejection
promise.catch(noop);
}
if (hasError) error(response);
return hasResponseErrorInterceptor ?
responseErrorInterceptor(response) :
$q.reject(response);
} :
undefined);
if (!isInstanceCall) {
// we are creating instance / collection
// - set the initial promise
// - return the instance / collection
value.$promise = promise;
value.$resolved = false;
if (cancellable) value.$cancelRequest = cancelRequest;
return value;
}
// instance call
return promise;
function cancelRequest(value) {
promise.catch(noop);
if (timeoutDeferred !== null) {
timeoutDeferred.resolve(value);
}
}
};
Resource.prototype['$' + name] = function(params, success, error) {
if (isFunction(params)) {
error = success; success = params; params = {};
}
var result = Resource[name].call(this, params, this, success, error);
return result.$promise || result;
};
});
return Resource;
}
return resourceFactory;
}];
});
})(window, window.angular);
| brat000012001/keycloak | themes/src/main/resources/theme/keycloak/common/resources/node_modules/angular-resource/angular-resource.js | JavaScript | apache-2.0 | 35,575 |
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Competency rule config.
*
* @package tool_lp
* @copyright 2015 Frédéric Massart - FMCorz.net
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
define(['jquery',
'core/str'],
function($, Str) {
var OUTCOME_NONE = 0,
OUTCOME_EVIDENCE = 1,
OUTCOME_COMPLETE = 2,
OUTCOME_RECOMMEND = 3;
return /** @alias module:tool_lp/competency_outcomes */ {
NONE: OUTCOME_NONE,
EVIDENCE: OUTCOME_EVIDENCE,
COMPLETE: OUTCOME_COMPLETE,
RECOMMEND: OUTCOME_RECOMMEND,
/**
* Get all the outcomes.
*
* @return {Object} Indexed by outcome code, contains code and name.
* @method getAll
*/
getAll: function() {
var self = this;
return Str.get_strings([
{ key: 'competencyoutcome_none', component: 'tool_lp' },
{ key: 'competencyoutcome_evidence', component: 'tool_lp' },
{ key: 'competencyoutcome_recommend', component: 'tool_lp' },
{ key: 'competencyoutcome_complete', component: 'tool_lp' },
]).then(function(strings) {
var outcomes = {};
outcomes[self.NONE] = { code: self.NONE, name: strings[0] };
outcomes[self.EVIDENCE] = { code: self.EVIDENCE, name: strings[1] };
outcomes[self.RECOMMEND] = { code: self.RECOMMEND, name: strings[2] };
outcomes[self.COMPLETE] = { code: self.COMPLETE, name: strings[3] };
return outcomes;
});
},
/**
* Get the string for an outcome.
*
* @param {Number} id The outcome code.
* @return {Promise Resolved with the string.
* @method getString
*/
getString: function(id) {
var self = this,
all = self.getAll();
return all.then(function(outcomes) {
if (typeof outcomes[id] === 'undefined') {
return $.Deferred().reject().promise();
}
return outcomes[id].name;
});
}
};
});
| tesler/cspt-moodle | moodle/admin/tool/lp/amd/src/competency_outcomes.js | JavaScript | mit | 2,874 |
/*
* Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* NASHORN-105 : parseFloat function is not spec. compliant.
*
* @test
* @run
*/
print(parseFloat("3.14xyz"));
print(parseFloat("2.18 43.4543"));
print(parseFloat("2.9e8E-45"));
print(parseFloat("55654.6756.4546"));
print(parseFloat("343e"));
print(parseFloat("343e+"));
print(parseFloat("343e-"));
print(parseFloat("343e+35"));
print(parseFloat("Infinity1"));
print(parseFloat("-Infinity1"));
print(parseFloat("1ex"));
print(parseFloat("2343+"));
print(parseFloat("2ex"));
// invalid stuff
print(parseFloat(""));
print(parseFloat("+"));
print(parseFloat("-"));
print(parseFloat("e"));
print(parseFloat("sjdfhdsj"));
| JetBrains/jdk8u_nashorn | test/script/basic/NASHORN-105.js | JavaScript | gpl-2.0 | 1,686 |
/****************************************************************************
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011-2012 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
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.
****************************************************************************/
/**
* <p>cc.Point extensions based on Chipmunk's cpVect file.<br />
* These extensions work both with cc.Point</p>
*
* <p>The "ccp" prefix means: "CoCos2d Point"</p>
*
* <p> //Examples:<br />
* - cc.pAdd( cc.p(1,1), cc.p(2,2) ); // preferred cocos2d way<br />
* - cc.pAdd( cc.p(1,1), cc.p(2,2) ); // also ok but more verbose<br />
* - cc.pAdd( cc.cpv(1,1), cc.cpv(2,2) ); // mixing chipmunk and cocos2d (avoid)</p>
*/
/**
* smallest such that 1.0+FLT_EPSILON != 1.0
* @constant
* @type Number
*/
cc.POINT_EPSILON = parseFloat('1.192092896e-07F');
/**
* Returns opposite of point.
* @param {cc.Point} point
* @return {cc.Point}
*/
cc.pNeg = function (point) {
return cc.p(-point.x, -point.y);
};
/**
* Calculates sum of two points.
* @param {cc.Point} v1
* @param {cc.Point} v2
* @return {cc.Point}
*/
cc.pAdd = function (v1, v2) {
return cc.p(v1.x + v2.x, v1.y + v2.y);
};
/**
* Calculates difference of two points.
* @param {cc.Point} v1
* @param {cc.Point} v2
* @return {cc.Point}
*/
cc.pSub = function (v1, v2) {
return cc.p(v1.x - v2.x, v1.y - v2.y);
};
/**
* Returns point multiplied by given factor.
* @param {cc.Point} point
* @param {Number} floatVar
* @return {cc.Point}
*/
cc.pMult = function (point, floatVar) {
return cc.p(point.x * floatVar, point.y * floatVar);
};
/**
* Calculates midpoint between two points.
* @param {cc.Point} v1
* @param {cc.Point} v2
* @return {cc.pMult}
*/
cc.pMidpoint = function (v1, v2) {
return cc.pMult(cc.pAdd(v1, v2), 0.5);
};
/**
* Calculates dot product of two points.
* @param {cc.Point} v1
* @param {cc.Point} v2
* @return {Number}
*/
cc.pDot = function (v1, v2) {
return v1.x * v2.x + v1.y * v2.y;
};
/**
* Calculates cross product of two points.
* @param {cc.Point} v1
* @param {cc.Point} v2
* @return {Number}
*/
cc.pCross = function (v1, v2) {
return v1.x * v2.y - v1.y * v2.x;
};
/**
* Calculates perpendicular of v, rotated 90 degrees counter-clockwise -- cross(v, perp(v)) >= 0
* @param {cc.Point} point
* @return {cc.Point}
*/
cc.pPerp = function (point) {
return cc.p(-point.y, point.x);
};
/**
* Calculates perpendicular of v, rotated 90 degrees clockwise -- cross(v, rperp(v)) <= 0
* @param {cc.Point} point
* @return {cc.Point}
*/
cc.pRPerp = function (point) {
return cc.p(point.y, -point.x);
};
/**
* Calculates the projection of v1 over v2.
* @param {cc.Point} v1
* @param {cc.Point} v2
* @return {cc.pMult}
*/
cc.pProject = function (v1, v2) {
return cc.pMult(v2, cc.pDot(v1, v2) / cc.pDot(v2, v2));
};
/**
* Rotates two points.
* @param {cc.Point} v1
* @param {cc.Point} v2
* @return {cc.Point}
*/
cc.pRotate = function (v1, v2) {
return cc.p(v1.x * v2.x - v1.y * v2.y, v1.x * v2.y + v1.y * v2.x);
};
/**
* Unrotates two points.
* @param {cc.Point} v1
* @param {cc.Point} v2
* @return {cc.Point}
*/
cc.pUnrotate = function (v1, v2) {
return cc.p(v1.x * v2.x + v1.y * v2.y, v1.y * v2.x - v1.x * v2.y);
};
/**
* Calculates the square length of a cc.Point (not calling sqrt() )
* @param {cc.Point} v
*@return {Number}
*/
cc.pLengthSQ = function (v) {
return cc.pDot(v, v);
};
/**
* Calculates the square distance between two points (not calling sqrt() )
* @param {cc.Point} point1
* @param {cc.Point} point2
* @return {Number}
*/
cc.pDistanceSQ = function(point1, point2){
return cc.pLengthSQ(cc.pSub(point1,point2));
};
/**
* Calculates distance between point an origin
* @param {cc.Point} v
* @return {Number}
*/
cc.pLength = function (v) {
return Math.sqrt(cc.pLengthSQ(v));
};
/**
* Calculates the distance between two points
* @param {cc.Point} v1
* @param {cc.Point} v2
* @return {Number}
*/
cc.pDistance = function (v1, v2) {
return cc.pLength(cc.pSub(v1, v2));
};
/**
* Returns point multiplied to a length of 1.
* @param {cc.Point} v
* @return {cc.Point}
*/
cc.pNormalize = function (v) {
var n = cc.pLength(v);
return n === 0 ? cc.p(v) : cc.pMult(v, 1.0 / n);
};
/**
* Converts radians to a normalized vector.
* @param {Number} a
* @return {cc.Point}
*/
cc.pForAngle = function (a) {
return cc.p(Math.cos(a), Math.sin(a));
};
/**
* Converts a vector to radians.
* @param {cc.Point} v
* @return {Number}
*/
cc.pToAngle = function (v) {
return Math.atan2(v.y, v.x);
};
/**
* Clamp a value between from and to.
* @param {Number} value
* @param {Number} min_inclusive
* @param {Number} max_inclusive
* @return {Number}
*/
cc.clampf = function (value, min_inclusive, max_inclusive) {
if (min_inclusive > max_inclusive) {
var temp = min_inclusive;
min_inclusive = max_inclusive;
max_inclusive = temp;
}
return value < min_inclusive ? min_inclusive : value < max_inclusive ? value : max_inclusive;
};
/**
* Clamp a point between from and to.
* @param {Point} p
* @param {Number} min_inclusive
* @param {Number} max_inclusive
* @return {cc.Point}
*/
cc.pClamp = function (p, min_inclusive, max_inclusive) {
return cc.p(cc.clampf(p.x, min_inclusive.x, max_inclusive.x), cc.clampf(p.y, min_inclusive.y, max_inclusive.y));
};
/**
* Quickly convert cc.Size to a cc.Point
* @param {cc.Size} s
* @return {cc.Point}
*/
cc.pFromSize = function (s) {
return cc.p(s.width, s.height);
};
/**
* Run a math operation function on each point component <br />
* Math.abs, Math.fllor, Math.ceil, Math.round.
* @param {cc.Point} p
* @param {Function} opFunc
* @return {cc.Point}
* @example
* //For example: let's try to take the floor of x,y
* var p = cc.pCompOp(cc.p(10,10),Math.abs);
*/
cc.pCompOp = function (p, opFunc) {
return cc.p(opFunc(p.x), opFunc(p.y));
};
/**
* Linear Interpolation between two points a and b
* alpha == 0 ? a
* alpha == 1 ? b
* otherwise a value between a..b
* @param {cc.Point} a
* @param {cc.Point} b
* @param {Number} alpha
* @return {cc.pAdd}
*/
cc.pLerp = function (a, b, alpha) {
return cc.pAdd(cc.pMult(a, 1 - alpha), cc.pMult(b, alpha));
};
/**
* @param {cc.Point} a
* @param {cc.Point} b
* @param {Number} variance
* @return {Boolean} if points have fuzzy equality which means equal with some degree of variance.
*/
cc.pFuzzyEqual = function (a, b, variance) {
if (a.x - variance <= b.x && b.x <= a.x + variance) {
if (a.y - variance <= b.y && b.y <= a.y + variance)
return true;
}
return false;
};
/**
* Multiplies a nd b components, a.x*b.x, a.y*b.y
* @param {cc.Point} a
* @param {cc.Point} b
* @return {cc.Point}
*/
cc.pCompMult = function (a, b) {
return cc.p(a.x * b.x, a.y * b.y);
};
/**
* @param {cc.Point} a
* @param {cc.Point} b
* @return {Number} the signed angle in radians between two vector directions
*/
cc.pAngleSigned = function (a, b) {
var a2 = cc.pNormalize(a);
var b2 = cc.pNormalize(b);
var angle = Math.atan2(a2.x * b2.y - a2.y * b2.x, cc.pDot(a2, b2));
if (Math.abs(angle) < cc.POINT_EPSILON)
return 0.0;
return angle;
};
/**
* @param {cc.Point} a
* @param {cc.Point} b
* @return {Number} the angle in radians between two vector directions
*/
cc.pAngle = function (a, b) {
var angle = Math.acos(cc.pDot(cc.pNormalize(a), cc.pNormalize(b)));
if (Math.abs(angle) < cc.POINT_EPSILON) return 0.0;
return angle;
};
/**
* Rotates a point counter clockwise by the angle around a pivot
* @param {cc.Point} v v is the point to rotate
* @param {cc.Point} pivot pivot is the pivot, naturally
* @param {Number} angle angle is the angle of rotation cw in radians
* @return {cc.Point} the rotated point
*/
cc.pRotateByAngle = function (v, pivot, angle) {
var r = cc.pSub(v, pivot);
var cosa = Math.cos(angle), sina = Math.sin(angle);
var t = r.x;
r.x = t * cosa - r.y * sina + pivot.x;
r.y = t * sina + r.y * cosa + pivot.y;
return r;
};
/**
* A general line-line intersection test
* indicating successful intersection of a line<br />
* note that to truly test intersection for segments we have to make<br />
* sure that s & t lie within [0..1] and for rays, make sure s & t > 0<br />
* the hit point is p3 + t * (p4 - p3);<br />
* the hit point also is p1 + s * (p2 - p1);
* @param {cc.Point} A A is the startpoint for the first line P1 = (p1 - p2).
* @param {cc.Point} B B is the endpoint for the first line P1 = (p1 - p2).
* @param {cc.Point} C C is the startpoint for the second line P2 = (p3 - p4).
* @param {cc.Point} D D is the endpoint for the second line P2 = (p3 - p4).
* @param {cc.Point} retP retP.x is the range for a hitpoint in P1 (pa = p1 + s*(p2 - p1)), <br />
* retP.y is the range for a hitpoint in P3 (pa = p2 + t*(p4 - p3)).
* @return {Boolean}
*/
cc.pLineIntersect = function (A, B, C, D, retP) {
if ((A.x === B.x && A.y === B.y) || (C.x === D.x && C.y === D.y)) {
return false;
}
var BAx = B.x - A.x;
var BAy = B.y - A.y;
var DCx = D.x - C.x;
var DCy = D.y - C.y;
var ACx = A.x - C.x;
var ACy = A.y - C.y;
var denom = DCy * BAx - DCx * BAy;
retP.x = DCx * ACy - DCy * ACx;
retP.y = BAx * ACy - BAy * ACx;
if (denom === 0) {
if (retP.x === 0 || retP.y === 0) {
// Lines incident
return true;
}
// Lines parallel and not incident
return false;
}
retP.x = retP.x / denom;
retP.y = retP.y / denom;
return true;
};
/**
* ccpSegmentIntersect return YES if Segment A-B intersects with segment C-D.
* @param {cc.Point} A
* @param {cc.Point} B
* @param {cc.Point} C
* @param {cc.Point} D
* @return {Boolean}
*/
cc.pSegmentIntersect = function (A, B, C, D) {
var retP = cc.p(0, 0);
if (cc.pLineIntersect(A, B, C, D, retP))
if (retP.x >= 0.0 && retP.x <= 1.0 && retP.y >= 0.0 && retP.y <= 1.0)
return true;
return false;
};
/**
* ccpIntersectPoint return the intersection point of line A-B, C-D
* @param {cc.Point} A
* @param {cc.Point} B
* @param {cc.Point} C
* @param {cc.Point} D
* @return {cc.Point}
*/
cc.pIntersectPoint = function (A, B, C, D) {
var retP = cc.p(0, 0);
if (cc.pLineIntersect(A, B, C, D, retP)) {
// Point of intersection
var P = cc.p(0, 0);
P.x = A.x + retP.x * (B.x - A.x);
P.y = A.y + retP.x * (B.y - A.y);
return P;
}
return cc.p(0,0);
};
/**
* check to see if both points are equal
* @param {cc.Point} A A ccp a
* @param {cc.Point} B B ccp b to be compared
* @return {Boolean} the true if both ccp are same
*/
cc.pSameAs = function (A, B) {
if ((A != null) && (B != null)) {
return (A.x === B.x && A.y === B.y);
}
return false;
};
// High Perfomance In Place Operationrs ---------------------------------------
/**
* sets the position of the point to 0
* @param {cc.Point} v
*/
cc.pZeroIn = function(v) {
v.x = 0;
v.y = 0;
};
/**
* copies the position of one point to another
* @param {cc.Point} v1
* @param {cc.Point} v2
*/
cc.pIn = function(v1, v2) {
v1.x = v2.x;
v1.y = v2.y;
};
/**
* multiplies the point with the given factor (inplace)
* @param {cc.Point} point
* @param {Number} floatVar
*/
cc.pMultIn = function(point, floatVar) {
point.x *= floatVar;
point.y *= floatVar;
};
/**
* subtracts one point from another (inplace)
* @param {cc.Point} v1
* @param {cc.Point} v2
*/
cc.pSubIn = function(v1, v2) {
v1.x -= v2.x;
v1.y -= v2.y;
};
/**
* adds one point to another (inplace)
* @param {cc.Point} v1
* @param {cc.point} v2
*/
cc.pAddIn = function(v1, v2) {
v1.x += v2.x;
v1.y += v2.y;
};
/**
* normalizes the point (inplace)
* @param {cc.Point} v
*/
cc.pNormalizeIn = function(v) {
cc.pMultIn(v, 1.0 / Math.sqrt(v.x * v.x + v.y * v.y));
};
| darkoverlordofdata/demo-cocos2d-tsc | web/frameworks/cocos2d-html5/cocos2d/core/support/CCPointExtension.js | JavaScript | mit | 13,129 |
/*! leaflet-routing-machine - v3.2.1 - 2016-10-11
* Copyright (c) 2013-2016 Per Liedman
* Distributed under the ISC license */
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}(g.L || (g.L = {})).Routing = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
function corslite(url, callback, cors) {
var sent = false;
if (typeof window.XMLHttpRequest === 'undefined') {
return callback(Error('Browser not supported'));
}
if (typeof cors === 'undefined') {
var m = url.match(/^\s*https?:\/\/[^\/]*/);
cors = m && (m[0] !== location.protocol + '//' + location.hostname +
(location.port ? ':' + location.port : ''));
}
var x = new window.XMLHttpRequest();
function isSuccessful(status) {
return status >= 200 && status < 300 || status === 304;
}
if (cors && !('withCredentials' in x)) {
// IE8-9
x = new window.XDomainRequest();
// Ensure callback is never called synchronously, i.e., before
// x.send() returns (this has been observed in the wild).
// See https://github.com/mapbox/mapbox.js/issues/472
var original = callback;
callback = function() {
if (sent) {
original.apply(this, arguments);
} else {
var that = this, args = arguments;
setTimeout(function() {
original.apply(that, args);
}, 0);
}
}
}
function loaded() {
if (
// XDomainRequest
x.status === undefined ||
// modern browsers
isSuccessful(x.status)) callback.call(x, null, x);
else callback.call(x, x, null);
}
// Both `onreadystatechange` and `onload` can fire. `onreadystatechange`
// has [been supported for longer](http://stackoverflow.com/a/9181508/229001).
if ('onload' in x) {
x.onload = loaded;
} else {
x.onreadystatechange = function readystate() {
if (x.readyState === 4) {
loaded();
}
};
}
// Call the callback with the XMLHttpRequest object as an error and prevent
// it from ever being called again by reassigning it to `noop`
x.onerror = function error(evt) {
// XDomainRequest provides no evt parameter
callback.call(this, evt || true, null);
callback = function() { };
};
// IE9 must have onprogress be set to a unique function.
x.onprogress = function() { };
x.ontimeout = function(evt) {
callback.call(this, evt, null);
callback = function() { };
};
x.onabort = function(evt) {
callback.call(this, evt, null);
callback = function() { };
};
// GET is the only supported HTTP Verb by XDomainRequest and is the
// only one supported here.
x.open('GET', url, true);
// Send the request. Sending data is not supported.
x.send(null);
sent = true;
return x;
}
if (typeof module !== 'undefined') module.exports = corslite;
},{}],2:[function(_dereq_,module,exports){
'use strict';
/**
* Based off of [the offical Google document](https://developers.google.com/maps/documentation/utilities/polylinealgorithm)
*
* Some parts from [this implementation](http://facstaff.unca.edu/mcmcclur/GoogleMaps/EncodePolyline/PolylineEncoder.js)
* by [Mark McClure](http://facstaff.unca.edu/mcmcclur/)
*
* @module polyline
*/
var polyline = {};
function encode(coordinate, factor) {
coordinate = Math.round(coordinate * factor);
coordinate <<= 1;
if (coordinate < 0) {
coordinate = ~coordinate;
}
var output = '';
while (coordinate >= 0x20) {
output += String.fromCharCode((0x20 | (coordinate & 0x1f)) + 63);
coordinate >>= 5;
}
output += String.fromCharCode(coordinate + 63);
return output;
}
/**
* Decodes to a [latitude, longitude] coordinates array.
*
* This is adapted from the implementation in Project-OSRM.
*
* @param {String} str
* @param {Number} precision
* @returns {Array}
*
* @see https://github.com/Project-OSRM/osrm-frontend/blob/master/WebContent/routing/OSRM.RoutingGeometry.js
*/
polyline.decode = function(str, precision) {
var index = 0,
lat = 0,
lng = 0,
coordinates = [],
shift = 0,
result = 0,
byte = null,
latitude_change,
longitude_change,
factor = Math.pow(10, precision || 5);
// Coordinates have variable length when encoded, so just keep
// track of whether we've hit the end of the string. In each
// loop iteration, a single coordinate is decoded.
while (index < str.length) {
// Reset shift, result, and byte
byte = null;
shift = 0;
result = 0;
do {
byte = str.charCodeAt(index++) - 63;
result |= (byte & 0x1f) << shift;
shift += 5;
} while (byte >= 0x20);
latitude_change = ((result & 1) ? ~(result >> 1) : (result >> 1));
shift = result = 0;
do {
byte = str.charCodeAt(index++) - 63;
result |= (byte & 0x1f) << shift;
shift += 5;
} while (byte >= 0x20);
longitude_change = ((result & 1) ? ~(result >> 1) : (result >> 1));
lat += latitude_change;
lng += longitude_change;
coordinates.push([lat / factor, lng / factor]);
}
return coordinates;
};
/**
* Encodes the given [latitude, longitude] coordinates array.
*
* @param {Array.<Array.<Number>>} coordinates
* @param {Number} precision
* @returns {String}
*/
polyline.encode = function(coordinates, precision) {
if (!coordinates.length) { return ''; }
var factor = Math.pow(10, precision || 5),
output = encode(coordinates[0][0], factor) + encode(coordinates[0][1], factor);
for (var i = 1; i < coordinates.length; i++) {
var a = coordinates[i], b = coordinates[i - 1];
output += encode(a[0] - b[0], factor);
output += encode(a[1] - b[1], factor);
}
return output;
};
function flipped(coords) {
var flipped = [];
for (var i = 0; i < coords.length; i++) {
flipped.push(coords[i].slice().reverse());
}
return flipped;
}
/**
* Encodes a GeoJSON LineString feature/geometry.
*
* @param {Object} geojson
* @param {Number} precision
* @returns {String}
*/
polyline.fromGeoJSON = function(geojson, precision) {
if (geojson && geojson.type === 'Feature') {
geojson = geojson.geometry;
}
if (!geojson || geojson.type !== 'LineString') {
throw new Error('Input must be a GeoJSON LineString');
}
return polyline.encode(flipped(geojson.coordinates), precision);
};
/**
* Decodes to a GeoJSON LineString geometry.
*
* @param {String} str
* @param {Number} precision
* @returns {Object}
*/
polyline.toGeoJSON = function(str, precision) {
var coords = polyline.decode(str, precision);
return {
type: 'LineString',
coordinates: flipped(coords)
};
};
if (typeof module === 'object' && module.exports) {
module.exports = polyline;
}
},{}],3:[function(_dereq_,module,exports){
(function() {
'use strict';
L.Routing = L.Routing || {};
L.Routing.Autocomplete = L.Class.extend({
options: {
timeout: 500,
blurTimeout: 100,
noResultsMessage: 'No results found.'
},
initialize: function(elem, callback, context, options) {
L.setOptions(this, options);
this._elem = elem;
this._resultFn = options.resultFn ? L.Util.bind(options.resultFn, options.resultContext) : null;
this._autocomplete = options.autocompleteFn ? L.Util.bind(options.autocompleteFn, options.autocompleteContext) : null;
this._selectFn = L.Util.bind(callback, context);
this._container = L.DomUtil.create('div', 'leaflet-routing-geocoder-result');
this._resultTable = L.DomUtil.create('table', '', this._container);
// TODO: looks a bit like a kludge to register same for input and keypress -
// browsers supporting both will get duplicate events; just registering
// input will not catch enter, though.
L.DomEvent.addListener(this._elem, 'input', this._keyPressed, this);
L.DomEvent.addListener(this._elem, 'keypress', this._keyPressed, this);
L.DomEvent.addListener(this._elem, 'keydown', this._keyDown, this);
L.DomEvent.addListener(this._elem, 'blur', function() {
if (this._isOpen) {
this.close();
}
}, this);
},
close: function() {
L.DomUtil.removeClass(this._container, 'leaflet-routing-geocoder-result-open');
this._isOpen = false;
},
_open: function() {
var rect = this._elem.getBoundingClientRect();
if (!this._container.parentElement) {
// See notes section under https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollX
// This abomination is required to support all flavors of IE
var scrollX = (window.pageXOffset !== undefined) ? window.pageXOffset
: (document.documentElement || document.body.parentNode || document.body).scrollLeft;
var scrollY = (window.pageYOffset !== undefined) ? window.pageYOffset
: (document.documentElement || document.body.parentNode || document.body).scrollTop;
this._container.style.left = (rect.left + scrollX) + 'px';
this._container.style.top = (rect.bottom + scrollY) + 'px';
this._container.style.width = (rect.right - rect.left) + 'px';
document.body.appendChild(this._container);
}
L.DomUtil.addClass(this._container, 'leaflet-routing-geocoder-result-open');
this._isOpen = true;
},
_setResults: function(results) {
var i,
tr,
td,
text;
delete this._selection;
this._results = results;
while (this._resultTable.firstChild) {
this._resultTable.removeChild(this._resultTable.firstChild);
}
for (i = 0; i < results.length; i++) {
tr = L.DomUtil.create('tr', '', this._resultTable);
tr.setAttribute('data-result-index', i);
td = L.DomUtil.create('td', '', tr);
text = document.createTextNode(results[i].name);
td.appendChild(text);
// mousedown + click because:
// http://stackoverflow.com/questions/10652852/jquery-fire-click-before-blur-event
L.DomEvent.addListener(td, 'mousedown', L.DomEvent.preventDefault);
L.DomEvent.addListener(td, 'click', this._createClickListener(results[i]));
}
if (!i) {
tr = L.DomUtil.create('tr', '', this._resultTable);
td = L.DomUtil.create('td', 'leaflet-routing-geocoder-no-results', tr);
td.innerHTML = this.options.noResultsMessage;
}
this._open();
if (results.length > 0) {
// Select the first entry
this._select(1);
}
},
_createClickListener: function(r) {
var resultSelected = this._resultSelected(r);
return L.bind(function() {
this._elem.blur();
resultSelected();
}, this);
},
_resultSelected: function(r) {
return L.bind(function() {
this.close();
this._elem.value = r.name;
this._lastCompletedText = r.name;
this._selectFn(r);
}, this);
},
_keyPressed: function(e) {
var index;
if (this._isOpen && e.keyCode === 13 && this._selection) {
index = parseInt(this._selection.getAttribute('data-result-index'), 10);
this._resultSelected(this._results[index])();
L.DomEvent.preventDefault(e);
return;
}
if (e.keyCode === 13) {
this._complete(this._resultFn, true);
return;
}
if (this._autocomplete && document.activeElement === this._elem) {
if (this._timer) {
clearTimeout(this._timer);
}
this._timer = setTimeout(L.Util.bind(function() { this._complete(this._autocomplete); }, this),
this.options.timeout);
return;
}
this._unselect();
},
_select: function(dir) {
var sel = this._selection;
if (sel) {
L.DomUtil.removeClass(sel.firstChild, 'leaflet-routing-geocoder-selected');
sel = sel[dir > 0 ? 'nextSibling' : 'previousSibling'];
}
if (!sel) {
sel = this._resultTable[dir > 0 ? 'firstChild' : 'lastChild'];
}
if (sel) {
L.DomUtil.addClass(sel.firstChild, 'leaflet-routing-geocoder-selected');
this._selection = sel;
}
},
_unselect: function() {
if (this._selection) {
L.DomUtil.removeClass(this._selection.firstChild, 'leaflet-routing-geocoder-selected');
}
delete this._selection;
},
_keyDown: function(e) {
if (this._isOpen) {
switch (e.keyCode) {
// Escape
case 27:
this.close();
L.DomEvent.preventDefault(e);
return;
// Up
case 38:
this._select(-1);
L.DomEvent.preventDefault(e);
return;
// Down
case 40:
this._select(1);
L.DomEvent.preventDefault(e);
return;
}
}
},
_complete: function(completeFn, trySelect) {
var v = this._elem.value;
function completeResults(results) {
this._lastCompletedText = v;
if (trySelect && results.length === 1) {
this._resultSelected(results[0])();
} else {
this._setResults(results);
}
}
if (!v) {
return;
}
if (v !== this._lastCompletedText) {
completeFn(v, completeResults, this);
} else if (trySelect) {
completeResults.call(this, this._results);
}
}
});
})();
},{}],4:[function(_dereq_,module,exports){
(function (global){
(function() {
'use strict';
var L = (typeof window !== "undefined" ? window['L'] : typeof global !== "undefined" ? global['L'] : null);
L.Routing = L.Routing || {};
L.extend(L.Routing, _dereq_('./L.Routing.Itinerary'));
L.extend(L.Routing, _dereq_('./L.Routing.Line'));
L.extend(L.Routing, _dereq_('./L.Routing.Plan'));
L.extend(L.Routing, _dereq_('./L.Routing.OSRMv1'));
L.extend(L.Routing, _dereq_('./L.Routing.Mapbox'));
L.extend(L.Routing, _dereq_('./L.Routing.ErrorControl'));
L.Routing.Control = L.Routing.Itinerary.extend({
options: {
fitSelectedRoutes: 'smart',
routeLine: function(route, options) { return L.Routing.line(route, options); },
autoRoute: true,
routeWhileDragging: false,
routeDragInterval: 500,
waypointMode: 'connect',
showAlternatives: false,
defaultErrorHandler: function(e) {
console.error('Routing error:', e.error);
}
},
initialize: function(options) {
L.Util.setOptions(this, options);
this._router = this.options.router || new L.Routing.OSRMv1(options);
this._plan = this.options.plan || L.Routing.plan(this.options.waypoints, options);
this._requestCount = 0;
L.Routing.Itinerary.prototype.initialize.call(this, options);
this.on('routeselected', this._routeSelected, this);
if (this.options.defaultErrorHandler) {
this.on('routingerror', this.options.defaultErrorHandler);
}
this._plan.on('waypointschanged', this._onWaypointsChanged, this);
if (options.routeWhileDragging) {
this._setupRouteDragging();
}
if (this.options.autoRoute) {
this.route();
}
},
onAdd: function(map) {
var container = L.Routing.Itinerary.prototype.onAdd.call(this, map);
this._map = map;
this._map.addLayer(this._plan);
this._map.on('zoomend', function() {
if (!this._selectedRoute ||
!this._router.requiresMoreDetail) {
return;
}
var map = this._map;
if (this._router.requiresMoreDetail(this._selectedRoute,
map.getZoom(), map.getBounds())) {
this.route({
callback: L.bind(function(err, routes) {
var i;
if (!err) {
for (i = 0; i < routes.length; i++) {
this._routes[i].properties = routes[i].properties;
}
this._updateLineCallback(err, routes);
}
}, this),
simplifyGeometry: false,
geometryOnly: true
});
}
}, this);
if (this._plan.options.geocoder) {
container.insertBefore(this._plan.createGeocoders(), container.firstChild);
}
return container;
},
onRemove: function(map) {
if (this._line) {
map.removeLayer(this._line);
}
map.removeLayer(this._plan);
if (this._alternatives && this._alternatives.length > 0) {
for (var i = 0, len = this._alternatives.length; i < len; i++) {
map.removeLayer(this._alternatives[i]);
}
}
return L.Routing.Itinerary.prototype.onRemove.call(this, map);
},
getWaypoints: function() {
return this._plan.getWaypoints();
},
setWaypoints: function(waypoints) {
this._plan.setWaypoints(waypoints);
return this;
},
spliceWaypoints: function() {
var removed = this._plan.spliceWaypoints.apply(this._plan, arguments);
return removed;
},
getPlan: function() {
return this._plan;
},
getRouter: function() {
return this._router;
},
_routeSelected: function(e) {
var route = this._selectedRoute = e.route,
alternatives = this.options.showAlternatives && e.alternatives,
fitMode = this.options.fitSelectedRoutes,
fitBounds =
(fitMode === 'smart' && !this._waypointsVisible()) ||
(fitMode !== 'smart' && fitMode);
this._updateLines({route: route, alternatives: alternatives});
if (fitBounds) {
this._map.fitBounds(this._line.getBounds());
}
if (this.options.waypointMode === 'snap') {
this._plan.off('waypointschanged', this._onWaypointsChanged, this);
this.setWaypoints(route.waypoints);
this._plan.on('waypointschanged', this._onWaypointsChanged, this);
}
},
_waypointsVisible: function() {
var wps = this.getWaypoints(),
mapSize,
bounds,
boundsSize,
i,
p;
try {
mapSize = this._map.getSize();
for (i = 0; i < wps.length; i++) {
p = this._map.latLngToLayerPoint(wps[i].latLng);
if (bounds) {
bounds.extend(p);
} else {
bounds = L.bounds([p]);
}
}
boundsSize = bounds.getSize();
return (boundsSize.x > mapSize.x / 5 ||
boundsSize.y > mapSize.y / 5) && this._waypointsInViewport();
} catch (e) {
return false;
}
},
_waypointsInViewport: function() {
var wps = this.getWaypoints(),
mapBounds,
i;
try {
mapBounds = this._map.getBounds();
} catch (e) {
return false;
}
for (i = 0; i < wps.length; i++) {
if (mapBounds.contains(wps[i].latLng)) {
return true;
}
}
return false;
},
_updateLines: function(routes) {
var addWaypoints = this.options.addWaypoints !== undefined ?
this.options.addWaypoints : true;
this._clearLines();
// add alternatives first so they lie below the main route
this._alternatives = [];
if (routes.alternatives) routes.alternatives.forEach(function(alt, i) {
this._alternatives[i] = this.options.routeLine(alt,
L.extend({
isAlternative: true
}, this.options.altLineOptions || this.options.lineOptions));
this._alternatives[i].addTo(this._map);
this._hookAltEvents(this._alternatives[i]);
}, this);
this._line = this.options.routeLine(routes.route,
L.extend({
addWaypoints: addWaypoints,
extendToWaypoints: this.options.waypointMode === 'connect'
}, this.options.lineOptions));
this._line.addTo(this._map);
this._hookEvents(this._line);
},
_hookEvents: function(l) {
l.on('linetouched', function(e) {
this._plan.dragNewWaypoint(e);
}, this);
},
_hookAltEvents: function(l) {
l.on('linetouched', function(e) {
var alts = this._routes.slice();
var selected = alts.splice(e.target._route.routesIndex, 1)[0];
this.fire('routeselected', {route: selected, alternatives: alts});
}, this);
},
_onWaypointsChanged: function(e) {
if (this.options.autoRoute) {
this.route({});
}
if (!this._plan.isReady()) {
this._clearLines();
this._clearAlts();
}
this.fire('waypointschanged', {waypoints: e.waypoints});
},
_setupRouteDragging: function() {
var timer = 0,
waypoints;
this._plan.on('waypointdrag', L.bind(function(e) {
waypoints = e.waypoints;
if (!timer) {
timer = setTimeout(L.bind(function() {
this.route({
waypoints: waypoints,
geometryOnly: true,
callback: L.bind(this._updateLineCallback, this)
});
timer = undefined;
}, this), this.options.routeDragInterval);
}
}, this));
this._plan.on('waypointdragend', function() {
if (timer) {
clearTimeout(timer);
timer = undefined;
}
this.route();
}, this);
},
_updateLineCallback: function(err, routes) {
if (!err) {
routes = routes.slice();
var selected = routes.splice(this._selectedRoute.routesIndex, 1)[0];
this._updateLines({route: selected, alternatives: routes });
} else if (err.type !== 'abort') {
this._clearLines();
}
},
route: function(options) {
var ts = ++this._requestCount,
wps;
if (this._pendingRequest && this._pendingRequest.abort) {
this._pendingRequest.abort();
this._pendingRequest = null;
}
options = options || {};
if (this._plan.isReady()) {
if (this.options.useZoomParameter) {
options.z = this._map && this._map.getZoom();
}
wps = options && options.waypoints || this._plan.getWaypoints();
this.fire('routingstart', {waypoints: wps});
this._pendingRequest = this._router.route(wps, function(err, routes) {
this._pendingRequest = null;
if (options.callback) {
return options.callback.call(this, err, routes);
}
// Prevent race among multiple requests,
// by checking the current request's count
// against the last request's; ignore result if
// this isn't the last request.
if (ts === this._requestCount) {
this._clearLines();
this._clearAlts();
if (err && err.type !== 'abort') {
this.fire('routingerror', {error: err});
return;
}
routes.forEach(function(route, i) { route.routesIndex = i; });
if (!options.geometryOnly) {
this.fire('routesfound', {waypoints: wps, routes: routes});
this.setAlternatives(routes);
} else {
var selectedRoute = routes.splice(0,1)[0];
this._routeSelected({route: selectedRoute, alternatives: routes});
}
}
}, this, options);
}
},
_clearLines: function() {
if (this._line) {
this._map.removeLayer(this._line);
delete this._line;
}
if (this._alternatives && this._alternatives.length) {
for (var i in this._alternatives) {
this._map.removeLayer(this._alternatives[i]);
}
this._alternatives = [];
}
}
});
L.Routing.control = function(options) {
return new L.Routing.Control(options);
};
module.exports = L.Routing;
})();
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./L.Routing.ErrorControl":5,"./L.Routing.Itinerary":8,"./L.Routing.Line":10,"./L.Routing.Mapbox":12,"./L.Routing.OSRMv1":13,"./L.Routing.Plan":14}],5:[function(_dereq_,module,exports){
(function() {
'use strict';
L.Routing = L.Routing || {};
L.Routing.ErrorControl = L.Control.extend({
options: {
header: 'Routing error',
formatMessage: function(error) {
if (error.status < 0) {
return 'Calculating the route caused an error. Technical description follows: <code><pre>' +
error.message + '</pre></code';
} else {
return 'The route could not be calculated. ' +
error.message;
}
}
},
initialize: function(routingControl, options) {
L.Control.prototype.initialize.call(this, options);
routingControl
.on('routingerror', L.bind(function(e) {
if (this._element) {
this._element.children[1].innerHTML = this.options.formatMessage(e.error);
this._element.style.visibility = 'visible';
}
}, this))
.on('routingstart', L.bind(function() {
if (this._element) {
this._element.style.visibility = 'hidden';
}
}, this));
},
onAdd: function() {
var header,
message;
this._element = L.DomUtil.create('div', 'leaflet-bar leaflet-routing-error');
this._element.style.visibility = 'hidden';
header = L.DomUtil.create('h3', null, this._element);
message = L.DomUtil.create('span', null, this._element);
header.innerHTML = this.options.header;
return this._element;
},
onRemove: function() {
delete this._element;
}
});
L.Routing.errorControl = function(routingControl, options) {
return new L.Routing.ErrorControl(routingControl, options);
};
})();
},{}],6:[function(_dereq_,module,exports){
(function (global){
(function() {
'use strict';
var L = (typeof window !== "undefined" ? window['L'] : typeof global !== "undefined" ? global['L'] : null);
L.Routing = L.Routing || {};
L.extend(L.Routing, _dereq_('./L.Routing.Localization'));
L.Routing.Formatter = L.Class.extend({
options: {
units: 'metric',
unitNames: null,
language: 'en',
roundingSensitivity: 1,
distanceTemplate: '{value} {unit}'
},
initialize: function(options) {
L.setOptions(this, options);
var langs = L.Util.isArray(this.options.language) ?
this.options.language :
[this.options.language, 'en'];
this._localization = new L.Routing.Localization(langs);
},
formatDistance: function(d /* Number (meters) */, sensitivity) {
var un = this.options.unitNames || this._localization.localize('units'),
simpleRounding = sensitivity <= 0,
round = simpleRounding ? function(v) { return v; } : L.bind(this._round, this),
v,
yards,
data,
pow10;
if (this.options.units === 'imperial') {
yards = d / 0.9144;
if (yards >= 1000) {
data = {
value: round(d / 1609.344, sensitivity),
unit: un.miles
};
} else {
data = {
value: round(yards, sensitivity),
unit: un.yards
};
}
} else {
v = round(d, sensitivity);
data = {
value: v >= 1000 ? (v / 1000) : v,
unit: v >= 1000 ? un.kilometers : un.meters
};
}
if (simpleRounding) {
data.value = data.value.toFixed(-sensitivity);
}
return L.Util.template(this.options.distanceTemplate, data);
},
_round: function(d, sensitivity) {
var s = sensitivity || this.options.roundingSensitivity,
pow10 = Math.pow(10, (Math.floor(d / s) + '').length - 1),
r = Math.floor(d / pow10),
p = (r > 5) ? pow10 : pow10 / 2;
return Math.round(d / p) * p;
},
formatTime: function(t /* Number (seconds) */) {
var un = this.options.unitNames || this._localization.localize('units');
// More than 30 seconds precision looks ridiculous
t = Math.round(t / 30) * 30;
if (t > 86400) {
return Math.round(t / 3600) + ' ' + un.hours;
} else if (t > 3600) {
return Math.floor(t / 3600) + ' ' + un.hours + ' ' +
Math.round((t % 3600) / 60) + ' ' + un.minutes;
} else if (t > 300) {
return Math.round(t / 60) + ' ' + un.minutes;
} else if (t > 60) {
return Math.floor(t / 60) + ' ' + un.minutes +
(t % 60 !== 0 ? ' ' + (t % 60) + ' ' + un.seconds : '');
} else {
return t + ' ' + un.seconds;
}
},
formatInstruction: function(instr, i) {
if (instr.text === undefined) {
return this.capitalize(L.Util.template(this._getInstructionTemplate(instr, i),
L.extend({}, instr, {
exitStr: instr.exit ? this._localization.localize('formatOrder')(instr.exit) : '',
dir: this._localization.localize(['directions', instr.direction]),
modifier: this._localization.localize(['directions', instr.modifier])
})));
} else {
return instr.text;
}
},
getIconName: function(instr, i) {
switch (instr.type) {
case 'Head':
if (i === 0) {
return 'depart';
}
break;
case 'WaypointReached':
return 'via';
case 'Roundabout':
return 'enter-roundabout';
case 'DestinationReached':
return 'arrive';
}
switch (instr.modifier) {
case 'Straight':
return 'continue';
case 'SlightRight':
return 'bear-right';
case 'Right':
return 'turn-right';
case 'SharpRight':
return 'sharp-right';
case 'TurnAround':
case 'Uturn':
return 'u-turn';
case 'SharpLeft':
return 'sharp-left';
case 'Left':
return 'turn-left';
case 'SlightLeft':
return 'bear-left';
}
},
capitalize: function(s) {
return s.charAt(0).toUpperCase() + s.substring(1);
},
_getInstructionTemplate: function(instr, i) {
var type = instr.type === 'Straight' ? (i === 0 ? 'Head' : 'Continue') : instr.type,
strings = this._localization.localize(['instructions', type]);
if (!strings) {
strings = [
this._localization.localize(['directions', type]),
' ' + this._localization.localize(['instructions', 'Onto'])
];
}
return strings[0] + (strings.length > 1 && instr.road ? strings[1] : '');
}
});
module.exports = L.Routing;
})();
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./L.Routing.Localization":11}],7:[function(_dereq_,module,exports){
(function (global){
(function() {
'use strict';
var L = (typeof window !== "undefined" ? window['L'] : typeof global !== "undefined" ? global['L'] : null);
L.Routing = L.Routing || {};
L.extend(L.Routing, _dereq_('./L.Routing.Autocomplete'));
function selectInputText(input) {
if (input.setSelectionRange) {
// On iOS, select() doesn't work
input.setSelectionRange(0, 9999);
} else {
// On at least IE8, setSeleectionRange doesn't exist
input.select();
}
}
L.Routing.GeocoderElement = L.Class.extend({
includes: L.Mixin.Events,
options: {
createGeocoder: function(i, nWps, options) {
var container = L.DomUtil.create('div', 'leaflet-routing-geocoder'),
input = L.DomUtil.create('input', '', container),
remove = options.addWaypoints ? L.DomUtil.create('span', 'leaflet-routing-remove-waypoint', container) : undefined;
input.disabled = !options.addWaypoints;
return {
container: container,
input: input,
closeButton: remove
};
},
geocoderPlaceholder: function(i, numberWaypoints, geocoderElement) {
var l = new L.Routing.Localization(geocoderElement.options.language).localize('ui');
return i === 0 ?
l.startPlaceholder :
(i < numberWaypoints - 1 ?
L.Util.template(l.viaPlaceholder, {viaNumber: i}) :
l.endPlaceholder);
},
geocoderClass: function() {
return '';
},
waypointNameFallback: function(latLng) {
var ns = latLng.lat < 0 ? 'S' : 'N',
ew = latLng.lng < 0 ? 'W' : 'E',
lat = (Math.round(Math.abs(latLng.lat) * 10000) / 10000).toString(),
lng = (Math.round(Math.abs(latLng.lng) * 10000) / 10000).toString();
return ns + lat + ', ' + ew + lng;
},
maxGeocoderTolerance: 200,
autocompleteOptions: {},
language: 'en',
},
initialize: function(wp, i, nWps, options) {
L.setOptions(this, options);
var g = this.options.createGeocoder(i, nWps, this.options),
closeButton = g.closeButton,
geocoderInput = g.input;
geocoderInput.setAttribute('placeholder', this.options.geocoderPlaceholder(i, nWps, this));
geocoderInput.className = this.options.geocoderClass(i, nWps);
this._element = g;
this._waypoint = wp;
this.update();
// This has to be here, or geocoder's value will not be properly
// initialized.
// TODO: look into why and make _updateWaypointName fix this.
geocoderInput.value = wp.name;
L.DomEvent.addListener(geocoderInput, 'click', function() {
selectInputText(this);
}, geocoderInput);
if (closeButton) {
L.DomEvent.addListener(closeButton, 'click', function() {
this.fire('delete', { waypoint: this._waypoint });
}, this);
}
new L.Routing.Autocomplete(geocoderInput, function(r) {
geocoderInput.value = r.name;
wp.name = r.name;
wp.latLng = r.center;
this.fire('geocoded', { waypoint: wp, value: r });
}, this, L.extend({
resultFn: this.options.geocoder.geocode,
resultContext: this.options.geocoder,
autocompleteFn: this.options.geocoder.suggest,
autocompleteContext: this.options.geocoder
}, this.options.autocompleteOptions));
},
getContainer: function() {
return this._element.container;
},
setValue: function(v) {
this._element.input.value = v;
},
update: function(force) {
var wp = this._waypoint,
wpCoords;
wp.name = wp.name || '';
if (wp.latLng && (force || !wp.name)) {
wpCoords = this.options.waypointNameFallback(wp.latLng);
if (this.options.geocoder && this.options.geocoder.reverse) {
this.options.geocoder.reverse(wp.latLng, 67108864 /* zoom 18 */, function(rs) {
if (rs.length > 0 && rs[0].center.distanceTo(wp.latLng) < this.options.maxGeocoderTolerance) {
wp.name = rs[0].name;
} else {
wp.name = wpCoords;
}
this._update();
}, this);
} else {
wp.name = wpCoords;
this._update();
}
}
},
focus: function() {
var input = this._element.input;
input.focus();
selectInputText(input);
},
_update: function() {
var wp = this._waypoint,
value = wp && wp.name ? wp.name : '';
this.setValue(value);
this.fire('reversegeocoded', {waypoint: wp, value: value});
}
});
L.Routing.geocoderElement = function(wp, i, nWps, plan) {
return new L.Routing.GeocoderElement(wp, i, nWps, plan);
};
module.exports = L.Routing;
})();
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./L.Routing.Autocomplete":3}],8:[function(_dereq_,module,exports){
(function (global){
(function() {
'use strict';
var L = (typeof window !== "undefined" ? window['L'] : typeof global !== "undefined" ? global['L'] : null);
L.Routing = L.Routing || {};
L.extend(L.Routing, _dereq_('./L.Routing.Formatter'));
L.extend(L.Routing, _dereq_('./L.Routing.ItineraryBuilder'));
L.Routing.Itinerary = L.Control.extend({
includes: L.Mixin.Events,
options: {
pointMarkerStyle: {
radius: 5,
color: '#03f',
fillColor: 'white',
opacity: 1,
fillOpacity: 0.7
},
summaryTemplate: '<h2>{name}</h2><h3>{distance}, {time}</h3>',
timeTemplate: '{time}',
containerClassName: '',
alternativeClassName: '',
minimizedClassName: '',
itineraryClassName: '',
totalDistanceRoundingSensitivity: -1,
show: true,
collapsible: undefined,
collapseBtn: function(itinerary) {
var collapseBtn = L.DomUtil.create('span', itinerary.options.collapseBtnClass);
L.DomEvent.on(collapseBtn, 'click', itinerary._toggle, itinerary);
itinerary._container.insertBefore(collapseBtn, itinerary._container.firstChild);
},
collapseBtnClass: 'leaflet-routing-collapse-btn'
},
initialize: function(options) {
L.setOptions(this, options);
this._formatter = this.options.formatter || new L.Routing.Formatter(this.options);
this._itineraryBuilder = this.options.itineraryBuilder || new L.Routing.ItineraryBuilder({
containerClassName: this.options.itineraryClassName
});
},
onAdd: function(map) {
var collapsible = this.options.collapsible;
collapsible = collapsible || (collapsible === undefined && map.getSize().x <= 640);
this._container = L.DomUtil.create('div', 'leaflet-routing-container leaflet-bar ' +
(!this.options.show ? 'leaflet-routing-container-hide ' : '') +
(collapsible ? 'leaflet-routing-collapsible ' : '') +
this.options.containerClassName);
this._altContainer = this.createAlternativesContainer();
this._container.appendChild(this._altContainer);
L.DomEvent.disableClickPropagation(this._container);
L.DomEvent.addListener(this._container, 'mousewheel', function(e) {
L.DomEvent.stopPropagation(e);
});
if (collapsible) {
this.options.collapseBtn(this);
}
return this._container;
},
onRemove: function() {
},
createAlternativesContainer: function() {
return L.DomUtil.create('div', 'leaflet-routing-alternatives-container');
},
setAlternatives: function(routes) {
var i,
alt,
altDiv;
this._clearAlts();
this._routes = routes;
for (i = 0; i < this._routes.length; i++) {
alt = this._routes[i];
altDiv = this._createAlternative(alt, i);
this._altContainer.appendChild(altDiv);
this._altElements.push(altDiv);
}
this._selectRoute({route: this._routes[0], alternatives: this._routes.slice(1)});
return this;
},
show: function() {
L.DomUtil.removeClass(this._container, 'leaflet-routing-container-hide');
},
hide: function() {
L.DomUtil.addClass(this._container, 'leaflet-routing-container-hide');
},
_toggle: function() {
var collapsed = L.DomUtil.hasClass(this._container, 'leaflet-routing-container-hide');
this[collapsed ? 'show' : 'hide']();
},
_createAlternative: function(alt, i) {
var altDiv = L.DomUtil.create('div', 'leaflet-routing-alt ' +
this.options.alternativeClassName +
(i > 0 ? ' leaflet-routing-alt-minimized ' + this.options.minimizedClassName : '')),
template = this.options.summaryTemplate,
data = L.extend({
name: alt.name,
distance: this._formatter.formatDistance(alt.summary.totalDistance, this.options.totalDistanceRoundingSensitivity),
time: this._formatter.formatTime(alt.summary.totalTime)
}, alt);
altDiv.innerHTML = typeof(template) === 'function' ? template(data) : L.Util.template(template, data);
L.DomEvent.addListener(altDiv, 'click', this._onAltClicked, this);
this.on('routeselected', this._selectAlt, this);
altDiv.appendChild(this._createItineraryContainer(alt));
return altDiv;
},
_clearAlts: function() {
var el = this._altContainer;
while (el && el.firstChild) {
el.removeChild(el.firstChild);
}
this._altElements = [];
},
_createItineraryContainer: function(r) {
var container = this._itineraryBuilder.createContainer(),
steps = this._itineraryBuilder.createStepsContainer(),
i,
instr,
step,
distance,
text,
icon;
container.appendChild(steps);
for (i = 0; i < r.instructions.length; i++) {
instr = r.instructions[i];
text = this._formatter.formatInstruction(instr, i);
distance = this._formatter.formatDistance(instr.distance);
icon = this._formatter.getIconName(instr, i);
step = this._itineraryBuilder.createStep(text, distance, icon, steps);
this._addRowListeners(step, r.coordinates[instr.index]);
}
return container;
},
_addRowListeners: function(row, coordinate) {
L.DomEvent.addListener(row, 'mouseover', function() {
this._marker = L.circleMarker(coordinate,
this.options.pointMarkerStyle).addTo(this._map);
}, this);
L.DomEvent.addListener(row, 'mouseout', function() {
if (this._marker) {
this._map.removeLayer(this._marker);
delete this._marker;
}
}, this);
L.DomEvent.addListener(row, 'click', function(e) {
this._map.panTo(coordinate);
L.DomEvent.stopPropagation(e);
}, this);
},
_onAltClicked: function(e) {
var altElem = e.target || window.event.srcElement;
while (!L.DomUtil.hasClass(altElem, 'leaflet-routing-alt')) {
altElem = altElem.parentElement;
}
var j = this._altElements.indexOf(altElem);
var alts = this._routes.slice();
var route = alts.splice(j, 1)[0];
this.fire('routeselected', {
route: route,
alternatives: alts
});
},
_selectAlt: function(e) {
var altElem,
j,
n,
classFn;
altElem = this._altElements[e.route.routesIndex];
if (L.DomUtil.hasClass(altElem, 'leaflet-routing-alt-minimized')) {
for (j = 0; j < this._altElements.length; j++) {
n = this._altElements[j];
classFn = j === e.route.routesIndex ? 'removeClass' : 'addClass';
L.DomUtil[classFn](n, 'leaflet-routing-alt-minimized');
if (this.options.minimizedClassName) {
L.DomUtil[classFn](n, this.options.minimizedClassName);
}
if (j !== e.route.routesIndex) n.scrollTop = 0;
}
}
L.DomEvent.stop(e);
},
_selectRoute: function(routes) {
if (this._marker) {
this._map.removeLayer(this._marker);
delete this._marker;
}
this.fire('routeselected', routes);
}
});
L.Routing.itinerary = function(options) {
return new L.Routing.Itinerary(options);
};
module.exports = L.Routing;
})();
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./L.Routing.Formatter":6,"./L.Routing.ItineraryBuilder":9}],9:[function(_dereq_,module,exports){
(function (global){
(function() {
'use strict';
var L = (typeof window !== "undefined" ? window['L'] : typeof global !== "undefined" ? global['L'] : null);
L.Routing = L.Routing || {};
L.Routing.ItineraryBuilder = L.Class.extend({
options: {
containerClassName: ''
},
initialize: function(options) {
L.setOptions(this, options);
},
createContainer: function(className) {
var table = L.DomUtil.create('table', className || ''),
colgroup = L.DomUtil.create('colgroup', '', table);
L.DomUtil.create('col', 'leaflet-routing-instruction-icon', colgroup);
L.DomUtil.create('col', 'leaflet-routing-instruction-text', colgroup);
L.DomUtil.create('col', 'leaflet-routing-instruction-distance', colgroup);
return table;
},
createStepsContainer: function() {
return L.DomUtil.create('tbody', '');
},
createStep: function(text, distance, icon, steps) {
var row = L.DomUtil.create('tr', '', steps),
span,
td;
td = L.DomUtil.create('td', '', row);
span = L.DomUtil.create('span', 'leaflet-routing-icon leaflet-routing-icon-'+icon, td);
td.appendChild(span);
td = L.DomUtil.create('td', '', row);
td.appendChild(document.createTextNode(text));
td = L.DomUtil.create('td', '', row);
td.appendChild(document.createTextNode(distance));
return row;
}
});
module.exports = L.Routing;
})();
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],10:[function(_dereq_,module,exports){
(function (global){
(function() {
'use strict';
var L = (typeof window !== "undefined" ? window['L'] : typeof global !== "undefined" ? global['L'] : null);
L.Routing = L.Routing || {};
L.Routing.Line = L.LayerGroup.extend({
includes: L.Mixin.Events,
options: {
styles: [
{color: 'black', opacity: 0.15, weight: 9},
{color: 'white', opacity: 0.8, weight: 6},
{color: 'red', opacity: 1, weight: 2}
],
missingRouteStyles: [
{color: 'black', opacity: 0.15, weight: 7},
{color: 'white', opacity: 0.6, weight: 4},
{color: 'gray', opacity: 0.8, weight: 2, dashArray: '7,12'}
],
addWaypoints: true,
extendToWaypoints: true,
missingRouteTolerance: 10
},
initialize: function(route, options) {
L.setOptions(this, options);
L.LayerGroup.prototype.initialize.call(this, options);
this._route = route;
if (this.options.extendToWaypoints) {
this._extendToWaypoints();
}
this._addSegment(
route.coordinates,
this.options.styles,
this.options.addWaypoints);
},
getBounds: function() {
return L.latLngBounds(this._route.coordinates);
},
_findWaypointIndices: function() {
var wps = this._route.inputWaypoints,
indices = [],
i;
for (i = 0; i < wps.length; i++) {
indices.push(this._findClosestRoutePoint(wps[i].latLng));
}
return indices;
},
_findClosestRoutePoint: function(latlng) {
var minDist = Number.MAX_VALUE,
minIndex,
i,
d;
for (i = this._route.coordinates.length - 1; i >= 0 ; i--) {
// TODO: maybe do this in pixel space instead?
d = latlng.distanceTo(this._route.coordinates[i]);
if (d < minDist) {
minIndex = i;
minDist = d;
}
}
return minIndex;
},
_extendToWaypoints: function() {
var wps = this._route.inputWaypoints,
wpIndices = this._getWaypointIndices(),
i,
wpLatLng,
routeCoord;
for (i = 0; i < wps.length; i++) {
wpLatLng = wps[i].latLng;
routeCoord = L.latLng(this._route.coordinates[wpIndices[i]]);
if (wpLatLng.distanceTo(routeCoord) >
this.options.missingRouteTolerance) {
this._addSegment([wpLatLng, routeCoord],
this.options.missingRouteStyles);
}
}
},
_addSegment: function(coords, styles, mouselistener) {
var i,
pl;
for (i = 0; i < styles.length; i++) {
pl = L.polyline(coords, styles[i]);
this.addLayer(pl);
if (mouselistener) {
pl.on('mousedown', this._onLineTouched, this);
}
}
},
_findNearestWpBefore: function(i) {
var wpIndices = this._getWaypointIndices(),
j = wpIndices.length - 1;
while (j >= 0 && wpIndices[j] > i) {
j--;
}
return j;
},
_onLineTouched: function(e) {
var afterIndex = this._findNearestWpBefore(this._findClosestRoutePoint(e.latlng));
this.fire('linetouched', {
afterIndex: afterIndex,
latlng: e.latlng
});
},
_getWaypointIndices: function() {
if (!this._wpIndices) {
this._wpIndices = this._route.waypointIndices || this._findWaypointIndices();
}
return this._wpIndices;
}
});
L.Routing.line = function(route, options) {
return new L.Routing.Line(route, options);
};
module.exports = L.Routing;
})();
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],11:[function(_dereq_,module,exports){
(function() {
'use strict';
var spanish = {
directions: {
N: 'norte',
NE: 'noreste',
E: 'este',
SE: 'sureste',
S: 'sur',
SW: 'suroeste',
W: 'oeste',
NW: 'noroeste',
SlightRight: 'leve giro a la derecha',
Right: 'derecha',
SharpRight: 'giro pronunciado a la derecha',
SlightLeft: 'leve giro a la izquierda',
Left: 'izquierda',
SharpLeft: 'giro pronunciado a la izquierda',
Uturn: 'media vuelta'
},
instructions: {
// instruction, postfix if the road is named
'Head':
['Derecho {dir}', ' sobre {road}'],
'Continue':
['Continuar {dir}', ' en {road}'],
'TurnAround':
['Dar vuelta'],
'WaypointReached':
['Llegó a un punto del camino'],
'Roundabout':
['Tomar {exitStr} salida en la rotonda', ' en {road}'],
'DestinationReached':
['Llegada a destino'],
'Fork': ['En el cruce gira a {modifier}', ' hacia {road}'],
'Merge': ['Incorpórate {modifier}', ' hacia {road}'],
'OnRamp': ['Gira {modifier} en la salida', ' hacia {road}'],
'OffRamp': ['Toma la salida {modifier}', ' hacia {road}'],
'EndOfRoad': ['Gira {modifier} al final de la carretera', ' hacia {road}'],
'Onto': 'hacia {road}'
},
formatOrder: function(n) {
return n + 'º';
},
ui: {
startPlaceholder: 'Inicio',
viaPlaceholder: 'Via {viaNumber}',
endPlaceholder: 'Destino'
},
units: {
meters: 'm',
kilometers: 'km',
yards: 'yd',
miles: 'mi',
hours: 'h',
minutes: 'min',
seconds: 's'
}
};
L.Routing = L.Routing || {};
L.Routing.Localization = L.Class.extend({
initialize: function(langs) {
this._langs = L.Util.isArray(langs) ? langs : [langs, 'en'];
for (var i = 0, l = this._langs.length; i < l; i++) {
if (!L.Routing.Localization[this._langs[i]]) {
throw new Error('No localization for language "' + this._langs[i] + '".');
}
}
},
localize: function(keys) {
var dict,
key,
value;
keys = L.Util.isArray(keys) ? keys : [keys];
for (var i = 0, l = this._langs.length; i < l; i++) {
dict = L.Routing.Localization[this._langs[i]];
for (var j = 0, nKeys = keys.length; dict && j < nKeys; j++) {
key = keys[j];
value = dict[key];
dict = value;
}
if (value) {
return value;
}
}
}
});
L.Routing.Localization = L.extend(L.Routing.Localization, {
'en': {
directions: {
N: 'north',
NE: 'northeast',
E: 'east',
SE: 'southeast',
S: 'south',
SW: 'southwest',
W: 'west',
NW: 'northwest',
SlightRight: 'slight right',
Right: 'right',
SharpRight: 'sharp right',
SlightLeft: 'slight left',
Left: 'left',
SharpLeft: 'sharp left',
Uturn: 'Turn around'
},
instructions: {
// instruction, postfix if the road is named
'Head':
['Head {dir}', ' on {road}'],
'Continue':
['Continue {dir}'],
'TurnAround':
['Turn around'],
'WaypointReached':
['Waypoint reached'],
'Roundabout':
['Take the {exitStr} exit in the roundabout', ' onto {road}'],
'DestinationReached':
['Destination reached'],
'Fork': ['At the fork, turn {modifier}', ' onto {road}'],
'Merge': ['Merge {modifier}', ' onto {road}'],
'OnRamp': ['Turn {modifier} on the ramp', ' onto {road}'],
'OffRamp': ['Take the ramp on the {modifier}', ' onto {road}'],
'EndOfRoad': ['Turn {modifier} at the end of the road', ' onto {road}'],
'Onto': 'onto {road}'
},
formatOrder: function(n) {
var i = n % 10 - 1,
suffix = ['st', 'nd', 'rd'];
return suffix[i] ? n + suffix[i] : n + 'th';
},
ui: {
startPlaceholder: 'Start',
viaPlaceholder: 'Via {viaNumber}',
endPlaceholder: 'End'
},
units: {
meters: 'm',
kilometers: 'km',
yards: 'yd',
miles: 'mi',
hours: 'h',
minutes: 'min',
seconds: 's'
}
},
'de': {
directions: {
N: 'Norden',
NE: 'Nordosten',
E: 'Osten',
SE: 'Südosten',
S: 'Süden',
SW: 'Südwesten',
W: 'Westen',
NW: 'Nordwesten'
},
instructions: {
// instruction, postfix if the road is named
'Head':
['Richtung {dir}', ' auf {road}'],
'Continue':
['Geradeaus Richtung {dir}', ' auf {road}'],
'SlightRight':
['Leicht rechts abbiegen', ' auf {road}'],
'Right':
['Rechts abbiegen', ' auf {road}'],
'SharpRight':
['Scharf rechts abbiegen', ' auf {road}'],
'TurnAround':
['Wenden'],
'SharpLeft':
['Scharf links abbiegen', ' auf {road}'],
'Left':
['Links abbiegen', ' auf {road}'],
'SlightLeft':
['Leicht links abbiegen', ' auf {road}'],
'WaypointReached':
['Zwischenhalt erreicht'],
'Roundabout':
['Nehmen Sie die {exitStr} Ausfahrt im Kreisverkehr', ' auf {road}'],
'DestinationReached':
['Sie haben ihr Ziel erreicht'],
},
formatOrder: function(n) {
return n + '.';
},
ui: {
startPlaceholder: 'Start',
viaPlaceholder: 'Via {viaNumber}',
endPlaceholder: 'Ziel'
}
},
'sv': {
directions: {
N: 'norr',
NE: 'nordost',
E: 'öst',
SE: 'sydost',
S: 'syd',
SW: 'sydväst',
W: 'väst',
NW: 'nordväst',
SlightRight: 'svagt höger',
Right: 'höger',
SharpRight: 'skarpt höger',
SlightLeft: 'svagt vänster',
Left: 'vänster',
SharpLeft: 'skarpt vänster',
Uturn: 'Vänd'
},
instructions: {
// instruction, postfix if the road is named
'Head':
['Åk åt {dir}', ' till {road}'],
'Continue':
['Fortsätt {dir}'],
'SlightRight':
['Svagt höger', ' till {road}'],
'Right':
['Sväng höger', ' till {road}'],
'SharpRight':
['Skarpt höger', ' till {road}'],
'TurnAround':
['Vänd'],
'SharpLeft':
['Skarpt vänster', ' till {road}'],
'Left':
['Sväng vänster', ' till {road}'],
'SlightLeft':
['Svagt vänster', ' till {road}'],
'WaypointReached':
['Viapunkt nådd'],
'Roundabout':
['Tag {exitStr} avfarten i rondellen', ' till {road}'],
'DestinationReached':
['Framme vid resans mål'],
'Fork': ['Tag av {modifier}', ' till {road}'],
'Merge': ['Anslut {modifier} ', ' till {road}'],
'OnRamp': ['Tag påfarten {modifier}', ' till {road}'],
'OffRamp': ['Tag avfarten {modifier}', ' till {road}'],
'EndOfRoad': ['Sväng {modifier} vid vägens slut', ' till {road}'],
'Onto': 'till {road}'
},
formatOrder: function(n) {
return ['första', 'andra', 'tredje', 'fjärde', 'femte',
'sjätte', 'sjunde', 'åttonde', 'nionde', 'tionde'
/* Can't possibly be more than ten exits, can there? */][n - 1];
},
ui: {
startPlaceholder: 'Från',
viaPlaceholder: 'Via {viaNumber}',
endPlaceholder: 'Till'
}
},
'es': spanish,
'sp': spanish,
'nl': {
directions: {
N: 'noordelijke',
NE: 'noordoostelijke',
E: 'oostelijke',
SE: 'zuidoostelijke',
S: 'zuidelijke',
SW: 'zuidewestelijke',
W: 'westelijke',
NW: 'noordwestelijke'
},
instructions: {
// instruction, postfix if the road is named
'Head':
['Vertrek in {dir} richting', ' de {road} op'],
'Continue':
['Ga in {dir} richting', ' de {road} op'],
'SlightRight':
['Volg de weg naar rechts', ' de {road} op'],
'Right':
['Ga rechtsaf', ' de {road} op'],
'SharpRight':
['Ga scherpe bocht naar rechts', ' de {road} op'],
'TurnAround':
['Keer om'],
'SharpLeft':
['Ga scherpe bocht naar links', ' de {road} op'],
'Left':
['Ga linksaf', ' de {road} op'],
'SlightLeft':
['Volg de weg naar links', ' de {road} op'],
'WaypointReached':
['Aangekomen bij tussenpunt'],
'Roundabout':
['Neem de {exitStr} afslag op de rotonde', ' de {road} op'],
'DestinationReached':
['Aangekomen op eindpunt'],
},
formatOrder: function(n) {
if (n === 1 || n >= 20) {
return n + 'ste';
} else {
return n + 'de';
}
},
ui: {
startPlaceholder: 'Vertrekpunt',
viaPlaceholder: 'Via {viaNumber}',
endPlaceholder: 'Bestemming'
}
},
'fr': {
directions: {
N: 'nord',
NE: 'nord-est',
E: 'est',
SE: 'sud-est',
S: 'sud',
SW: 'sud-ouest',
W: 'ouest',
NW: 'nord-ouest'
},
instructions: {
// instruction, postfix if the road is named
'Head':
['Tout droit au {dir}', ' sur {road}'],
'Continue':
['Continuer au {dir}', ' sur {road}'],
'SlightRight':
['Légèrement à droite', ' sur {road}'],
'Right':
['A droite', ' sur {road}'],
'SharpRight':
['Complètement à droite', ' sur {road}'],
'TurnAround':
['Faire demi-tour'],
'SharpLeft':
['Complètement à gauche', ' sur {road}'],
'Left':
['A gauche', ' sur {road}'],
'SlightLeft':
['Légèrement à gauche', ' sur {road}'],
'WaypointReached':
['Point d\'étape atteint'],
'Roundabout':
['Au rond-point, prenez la {exitStr} sortie', ' sur {road}'],
'DestinationReached':
['Destination atteinte'],
},
formatOrder: function(n) {
return n + 'º';
},
ui: {
startPlaceholder: 'Départ',
viaPlaceholder: 'Intermédiaire {viaNumber}',
endPlaceholder: 'Arrivée'
}
},
'it': {
directions: {
N: 'nord',
NE: 'nord-est',
E: 'est',
SE: 'sud-est',
S: 'sud',
SW: 'sud-ovest',
W: 'ovest',
NW: 'nord-ovest'
},
instructions: {
// instruction, postfix if the road is named
'Head':
['Dritto verso {dir}', ' su {road}'],
'Continue':
['Continuare verso {dir}', ' su {road}'],
'SlightRight':
['Mantenere la destra', ' su {road}'],
'Right':
['A destra', ' su {road}'],
'SharpRight':
['Strettamente a destra', ' su {road}'],
'TurnAround':
['Fare inversione di marcia'],
'SharpLeft':
['Strettamente a sinistra', ' su {road}'],
'Left':
['A sinistra', ' sur {road}'],
'SlightLeft':
['Mantenere la sinistra', ' su {road}'],
'WaypointReached':
['Punto di passaggio raggiunto'],
'Roundabout':
['Alla rotonda, prendere la {exitStr} uscita'],
'DestinationReached':
['Destinazione raggiunta'],
},
formatOrder: function(n) {
return n + 'º';
},
ui: {
startPlaceholder: 'Partenza',
viaPlaceholder: 'Intermedia {viaNumber}',
endPlaceholder: 'Destinazione'
}
},
'pt': {
directions: {
N: 'norte',
NE: 'nordeste',
E: 'leste',
SE: 'sudeste',
S: 'sul',
SW: 'sudoeste',
W: 'oeste',
NW: 'noroeste',
SlightRight: 'curva ligeira a direita',
Right: 'direita',
SharpRight: 'curva fechada a direita',
SlightLeft: 'ligeira a esquerda',
Left: 'esquerda',
SharpLeft: 'curva fechada a esquerda',
Uturn: 'Meia volta'
},
instructions: {
// instruction, postfix if the road is named
'Head':
['Siga {dir}', ' na {road}'],
'Continue':
['Continue {dir}', ' na {road}'],
'SlightRight':
['Curva ligeira a direita', ' na {road}'],
'Right':
['Curva a direita', ' na {road}'],
'SharpRight':
['Curva fechada a direita', ' na {road}'],
'TurnAround':
['Retorne'],
'SharpLeft':
['Curva fechada a esquerda', ' na {road}'],
'Left':
['Curva a esquerda', ' na {road}'],
'SlightLeft':
['Curva ligueira a esquerda', ' na {road}'],
'WaypointReached':
['Ponto de interesse atingido'],
'Roundabout':
['Pegue a {exitStr} saída na rotatória', ' na {road}'],
'DestinationReached':
['Destino atingido'],
'Fork': ['Na encruzilhada, vire a {modifier}', ' na {road}'],
'Merge': ['Entre à {modifier}', ' na {road}'],
'OnRamp': ['Vire {modifier} na rampa', ' na {road}'],
'OffRamp': ['Entre na rampa na {modifier}', ' na {road}'],
'EndOfRoad': ['Vire {modifier} no fim da rua', ' na {road}'],
'Onto': 'na {road}'
},
formatOrder: function(n) {
return n + 'º';
},
ui: {
startPlaceholder: 'Origem',
viaPlaceholder: 'Intermédio {viaNumber}',
endPlaceholder: 'Destino'
}
},
'sk': {
directions: {
N: 'sever',
NE: 'serverovýchod',
E: 'východ',
SE: 'juhovýchod',
S: 'juh',
SW: 'juhozápad',
W: 'západ',
NW: 'serverozápad'
},
instructions: {
// instruction, postfix if the road is named
'Head':
['Mierte na {dir}', ' na {road}'],
'Continue':
['Pokračujte na {dir}', ' na {road}'],
'SlightRight':
['Mierne doprava', ' na {road}'],
'Right':
['Doprava', ' na {road}'],
'SharpRight':
['Prudko doprava', ' na {road}'],
'TurnAround':
['Otočte sa'],
'SharpLeft':
['Prudko doľava', ' na {road}'],
'Left':
['Doľava', ' na {road}'],
'SlightLeft':
['Mierne doľava', ' na {road}'],
'WaypointReached':
['Ste v prejazdovom bode.'],
'Roundabout':
['Odbočte na {exitStr} výjazde', ' na {road}'],
'DestinationReached':
['Prišli ste do cieľa.'],
},
formatOrder: function(n) {
var i = n % 10 - 1,
suffix = ['.', '.', '.'];
return suffix[i] ? n + suffix[i] : n + '.';
},
ui: {
startPlaceholder: 'Začiatok',
viaPlaceholder: 'Cez {viaNumber}',
endPlaceholder: 'Koniec'
}
},
'el': {
directions: {
N: 'βόρεια',
NE: 'βορειοανατολικά',
E: 'ανατολικά',
SE: 'νοτιοανατολικά',
S: 'νότια',
SW: 'νοτιοδυτικά',
W: 'δυτικά',
NW: 'βορειοδυτικά'
},
instructions: {
// instruction, postfix if the road is named
'Head':
['Κατευθυνθείτε {dir}', ' στην {road}'],
'Continue':
['Συνεχίστε {dir}', ' στην {road}'],
'SlightRight':
['Ελαφρώς δεξιά', ' στην {road}'],
'Right':
['Δεξιά', ' στην {road}'],
'SharpRight':
['Απότομη δεξιά στροφή', ' στην {road}'],
'TurnAround':
['Κάντε αναστροφή'],
'SharpLeft':
['Απότομη αριστερή στροφή', ' στην {road}'],
'Left':
['Αριστερά', ' στην {road}'],
'SlightLeft':
['Ελαφρώς αριστερά', ' στην {road}'],
'WaypointReached':
['Φτάσατε στο σημείο αναφοράς'],
'Roundabout':
['Ακολουθήστε την {exitStr} έξοδο στο κυκλικό κόμβο', ' στην {road}'],
'DestinationReached':
['Φτάσατε στον προορισμό σας'],
},
formatOrder: function(n) {
return n + 'º';
},
ui: {
startPlaceholder: 'Αφετηρία',
viaPlaceholder: 'μέσω {viaNumber}',
endPlaceholder: 'Προορισμός'
}
},
'ca': {
directions: {
N: 'nord',
NE: 'nord-est',
E: 'est',
SE: 'sud-est',
S: 'sud',
SW: 'sud-oest',
W: 'oest',
NW: 'nord-oest',
SlightRight: 'lleu gir a la dreta',
Right: 'dreta',
SharpRight: 'gir pronunciat a la dreta',
SlightLeft: 'gir pronunciat a l\'esquerra',
Left: 'esquerra',
SharpLeft: 'lleu gir a l\'esquerra',
Uturn: 'mitja volta'
},
instructions: {
'Head':
['Recte {dir}', ' sobre {road}'],
'Continue':
['Continuar {dir}'],
'TurnAround':
['Donar la volta'],
'WaypointReached':
['Ha arribat a un punt del camí'],
'Roundabout':
['Agafar {exitStr} sortida a la rotonda', ' a {road}'],
'DestinationReached':
['Arribada al destí'],
'Fork': ['A la cruïlla gira a la {modifier}', ' cap a {road}'],
'Merge': ['Incorpora\'t {modifier}', ' a {road}'],
'OnRamp': ['Gira {modifier} a la sortida', ' cap a {road}'],
'OffRamp': ['Pren la sortida {modifier}', ' cap a {road}'],
'EndOfRoad': ['Gira {modifier} al final de la carretera', ' cap a {road}'],
'Onto': 'cap a {road}'
},
formatOrder: function(n) {
return n + 'º';
},
ui: {
startPlaceholder: 'Origen',
viaPlaceholder: 'Via {viaNumber}',
endPlaceholder: 'Destí'
},
units: {
meters: 'm',
kilometers: 'km',
yards: 'yd',
miles: 'mi',
hours: 'h',
minutes: 'min',
seconds: 's'
}
}
});
module.exports = L.Routing;
})();
},{}],12:[function(_dereq_,module,exports){
(function (global){
(function() {
'use strict';
var L = (typeof window !== "undefined" ? window['L'] : typeof global !== "undefined" ? global['L'] : null);
L.Routing = L.Routing || {};
L.extend(L.Routing, _dereq_('./L.Routing.OSRMv1'));
/**
* Works against OSRM's new API in version 5.0; this has
* the API version v1.
*/
L.Routing.Mapbox = L.Routing.OSRMv1.extend({
options: {
serviceUrl: 'https://api.mapbox.com/directions/v5',
profile: 'mapbox/driving',
useHints: false
},
initialize: function(accessToken, options) {
L.Routing.OSRMv1.prototype.initialize.call(this, options);
this.options.requestParameters = this.options.requestParameters || {};
/* jshint camelcase: false */
this.options.requestParameters.access_token = accessToken;
/* jshint camelcase: true */
}
});
L.Routing.mapbox = function(accessToken, options) {
return new L.Routing.Mapbox(accessToken, options);
};
module.exports = L.Routing;
})();
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./L.Routing.OSRMv1":13}],13:[function(_dereq_,module,exports){
(function (global){
(function() {
'use strict';
var L = (typeof window !== "undefined" ? window['L'] : typeof global !== "undefined" ? global['L'] : null),
corslite = _dereq_('corslite'),
polyline = _dereq_('polyline');
// Ignore camelcase naming for this file, since OSRM's API uses
// underscores.
/* jshint camelcase: false */
L.Routing = L.Routing || {};
L.extend(L.Routing, _dereq_('./L.Routing.Waypoint'));
/**
* Works against OSRM's new API in version 5.0; this has
* the API version v1.
*/
L.Routing.OSRMv1 = L.Class.extend({
options: {
serviceUrl: 'https://router.project-osrm.org/route/v1',
profile: 'driving',
timeout: 30 * 1000,
routingOptions: {
alternatives: true,
steps: true
},
polylinePrecision: 5,
useHints: true
},
initialize: function(options) {
L.Util.setOptions(this, options);
this._hints = {
locations: {}
};
},
route: function(waypoints, callback, context, options) {
var timedOut = false,
wps = [],
url,
timer,
wp,
i,
xhr;
options = L.extend({}, this.options.routingOptions, options);
url = this.buildRouteUrl(waypoints, options);
if (this.options.requestParameters) {
url += L.Util.getParamString(this.options.requestParameters, url);
}
timer = setTimeout(function() {
timedOut = true;
callback.call(context || callback, {
status: -1,
message: 'OSRM request timed out.'
});
}, this.options.timeout);
// Create a copy of the waypoints, since they
// might otherwise be asynchronously modified while
// the request is being processed.
for (i = 0; i < waypoints.length; i++) {
wp = waypoints[i];
wps.push(new L.Routing.Waypoint(wp.latLng, wp.name, wp.options));
}
return xhr = corslite(url, L.bind(function(err, resp) {
var data,
error = {};
clearTimeout(timer);
if (!timedOut) {
if (!err) {
try {
data = JSON.parse(resp.responseText);
try {
return this._routeDone(data, wps, options, callback, context);
} catch (ex) {
error.status = -3;
error.error = ex.toString();
}
} catch (ex) {
error.status = -2;
error.error = 'Error parsing OSRM response: ' + ex.toString();
}
} else {
error = L.extend({}, err, {
error: 'HTTP request failed: ' + err.type,
status: -1
})
}
callback.call(context || callback, error);
} else {
xhr.abort();
}
}, this));
},
requiresMoreDetail: function(route, zoom, bounds) {
if (!route.properties.isSimplified) {
return false;
}
var waypoints = route.inputWaypoints,
i;
for (i = 0; i < waypoints.length; ++i) {
if (!bounds.contains(waypoints[i].latLng)) {
return true;
}
}
return false;
},
_routeDone: function(response, inputWaypoints, options, callback, context) {
var alts = [],
actualWaypoints,
i,
route;
context = context || callback;
if (response.code !== 'Ok') {
callback.call(context, {
status: response.code
});
return;
}
actualWaypoints = this._toWaypoints(inputWaypoints, response.waypoints);
for (i = 0; i < response.routes.length; i++) {
route = this._convertRoute(response.routes[i]);
route.inputWaypoints = inputWaypoints;
route.waypoints = actualWaypoints;
route.properties = {isSimplified: !options || !options.geometryOnly || options.simplifyGeometry};
alts.push(route);
}
this._saveHintData(response.waypoints, inputWaypoints);
callback.call(context, null, alts);
},
_convertRoute: function(responseRoute) {
var result = {
name: '',
coordinates: [],
instructions: [],
summary: {
totalDistance: responseRoute.distance,
totalTime: responseRoute.duration
}
},
legNames = [],
index = 0,
legCount = responseRoute.legs.length,
hasSteps = responseRoute.legs[0].steps.length > 0,
i,
j,
leg,
step,
geometry,
type,
modifier;
for (i = 0; i < legCount; i++) {
leg = responseRoute.legs[i];
legNames.push(leg.summary && leg.summary.charAt(0).toUpperCase() + leg.summary.substring(1));
for (j = 0; j < leg.steps.length; j++) {
step = leg.steps[j];
geometry = this._decodePolyline(step.geometry);
result.coordinates.push.apply(result.coordinates, geometry);
type = this._maneuverToInstructionType(step.maneuver, i === legCount - 1);
modifier = this._maneuverToModifier(step.maneuver);
if (type) {
result.instructions.push({
type: type,
distance: step.distance,
time: step.duration,
road: step.name,
direction: this._bearingToDirection(step.maneuver.bearing_after),
exit: step.maneuver.exit,
index: index,
mode: step.mode,
modifier: modifier
});
}
index += geometry.length;
}
}
result.name = legNames.join(', ');
if (!hasSteps) {
result.coordinates = this._decodePolyline(responseRoute.geometry);
}
return result;
},
_bearingToDirection: function(bearing) {
var oct = Math.round(bearing / 45) % 8;
return ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'][oct];
},
_maneuverToInstructionType: function(maneuver, lastLeg) {
switch (maneuver.type) {
case 'new name':
return 'Continue';
case 'depart':
return 'Head';
case 'arrive':
return lastLeg ? 'DestinationReached' : 'WaypointReached';
case 'roundabout':
case 'rotary':
return 'Roundabout';
case 'merge':
case 'fork':
case 'on ramp':
case 'off ramp':
case 'end of road':
return this._camelCase(maneuver.type);
// These are all reduced to the same instruction in the current model
//case 'turn':
//case 'ramp': // deprecated in v5.1
default:
return this._camelCase(maneuver.modifier);
}
},
_maneuverToModifier: function(maneuver) {
var modifier = maneuver.modifier;
switch (maneuver.type) {
case 'merge':
case 'fork':
case 'on ramp':
case 'off ramp':
case 'end of road':
modifier = this._leftOrRight(modifier);
}
return modifier && this._camelCase(modifier);
},
_camelCase: function(s) {
var words = s.split(' '),
result = '';
for (var i = 0, l = words.length; i < l; i++) {
result += words[i].charAt(0).toUpperCase() + words[i].substring(1);
}
return result;
},
_leftOrRight: function(d) {
return d.indexOf('left') >= 0 ? 'Left' : 'Right';
},
_decodePolyline: function(routeGeometry) {
var cs = polyline.decode(routeGeometry, this.options.polylinePrecision),
result = new Array(cs.length),
i;
for (i = cs.length - 1; i >= 0; i--) {
result[i] = L.latLng(cs[i]);
}
return result;
},
_toWaypoints: function(inputWaypoints, vias) {
var wps = [],
i,
viaLoc;
for (i = 0; i < vias.length; i++) {
viaLoc = vias[i].location;
wps.push(L.Routing.waypoint(L.latLng(viaLoc[1], viaLoc[0]),
inputWaypoints[i].name,
inputWaypoints[i].options));
}
return wps;
},
buildRouteUrl: function(waypoints, options) {
var locs = [],
hints = [],
wp,
latLng,
computeInstructions,
computeAlternative = true;
for (var i = 0; i < waypoints.length; i++) {
wp = waypoints[i];
latLng = wp.latLng;
locs.push(latLng.lng + ',' + latLng.lat);
hints.push(this._hints.locations[this._locationKey(latLng)] || '');
}
computeInstructions =
!(options && options.geometryOnly);
return this.options.serviceUrl + '/' + this.options.profile + '/' +
locs.join(';') + '?' +
(options.geometryOnly ? (options.simplifyGeometry ? '' : 'overview=full') : 'overview=false') +
'&alternatives=' + computeAlternative.toString() +
'&steps=' + computeInstructions.toString() +
(this.options.useHints ? '&hints=' + hints.join(';') : '') +
(options.allowUTurns ? '&continue_straight=' + !options.allowUTurns : '');
},
_locationKey: function(location) {
return location.lat + ',' + location.lng;
},
_saveHintData: function(actualWaypoints, waypoints) {
var loc;
this._hints = {
locations: {}
};
for (var i = actualWaypoints.length - 1; i >= 0; i--) {
loc = waypoints[i].latLng;
this._hints.locations[this._locationKey(loc)] = actualWaypoints[i].hint;
}
},
});
L.Routing.osrmv1 = function(options) {
return new L.Routing.OSRMv1(options);
};
module.exports = L.Routing;
})();
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./L.Routing.Waypoint":15,"corslite":1,"polyline":2}],14:[function(_dereq_,module,exports){
(function (global){
(function() {
'use strict';
var L = (typeof window !== "undefined" ? window['L'] : typeof global !== "undefined" ? global['L'] : null);
L.Routing = L.Routing || {};
L.extend(L.Routing, _dereq_('./L.Routing.GeocoderElement'));
L.extend(L.Routing, _dereq_('./L.Routing.Waypoint'));
L.Routing.Plan = (L.Layer || L.Class).extend({
includes: L.Mixin.Events,
options: {
dragStyles: [
{color: 'black', opacity: 0.15, weight: 9},
{color: 'white', opacity: 0.8, weight: 6},
{color: 'red', opacity: 1, weight: 2, dashArray: '7,12'}
],
draggableWaypoints: true,
routeWhileDragging: false,
addWaypoints: true,
reverseWaypoints: false,
addButtonClassName: '',
language: 'en',
createGeocoderElement: L.Routing.geocoderElement,
createMarker: function(i, wp) {
var options = {
draggable: this.draggableWaypoints
},
marker = L.marker(wp.latLng, options);
return marker;
},
geocodersClassName: ''
},
initialize: function(waypoints, options) {
L.Util.setOptions(this, options);
this._waypoints = [];
this.setWaypoints(waypoints);
},
isReady: function() {
var i;
for (i = 0; i < this._waypoints.length; i++) {
if (!this._waypoints[i].latLng) {
return false;
}
}
return true;
},
getWaypoints: function() {
var i,
wps = [];
for (i = 0; i < this._waypoints.length; i++) {
wps.push(this._waypoints[i]);
}
return wps;
},
setWaypoints: function(waypoints) {
var args = [0, this._waypoints.length].concat(waypoints);
this.spliceWaypoints.apply(this, args);
return this;
},
spliceWaypoints: function() {
var args = [arguments[0], arguments[1]],
i;
for (i = 2; i < arguments.length; i++) {
args.push(arguments[i] && arguments[i].hasOwnProperty('latLng') ? arguments[i] : L.Routing.waypoint(arguments[i]));
}
[].splice.apply(this._waypoints, args);
// Make sure there's always at least two waypoints
while (this._waypoints.length < 2) {
this.spliceWaypoints(this._waypoints.length, 0, null);
}
this._updateMarkers();
this._fireChanged.apply(this, args);
},
onAdd: function(map) {
this._map = map;
this._updateMarkers();
},
onRemove: function() {
var i;
this._removeMarkers();
if (this._newWp) {
for (i = 0; i < this._newWp.lines.length; i++) {
this._map.removeLayer(this._newWp.lines[i]);
}
}
delete this._map;
},
createGeocoders: function() {
var container = L.DomUtil.create('div', 'leaflet-routing-geocoders ' + this.options.geocodersClassName),
waypoints = this._waypoints,
addWpBtn,
reverseBtn;
this._geocoderContainer = container;
this._geocoderElems = [];
if (this.options.addWaypoints) {
addWpBtn = L.DomUtil.create('button', 'leaflet-routing-add-waypoint ' + this.options.addButtonClassName, container);
addWpBtn.setAttribute('type', 'button');
L.DomEvent.addListener(addWpBtn, 'click', function() {
this.spliceWaypoints(waypoints.length, 0, null);
}, this);
}
if (this.options.reverseWaypoints) {
reverseBtn = L.DomUtil.create('button', 'leaflet-routing-reverse-waypoints', container);
reverseBtn.setAttribute('type', 'button');
L.DomEvent.addListener(reverseBtn, 'click', function() {
this._waypoints.reverse();
this.setWaypoints(this._waypoints);
}, this);
}
this._updateGeocoders();
this.on('waypointsspliced', this._updateGeocoders);
return container;
},
_createGeocoder: function(i) {
var geocoder = this.options.createGeocoderElement(this._waypoints[i], i, this._waypoints.length, this.options);
geocoder
.on('delete', function() {
if (i > 0 || this._waypoints.length > 2) {
this.spliceWaypoints(i, 1);
} else {
this.spliceWaypoints(i, 1, new L.Routing.Waypoint());
}
}, this)
.on('geocoded', function(e) {
this._updateMarkers();
this._fireChanged();
this._focusGeocoder(i + 1);
this.fire('waypointgeocoded', {
waypointIndex: i,
waypoint: e.waypoint
});
}, this)
.on('reversegeocoded', function(e) {
this.fire('waypointgeocoded', {
waypointIndex: i,
waypoint: e.waypoint
});
}, this);
return geocoder;
},
_updateGeocoders: function() {
var elems = [],
i,
geocoderElem;
for (i = 0; i < this._geocoderElems.length; i++) {
this._geocoderContainer.removeChild(this._geocoderElems[i].getContainer());
}
for (i = this._waypoints.length - 1; i >= 0; i--) {
geocoderElem = this._createGeocoder(i);
this._geocoderContainer.insertBefore(geocoderElem.getContainer(), this._geocoderContainer.firstChild);
elems.push(geocoderElem);
}
this._geocoderElems = elems.reverse();
},
_removeMarkers: function() {
var i;
if (this._markers) {
for (i = 0; i < this._markers.length; i++) {
if (this._markers[i]) {
this._map.removeLayer(this._markers[i]);
}
}
}
this._markers = [];
},
_updateMarkers: function() {
var i,
m;
if (!this._map) {
return;
}
this._removeMarkers();
for (i = 0; i < this._waypoints.length; i++) {
if (this._waypoints[i].latLng) {
m = this.options.createMarker(i, this._waypoints[i], this._waypoints.length);
if (m) {
m.addTo(this._map);
if (this.options.draggableWaypoints) {
this._hookWaypointEvents(m, i);
}
}
} else {
m = null;
}
this._markers.push(m);
}
},
_fireChanged: function() {
this.fire('waypointschanged', {waypoints: this.getWaypoints()});
if (arguments.length >= 2) {
this.fire('waypointsspliced', {
index: Array.prototype.shift.call(arguments),
nRemoved: Array.prototype.shift.call(arguments),
added: arguments
});
}
},
_hookWaypointEvents: function(m, i, trackMouseMove) {
var eventLatLng = function(e) {
return trackMouseMove ? e.latlng : e.target.getLatLng();
},
dragStart = L.bind(function(e) {
this.fire('waypointdragstart', {index: i, latlng: eventLatLng(e)});
}, this),
drag = L.bind(function(e) {
this._waypoints[i].latLng = eventLatLng(e);
this.fire('waypointdrag', {index: i, latlng: eventLatLng(e)});
}, this),
dragEnd = L.bind(function(e) {
this._waypoints[i].latLng = eventLatLng(e);
this._waypoints[i].name = '';
if (this._geocoderElems) {
this._geocoderElems[i].update(true);
}
this.fire('waypointdragend', {index: i, latlng: eventLatLng(e)});
this._fireChanged();
}, this),
mouseMove,
mouseUp;
if (trackMouseMove) {
mouseMove = L.bind(function(e) {
this._markers[i].setLatLng(e.latlng);
drag(e);
}, this);
mouseUp = L.bind(function(e) {
this._map.dragging.enable();
this._map.off('mouseup', mouseUp);
this._map.off('mousemove', mouseMove);
dragEnd(e);
}, this);
this._map.dragging.disable();
this._map.on('mousemove', mouseMove);
this._map.on('mouseup', mouseUp);
dragStart({latlng: this._waypoints[i].latLng});
} else {
m.on('dragstart', dragStart);
m.on('drag', drag);
m.on('dragend', dragEnd);
}
},
dragNewWaypoint: function(e) {
var newWpIndex = e.afterIndex + 1;
if (this.options.routeWhileDragging) {
this.spliceWaypoints(newWpIndex, 0, e.latlng);
this._hookWaypointEvents(this._markers[newWpIndex], newWpIndex, true);
} else {
this._dragNewWaypoint(newWpIndex, e.latlng);
}
},
_dragNewWaypoint: function(newWpIndex, initialLatLng) {
var wp = new L.Routing.Waypoint(initialLatLng),
prevWp = this._waypoints[newWpIndex - 1],
nextWp = this._waypoints[newWpIndex],
marker = this.options.createMarker(newWpIndex, wp, this._waypoints.length + 1),
lines = [],
mouseMove = L.bind(function(e) {
var i;
if (marker) {
marker.setLatLng(e.latlng);
}
for (i = 0; i < lines.length; i++) {
lines[i].spliceLatLngs(1, 1, e.latlng);
}
}, this),
mouseUp = L.bind(function(e) {
var i;
if (marker) {
this._map.removeLayer(marker);
}
for (i = 0; i < lines.length; i++) {
this._map.removeLayer(lines[i]);
}
this._map.off('mousemove', mouseMove);
this._map.off('mouseup', mouseUp);
this.spliceWaypoints(newWpIndex, 0, e.latlng);
}, this),
i;
if (marker) {
marker.addTo(this._map);
}
for (i = 0; i < this.options.dragStyles.length; i++) {
lines.push(L.polyline([prevWp.latLng, initialLatLng, nextWp.latLng],
this.options.dragStyles[i]).addTo(this._map));
}
this._map.on('mousemove', mouseMove);
this._map.on('mouseup', mouseUp);
},
_focusGeocoder: function(i) {
if (this._geocoderElems[i]) {
this._geocoderElems[i].focus();
} else {
document.activeElement.blur();
}
}
});
L.Routing.plan = function(waypoints, options) {
return new L.Routing.Plan(waypoints, options);
};
module.exports = L.Routing;
})();
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./L.Routing.GeocoderElement":7,"./L.Routing.Waypoint":15}],15:[function(_dereq_,module,exports){
(function (global){
(function() {
'use strict';
var L = (typeof window !== "undefined" ? window['L'] : typeof global !== "undefined" ? global['L'] : null);
L.Routing = L.Routing || {};
L.Routing.Waypoint = L.Class.extend({
options: {
allowUTurn: false,
},
initialize: function(latLng, name, options) {
L.Util.setOptions(this, options);
this.latLng = L.latLng(latLng);
this.name = name;
}
});
L.Routing.waypoint = function(latLng, name, options) {
return new L.Routing.Waypoint(latLng, name, options);
};
module.exports = L.Routing;
})();
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}]},{},[4])(4)
}); | emmy41124/cdnjs | ajax/libs/leaflet-routing-machine/3.2.1/leaflet-routing-machine.js | JavaScript | mit | 82,594 |